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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a784ee01eba02c0b97c56df93bb5bb71bd0084e9
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Dependencies/Xerces/include/xercesc/validators/schema/identity/FieldActivator.hpp
|
ba16bc2ae314e2e8cbdff80b8c6111c339a35c25
|
[] |
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,060 |
hpp
|
/*
* Copyright 2001-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: FieldActivator.hpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
#if !defined(FIELDACTIVATOR_HPP)
#define FIELDACTIVATOR_HPP
/**
* This class is responsible for activating fields within a specific scope;
* the caller merely requests the fields to be activated.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/ValueHashTableOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Forward Declaration
// ---------------------------------------------------------------------------
class IdentityConstraint;
class XPathMatcher;
class ValueStoreCache;
class IC_Field;
class XPathMatcherStack;
class VALIDATORS_EXPORT FieldActivator : public XMemory
{
public:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
FieldActivator(ValueStoreCache* const valueStoreCache,
XPathMatcherStack* const matcherStack,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
FieldActivator(const FieldActivator& other);
~FieldActivator();
// -----------------------------------------------------------------------
// Operator methods
// -----------------------------------------------------------------------
FieldActivator& operator =(const FieldActivator& other);
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
bool getMayMatch(IC_Field* const field);
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setValueStoreCache(ValueStoreCache* const other);
void setMatcherStack(XPathMatcherStack* const matcherStack);
void setMayMatch(IC_Field* const field, bool value);
// -----------------------------------------------------------------------
// Activation methods
// -----------------------------------------------------------------------
/**
* Start the value scope for the specified identity constraint. This
* method is called when the selector matches in order to initialize
* the value store.
*/
void startValueScopeFor(const IdentityConstraint* const ic, const int initialDepth);
/**
* Request to activate the specified field. This method returns the
* matcher for the field.
*/
XPathMatcher* activateField(IC_Field* const field, const int initialDepth);
/**
* Ends the value scope for the specified identity constraint.
*/
void endValueScopeFor(const IdentityConstraint* const ic, const int initialDepth);
private:
// -----------------------------------------------------------------------
// Data
// -----------------------------------------------------------------------
ValueStoreCache* fValueStoreCache;
XPathMatcherStack* fMatcherStack;
ValueHashTableOf<bool>* fMayMatch;
MemoryManager* fMemoryManager;
};
// ---------------------------------------------------------------------------
// FieldActivator: Getter methods
// ---------------------------------------------------------------------------
inline bool FieldActivator::getMayMatch(IC_Field* const field) {
return fMayMatch->get(field);
}
// ---------------------------------------------------------------------------
// FieldActivator: Setter methods
// ---------------------------------------------------------------------------
inline void FieldActivator::setValueStoreCache(ValueStoreCache* const other) {
fValueStoreCache = other;
}
inline void
FieldActivator::setMatcherStack(XPathMatcherStack* const matcherStack) {
fMatcherStack = matcherStack;
}
inline void FieldActivator::setMayMatch(IC_Field* const field, bool value) {
fMayMatch->put(field, value);
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file FieldActivator.hpp
*/
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
141
]
]
] |
fb8c4935c370a588c357e3c5eddec2f589268f70
|
e6d2a9ae338f4624435dba74c7e7e6e58486492f
|
/Negocio/Factura.h
|
358710a79f6b6fb952b1aabbc9dc16f97c6d154f
|
[] |
no_license
|
marcosgabarda/seoane
|
054608b2a2c00a56d103568d2e03093671019292
|
1956161ddbbb329db6c5eef666c64f7c6a5b2059
|
refs/heads/master
| 2020-12-24T17:26:58.747877 | 2008-12-25T23:52:01 | 2008-12-25T23:52:01 | 32,239,598 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,419 |
h
|
#ifndef FACTURA_H_
#define FACTURA_H_
#include "Cliente.h"
#include "LineaArticulo.h"
#include "Articulo.h"
#include <string>
#include <list>
using namespace std;
class Factura
{
private:
int id;
int n_factura;
string fecha;
string aparato;
string marca;
string modelo;
int n_fabricacion;
bool *lugar_reparacion;
Cliente *cliente;
list <LineaArticulo> lista_articulos;
string averia;
string trabajo_realizado;
string tiempo_empleado;
string fecha_terminacion;
string observaciones;
double precio_materiales;
double precio_mano_obra;
double precio_desplazamiento;
double precio_transporte;
int iva;
public:
Factura();
virtual ~Factura();
//metodos get
int getid();
int getn_factura();
string getfecha();
string getaparato();
string getmarca();
string getmodelo();
int getn_fabricacion();
bool *getlugar_reparacion();
Cliente *getcliente();
list<LineaArticulo> getlista_articulos();
string getaveria();
string gettrabajo_realizado();
string gettiempo_empleado();
string getfecha_terminacion();
string getobservaciones();
double getprecio_materiales();
double getprecio_mano_obra();
double getprecio_desplazamiento();
double getprecio_transporte();
double getiva();
//metodos set
void setid(int id);
void setn_factura(int n_factura);
void setfecha(string fecha);
void setaparato(string aparato);
void setmarca(string marca);
void setmodelo(string modelo);
void setn_fabricacion(int n_fabricacion);
void setlugar_reparacion(bool *lugar_reparacion);
void setcliente(Cliente *cliente);
void setlista_articulos(list <LineaArticulo> l);
void setaveria(string a);
void settrabajo_realizado(string t);
void settiempo_empleado(string t);
void setfecha_terminacion(string f);
void setobservaciones(string o);
void setprecio_materiales(double p);
void setprecio_mano_obra(double p);
void setprecio_desplazamiento(double p);
void setprecio_transporte(double p);
void setiva(double i);
//metodos para la lista de articulos
void addArticulo(LineaArticulo la);
void addArticulo(Articulo a, int c);
bool eliminarArticulo(Articulo a);
bool modificarArticulo(Articulo a, int c);
bool modificarArticulo(LineaArticulo la);
double getMateriales ();
double getSubTotal();
double getTotal();
//sobrecrga del operador =
Factura operator=(Factura f);
};
#endif
|
[
"cyberslas@9c3cf54a-d2bc-11dd-9042-6d746b85d38b"
] |
[
[
[
1,
99
]
]
] |
5c0558ce233678bb657b69ab879b20cc608b6d02
|
22b6d8a368ecfa96cb182437b7b391e408ba8730
|
/engine/source/quanticvortex/qvPhysicsManager.cpp
|
50b1cbd26301a7e0eb5115091e68df3998c57268
|
[
"MIT"
] |
permissive
|
drr00t/quanticvortex
|
2d69a3e62d1850b8d3074ec97232e08c349e23c2
|
b780b0f547cf19bd48198dc43329588d023a9ad9
|
refs/heads/master
| 2021-01-22T22:16:50.370688 | 2010-12-18T12:06:33 | 2010-12-18T12:06:33 | 85,525,059 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 10,815 |
cpp
|
#include "qvPhysicsManager.h"
#include "btBulletCollisionCommon.h"
#include "btBulletDynamicsCommon.h"
#include "BulletCollision/CollisionDispatch/btGhostObject.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h"
namespace qv
{
namespace physics
{
//-----------------------------------------------------------------------------------------
PhysicsManager::PhysicsManager(qv::CommandManager* commandManager)
: mBulletDynamicsWorld(0), mBulletBroadphaseInterface(0),
mBulletCollisionDispatcher(0), mBulletConstraintSolver(0),
mBulletDefaultCollisionConfiguration(0), mCommandManager(commandManager)
{
initialize();
}
//-----------------------------------------------------------------------------------------
PhysicsManager::~PhysicsManager()
{
finalize();
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::initialize()
{
mBulletDefaultCollisionConfiguration = new btDefaultCollisionConfiguration();
mBulletCollisionDispatcher = new btCollisionDispatcher(mBulletDefaultCollisionConfiguration);
mBulletBroadphaseInterface = new btDbvtBroadphase();
mBulletConstraintSolver = new btSequentialImpulseConstraintSolver();
mBulletDynamicsWorld = new btDiscreteDynamicsWorld(mBulletCollisionDispatcher,
mBulletBroadphaseInterface,
mBulletConstraintSolver,
mBulletDefaultCollisionConfiguration);
mBulletDynamicsWorld->setGravity(btVector3(0, -0.98, 0));
///register an additional callback for characters/ghost objects
btOverlappingPairCallback* ghostPairCallback = new btGhostPairCallback();
mBulletDynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback);
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::finalize()
{
delete mBulletDynamicsWorld;
delete mBulletConstraintSolver;
delete mBulletBroadphaseInterface;
delete mBulletCollisionDispatcher;
delete mBulletDefaultCollisionConfiguration;
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::update( qv::u32 elapsedTimeMs)
{
mBulletDynamicsWorld->stepSimulation(btScalar(elapsedTimeMs / 1000.0f), 2); //just twos sub steps, is enough???);
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::addShape(qv::real radius, qv::gaming::Actor *actor, qv::real specificGravity)
{
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::addBox(const btVector3 &dimensions, qv::gaming::Actor *actor, qv::real specificGravity)
{
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::addConvexHull( btVector3 *verts, qv::s32 numPoints, qv::gaming::Actor *actor, qv::real specificGravity)
{
}
//-----------------------------------------------------------------------------------------
void PhysicsManager::addSphere( qv::real radius, qv::gaming::Actor *actor, qv::real specificGravity)
{
// btSphereShape* sphereShape = new btSphereShape(btScalar(radius));
}
//-----------------------------------------------------------------------------------------
// void _addPhysicsObject(irr::scene::ISceneNode* node, irr::io::IAttributes* userData)
// {
// struct PhysicsAttributes attr;
// scene::IMesh* mesh=0;
//
// switch(node->getType())
// {
// case scene::ESNT_ANIMATED_MESH:
// mesh = static_cast<scene::IAnimatedMeshSceneNode*>(node)->getMesh();
// break;
// case scene::ESNT_MESH:
// mesh = static_cast<scene::IMeshSceneNode*>(node)->getMesh();
// break;
// }
// if(!mesh)
// {
// printf("Error creating physics object - Mesh is NULL for %s\n", node->getName());
// return;
// }
//
// // convert .irr node "UserData" to PhysicsAttributes structure for
// // easier access.
// _setPhysicsAttributes(userData, attr);
//
// node->OnRegisterSceneNode();
// node->updateAbsolutePosition();
// core::aabbox3d<f32> aabb = node->getBoundingBox();
// core::vector3df iExtent = aabb.getExtent();
// core::vector3df iHalfExtent = iExtent / 2.f;
//
// btCollisionShape* shape=0;
// btVector3 halfExtents(iHalfExtent.X, iHalfExtent.Y, iHalfExtent.Z);
//
// // create collision shape based on PhysicsAttributes shape
// switch(attr.Shapetype)
// {
// case stBox:
// {
// shape = new btBoxShape(halfExtents);
// }
// break;
// case stPlane:
// {
// }
// break;
// case stSphere:
// {
// shape = new btSphereShape(halfExtents.x());
// }
// break;
// case stCone:
// {
// shape = new btConeShape(halfExtents.x(), halfExtents.y());
// }
// break;
// case stCylinder:
// {
// shape = new btCylinderShape(halfExtents);
// }
// break;
// case stConvexMesh:
// {
// btTriangleMesh* triMesh = _extractTriangles(mesh, true);
// //if(attr.BodyType == btStatic)
// // {
// //shape = new btBvhTriangleMeshShape(triMesh, true, true);
// const unsigned char *verts;
// const unsigned char *indexes;
// PHY_ScalarType vtype, itype;
// int numverts, numfaces, vstride,istride;
//
// triMesh->getLockedReadOnlyVertexIndexBase(&verts, numverts, vtype, vstride, &indexes, istride, numfaces, itype);
// shape = new btConvexHullShape((const btScalar*)verts, numverts, vstride);
// triMesh->unLockReadOnlyVertexBase(0);
// //}
// //else
// //{
// // btConvexShape* tmpConvexShape = new btConvexTriangleMeshShape(triMesh);
// // shape = tmpConvexShape;
// // }
// }
// break;
// case stConcaveMesh:
// {
// btTriangleMesh* triMesh = _extractTriangles(mesh, true);
// if(attr.BodyType == btStatic)
// {
// btBvhTriangleMeshShape* bShape = new btBvhTriangleMeshShape(triMesh, true, true);
// shape = bShape;
//
// btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
//
//
// btGenerateInternalEdgeInfo(bShape,triangleInfoMap);
// }
// else
// {
// // generate convex hull
// btConvexShape* tmpConvexShape = new btConvexTriangleMeshShape(triMesh);
//
// btShapeHull* hull = new btShapeHull(tmpConvexShape);
// btScalar margin = tmpConvexShape->getMargin();
// hull->buildHull(margin);
// tmpConvexShape->setUserPointer(hull);
//
//
// printf(" hull vert count: %d\n", hull->numVertices());
// printf(" hull tri count: %d\n", hull->numTriangles());
//
// btConvexHullShape* chShape = new btConvexHullShape();
//
// const btVector3* vp = hull->getVertexPointer();
// const unsigned int* ip = hull->getIndexPointer();
// for (int i=0;i<hull->numTriangles();i++)
// {
// chShape->addPoint(vp[ip[i*3]]);
// chShape->addPoint(vp[ip[i*3+1]]);
// chShape->addPoint(vp[ip[i*3+2]]);
// }
//
// shape = chShape;
// delete hull;
// delete tmpConvexShape;
// }
// }
// break;
// }
//
// if(!shape)
// {
// printf("undefined shape for: %s\n", node->getName());
// return;
// }
//
// // calculate local intertia for dynamic objects
// btVector3 localInertia(0,0,0);
// if (attr.mass != 0.f && attr.BodyType == btDynamic)
// shape->calculateLocalInertia(attr.mass,localInertia);
//
// btRigidBody* rigidBody = new btRigidBody(attr.mass, new MotionState(node),
// shape, localInertia);
// rigidBody->setUserPointer(node);
//
// rigidBody->getMotionState()->setWorldTransform(rigidBody->getWorldTransform());
//
// int cflags = rigidBody->getCollisionFlags();
// rigidBody->setCollisionFlags(0);
// if(attr.BodyType == btStatic)
// rigidBody->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT);
// else if(attr.BodyType == btKinematic)
// rigidBody->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT);
//
// if(attr.Shapetype == stConcaveMesh && attr.BodyType == btStatic)
// rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
//
// if(attr.sensor)
// {
// // collision with no response
// rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
// //rigidBody->setCollisionFlags(btCollisionObject::CF_NO_CONTACT_RESPONSE);
// m_sensors.push_back(rigidBody);
// }
//
// m_bulletWorld->addRigidBody(rigidBody);
//
// // collision only ?
// if(!attr.visible)
// {
// // turn off visibility
// node->setVisible(false);
// }
// }
}
}
|
[
"[email protected]"
] |
[
[
[
1,
255
]
]
] |
f602febecfc28666c0d35bd1516587ca4b4c7d0c
|
709cd826da3ae55945fd7036ecf872ee7cdbd82a
|
/Term/WildMagic2/Source/Physics/WmlLCPPolyDist.h
|
fc89e67add0136a10e09c7468481424692f59f38
|
[] |
no_license
|
argapratama/kucgbowling
|
20dbaefe1596358156691e81ccceb9151b15efb0
|
65e40b6f33c5511bddf0fa350c1eefc647ace48a
|
refs/heads/master
| 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,022 |
h
|
// Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Game Physics source code is supplied under the terms of the license
// agreement http://www.magic-software.com/License/GamePhysics.pdf and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
#ifndef WMLLCPPOLYDIST_H
#define WMLLCPPOLYDIST_H
#include "WmlTuple.h"
#include "WmlVector2.h"
#include "WmlVector3.h"
#include "WmlLCPSolver.h"
#include <fstream>
#include <string>
namespace Wml
{
template <class VectorIn, class TVector, class TTuple>
class WML_ITEM LCPPolyDist
{
public:
// A class for computing the distance between two convex polygons or two
// convex polyhedra. The distance algorithm is formulated as a linear
// complementarity problem (LCP) for three-dimensional data. For convex
// polygons in two dimensions, the third component of the vertices must
// be zero.
// Status codes returned by the polyhedra distance calculation.
enum
{
SC_FOUND_SOLUTION
= LCPSolver::SC_FOUND_SOLUTION, // solution
SC_FOUND_TRIVIAL_SOLUTION
= LCPSolver::SC_FOUND_TRIVIAL_SOLUTION, // solution (z = 0, w = q)
SC_CANNOT_REMOVE_COMPLEMENTARY
= LCPSolver::SC_CANNOT_REMOVE_COMPLEMENTARY, // no solution
SC_EXCEEDED_MAX_RETRIES
= LCPSolver::SC_EXCEEDED_MAX_RETRIES,
// no solution (round-off problems?)
SC_VERIFY_FAILURE, // VerifySolution failed
SC_TEST_POINTS_TEST_FAILED, // VerifyWithTestPoints failed
};
// Polygons represented by vertices and edges. The vertices are stored
// as vectors in 3D with the last component always zero.
// iNumPoints1 = number of vertices of first polygon
// akPoint1 = array of vertices
// iNumFaces1 = number of edges (same as iNumPoints1)
// akFace1 = array of edges, each edge a pair of indices into the
// vertex array akPoint1: <0,1>, <1,2>, ..., <n-2,n-1>,
// <n-1,0>
// iNumPoints2 = number of vertices of second polygon
// akPoint2 = array of vertices
// iNumFaces2 = number of edges (same as iNumPoints2)
// akFace2 = array of edges, each edge a pair of indices into the
// vertex array akPoint2: <0,1>, <1,2>, ..., <n-2,n-1>,
// <n-1,0>
// riStatusCode = the status of the LCP numerical solver
// rfDistance = distance between the polygons
// akRes = array of two closest points, one on each polygon
//
// Polyhedra represented by vertices and faces.
// iNumPoints1 = number of vertices of first polyhedron
// akPoint1 = array of vertices
// iNumFaces1 = number of triangular faces
// akFace1 = array of faces, each face a triple of indices into
// the vertex array akPoint1
// iNumPoints2 = number of vertices of second polyhedron
// akPoint2 = array of vertices
// iNumFaces2 = number of triangular faces
// akFace2 = array of faces, each face a triple of indices into
// the vertex array akPoint2
// riStatusCode = the status of the LCP numerical solver
// rfDistance = distance between the polyhedra
// akClosest = array of two closest points, one on each polyhedron
LCPPolyDist (int iNumPoints1, VectorIn* akPoint1, int iNumFaces1,
TTuple* akFace1, int iNumPoints2, VectorIn* akPoint2, int iNumFaces2,
TTuple* akFace2, int& riStatusCode, float& rfDistance,
VectorIn akClosest[/*2*/]);
// Polygons and polyhedra represented by halfspaces. The halfspaces are
// all the points p such that p.Dot(akAn[i]) <= afBn[i], n = 1 or 2. The
// arrays akAn[] are the outer pointing edge/face normals. The arrays
// afBn[] are the line/plane constants.
// iNum1 = number of halfspaces of first polygon/polyhedron
// afB1 = array of line/plane constants
// akA1 = array of outer pointing edge/face normals
// iNum2 = number of halfspaces of second polygon/polyhedron
// afB2 = array of line/plane constants
// akA2 = array of outer pointing edge/face normals
// riStatusCode = the status of the LCP numerical solver
// rfDistance = distance between the polygons/polyhedra
// akClosest = array of two closest points, one on each
// polygon/polyhedron
LCPPolyDist (int iNum1, float* afB1, VectorIn* akA1, int iNum2,
float* afB2, VectorIn* akA2, int& riStatusCode, float& rfDistance,
VectorIn akClosest[/*2*/]);
// Solution vectors are tested to determine if they meet constraints
// imposed by the halfspace statement of the problem: V o Z <= B.
// VERIFY_MIN_DIFFERENCE is the amount that this dot product can exceed
// B without reporting an error. Default value is 0.00001.
static double VERIFY_MIN_DIFFERENCE;
// Used in GenerateHalfSpaceDescription to produce a random array of
// vertices whose means are the input values to FuzzArray. Each vertex
// is selected from a uniform distribution of width RANDOM_WIDTH.
// Default value = 0.0, i.e. no random variation.
static double RANDOM_WIDTH;
private:
double ProcessLoop (bool bHS, int& riError, VectorIn* akRes);
bool BuildMatrices (double** aadM, double* adQ);
void ComputeHalfspaces (int iNumPoints, const TVector* akP,
int iNumFaces, const TTuple* akF, TVector* akA, double* afB);
void GenerateHalfSpaceDescription (int iNumPoints, TVector* akP1,
int iNumFaces, TTuple* akF, double* afB, TVector* akA);
void ChangeFaceOrder (int iNumFaces, TTuple* akF);
void MoveHalfspaces (int iNumFaces, double* afB, TVector* akA);
void MovePoints ();
int VerifySolution (const TVector* akRes);
int m_iDimension;
int m_iNumEquations;
int m_iNumPoints1;
int m_iNumPoints2;
int m_iNumFaces1;
int m_iNumFaces2;
double* m_adB1; // halfspace constants
double* m_adB2;
TVector* m_akA1; // halfspace vectors
TVector* m_akA2;
TVector* m_akP1; // points
TVector* m_akP2;
TTuple* m_akF1; // faces
TTuple* m_akF2;
// For writing messages to a log file during testing and debugging. If you
// enable this, the distance calculator significantly slows down.
//
//#define LCPPOLYDIST_LOG
#ifdef LCPPOLYDIST_LOG
#define LOGFUNCTION(func) func;
#else
#define LOGFUNCTION(func)
#endif
#ifdef LCPPOLYDIST_LOG
void OpenLog ();
void CloseLog ();
void PrintMatrices (double** aadM, double* adQ);
void LogRetries (int iTryNumber);
void LCPSolverLoopLimit ();
void LogVertices (const TVector* akP, int iNum);
void LogVerticesAndFaces (int iNumPoints, const VectorIn* akP,
int iNumFaces, const TTuple* akF);
void LogHalfspaces (const double* afB, const TVector* akP, int iNum);
void SetupTestPoints (int iI, int iNumFaces, int iNumPoints,
TVector kZRes, const double* afB, const TVector* akA,
const TVector* akP, TVector* akTestPoints);
void LogTestPoints (const TVector* akTestPoints);
void LogSolutionWithTestPoints (int iI, TVector kZResult,
const TVector* akTestPoints);
void VerifyWithTestPoints (const TVector* akRes, int& riError);
void RandomizeArray (int iNumPoints, TVector* akP);
void RandomizeHalfspaces ();
void LogVerifyFailure (int iWhich, int i, double fDiff);
std::ofstream m_kLog;
#endif
};
typedef Tuple<2> Tuple2;
typedef Tuple<3> Tuple3;
typedef LCPPolyDist<Vector2f,Vector2d,Tuple2> LCPPolyDist2;
typedef LCPPolyDist<Vector3f,Vector3d,Tuple3> LCPPolyDist3;
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
191
]
]
] |
f812f848595eff46622c4daa8936434f38b7e70e
|
335783c9e5837a1b626073d1288b492f9f6b057f
|
/source/fbxcmd/fbxcmd/Plugins/fbxdao/common/IniSection.h
|
3b0e1821afac6ee5da648c5c8084a3d602363443
|
[
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] |
permissive
|
code-google-com/fbx4eclipse
|
110766ee9760029d5017536847e9f3dc09e6ebd2
|
cc494db4261d7d636f8c4d0313db3953b781e295
|
refs/heads/master
| 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,177 |
h
|
#pragma once
#include <string>
#include <list>
enum VARIABLETYPE
{
vtUnknown,
vtInteger,
vtFloat,
vtDouble,
vtBoolean,
vtText,
};
struct VARIABLE
{
VARIABLE() : ShortName(NULL), IniName(NULL), MemberAddr(0), Description(NULL), DefaultValue(NULL), ValueSize(0) {
}
~VARIABLE() {
if (ValueSize && DefaultValue) {
delete DefaultValue;
DefaultValue = NULL;
ValueSize = 0;
}
}
template<typename U>
VARIABLE(LPCTSTR sName, LPCTSTR iName, const U& member, U default, LPCTSTR desc, VARIABLETYPE type)
: ShortName(sName), IniName(iName), MemberAddr(NULL), Description(NULL), MemberType(type) {
SetDefault(default);
}
template<>
VARIABLE(LPCTSTR sName, LPCTSTR iName, const std::string& member, std::string default, LPCTSTR desc, VARIABLETYPE type)
: ShortName(sName), IniName(iName), MemberAddr((DWORD)&member), Description(NULL) {
MemberType = type==vtUnknown?vtText:type;
SetDefault(default);
}
template<>
VARIABLE(LPCTSTR sName, LPCTSTR iName, const int& member, int default, LPCTSTR desc, VARIABLETYPE type)
: ShortName(sName), IniName(iName), MemberAddr((DWORD)&member), Description(NULL) {
MemberType = type==vtUnknown?vtInteger:type;
SetDefault(default);
}
template<>
VARIABLE(LPCTSTR sName, LPCTSTR iName, const float& member, float default, LPCTSTR desc, VARIABLETYPE type)
: ShortName(sName), IniName(iName), MemberAddr((DWORD)&member), Description(NULL) {
MemberType = type==vtUnknown?vtFloat:type;
SetDefault(default);
}
template<>
VARIABLE(LPCTSTR sName, LPCTSTR iName, const double& member, double default, LPCTSTR desc, VARIABLETYPE type)
: ShortName(sName), IniName(iName), MemberAddr((DWORD)&member), Description(NULL) {
MemberType = type==vtUnknown?vtDouble:type;
SetDefault(default);
}
template<>
VARIABLE(LPCTSTR sName, LPCTSTR iName, const bool& member, bool default, LPCTSTR desc, VARIABLETYPE type)
: ShortName(sName), IniName(iName), MemberAddr((DWORD)&member), Description(NULL) {
MemberType = type==vtUnknown?vtBoolean:type;
SetDefault(default);
}
template<typename U>
void SetDefault(U default) {
ValueSize = sizeof(U);
DefaultValue = new U(default);
}
template <typename U>
const U& GetDefault() const {
return *(U*)DefaultValue;
}
LPCTSTR ShortName;
LPCTSTR IniName;
DWORD MemberAddr;
VARIABLETYPE MemberType;
LPCTSTR Description;
LPVOID DefaultValue;
DWORD ValueSize;
};
#define BEGIN_INI_MAP(name) \
virtual void *GetMember(const VARIABLE* memptr) const { return (void*)(((char*)this) + memptr->MemberAddr); } \
virtual const VARIABLE* GetInfDefmap() const { return InternalGetInfDefmap(); } \
static VARIABLE* InternalGetInfDefmap() { \
const name* pThis = 0; \
static VARIABLE map[] = { \
#define BEGIN_INI_MAP_WITH_BASE(name, base) \
virtual void *GetMember(const VARIABLE* memptr) const { return (void*)(((char*)this) + memptr->MemberAddr); } \
virtual const VARIABLE* GetInfDefmap() const { return InternalGetInfDefmap(); } \
static VARIABLE* InternalGetInfDefmap() { \
const name* pThis = 0; \
static VARIABLE map[] = { \
#define END_INI_MAP() \
VARIABLE() };\
return map;\
}
#define INI_ITEM(sName, iName, member, desc) \
VARIABLE(sName, iName, pThis->member, desc, vtUnknown), \
#define INI_ITEMEX(sName, iName, member, type, desc) \
VARIABLE(sName, iName, pThis->member, desc, type), \
struct IniFileSection
{
virtual LPCTSTR GetName() const = 0;
virtual const VARIABLE* GetInfDefmap() const = 0;
virtual void *GetMember(const VARIABLE* memptr) const = 0;
};
typedef std::list<IniFileSection*> IniFileSectionList;
inline int GetIniDefSectionSize(IniFileSection *section) {
int len = 0;
for (const VARIABLE *inidef = section->GetInfDefmap()
; inidef != NULL && inidef->ShortName
; ++inidef)
++len;
return len;
}
|
[
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
] |
[
[
[
1,
132
]
]
] |
91b351bce347c6554743b0317b3b59846fbb912d
|
fac8de123987842827a68da1b580f1361926ab67
|
/inc/physics/Common/Serialize/Packfile/Xml/hkXmlPackfileReader.h
|
b3fe0b496ba17924153364d9120e352ddad2377a
|
[] |
no_license
|
blockspacer/transporter-game
|
23496e1651b3c19f6727712a5652f8e49c45c076
|
083ae2ee48fcab2c7d8a68670a71be4d09954428
|
refs/heads/master
| 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,720 |
h
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_XML_PACKFILE_READER_H
#define HK_XML_PACKFILE_READER_H
#include <Common/Serialize/Packfile/hkPackfileReader.h>
#include <Common/Base/Container/StringMap/hkStringMap.h>
class hkRelocationInfo;
class hkDynamicClassNameRegistry;
class hkXmlPackfileUpdateTracker;
template <typename K, typename V> class hkPointerMap;
/// Reads an XML packfile.
class hkXmlPackfileReader : public hkPackfileReader
{
public:
///
hkXmlPackfileReader();
///
~hkXmlPackfileReader();
/// Load the entire file, fixes up all pointers.
/// If the root element packfile has a "classversion" attribute,
/// we use the hkVersionRegistry to find the metadata for this version.
virtual hkResult loadEntireFile( hkStreamReader* reader );
/// Load the entire file, fixes up all pointers.
/// If classes are present in the file they are used, falling
/// back to the supplied registry if not found. See also loadEntireFile.
virtual hkResult loadEntireFileWithRegistry( hkStreamReader* reader, const hkClassNameRegistry* reg );
// Inherited from hkPackfileReader
virtual void* getContentsWithRegistry( const char* className, const hkTypeInfoRegistry* finish );
// Inherited from hkPackfileReader
virtual const char* getContentsClassName() const;
// Inherited from hkPackfileReader
virtual hkPackfileData* getPackfileData() const;
// Inherited from hkPackfileReader
virtual hkArray<hkVariant>& getLoadedObjects() const;
// Inherited from hkPackfileReader
virtual hkObjectUpdateTracker& getUpdateTracker() const;
protected:
const hkClass* getClassByName( const char* className, hkDynamicClassNameRegistry& reg, hkStringMap<hkClass*>& partiallyLoadedClasses, hkPointerMap<const hkClass*, int>& offsetsRecomputed, int classVersion, const char* contentsVersion ) const;
void handleInterObjectReferences( const char* objName, void* object, const hkRelocationInfo& reloc, const hkStringMap<void*>& nameToObject, hkStringMap<int>& unresolvedReferences );
protected:
// Contains all data which may persist after this reader is destroyed.
AllocatedData* m_data;
// Names (tags) of sections in the order they appear.
hkArray<char*> m_knownSections;
// Maps section tag to physical index. (see m_knownSections).
hkStringMap<int> m_sectionTagToIndex;
// Loaded non-class objects
mutable hkArray<hkVariant> m_loadedObjects;
// Tracker
hkXmlPackfileUpdateTracker* m_tracker;
};
#endif // HK_XML_PACKFILE_READER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
|
[
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] |
[
[
[
1,
93
]
]
] |
0f4be47d36cc5c0e81307c06fb4ecc43a004ac40
|
45479b6849f2d5d7e69771c80733bf937affb6a0
|
/CorProfilerCallbackImpl.h
|
c6678bf43b493b84862f6604d7198adbce0b0a9a
|
[] |
no_license
|
IronScheme/IronScheme.Profiler
|
4a646e5926aef2edb63bc4cdfd24967812b20619
|
85252eb25ccbd03658213cfe3cbb7ebbed0571d9
|
refs/heads/master
| 2021-05-27T21:14:36.269541 | 2011-12-06T10:18:20 | 2011-12-06T10:18:20 | 2,247,557 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,323 |
h
|
/*****************************************************************************
* DotNetProfiler
*
* Copyright (c) 2006 Scott Hackett
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the author be held liable for any damages arising from the
* use of this software. Permission to use, copy, modify, distribute and sell
* this software for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation.
*
* Scott Hackett ([email protected])
*****************************************************************************/
#pragma once
#include "cor.h"
#include "corprof.h"
class CCorProfilerCallbackImpl : public ICorProfilerCallback3
{
public:
CCorProfilerCallbackImpl();
// ICorProfilerCallback interface implementation
// STARTUP/SHUTDOWN EVENTS
STDMETHOD(Initialize)(IUnknown *pICorProfilerInfoUnk);
STDMETHOD(Shutdown)();
// APPLICATION DOMAIN EVENTS
STDMETHOD(AppDomainCreationStarted)(AppDomainID appDomainID);
STDMETHOD(AppDomainCreationFinished)(AppDomainID appDomainID, HRESULT hrStatus);
STDMETHOD(AppDomainShutdownStarted)(AppDomainID appDomainID);
STDMETHOD(AppDomainShutdownFinished)(AppDomainID appDomainID, HRESULT hrStatus);
// ASSEMBLY EVENTS
STDMETHOD(AssemblyLoadStarted)(AssemblyID assemblyID);
STDMETHOD(AssemblyLoadFinished)(AssemblyID assemblyID, HRESULT hrStatus);
STDMETHOD(AssemblyUnloadStarted)(AssemblyID assemblyID);
STDMETHOD(AssemblyUnloadFinished)(AssemblyID assemblyID, HRESULT hrStatus);
// MODULE EVENTS
STDMETHOD(ModuleLoadStarted)(ModuleID moduleID);
STDMETHOD(ModuleLoadFinished)(ModuleID moduleID, HRESULT hrStatus);
STDMETHOD(ModuleUnloadStarted)(ModuleID moduleID);
STDMETHOD(ModuleUnloadFinished)(ModuleID moduleID, HRESULT hrStatus);
STDMETHOD(ModuleAttachedToAssembly)(ModuleID moduleID, AssemblyID assemblyID);
// CLASS EVENTS
STDMETHOD(ClassLoadStarted)(ClassID classID);
STDMETHOD(ClassLoadFinished)(ClassID classID, HRESULT hrStatus);
STDMETHOD(ClassUnloadStarted)(ClassID classID);
STDMETHOD(ClassUnloadFinished)(ClassID classID, HRESULT hrStatus);
STDMETHOD(FunctionUnloadStarted)(FunctionID functionID);
// JIT EVENTS
STDMETHOD(JITCompilationStarted)(FunctionID functionID, BOOL fIsSafeToBlock);
STDMETHOD(JITCompilationFinished)(FunctionID functionID, HRESULT hrStatus, BOOL fIsSafeToBlock);
STDMETHOD(JITCachedFunctionSearchStarted)(FunctionID functionID, BOOL *pbUseCachedFunction);
STDMETHOD(JITCachedFunctionSearchFinished)(FunctionID functionID, COR_PRF_JIT_CACHE result);
STDMETHOD(JITFunctionPitched)(FunctionID functionID);
STDMETHOD(JITInlining)(FunctionID callerID, FunctionID calleeID, BOOL *pfShouldInline);
// THREAD EVENTS
STDMETHOD(ThreadCreated)(ThreadID threadID);
STDMETHOD(ThreadDestroyed)(ThreadID threadID);
STDMETHOD(ThreadAssignedToOSThread)(ThreadID managedThreadID, DWORD osThreadID);
// REMOTING EVENTS
// Client-side events
STDMETHOD(RemotingClientInvocationStarted)();
STDMETHOD(RemotingClientSendingMessage)(GUID *pCookie, BOOL fIsAsync);
STDMETHOD(RemotingClientReceivingReply)(GUID *pCookie, BOOL fIsAsync);
STDMETHOD(RemotingClientInvocationFinished)();
// Server-side events
STDMETHOD(RemotingServerReceivingMessage)(GUID *pCookie, BOOL fIsAsync);
STDMETHOD(RemotingServerInvocationStarted)();
STDMETHOD(RemotingServerInvocationReturned)();
STDMETHOD(RemotingServerSendingReply)(GUID *pCookie, BOOL fIsAsync);
// CONTEXT EVENTS
STDMETHOD(UnmanagedToManagedTransition)(FunctionID functionID, COR_PRF_TRANSITION_REASON reason);
STDMETHOD(ManagedToUnmanagedTransition)(FunctionID functionID, COR_PRF_TRANSITION_REASON reason);
// SUSPENSION EVENTS
STDMETHOD(RuntimeSuspendStarted)(COR_PRF_SUSPEND_REASON suspendReason);
STDMETHOD(RuntimeSuspendFinished)();
STDMETHOD(RuntimeSuspendAborted)();
STDMETHOD(RuntimeResumeStarted)();
STDMETHOD(RuntimeResumeFinished)();
STDMETHOD(RuntimeThreadSuspended)(ThreadID threadid);
STDMETHOD(RuntimeThreadResumed)(ThreadID threadid);
// GC EVENTS
STDMETHOD(MovedReferences)(ULONG cmovedObjectIDRanges, ObjectID oldObjectIDRangeStart[], ObjectID newObjectIDRangeStart[], ULONG cObjectIDRangeLength[]);
STDMETHOD(ObjectAllocated)(ObjectID objectID, ClassID classID);
STDMETHOD(ObjectsAllocatedByClass)(ULONG classCount, ClassID classIDs[], ULONG objects[]);
STDMETHOD(ObjectReferences)(ObjectID objectID, ClassID classID, ULONG cObjectRefs, ObjectID objectRefIDs[]);
STDMETHOD(RootReferences)(ULONG cRootRefs, ObjectID rootRefIDs[]);
// EXCEPTION EVENTS
// Exception creation
STDMETHOD(ExceptionThrown)(ObjectID thrownObjectID);
// Search phase
STDMETHOD(ExceptionSearchFunctionEnter)(FunctionID functionID);
STDMETHOD(ExceptionSearchFunctionLeave)();
STDMETHOD(ExceptionSearchFilterEnter)(FunctionID functionID);
STDMETHOD(ExceptionSearchFilterLeave)();
STDMETHOD(ExceptionSearchCatcherFound)(FunctionID functionID);
STDMETHOD(ExceptionCLRCatcherFound)();
STDMETHOD(ExceptionCLRCatcherExecute)();
STDMETHOD(ExceptionOSHandlerEnter)(FunctionID functionID);
STDMETHOD(ExceptionOSHandlerLeave)(FunctionID functionID);
// Unwind phase
STDMETHOD(ExceptionUnwindFunctionEnter)(FunctionID functionID);
STDMETHOD(ExceptionUnwindFunctionLeave)();
STDMETHOD(ExceptionUnwindFinallyEnter)(FunctionID functionID);
STDMETHOD(ExceptionUnwindFinallyLeave)();
STDMETHOD(ExceptionCatcherEnter)(FunctionID functionID, ObjectID objectID);
STDMETHOD(ExceptionCatcherLeave)();
// COM CLASSIC VTable
STDMETHOD(COMClassicVTableCreated)(ClassID wrappedClassID, REFGUID implementedIID, void *pVTable, ULONG cSlots);
STDMETHOD(COMClassicVTableDestroyed)(ClassID wrappedClassID, REFGUID implementedIID, void *pVTable);
// End of ICorProfilerCallback interface implementation
// ICorProfilerCallback2 interface implementation
STDMETHOD(ThreadNameChanged)(ThreadID threadId, ULONG cchName, WCHAR name[]);
STDMETHOD(GarbageCollectionStarted)(int cGenerations, BOOL generationCollected[], COR_PRF_GC_REASON reason);
STDMETHOD(SurvivingReferences)(ULONG cSurvivingObjectIDRanges, ObjectID objectIDRangeStart[], ULONG cObjectIDRangeLength[]);
STDMETHOD(GarbageCollectionFinished)();
STDMETHOD(FinalizeableObjectQueued)(DWORD finalizerFlags, ObjectID objectID);
STDMETHOD(RootReferences2)(ULONG cRootRefs, ObjectID rootRefIds[], COR_PRF_GC_ROOT_KIND rootKinds[], COR_PRF_GC_ROOT_FLAGS rootFlags[], UINT_PTR rootIds[]);
STDMETHOD(HandleCreated)(GCHandleID handleId, ObjectID initialObjectId);
STDMETHOD(HandleDestroyed)(GCHandleID handleId);
// End of ICorProfilerCallback2 interface implementation
STDMETHOD(InitializeForAttach)(
/* [in] */ IUnknown *pCorProfilerInfoUnk,
/* [in] */ void *pvClientData,
/* [in] */ UINT cbClientData);
STDMETHOD(ProfilerAttachComplete)( void);
STDMETHOD(ProfilerDetachSucceeded)( void);
};
|
[
"[email protected]"
] |
[
[
[
1,
137
]
]
] |
13a31e40669de91c1bf615dfee6182e35889113b
|
bf3bc7ec0580d9da732fc16ce00baccda68f2f42
|
/common_config.cpp
|
41f938383a724c38db07d1ded7e0fbb05c488824
|
[] |
no_license
|
rexzhang/ngpodwc
|
69ddbfd736e955bb9d223fb900dec7f026105261
|
02a7d7c9afc5cf6d34d7dd865969b5478bae4bb7
|
refs/heads/master
| 2020-07-26T23:25:56.308274 | 2008-07-24T13:08:57 | 2008-07-24T13:08:57 | 208,796,954 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 8,012 |
cpp
|
/////////////////////////////////////////////////////////////////////////////
// Name: common_config.cpp
// Purpose:
// Author: Rex Zhang
// Modified by:
// Created: 09/02/2006
// RCS-ID:
// Copyright: (c) 2006 Rex Zhang
// Licence: GNU General Public License (GPL) version 2
/////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/wfstream.h>
#include <wx/fileconf.h>
#include <wx/intl.h>
//#include
#include "common_config.h"
#include "ngpodwc_common_datetime.h"
//---------------------------------------------------------------------------
//!
//---------------------------------------------------------------------------
ngpodwcConfig::ngpodwcConfig()
{
Init();
}
ngpodwcConfig::~ngpodwcConfig()
{
//dtor
}
//---------------------------------------------------------------------------
//!config类初始化
//---------------------------------------------------------------------------
void ngpodwcConfig::Init()
{
ConfigFileName = wxT("ngpodwc.ini");
SetConfigFilePath(wxEmptyString);//ConfigFile = wxEmptyString + ConfigFileName;
//先重置config为默认值,作为补充(兼容升级后配置信息增加的情况)
SetDefault();
//config。ini只初始化为默认参数,不读入文件
}
//---------------------------------------------------------------------------
//!config类配置文件存储路径设置
//---------------------------------------------------------------------------
void ngpodwcConfig::SetConfigFilePath(wxString configFullPath)
{
if (configFullPath == wxEmptyString)
ConfigFile = ConfigFileName;
else
ConfigFile = configFullPath + wxT("\\") +ConfigFileName;
}
//---------------------------------------------------------------------------
//!config类配置文件存储文件名(全路径)获取
//---------------------------------------------------------------------------
wxString ngpodwcConfig::GetConfigFile()
{
return ConfigFile;
}
//---------------------------------------------------------------------------
//!重置config为默认值
//---------------------------------------------------------------------------
void ngpodwcConfig::SetDefault()
{
PictureSource = PICTURESOURCE_LOCALFILE;
UILanguage = wxLANGUAGE_DEFAULT;
///////////////////
PodBasePath = wxEmptyString;
PodDatabaseName = wxT("pod.mdb");//wxEmptyString;
PodPictureMode = wxEmptyString;
PodPicturePath = wxT("POD\\pictures\\lg_wallpaper");
//2001-1-14后有断档,所以直接从2001-4-21开始
toWxDateTime(2001, 4, 21, &PodDate);
//////////////
LocalPicturePath = wxEmptyString;
////////////////
ScreenWidth = 1024;
ScreenHeight = 768;
ScreenPicturePath = wxEmptyString;
ScreenPictureName = wxT("POD_Wallpaper.bmp");
////////////////
//Locked = false;
PauseChangeWallpaper = false;//old-----bool Locked;
ShowSplash = true;
ShowDisc = true;
return;
}
//---------------------------------------------------------------------------
//!读取配置信息到内存
//---------------------------------------------------------------------------
bool ngpodwcConfig::ReadConfig()
{
//检查配置文件是否存在
if ( !wxFileExists(ConfigFile) )
{
//没有配置文件
wxLogWarning(_("Can't found .INI(%s) file. Skip read config."), ConfigFile.c_str());
return false;
}
//打开配置文件
wxFileInputStream ConfigInputStream(ConfigFile);
if(!ConfigInputStream.Ok())//检查配置文件是否打开成功
{
//告警
wxLogWarning(_("Can't open .INI(%s) file with READ mode. Skip read config."), ConfigFile.c_str());
return false;
}
//建立到配置文件的连接
wxFileConfig *pFileConfig = new wxFileConfig(ConfigInputStream, wxConvUTF8);
//读取配置文件->内存
pFileConfig->Read(wxT("PictureSource"), &(PictureSource));
///////////////////////
PodBasePath = pFileConfig->Read(wxT("PodBasePath"));
PodDatabaseName = pFileConfig->Read(wxT("PodDatabaseName"));
PodPicturePath = pFileConfig->Read(wxT("PodPicturePath"));
int year,month,mday;
pFileConfig->Read(wxT("PodYear"), &(year));
pFileConfig->Read(wxT("PodMonth"), &(month));
pFileConfig->Read(wxT("PodDays"), &(mday));
toWxDateTime(year, month, mday, &PodDate);
///////////////
LocalPicturePath = pFileConfig->Read(wxT("LocalPicturePath"));
/////////////
ScreenPicturePath = pFileConfig->Read(wxT("ScreenPicturePath"));
ScreenPictureName = pFileConfig->Read(wxT("ScreenPictureName"));
pFileConfig->Read(wxT("ScreenWidth"), &(ScreenWidth));
pFileConfig->Read(wxT("ScreenHeight"), &(ScreenHeight));
/////////////////
pFileConfig->Read(wxT("ShowDisc"), &(ShowDisc));
pFileConfig->Read(wxT("PauseChangeWallpaper"), &(PauseChangeWallpaper));
pFileConfig->Read(wxT("ShowSplash"), &(ShowSplash));
//将UICanonicalName(ISO名字xx_XX)转换为UILanguage(数字)
wxString UICanonicalName;
if(pFileConfig->Read(wxT("UILanguage"), &(UICanonicalName)))
{
//wxLocale UIwxLocale;
const wxLanguageInfo* UILanguageInfo = wxLocale::FindLanguageInfo(UICanonicalName);
UILanguage = UILanguageInfo->Language;
}
//!ConfigInputStream.Close();
//!ngpodwc.cpp:64: error: 'class wxFileInputStream' has no member named 'Close'
return true;
}
//---------------------------------------------------------------------------
//!将内存中的配置信息写回配置文件
//---------------------------------------------------------------------------
bool ngpodwcConfig::WriteConfig()
{
//打开配置文件
wxFileOutputStream ConfigOutputStream(ConfigFile);
if(!ConfigOutputStream.Ok())//检查配置文件是否打开成功
{
wxLogWarning(_("Can't open .INI(%s) file with WRITE mode. Skip write config."), ConfigFile.c_str());
return false;
}
//wxFileConfig *pFileConfig = new wxFileConfig(ConfigOutputStream, wxConvUTF8);
wxFileConfig *pFileConfig = new wxFileConfig();
/////////////////
pFileConfig->Write(wxT("PictureSource"), PictureSource);
/////////////////////
pFileConfig->Write(wxT("PodBasePath"), PodBasePath);
pFileConfig->Write(wxT("PodDatabaseName"), PodDatabaseName);
pFileConfig->Write(wxT("PodPicturePath"), PodPicturePath);
int year,month,mday;
toDate(PodDate, &year, &month, &mday);
pFileConfig->Write(wxT("PodYear"), year);
pFileConfig->Write(wxT("PodMonth"), month);
pFileConfig->Write(wxT("PodDays"), mday);
////////////////////
pFileConfig->Write(wxT("LocalPicturePath"), LocalPicturePath);
/////////////////////
pFileConfig->Write(wxT("ScreenPicturePath"), ScreenPicturePath);
pFileConfig->Write(wxT("ScreenPictureName"), ScreenPictureName);
pFileConfig->Write(wxT("ScreenWidth"), ScreenWidth);
pFileConfig->Write(wxT("ScreenHeight"), ScreenHeight);
//////////////////////
pFileConfig->Write(wxT("ShowDisc"), ShowDisc);
pFileConfig->Write(wxT("PauseChangeWallpaper"), PauseChangeWallpaper);
pFileConfig->Write(wxT("ShowSplash"), ShowSplash);
//将UILanguage(数字)转换为UICanonicalName(ISO名字xx_XX)
wxString UICanonicalName;
const wxLanguageInfo* UILanguageInfo = wxLocale::GetLanguageInfo(UILanguage);
UICanonicalName = UILanguageInfo->CanonicalName;
pFileConfig->Write(wxT("UILanguage"), UICanonicalName);
//保存到文件
pFileConfig->Save(ConfigOutputStream, wxConvUTF8);
ConfigOutputStream.Close();
return true;
}
|
[
"[email protected]"
] |
[
[
[
1,
243
]
]
] |
1d38296169e9c72e7fc0f5c4f5374deb915c8a78
|
74c8da5b29163992a08a376c7819785998afb588
|
/NetAnimal/Game/Hunter/NewGame/NewGameComponents/ui/include/Number.h
|
c55ba486bd7305ff4a0229b1d92a8077b58bdb38
|
[] |
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 | 749 |
h
|
#ifndef __Orz_Number__
#define __Orz_Number__
namespace Orz
{
namespace UI
{
class Number
{
public:
Number(void)
{
}
void show(int num)
{
std::vector<CEGUI::Window *>::iterator it;
for(it = _windows.begin(); it != _windows.end(); ++it)
{
(*it)->setProperty("Image", _numbers[num%10]);
num/=10;
}
}
~Number(void)
{
}
void push_back(CEGUI::Window * window)
{
_windows.push_back(window);
}
void clear(void)
{
_windows.clear();
}
void setFigure(int i, const std::string & figure)
{
_numbers[i] = figure;
}
private:
std::vector<CEGUI::Window *> _windows;
boost::array<std::string, 10> _numbers;
};
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
53
]
]
] |
5cd14bf45bea254ba55fae6aad0ffe42a824485f
|
35231241243cb13bd3187983d224e827bb693df3
|
/cgpsmapper/MPReader/error.h
|
95272b2f683be47ff39bc433a96eed7ab01b66ec
|
[] |
no_license
|
casaretto/cgpsmapper
|
b597aa2775cc112bf98732b182a9bc798c3dd967
|
76d90513514188ef82f4d869fc23781d6253f0ba
|
refs/heads/master
| 2021-05-15T01:42:47.532459 | 2011-06-25T23:16:34 | 2011-06-25T23:16:34 | 1,943,334 | 2 | 2 | null | 2019-06-11T00:26:40 | 2011-06-23T18:31:36 |
C++
|
UTF-8
|
C++
| false | false | 473 |
h
|
#ifndef __ERROR_H
#define __ERROR_H
#ifdef _WIN32
#include <windows.h>
#endif
#include "wx/wx.h"
const int _message_max = 90;
const int _message_len = 150;
class errorClass {
static char warn_messages[_message_max][_message_len];
static wxTextCtrl* txtControl;
public:
static bool show_message_error;
void static redirectMessages(wxTextCtrl* _txtControl);
void static showError(int line,const char* file_name,const char* code);
};
#endif
|
[
"cgpsmapper@ad713ecf-6e55-4363-b790-59b81426eeec"
] |
[
[
[
1,
24
]
]
] |
86f95398ac2499242785ac2d31dc2c428bb47694
|
3324b5188e8a3b7ee1662e16110e725e04eae37d
|
/tests/treemapwidgettest.cpp
|
5db3c39591913406355bf3a4dcc171f6d55efb18
|
[] |
no_license
|
tom3q/file-dragon
|
438703e78184a71baa68f881f69596a34abac4ec
|
57254a383d4e97610f9224f1739fdee0836b005b
|
refs/heads/master
| 2021-01-20T04:32:53.217530 | 2011-06-04T16:12:05 | 2011-06-04T16:12:05 | 32,119,393 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,543 |
cpp
|
#include <algorithm>
#include <QtTest/QtTest>
#include <QObject>
#include <QSet>
#include "../treemapwidget.h"
#include "../abstractrenderer.h"
#include "../filenode.h"
#include "../directorynode.h"
#include "../defaultrenderer.h"
using namespace std;
class TreemapWidgetTest : public QObject
{
Q_OBJECT
class TestRenderer : public DefaultRenderer
{
public:
TestRenderer(QHash<FileNode *, QRectF> *n, TreemapWidget *w) : nodes(n), DefaultRenderer(w) {}
private:
virtual void renderCell(QPainter &painter, QRectF &rect, FileNode *file)
{
QVERIFY(nodes->find(file) != nodes->end());
nodes->operator[](file) = rect;
DefaultRenderer::renderCell(painter, rect, file);
}
QHash<FileNode *, QRectF> *nodes;
};
static const int NUM_FILES = 16;
static const int NUM_SUBDIRS = 4;
static const int MAX_SIZE = 2048;
static const int MIN_SIZE = 1024;
static const int MAX_DEPTH = 4;
qint64 generateTree(DirectoryNode *tree, unsigned depth, int &count)
{
qint64 sum = 0;
for (int i = 0; i < NUM_FILES; ++i) {
FileNode *f = new FileNode();
qint64 size = MIN_SIZE + i*((MAX_SIZE - MIN_SIZE)/(NUM_FILES-1));
f->setName(tree->getName() + QString("/File%1").arg(i));
f->setSize(size);
f->setModified(QDateTime::currentDateTime());
tree->addFile(f);
nodes.insert(f, QRectF());
sum += size;
}
count = NUM_FILES;
if (depth > 1)
{
for (int i = 0; i < NUM_SUBDIRS; ++i) {
DirectoryNode *d = tree->addDir(tree->getName() + QString("/Subdir%1").arg(i));
int subCount = 0;
qint64 size = generateTree(d, depth - 1, subCount);
count += subCount;
sum += size;
}
}
tree->setSize(sum);
return sum;
}
class SelectNodeFunc
{
TreemapWidget *widget;
public:
SelectNodeFunc(TreemapWidget *w) : widget(w) {}
void operator()(FileNode *f, QRectF r)
{
QRect alignedRect = r.toAlignedRect();
if (alignedRect.width() == 0 || alignedRect.height() == 0)
return;
QTest::mouseClick(widget, Qt::LeftButton, 0, alignedRect.center());
QCOMPARE(widget->getSelectedCount(), 1);
QCOMPARE(widget->getSelected(0), f);
QCOMPARE(widget->getSelectedFiles().size(), (unsigned)1);
QCOMPARE(*(widget->getSelectedFiles().begin()), f);
}
};
class SelectAllFunc
{
TreemapWidget *widget;
public:
SelectAllFunc(TreemapWidget *w) : widget(w) {}
void operator()(FileNode *f, QRectF r)
{
QRect alignedRect = r.toAlignedRect();
if (alignedRect.width() == 0 || alignedRect.height() == 0)
return;
QTest::mouseClick(widget, Qt::LeftButton, Qt::ControlModifier, r.toAlignedRect().center());
}
};
QHash<FileNode *, QRectF> nodes;
TreemapWidget *widget;
TestRenderer *renderer;
DirectoryNode *root;
int expectedFileCount;
private slots:
void initTestCase()
{
// Prepare the widget
widget = new TreemapWidget();
QVERIFY(widget != 0);
widget->resize(800, 600);
widget->show();
// Prepare the renderer
renderer = new TestRenderer(&nodes, widget);
QVERIFY(renderer != 0);
widget->setRenderer(renderer);
// Prepare sample directory tree
root = widget->getFileTree().getRoot();
QVERIFY(root != 0);
root->setName("root");
qint64 size = generateTree(root, MAX_DEPTH, expectedFileCount);
root->setSize(size);
//dumpTree(root);
}
void renderingTest()
{
widget->fileTreeUpdated();
widget->repaint();
}
void selectionTest()
{
QHash<FileNode *, QRectF>::const_iterator it;
// Select each single node and check the selection
SelectNodeFunc f1 = SelectNodeFunc(widget);
for (it = nodes.constBegin(); it != nodes.constEnd(); ++it)
f1(it.key(), it.value());
widget->removeSelection();
// Select all nodes
SelectAllFunc f2 = SelectAllFunc(widget);
for (it = nodes.constBegin(); it != nodes.constEnd(); ++it)
f2(it.key(), it.value());
// Check the selection
QHash<FileNode *, QRectF> hash(nodes);
for (int i = 0; i < widget->getSelectedCount(); ++i)
{
QHash<FileNode *, QRectF>::iterator it;
it = hash.find(widget->getSelected(i));
QVERIFY(it != hash.end());
hash.erase(it);
}
for (it = hash.constBegin(); it != hash.constEnd(); ++it)
{
QRect alignedRect = it.value().toAlignedRect();
QVERIFY(alignedRect.width() == 0 || alignedRect.height() == 0);
}
}
void cleanupTestCase()
{
delete widget;
}
};
QTEST_MAIN(TreemapWidgetTest)
#include "treemapwidgettest.moc"
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
81
],
[
83,
100
],
[
102,
176
]
],
[
[
82,
82
],
[
101,
101
]
]
] |
426534bb7899f9a191baedbf9829e380a360a20e
|
6188f1aaaf5508e046cde6da16b56feb3d5914bc
|
/CamFighter/Graphics/OGL/GuiSlider.h
|
8ad016da7bb9df2c267e7efb25b1d8ddbcaf0ad0
|
[] |
no_license
|
dogtwelve/fighter3d
|
7bb099f0dc396e8224c573743ee28c54cdd3d5a2
|
c073194989bc1589e4aa665714c5511f001e6400
|
refs/heads/master
| 2021-04-30T15:58:11.300681 | 2011-06-27T18:51:30 | 2011-06-27T18:51:30 | 33,675,635 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,531 |
h
|
#ifndef __incl_Graphics_OGL_GuiSlider_h
#define __incl_Graphics_OGL_GuiSlider_h
#include "Utils.h"
#include "../FontMgr.h"
#include "../Textures/TextureMgr.h"
#include "GuiControl.h"
#include "../../Utils/xString.h"
namespace Graphics { namespace OGL {
class CGuiSlider : public CGuiControl
{
private:
HTexture m_pIconBox;
HTexture m_pIconSlider;
enum EButtonState
{
BS_Normal = 0,
BS_Hover = 1,
BS_Down = 2,
BS_Disabled = 3,
};
EButtonState m_nState;
xSHORT m_nBoxX, m_nBoxY;
xSHORT m_nSliderWidth, m_nSliderHeight;
xSHORT m_nBoxWidth, m_nBoxHeight;
xFLOAT m_fCurValue;
xFLOAT m_fMinValue;
xFLOAT m_fMaxValue;
public:
void SetImage(const char *sIconSlider = 0, xSHORT nSliderWidth = 0, xSHORT nSliderHeight = 0,
const char *sIconBox = 0, xSHORT nBoxWidth = 0, xSHORT nBoxHeight = 0 );
void SetValuePercent(float fAmount)
{
SetValue(m_fMinValue + (m_fMaxValue - m_fMinValue) * fAmount);
}
void SetValue(xFLOAT fValue)
{
if (fValue < m_fMinValue) fValue = m_fMinValue;
else
if (fValue > m_fMaxValue) fValue = m_fMaxValue;
if (fValue != m_fCurValue)
{
m_fCurValue = fValue;
OnValueChanged();
}
}
xFLOAT GetValue() { return m_fCurValue; }
void SetMinValue(xFLOAT fMinValue)
{
if (fMinValue != m_fMinValue)
{
m_fMinValue = fMinValue;
if (m_fMinValue > m_fMaxValue)
m_fMaxValue = m_fMinValue;
SetValue(m_fCurValue);
}
}
xFLOAT GetMinValue() { return m_fMinValue; }
void SetMaxValue(xFLOAT fMaxValue)
{
if (fMaxValue != m_fMaxValue)
{
m_fMaxValue = fMaxValue;
if (m_fMinValue > m_fMaxValue)
m_fMinValue = m_fMaxValue;
SetValue(m_fCurValue);
}
}
xFLOAT GetMaxValue() { return m_fMaxValue; }
ControlEvent OnValueChanged;
CGuiSlider()
: CGuiControl()
, m_pIconBox(HTexture()), m_pIconSlider(HTexture())
, m_nState(BS_Normal), m_fCurValue(0.5f), m_fMinValue(0.f), m_fMaxValue(1.f)
{ OnValueChanged = ControlEvent(*this); }
CGuiSlider(xSHORT nX, xSHORT nY, xSHORT nWidth, xSHORT nHeight)
: CGuiControl(nX, nY, nWidth, nHeight)
, m_pIconBox(HTexture()), m_pIconSlider(HTexture())
, m_nState(BS_Normal), m_fCurValue(0.5f), m_fMinValue(0.f), m_fMaxValue(1.f)
{ OnValueChanged = ControlEvent(*this); }
virtual ~CGuiSlider()
{
g_TextureMgr.Release(m_pIconBox);
g_TextureMgr.Release(m_pIconSlider);
}
virtual void OnMouseLeftDown(bool receiver);
virtual void OnMouseLeftUp (bool receiver);
virtual void OnMouseMove (bool receiver, xSHORT nX, xSHORT nY);
virtual void OnMouseEnter ();
virtual void OnMouseLeave ();
virtual void OnRender();
};
} } // namespace Graphics::OGL
#endif // __incl_Graphics_OGL_GuiSlider_h
|
[
"[email protected]@f75eed02-8a0f-11dd-b20b-83d96e936561"
] |
[
[
[
1,
108
]
]
] |
51667eb076625d7e001716728186e31f090c0e1c
|
cd0987589d3815de1dea8529a7705caac479e7e9
|
/webkit/WebKit/chromium/public/WebIDBTransaction.h
|
581ff0a422b13df7e4eebc83e843fb7fa8774249
|
[
"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,256 |
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:
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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 WebIDBTransaction_h
#define WebIDBTransaction_h
#include "WebString.h"
namespace WebKit {
class WebIDBObjectStore;
class WebIDBTransactionCallbacks;
// See comment in WebIndexedDatabase for a high level overview of these classes.
class WebIDBTransaction {
public:
virtual ~WebIDBTransaction() { }
virtual int mode() const
{
WEBKIT_ASSERT_NOT_REACHED();
return 0;
}
virtual WebIDBObjectStore* objectStore(const WebString& name)
{
WEBKIT_ASSERT_NOT_REACHED();
return 0;
}
virtual void abort() { WEBKIT_ASSERT_NOT_REACHED(); }
virtual int id() const
{
WEBKIT_ASSERT_NOT_REACHED();
return 0;
}
virtual void setCallbacks(WebIDBTransactionCallbacks*) { WEBKIT_ASSERT_NOT_REACHED(); }
};
} // namespace WebKit
#endif // WebIDBTransaction_h
|
[
"[email protected]"
] |
[
[
[
1,
62
]
]
] |
435dfdfff6058dc828c8376ffc49514c1f604278
|
6dac9369d44799e368d866638433fbd17873dcf7
|
/src/branches/01032005/vfs/jpeg/VFSPlugin_JPEG_dll.cpp
|
c8d38c0bf8d8feed0586d032fb4d4c44bf8dc5ae
|
[] |
no_license
|
christhomas/fusionengine
|
286b33f2c6a7df785398ffbe7eea1c367e512b8d
|
95422685027bb19986ba64c612049faa5899690e
|
refs/heads/master
| 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 806 |
cpp
|
#include <FusionPlugin.h>
#include <VFSPlugin_JPEG.h>
Fusion *fusion;
VFSPlugin *plugin = NULL;
/** Creates the JPEG Plugin
* @ingroup VFSPlugin_JPEG_Group
*
* @param f The Fusion object, if this plugin needs to call fusion for something
*
* @returns A VFSPlugin object for this plugin type
*
* The plugin function is simple, each time called
* create the appropiate plugin, increment the counter
* so next time it's called, it'll create the NEXT plugin
* then when you have no more plugins to create, return NULL
*/
FUSIONPLUGIN VFSPlugin * CreatePlugin(Fusion *f)
{
fusion = f;
if(plugin == NULL) plugin = new VFSPlugin_JPEG();
return plugin;
}
/** Function to destroy a JPEG Plugin
*
*/
FUSIONPLUGIN void DestroyPlugin(void)
{
delete plugin;
}
|
[
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] |
[
[
[
1,
34
]
]
] |
447390a11d47477b696118fb8c897269103caae6
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/Neuz/HelperWebBox.cpp
|
738fa23f0a48029d026a6b7e6a259556afe30fe5
|
[] |
no_license
|
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 | 6,664 |
cpp
|
#include "StdAfx.h"
#ifdef __NEW_WEB_BOX
#ifdef __CLIENT
#include "HelperWebBox.h"
#include "WebCtrl.h"
//-----------------------------------------------------------------------------
BOOL CALLBACK HelperWebDialogProc( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam );
//-----------------------------------------------------------------------------
CHelperWebBox::CHelperWebBox( void ) :
m_strHelperWebAddress( _T( "" ) ),
m_hInstance( NULL ),
m_hParent( NULL ),
m_hDialog( NULL ),
m_hDialogBox( NULL ),
m_rectHelperWeb( 0, 0, 0, 0 )
{
}
//-----------------------------------------------------------------------------
CHelperWebBox::~CHelperWebBox( void )
{
Close();
}
//-----------------------------------------------------------------------------
CHelperWebBox* CHelperWebBox::GetInstance( void )
{
static CHelperWebBox sHelperWebBox;
return &sHelperWebBox;
}
//-----------------------------------------------------------------------------
void CHelperWebBox::Initialize( void )
{
InitializeWebInformation();
D3DDEVICE->SetDialogBoxMode( TRUE );
m_hInstance = g_Neuz.m_hInstance;
m_hParent = g_Neuz.GetSafeHwnd();
if( g_Option.m_nResWidth >= 1024 && g_Option.m_nResHeight >= 768 )
{
m_rectHelperWeb.SetRect( -1, 0, HELPER_WEB_SIZE_LARGE_X + 5, HELPER_WEB_SIZE_LARGE_Y );
}
else
{
m_rectHelperWeb.SetRect( -1, 0, HELPER_WEB_SIZE_NORMAL_X + 5, HELPER_WEB_SIZE_NORMAL_Y );
}
Close();
ShowWindow( m_hDialogBox, SW_HIDE );
SetFocus( m_hParent );
HINSTANCE hInstance = GetModuleHandle( NULL );
m_hDialog = CreateDialog( hInstance, MAKEINTRESOURCE( IDD_WEBDLG ), m_hParent, HelperWebDialogProc );
m_hDialogBox = CreateWindow(
WC_WEBCTRL,
m_strHelperWebAddress,
WS_EX_TOPMOST | WS_CHILDWINDOW,
m_rectHelperWeb.left,
m_rectHelperWeb.top,
m_rectHelperWeb.right,
m_rectHelperWeb.bottom,
m_hDialog,
NULL,
m_hInstance,
NULL );
GoFirstPage();
ShowWindow( m_hDialogBox, SW_SHOW );
SetFocus( m_hDialogBox );
}
//-----------------------------------------------------------------------------
void CHelperWebBox::Process( void )
{
if( m_hDialogBox )
{
static BOOL bBackKeySwitch = FALSE;
if( GetAsyncKeyState( VK_BACK ) & 0x8000 )
{
if( bBackKeySwitch == FALSE )
{
SendMessage( m_hDialogBox, WEB_CTRL_GO_BACK, 0, 0 );
bBackKeySwitch = TRUE;
}
}
else
{
if( bBackKeySwitch == TRUE )
{
bBackKeySwitch = FALSE;
}
}
static BOOL bF5KeySwitch = FALSE;
if( GetAsyncKeyState( VK_F5 ) & 0x8000 )
{
if( bF5KeySwitch == FALSE )
{
SendMessage( m_hDialogBox, WEB_CTRL_REFRESH, 0, 0 );
bF5KeySwitch = TRUE;
}
}
else
{
if( bF5KeySwitch == TRUE )
{
bF5KeySwitch = FALSE;
}
}
}
}
//-----------------------------------------------------------------------------
void CHelperWebBox::Release( void )
{
ShowWindow( m_hDialogBox, SW_HIDE );
SetFocus( m_hParent );
Close();
UninitWebCtrl();
}
//-----------------------------------------------------------------------------
void CHelperWebBox::InitializeWebInformation( void )
{
switch( ::GetLanguage() )
{
#ifdef __INTERNALSERVER
case LANG_KOR:
{
m_strHelperWebAddress = _T( "http://flyff-wiki.gpotato.com/index.php/Main_Page" );
break;
}
#endif // __INTERNALSERVER
case LANG_ENG:
{
switch( ::GetSubLanguage() )
{
case LANG_SUB_USA:
{
m_strHelperWebAddress = _T( "http://flyff-wiki.gpotato.com/index.php/Main_Page" );
break;
}
}
break;
}
}
}
//-----------------------------------------------------------------------------
void CHelperWebBox::Close( void )
{
if( m_hDialogBox )
{
DestroyWindow( m_hDialogBox );
m_hDialogBox = NULL;
}
if( m_hDialog )
{
DestroyWindow( m_hDialog );
m_hDialog = NULL;
}
}
//-----------------------------------------------------------------------------
void CHelperWebBox::GoFirstPage( void )
{
if( m_strHelperWebAddress == _T( "" ) )
{
return;
}
TCHAR szHelperWebAddress[ 512 ] = { 0, };
TCHAR header[WEB_STR_LEN] = { 0, };
strcpy( szHelperWebAddress, m_strHelperWebAddress );
SendMessage( m_hDialogBox, WEB_CTRL_ADDRESS, 0, ( LPARAM )szHelperWebAddress );
SendMessage( m_hDialogBox, WEB_CTRL_NAVIGATE, 0, 0 );
}
//-----------------------------------------------------------------------------
const CString& CHelperWebBox::GetHelperWebAddress( void ) const
{
return m_strHelperWebAddress;
}
//-----------------------------------------------------------------------------
const HWND& CHelperWebBox::GetParentHandle( void ) const
{
return m_hParent;
}
//-----------------------------------------------------------------------------
const HWND& CHelperWebBox::GetDialogHandle( void ) const
{
return m_hDialog;
}
//-----------------------------------------------------------------------------
const HWND& CHelperWebBox::GetDialogBoxHandle( void ) const
{
return m_hDialogBox;
}
//-----------------------------------------------------------------------------
BOOL CALLBACK HelperWebDialogProc( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam )
{
CHelperWebBox* pHelperWebBox = CHelperWebBox::GetInstance();
int nHelperWebSizeX = CHelperWebBox::HELPER_WEB_SIZE_NORMAL_X;
int nHelperWebSizeY = CHelperWebBox::HELPER_WEB_SIZE_NORMAL_Y;
if( g_Option.m_nResWidth >= 1024 && g_Option.m_nResHeight >= 768 )
{
nHelperWebSizeX = CHelperWebBox::HELPER_WEB_SIZE_LARGE_X;
nHelperWebSizeY = CHelperWebBox::HELPER_WEB_SIZE_LARGE_Y;
}
switch( Msg )
{
case WM_INITDIALOG:
{
CRect rcCenter( 0, 0, 0, 0 );
GetWindowRect( pHelperWebBox->GetParentHandle(), &rcCenter );
int xLeft = ( rcCenter.left + rcCenter.right ) / 2 - nHelperWebSizeX / 2;
int yTop = ( rcCenter.top + rcCenter.bottom ) / 2 - nHelperWebSizeY / 2;
DWORD CapH = 0;
if( g_Neuz.IsWindow() == true )
CapH = GetSystemMetrics( SM_CYCAPTION );
else
CapH = 9;
if( g_Neuz.m_bFakeFullMode )
{
if( g_Option.m_bStartFullScreen )
CapH = 5;
else
CapH = 20;
}
SetWindowPos( hWnd, NULL, xLeft, yTop+CapH, nHelperWebSizeX, nHelperWebSizeY, SWP_NOZORDER | SWP_NOACTIVATE );
break;
}
case WM_COMMAND:
{
switch( wParam )
{
case IDCANCEL:
{
ShowWindow( pHelperWebBox->GetDialogHandle(), SW_HIDE );
break;
}
}
break;
}
}
return FALSE;
}
//-----------------------------------------------------------------------------
#endif // __CLIENT
#endif // __NEW_WEB_BOX
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
257
]
]
] |
d2a2ef15cc309451c21e16429bfc9cc989794141
|
a1dc22c5f671b7859339aaef69b3461fad583d58
|
/examples/bcpp6/sounds/CSound.cpp
|
33440035f80b578936179669d5f35f18fd28a0b0
|
[] |
no_license
|
remis/chai3d
|
cd694053f55773ca6883a9ea30047e95e70a33e8
|
15323a24b97be73df6f7172bc0b41cc09631c94e
|
refs/heads/master
| 2021-01-18T08:46:44.253084 | 2009-05-11T21:51:22 | 2009-05-11T22:10:52 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,416 |
cpp
|
//===========================================================================
/*
This file is part of the CHAI 3D visualization and haptics libraries.
Copyright (C) 2003-2004 by CHAI 3D. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License("GPL") version 2
as published by the Free Software Foundation.
For using the CHAI 3D libraries with software that can not be combined
with the GNU GPL, and for taking advantage of the additional benefits
of our support services, please contact CHAI 3D about acquiring a
Professional Edition License.
The sound card output is based on a tutorial by David Overton, at
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4422&lngWId=3.
Sound generation is based on the algorithm by Kies Van den Doel K and
Dinesh Pai in "The sounds of physical shapes". Presence 1998, 7(4): 382-395,
and "The AHI: An Audio and Haptic Interface For Contact Interactions" by
DiFilippo and Pai.
\author: <http://www.chai3d.org>
\author: Chris Sewell
\version 1.1
\date 06/2005
*/
//===========================================================================
//---------------------------------------------------------------------------
#include <windows.h>
#include <mmsystem.h>
#include <stdio.h>
#include <conio.h>
#include "CSound.h"
//---------------------------------------------------------------------------
// Change these values if your computer is slow and the sound is jerky:
// Sample rate
#define SAMPLE_RATE 44100
//---------------------------------------------------------------------------
//===========================================================================
// - PUBLIC METHOD -
/*!
This method takes as an input one of the pre-defined sound types
(enumerated in CSound.h), and reads in the corresponding .sy file
which contains the modes and their amplitudes and decay coefficents
(data from Kies van den Doel's JASS program). It also precomputes
some values. Reference: "The AHI: An Audio and Haptic Interface
for Contact Interactions" by DiFilippo and Pai.
\fn void cSound::setParams(sounds choice)
*/
//===========================================================================
void cSound::setParams(sounds a_choice)
{
int i, j;
// select .sy data file based on input sound option
FILE* dfile;
switch (a_choice)
{
case BELL:
dfile = fopen("resources\\sounds\\handbell.sy", "r");
scale = 1.0;
break;
case TEAPOT:
dfile = fopen("resources\\sounds\\teapot.sy", "r");
scale = 6.0;
break;
}
// read in the number of modes, amplitudes, and decay coefficients
char file_buffer[32];
fgets(file_buffer, 256, dfile);
fgets(file_buffer, 256, dfile);
n = atoi(file_buffer);
a.clear();
f.clear();
d.clear();
// ignore header
for (i=0; i<11; i++)
fgets(file_buffer, 256, dfile);
// read in the modes
for (i=0; i<n; i++)
{
fgets(file_buffer, 256, dfile);
f.push_back(atof(file_buffer));
}
// read in the decay coefficients
fgets(file_buffer, 256, dfile);
for (i=0; i<n; i++)
{
fgets(file_buffer, 256, dfile);
d.push_back(atof(file_buffer));
}
// read in the amplitudes
fgets(file_buffer, 256, dfile);
for (i=0; i<n; i++)
{
fgets(file_buffer, 256, dfile);
a.push_back(atof(file_buffer));
}
fclose(dfile);
// allocate space for sound calculations
treal = new double[n];
timag = new double[n];
yreal = new double[n];
yimag = new double[n];
tyreal = new double[n];
tyimag = new double[n];
// precompute real and imaginary parts of e^(i*omegan/Fs)
for (j=0; j<n; j++)
{
treal[j] = exp(-d[j]/SAMPLE_RATE)*cos(2*3.14159*f[j]/SAMPLE_RATE);
timag[j] = exp(-d[j]/SAMPLE_RATE)*sin(2*3.14159*f[j]/SAMPLE_RATE);
}
// equation 2 from "Active Haptics Interfaces" paper: yn(0) = an
for (j=0; j<n; j++)
{
yreal[j] = 0.0;
yimag[j] = 0.0;
}
m_counter = 0;
}
//===========================================================================
// - PUBLIC METHOD -
/*!
This method resets the sound data and should be called when a new
contact is made.
\fn void cSound::reset()
*/
//===========================================================================
void cSound::reset()
{
for (int j=0; j<n; j++)
{
yreal[j] = a[j];
yimag[j] = 0.0;
}
m_counter = 0;
}
//===========================================================================
// - PUBLIC METHOD -
/*!
This method generates a sound wave based on the sound properties
of the material and contact interactions, and writes it to a sound
device to be played. The sound model is based on "The AHI: An Audio
and Haptic Interface For Contact Interactions" by DiFilippo and Pai.
It returns one sample at a time and should be called repeatedly
to fill the buffer in a BASS callback function.
\fn int cSound::play()
*/
//===========================================================================
int cSound::play()
{
// attenuate the normal force so that the contact force decays gradually
// rather than as a square function (which would produce a spurious
// second hit)
double audioForce = pow(0.85, m_counter++)*m_normalForce.length() + m_tangentialForce.length();
// clamp the amplitude
if (audioForce > 2.0) audioForce = 2.0;
// convolve the haptic normal force with the sound modes; see the Pai papers
// for an explanation of this calculation
double lpTemp = 0.0;
for (int j=0; j<n; j++)
{
tyreal[j] = treal[j]*yreal[j] - timag[j]*yimag[j];
tyimag[j] = treal[j]*yimag[j] + timag[j]*yreal[j];
yreal[j] = tyreal[j];
yimag[j] = tyimag[j];
yreal[j] += audioForce*a[j];
lpTemp += yreal[j];
}
int value = (int)(lpTemp/scale) + 128;
if (value > 255) value = 255;
return value;
}
//===========================================================================
// END OF FILE
//===========================================================================
|
[
"[email protected]"
] |
[
[
[
1,
205
]
]
] |
704228768bca2f6d360e7388fe5188167cca9bed
|
ce262ae496ab3eeebfcbb337da86d34eb689c07b
|
/SampleFoundation/DynamicShader/DynamicMultiTextureEffect.cpp
|
e9b9e188e321f1c7e0b8f63c3c4c8479ae18a292
|
[] |
no_license
|
pizibing/swingengine
|
d8d9208c00ec2944817e1aab51287a3c38103bea
|
e7109d7b3e28c4421c173712eaf872771550669e
|
refs/heads/master
| 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,966 |
cpp
|
// Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEFoundationPCH.h"
#include "DynamicMultiTextureEffect.h"
using namespace Swing;
SE_IMPLEMENT_RTTI(Swing, DynamicMultiTextureEffect, SEShaderEffect);
SE_IMPLEMENT_STREAM(DynamicMultiTextureEffect);
SE_IMPLEMENT_DEFAULT_NAME_ID(DynamicMultiTextureEffect, SEShaderEffect);
SE_REGISTER_STREAM(DynamicMultiTextureEffect);
SEVector3f DynamicMultiTextureEffect::ConstantColor = SEVector3f::ZERO;
//----------------------------------------------------------------------------
DynamicMultiTextureEffect::DynamicMultiTextureEffect(int iTextureCount)
:
SEShaderEffect(1)
{
m_aImageName = 0;
m_aTextureTypeName = 0;
SetTextureCount(iTextureCount);
}
//----------------------------------------------------------------------------
DynamicMultiTextureEffect::DynamicMultiTextureEffect()
{
m_iTextureCount = 0;
m_aImageName = 0;
m_aTextureTypeName = 0;
}
//----------------------------------------------------------------------------
DynamicMultiTextureEffect::~DynamicMultiTextureEffect()
{
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::SetTextureCount(int iTextureCount)
{
SE_ASSERT( iTextureCount >= 1 );
m_iTextureCount = iTextureCount;
SE_DELETE[] m_aImageName;
m_aImageName = SE_NEW std::string[m_iTextureCount];
SE_DELETE[] m_aTextureTypeName;
m_aTextureTypeName = SE_NEW std::string[m_iTextureCount];
}
//----------------------------------------------------------------------------
int DynamicMultiTextureEffect::GetTextureCount() const
{
return m_iTextureCount;
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::SetImageName(int i, const std::string&
rImageName)
{
SE_ASSERT( 0 <= i && i < m_iTextureCount );
m_aImageName[i] = rImageName;
}
//----------------------------------------------------------------------------
const std::string& DynamicMultiTextureEffect::GetImageName(int i) const
{
SE_ASSERT( 0 <= i && i < m_iTextureCount );
return m_aImageName[i];
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::SetTextureTypeName(int i,
const std::string& rTextureTypeName)
{
SE_ASSERT( 0 <= i && i < m_iTextureCount );
m_aTextureTypeName[i] = rTextureTypeName;
}
//----------------------------------------------------------------------------
const std::string& DynamicMultiTextureEffect::GetTextureTypeName(int i) const
{
SE_ASSERT( 0 <= i && i < m_iTextureCount );
return m_aTextureTypeName[i];
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::Configure()
{
m_VShader[0] = SE_NEW SEVertexShader("ITexture.v_ITexture");
m_PShader[0] = SE_NEW SEPixelShader("ITexture.p_ITexture");
m_PShader[0]->SetTextureCount(m_iTextureCount);
for( int i = 0; i < m_iTextureCount; i++ )
{
m_PShader[0]->SetImageName(i, m_aImageName[i]);
SETexture* pTexture = m_PShader[0]->GetTexture(i);
pTexture->SetFilterType(SETexture::NEAREST);
}
SEInterfaceDescriptor* pInterfaceDesc = SE_NEW SEInterfaceDescriptor;
m_PShader[0]->SetInterfaceDescriptor(pInterfaceDesc);
SEDescriptorItem* pDescItem = SE_NEW SEDescriptorItem;
pInterfaceDesc->AttachItem(pDescItem);
pDescItem->IsArray = true;
pDescItem->SetInstanceName("aTextures");
for( int i = 0; i < m_iTextureCount; i++ )
pDescItem->AttachTypeName(m_aTextureTypeName[i]);
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::OnLoadPrograms(int, SEProgram*,
SEProgram* pPProgram, SEProgram*)
{
SEUserConstant* pUC = pPProgram->GetUC("aTextures[3].kColor");
if( pUC )
pUC->SetDataSource((float*)ConstantColor);
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::Load(SEStream& rStream, SEStream::SELink*
pLink)
{
SE_BEGIN_DEBUG_STREAM_LOAD;
SEShaderEffect::Load(rStream, pLink);
// native data
rStream.Read(m_iTextureCount);
SetTextureCount(m_iTextureCount);
for( int i = 0; i < m_iTextureCount; i++ )
{
rStream.Read(m_aImageName[i]);
rStream.Read(m_aTextureTypeName[i]);
}
SE_END_DEBUG_STREAM_LOAD(DynamicMultiTextureEffect);
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::Link(SEStream& rStream, SEStream::SELink*
pLink)
{
SEShaderEffect::Link(rStream, pLink);
}
//----------------------------------------------------------------------------
bool DynamicMultiTextureEffect::Register(SEStream& rStream) const
{
return SEShaderEffect::Register(rStream);
}
//----------------------------------------------------------------------------
void DynamicMultiTextureEffect::Save(SEStream& rStream) const
{
SE_BEGIN_DEBUG_STREAM_SAVE;
SEShaderEffect::Save(rStream);
// native data
rStream.Write(m_iTextureCount);
for( int i = 0; i < m_iTextureCount; i++ )
{
rStream.Write(m_aImageName[i]);
rStream.Write(m_aTextureTypeName[i]);
}
SE_END_DEBUG_STREAM_SAVE(DynamicMultiTextureEffect);
}
//----------------------------------------------------------------------------
int DynamicMultiTextureEffect::GetDiskUsed(const SEStreamVersion& rVersion)
const
{
int iSize = SEShaderEffect::GetDiskUsed(rVersion) +
sizeof(m_iTextureCount);
for( int i = 0; i < m_iTextureCount; i++ )
{
iSize += sizeof(int) + (int)m_aImageName[i].length() +
sizeof(int) + (int)m_aTextureTypeName[i].length();
}
return iSize;
}
//----------------------------------------------------------------------------
SEStringTree* DynamicMultiTextureEffect::SaveStrings(const char*)
{
SEStringTree* pTree = SE_NEW SEStringTree;
// strings
pTree->Append(Format(&TYPE, GetName().c_str()));
pTree->Append(Format("texture count =", m_iTextureCount));
const size_t uiTitleSize = 16;
char acTitle[uiTitleSize];
for( int i = 0; i < m_iTextureCount; i++ )
{
SESystem::SE_Sprintf(acTitle, uiTitleSize, "image[%d] =", i);
pTree->Append(Format(acTitle, m_aImageName[i].c_str()));
SESystem::SE_Sprintf(acTitle, uiTitleSize, "type[%d] =", i);
pTree->Append(Format(acTitle, m_aTextureTypeName[i].c_str()));
}
// children
pTree->Append(SEShaderEffect::SaveStrings());
return pTree;
}
//----------------------------------------------------------------------------
|
[
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] |
[
[
[
1,
223
]
]
] |
bf87886eadcdbe5a4aa044bae8dbc07e9e004045
|
6581dacb25182f7f5d7afb39975dc622914defc7
|
/EDStock/GridCell.cpp
|
42c4f4244f0747c7a62739bb111cb0ce3ed09fb6
|
[] |
no_license
|
dice2019/alexlabonline
|
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
|
4c433839965ed0cff99dad82f0ba1757366be671
|
refs/heads/master
| 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,136 |
cpp
|
// GridCell.cpp : implementation file
//
// MFC Grid Control - Main grid cell class
//
// Provides the implementation for the "default" cell type of the
// grid control. Adds in cell editing.
//
// Written by Chris Maunder <[email protected]>
// Copyright (c) 1998-2005. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.20+
//
// History:
// Eric Woodruff - 20 Feb 2000 - Added PrintCell() plus other minor changes
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// <[email protected]>
// C Maunder - 17 Jun 2000 - Font handling optimsed, Added CGridDefaultCell
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCell.h"
#include "InPlaceEdit.h"
#include "GridCtrl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGridCell, CGridCellBase)
IMPLEMENT_DYNCREATE(CGridDefaultCell, CGridCell)
/////////////////////////////////////////////////////////////////////////////
// GridCell
CGridCell::CGridCell()
{
m_plfFont = NULL;
CGridCell::Reset();
}
CGridCell::~CGridCell()
{
delete m_plfFont;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Attributes
void CGridCell::operator=(const CGridCell& cell)
{
if (this != &cell) CGridCellBase::operator=(cell);
}
void CGridCell::Reset()
{
CGridCellBase::Reset();
m_strText.Empty();
m_nImage = -1;
m_lParam = NULL; // BUG FIX J. Bloggs 20/10/03
m_pGrid = NULL;
m_bEditing = FALSE;
m_pEditWnd = NULL;
m_nFormat = (DWORD)-1; // Use default from CGridDefaultCell
m_crBkClr = CLR_DEFAULT; // Background colour (or CLR_DEFAULT)
m_crFgClr = CLR_DEFAULT; // Forground colour (or CLR_DEFAULT)
m_nMargin = (UINT)-1; // Use default from CGridDefaultCell
delete m_plfFont;
m_plfFont = NULL; // Cell font
}
void CGridCell::SetFont(const LOGFONT* plf)
{
if (plf == NULL)
{
delete m_plfFont;
m_plfFont = NULL;
}
else
{
if (!m_plfFont)
m_plfFont = new LOGFONT;
if (m_plfFont)
memcpy(m_plfFont, plf, sizeof(LOGFONT));
}
}
LOGFONT* CGridCell::GetFont() const
{
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFont();
}
return m_plfFont;
}
CFont* CGridCell::GetFontObject() const
{
// If the default font is specified, use the default cell implementation
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFontObject();
}
else
{
static CFont Font;
Font.DeleteObject();
Font.CreateFontIndirect(m_plfFont);
return &Font;
}
}
DWORD CGridCell::GetFormat() const
{
if (m_nFormat == (DWORD)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetFormat();
}
return m_nFormat;
}
UINT CGridCell::GetMargin() const
{
if (m_nMargin == (UINT)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetMargin();
}
return m_nMargin;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Operations
BOOL CGridCell::Edit(int nRow, int nCol, CRect rect, CPoint /* point */, UINT nID, UINT nChar)
{
if ( m_bEditing )
{
if (m_pEditWnd)
m_pEditWnd->SendMessage ( WM_CHAR, nChar );
}
else
{
DWORD dwStyle = ES_LEFT;
if (GetFormat() & DT_RIGHT)
dwStyle = ES_RIGHT;
else if (GetFormat() & DT_CENTER)
dwStyle = ES_CENTER;
m_bEditing = TRUE;
// InPlaceEdit auto-deletes itself
CGridCtrl* pGrid = GetGrid();
m_pEditWnd = new CInPlaceEdit(pGrid, rect, dwStyle, nID, nRow, nCol, GetText(), nChar);
}
return TRUE;
}
void CGridCell::EndEdit()
{
if (m_pEditWnd)
((CInPlaceEdit*)m_pEditWnd)->EndEdit();
}
void CGridCell::OnEndEdit()
{
m_bEditing = FALSE;
m_pEditWnd = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CGridDefaultCell
CGridDefaultCell::CGridDefaultCell()
{
#ifdef _WIN32_WCE
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX;
#else
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX | DT_END_ELLIPSIS;
#endif
m_crFgClr = CLR_DEFAULT;
m_crBkClr = CLR_DEFAULT;
m_crSelectedBkClr = ::GetSysColor(COLOR_HIGHLIGHT);
m_Size = CSize(30,10);
m_dwStyle = 0;
#ifdef _WIN32_WCE
LOGFONT lf;
GetObject(GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lf);
SetFont(&lf);
#else // not CE
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(NONCLIENTMETRICS);
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
SetFont(&(ncm.lfMessageFont));
#endif
}
CGridDefaultCell::~CGridDefaultCell()
{
m_Font.DeleteObject();
}
void CGridDefaultCell::SetFont(const LOGFONT* plf)
{
ASSERT(plf);
if (!plf) return;
m_Font.DeleteObject();
m_Font.CreateFontIndirect(plf);
CGridCell::SetFont(plf);
// Get the font size and hence the default cell size
CDC* pDC = CDC::FromHandle(::GetDC(NULL));
if (pDC)
{
CFont* pOldFont = pDC->SelectObject(&m_Font);
SetMargin(pDC->GetTextExtent(_T(" "), 1).cx);
m_Size = pDC->GetTextExtent(_T(" XXXXXXXXXXXX "), 14);
m_Size.cy = (m_Size.cy * 3) / 2;
pDC->SelectObject(pOldFont);
ReleaseDC(NULL, pDC->GetSafeHdc());
}
else
{
SetMargin(3);
m_Size = CSize(40,16);
}
}
LOGFONT* CGridDefaultCell::GetFont() const
{
ASSERT(m_plfFont); // This is the default - it CAN'T be NULL!
return m_plfFont;
}
CFont* CGridDefaultCell::GetFontObject() const
{
ASSERT(m_Font.GetSafeHandle());
return (CFont*) &m_Font;
}
|
[
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] |
[
[
[
1,
280
]
]
] |
3464ef507738168ac8884c61f9c9b928b13cea41
|
3dca0a6382ea348a8617be05e1bfa6f4ed70d77c
|
/AudioSystems/Audiere/PgeAudiereArchiveFile.h
|
b2ed00a5e214243ec99eb795f5bcde6155db44c1
|
[] |
no_license
|
David-Haim-zz/pharaoh-game-engine
|
9c766916559f9c74667e981b9b3f03b43920bc4e
|
b71db3fd99ebad0ab40a0888360d560748f63131
|
refs/heads/master
| 2021-05-29T15:17:23.043407 | 2011-01-23T17:53:39 | 2011-01-23T17:53:39 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,335 |
h
|
/*! $Id$
* @file PgeAudiereArchiveFile.h
* @author Chad M. Draper
* @date November 7, 2008
* @brief Provides an interface between an archive file and audiere::File.
*
*/
#ifndef PGEAUDIEREARCHIVEFILE_H
#define PGEAUDIEREARCHIVEFILE_H
#include "PgeTypes.h"
#include "PgeSharedPtr.h"
#include "audiere.h"
#include <fstream>
#include <stdio.h>
namespace PGE
{
class ArchiveFile;
/** @class AudiereArchiveFile
Allows Audiere to use an archive file as the source. This class is
derived from audiere::RefImplementation<audiere::File>, and has an
ArchiveFile member. The implementation of the audiere::File class
wraps the archive file.
*/
class _PgeExport AudiereArchiveFile : public audiere::RefImplementation<audiere::File>
{
protected:
typedef SharedPtr< ArchiveFile > ArchiveFilePtr;
//std::ifstream mFileStream;
ArchiveFilePtr mArchiveFile;
public:
AudiereArchiveFile();
AudiereArchiveFile( const String& fileName );
virtual ~AudiereArchiveFile();
/** Open a file for reading. */
bool Open( const String& fileName );
/**
* Read size bytes from the file, storing them in buffer.
*
* @param buffer buffer to read into
* @param size number of bytes to read
*
* @return number of bytes successfully read
*/
ADR_METHOD(int) read( void* buffer, int size );
/**
* Jump to a new position in the file, using the specified seek
* mode. Remember: if mode is END, the position must be negative,
* to seek backwards from the end of the file into its contents.
* If the seek fails, the current position is undefined.
*
* @param position position relative to the mode
* @param mode where to seek from in the file
*
* @return true on success, false otherwise
*/
ADR_METHOD(bool) seek( int position, SeekMode mode );
/**
* Get current position within the file.
*
* @return current position
*/
ADR_METHOD(int) tell();
};
} // namespace PGE
#endif // PGEAUDIEREARCHIVEFILE_H
|
[
"pharaohgameengine@555db735-7c4c-0410-acd0-0358cc0c1ac3"
] |
[
[
[
1,
77
]
]
] |
642009324573fbdcf13f3bada8782383eeab9f2d
|
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
|
/depends/ClanLib/src/Core/Math/angle.cpp
|
f73497825fcde8d553dbef27fa222cefa9ecacdf
|
[] |
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 | 4,503 |
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):
**
** Harry Storbacka
*/
#include "precomp.h"
#include "API/Core/Math/angle.h"
#include "API/Core/Math/cl_math.h"
/////////////////////////////////////////////////////////////////////////////
// CL_Angle Construction:
CL_Angle::CL_Angle() : value_rad(0)
{
}
CL_Angle::CL_Angle(float value, CL_AngleUnit unit)
{
if (unit == cl_radians)
{
value_rad = value;
}
else
{
value_rad = value * float(CL_PI) / 180.0f;
}
}
CL_Angle CL_Angle::from_radians(float value)
{
return CL_Angle(value, cl_radians);
}
CL_Angle CL_Angle::from_degrees(float value)
{
return CL_Angle(value, cl_degrees);
}
/////////////////////////////////////////////////////////////////////////////
// CL_Angle Attributes:
float CL_Angle::to_degrees() const
{
return value_rad * 180.0f / float(CL_PI);
}
float CL_Angle::to_radians() const
{
return value_rad;
}
/////////////////////////////////////////////////////////////////////////////
// CL_Angle Operations:
void CL_Angle::set_degrees(float degrees)
{
value_rad = degrees * float(CL_PI) / 180.0f;
}
void CL_Angle::set_radians(float radians)
{
value_rad = radians;
}
CL_Angle &CL_Angle::normalize()
{
value_rad = fmod(value_rad, CL_PI*2.0f);
if (value_rad < 0.0f)
value_rad += CL_PI*2.0f;
return *this;
}
CL_Angle &CL_Angle::normalize_180()
{
normalize();
if (value_rad > CL_PI)
value_rad -= CL_PI * 2.0f;
return *this;
}
/////////////////////////////////////////////////////////////////////////////
// CL_Angle Operators:
void CL_Angle::operator+=( const CL_Angle &angle )
{
value_rad += angle.value_rad;
}
void CL_Angle::operator-=( const CL_Angle &angle )
{
value_rad -= angle.value_rad;
}
void CL_Angle::operator*=( const CL_Angle &angle )
{
value_rad *= angle.value_rad;
}
void CL_Angle::operator/=( const CL_Angle &angle )
{
value_rad /= angle.value_rad;
}
CL_Angle CL_Angle::operator+( const CL_Angle &angle ) const
{
return CL_Angle(value_rad + angle.value_rad, cl_radians);
}
CL_Angle CL_Angle::operator-( const CL_Angle &angle ) const
{
return CL_Angle(value_rad - angle.value_rad, cl_radians);
}
CL_Angle CL_Angle::operator*( const CL_Angle &angle ) const
{
return CL_Angle(value_rad * angle.value_rad, cl_radians);
}
CL_Angle CL_Angle::operator*( float value ) const
{
return CL_Angle(value_rad * value, cl_radians);
}
CL_Angle CL_Angle::operator/( const CL_Angle &angle ) const
{
return CL_Angle(value_rad / angle.value_rad, cl_radians);
}
CL_Angle CL_Angle::operator/( float value ) const
{
return CL_Angle(value_rad / value, cl_radians);
}
bool CL_Angle::operator<( const CL_Angle &angle ) const
{
return value_rad < angle.value_rad;
}
bool CL_Angle::operator>( const CL_Angle &angle ) const
{
return value_rad > angle.value_rad;
}
bool CL_Angle::operator<=( const CL_Angle &angle ) const
{
return value_rad <= angle.value_rad;
}
bool CL_Angle::operator>=( const CL_Angle &angle ) const
{
return value_rad >= angle.value_rad;
}
bool CL_Angle::operator==( const CL_Angle &angle ) const
{
return value_rad == angle.value_rad;
}
bool CL_Angle::operator!=( const CL_Angle &angle ) const
{
return value_rad != angle.value_rad;
}
/////////////////////////////////////////////////////////////////////////////
// CL_Angle Implementation:
|
[
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
] |
[
[
[
1,
190
]
]
] |
4de4182011aefab9ad1847b839475a1b4b3c2a3f
|
58ef4939342d5253f6fcb372c56513055d589eb8
|
/ScheduleKiller/source/control/src/DetailListItemDrawer.cpp
|
d8f4526959b62de9935a9f7517f9e61a081e0120
|
[] |
no_license
|
flaithbheartaigh/lemonplayer
|
2d77869e4cf787acb0aef51341dc784b3cf626ba
|
ea22bc8679d4431460f714cd3476a32927c7080e
|
refs/heads/master
| 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 6,816 |
cpp
|
/*
============================================================================
Name : DetailListItemDrawer.cpp
Author : JohnLZeng
Version : 1.0
Copyright : Your copyright notice
Description : CDetailListItemDrawer implementation
============================================================================
*/
#include "DetailListItemDrawer.h"
#include <EIKENV.H>
#include <eiktxlbm.h>
#include <aknsskininstance.h>
#include <aknsutils.h>
#include "SHPlatform.h"
#include "MacroUtil.h"
#include "UI_Layout.h"
#include "LMSvgUtil.h"
//#include <ScheduleKiller.mbg>
CDetailListItemDrawer::CDetailListItemDrawer(const CEikTextListBox& aListBox) :
CListItemDrawer(), iListBox(aListBox)
{
// 设置图形上下文
iGc = &CCoeEnv::Static()->SystemGc();
SetGc(iGc);
InitIcons();
}
CDetailListItemDrawer::~CDetailListItemDrawer()
{
SAFE_DELETE(iDeleteIcon)
SAFE_DELETE_RPONTERARRAY(iClock)
}
void CDetailListItemDrawer::DrawActualItem(TInt aItemIndex,
const TRect& aActualItemRect, TBool aItemIsCurrent,
TBool aViewIsEmphasized, TBool /*aViewIsDimmed*/, TBool /*aItemIsSelected*/) const
{
DrawClock(aItemIndex,aActualItemRect);
DrawApp(aItemIndex,aActualItemRect);
if (aItemIsCurrent && aViewIsEmphasized )
DrawDelButton(aActualItemRect);
}
void CDetailListItemDrawer::InitIcons()
{
iClock = new RPointerArray<CGulIcon> (4);
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewZero, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewOne, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewTwo, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewThree, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewFour, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewFive, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewSix, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewSeven, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewEight, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewNine, ETrue));
iClock->Append(AknsUtils::CreateGulIconL(AknsUtils::SkinInstance(),
KAknsIIDQsnCpClockDigitalNewColon, ETrue));
// MAknsSkinInstance* skin = AknsUtils::SkinInstance();
// iDeleteIcon = AknsUtils::CreateGulIconL(skin, KAknsIIDQgnMenuUnknownLst, ETrue);
iDeleteIcon = CGulIcon::NewL();
CFbsBitmap* bitmap;
CFbsBitmap* mask;
LMSvgUtil::GetImageAndMaskFormResourceL(bitmap,mask,
EMbmSchedulekillerRemove,EMbmSchedulekillerRemove_mask);
iDeleteIcon->SetBitmap(bitmap);
iDeleteIcon->SetMask(mask);
}
void CDetailListItemDrawer::DrawClock(TInt aItemIndex,const TRect& aRect) const
{
RPointerArray<TaskInfo>& tasks = SHModel()->GetTaskInfoManager()->GetTaskList();
if (aItemIndex >= tasks.Count())
return;
pTaskInfo info = tasks[aItemIndex];
RArray<TInt>& array = info->iNumArray;
TInt x, y ,colon;
TInt count = array.Count();
//冒号对齐
for (TInt i = 0; i < count; i++)
{
TInt index = array[i];
if (index >= 10)
{
colon = i;
break;
}
}
x = (3-colon) * LIST_DIGITAL_SIZE.iWidth + LIST_DELETE_AREA_SIZE.iWidth + aRect.iTl.iX;
y = (LIST_APP_TIME_AREA_SIZE.iHeight - LIST_DIGITAL_SIZE.iHeight)/2 + aRect.iTl.iY
+ LIST_APP_ICON_AREA_SIZE.iHeight;
for (TInt i = 0; i < count; i++)
{
TInt index = array[i];
DrawClockDigital(index, TPoint(x, y));
if (index < 10)
x += LIST_DIGITAL_SIZE.iWidth;
else
x += LIST_COLON_SIZE.iWidth;
}
}
void CDetailListItemDrawer::DrawApp(TInt aItemIndex,const TRect& aRect) const
{
RPointerArray<TaskInfo>& tasks = SHModel()->GetTaskInfoManager()->GetTaskList();
if (aItemIndex >= tasks.Count())
return;
TPtrC name = tasks[aItemIndex]->iName;
const CFont* font = SHUI()->GetFont();
TInt x = (LIST_APP_ICON_AREA_SIZE.iWidth - LIST_APP_ICON_SIZE.iWidth)/2 + aRect.iTl.iX
+ LIST_DELETE_AREA_SIZE.iWidth;
TInt y = (LIST_APP_ICON_AREA_SIZE.iHeight - LIST_APP_ICON_SIZE.iHeight)/2 + aRect.iTl.iY;
TSize size = LIST_APP_ICON_SIZE;
CGulIcon* icon = tasks[aItemIndex]->iIcon;
CFbsBitmap* b1 = icon->Bitmap();
CFbsBitmap* b2 = icon->Mask();
AknIconUtils::SetSize(b1, size, EAspectRatioNotPreserved);
AknIconUtils::SetSize(b2, size, EAspectRatioNotPreserved);
TPoint point = TPoint(x, y);
iGc->BitBltMasked(point, b1, size, b2, EFalse);
TInt fontWidth = font->MeasureText(name);
TInt fontHeight = font->HeightInPixels();
x += LIST_APP_ICON_AREA_SIZE.iWidth;
y = (LIST_APP_NAME_AREA_SIZE.iHeight - fontHeight ) / 2 + aRect.iTl.iY;
size.iWidth = fontWidth;
size.iHeight = fontHeight;
TRect rect = TRect(TPoint(x, y), size);
TRgb color;
AknsUtils::GetCachedColor(AknsUtils::SkinInstance(), color,
KAknsIIDQsnTextColors, EAknsCIQsnTextColorsCG1/*EAknsCIQsnLineColorsCG1 */);
iGc->SetPenStyle(CGraphicsContext::ESolidPen);
iGc->SetPenColor(color);
iGc->UseFont(font);
iGc->DrawText(name, rect, rect.Height() / 2 + font->AscentInPixels() / 2,
CGraphicsContext::ELeft, 0);
iGc->DiscardFont();
}
void CDetailListItemDrawer::DrawClockDigital(TInt& aNumber, const TPoint& aPoint) const
{
if (aNumber >= 0)
{
TInt index = aNumber;
if (aNumber > 9)
index = 10;
CGulIcon* icon = (*iClock)[index];
TSize size;
if (aNumber < 10)
size = LIST_DIGITAL_SIZE;
else
size = LIST_COLON_SIZE;
CFbsBitmap* b1 = icon->Bitmap();
CFbsBitmap* b2 = icon->Mask();
AknIconUtils::SetSize(b1, size, EAspectRatioNotPreserved);
AknIconUtils::SetSize(b2, size, EAspectRatioNotPreserved);
iGc->BitBltMasked(aPoint, b1, size, b2, EFalse);
}
}
void CDetailListItemDrawer::DrawDelButton(const TRect& aRect) const
{
TInt x = (LIST_DELETE_AREA_SIZE.iWidth - LIST_DELETE_ICON_SIZE.iWidth)/2 + aRect.iTl.iX ;
TInt y = (LIST_DELETE_AREA_SIZE.iHeight - LIST_DELETE_ICON_SIZE.iHeight)/2 + aRect.iTl.iY;
TPoint point = TPoint(x, y);
TSize size = LIST_DELETE_ICON_SIZE;
if (iDeleteIcon)
{
CFbsBitmap* b1 = iDeleteIcon->Bitmap();
CFbsBitmap* b2 = iDeleteIcon->Mask();
AknIconUtils::SetSize(b1, size, EAspectRatioNotPreserved);
AknIconUtils::SetSize(b2, size, EAspectRatioNotPreserved);
iGc->BitBltMasked(point, b1, size, b2, EFalse);
}
}
|
[
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] |
[
[
[
1,
203
]
]
] |
210d78188897a23534d9c91524d79f47c9f04b7b
|
3fb88529ec63d45506d159bee677695698e690ee
|
/statsgraph.h
|
0bb1b73742733ce52f947a368adf2b5f506e7ef7
|
[] |
no_license
|
cristifalcas/qt-rrd
|
588f1d51555b146590dd84d969052123700a5217
|
249c1cb702020bcfe79465381053430e9e6f4e80
|
refs/heads/master
| 2021-01-14T13:20:53.669503 | 2009-11-12T22:16:08 | 2009-11-12T22:16:08 | 34,001,301 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,857 |
h
|
#ifndef STATSGRAPH_H_INCLUDED
#define STATSGRAPH_H_INCLUDED
#include "pagegeneralconfiguration.h"
#include "pagegenerategraph.h"
#include "pageextractstats.h"
#include "parsingstats.h"
#include "rrdtool.h"
#include "rrdinfo.h"
#include "mythread.h"
#include "messages.h"
#include <QDialog>
#include <QStackedWidget>
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
#include <QFile>
#include <QMap>
#include <QStatusBar>
class statsGraph : public QDialog
{
Q_OBJECT
public:
statsGraph();
~statsGraph();
void draw();
private:
enum typeWorkStatus {
stNOTHING,
stEXTRACT,
stCREATE,
stUPDATE,
stDONE,
stCANCEL,
last
} status;
static const QString stringWorkStatus[last];
QStatusBar *statusBar;
QStackedWidget *stackedWidget;
QListWidget *listWidget;
QListWidgetItem *listwidgetitemGeneralConfiguration,
*listwidgetitemExtractStats, *listwidgetitemGenerateGraph;
QString step;
QMutex mutex;
bool frommsgbox; //used to not answer second time the message box
PageGeneralConfiguration *widgetstackedGeneralConfiguration;
PageExtractStats *widgetstackedExtractStats;
PageGenerateGraph * widgetstackedGenerateGraph;
ParsingStats *parser;
mythread *extract;
RRDTool *rrdprogram;
RRDInfo *inforrd;
Messages *message;
void init();
void connects();
void layout();
void parseFiles();
//void disable();
void setEnable(bool);
public slots:
void updatePage(QListWidgetItem *crt, QListWidgetItem *prev);
void printMessageBox(QString);
void terminated();
void startWork();
void stopWork();
void begin();
void cancel();
};
#endif // STATSGRAPH_H_INCLUDED
|
[
"[email protected]"
] |
[
[
[
1,
81
]
]
] |
7074a82d0be6bf1bb5793caba38b55a64937b04b
|
b2155efef00dbb04ae7a23e749955f5ec47afb5a
|
/source/OECore/OERender/OESkyboxRender_Impl.cpp
|
f1e61bbdf586301a7d874a3df94dcf67332cebbd
|
[] |
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 | 2,209 |
cpp
|
/*!
* \file OESkyboxRender_Impl.cpp
* \date 10-25-2010 13:56:27
*
*
* \author zjhlogo ([email protected])
*/
#include "OESkyboxRender_Impl.h"
#include <OECore/IOECore.h>
#include <OECore/IOERenderSystem.h>
#include <OECore/OERenderSystemUtil.h>
#include <OECore/IOENode.h>
#include <libOEMsg/OEMsgShaderParam.h>
COESkyboxRender_Impl::COESkyboxRender_Impl()
{
m_bOK = Init();
}
COESkyboxRender_Impl::~COESkyboxRender_Impl()
{
Destroy();
}
bool COESkyboxRender_Impl::Init()
{
// TODO:
return true;
}
void COESkyboxRender_Impl::Destroy()
{
// TODO:
}
bool COESkyboxRender_Impl::Render(IOERenderData* pRenderData)
{
IOEMesh* pMesh = pRenderData->GetMesh(TS("MainMesh"));
if (!pMesh) return false;
IOEMaterialsList* pMaterialsList = pRenderData->GetMaterialsList(TS("MainMaterialsList"));
if (!pMaterialsList) return false;
CMatrix4x4 matWorldToProject;
g_pOERenderSystem->GetTransform(matWorldToProject, TT_WORLD_VIEW);
COEMath::SetMatrixTranslation(matWorldToProject, COEMath::VECTOR_ZERO);
g_pOERenderSystem->GetTransform(matWorldToProject, TT_PROJECTION);
CDefaultRenderState DefaultState(TS("ModelSpace"));
g_pOERenderSystem->EnableZBuffer(false);
int nNumPiece = pMesh->GetNumPieces();
for (int i = 0; i < nNumPiece; ++i)
{
IOEPiece* pPiece = pMesh->GetPiece(i);
if (!pPiece) continue;
IOEMaterial* pMaterial = pMaterialsList->GetMaterial(pPiece->GetMaterialID());
if (!pMaterial) continue;
IOEShader* pShader = pMaterial->GetShader();
if (!pShader) continue;
if (pPiece->GetVertDeclMask() != pMaterial->GetVertDeclMask()) continue;
// give user chance to setup shader parameter
IOEObject* pHolder = pRenderData->GetObject(TS("Holder"));
if (pHolder)
{
COEMsgShaderParam msg(pShader, pMaterial);
pHolder->CallEvent(msg);
}
pShader->SetMatrix(TS("g_matWorldToProject"), matWorldToProject);
pShader->SetTexture(TS("g_texDiffuse"), pMaterial->GetTexture(MTT_DIFFUSE));
g_pOERenderSystem->SetShader(pShader);
g_pOERenderSystem->DrawTriList(pPiece->GetVerts(), pPiece->GetNumVerts(), pPiece->GetIndis(), pPiece->GetNumIndis());
}
return true;
}
|
[
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] |
[
[
[
1,
83
]
]
] |
b7df0ac85c5fa1ec79fea026b81a62e251314a74
|
1775576281b8c24b5ce36b8685bc2c6919b35770
|
/trunk/splash.cpp
|
2c070eb1391360e2664607c192e734ee14fa43a5
|
[] |
no_license
|
BackupTheBerlios/gtkslade-svn
|
933a1268545eaa62087f387c057548e03497b412
|
03890e3ba1735efbcccaf7ea7609d393670699c1
|
refs/heads/master
| 2016-09-06T18:35:25.336234 | 2006-01-01T11:05:50 | 2006-01-01T11:05:50 | 40,615,146 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,019 |
cpp
|
#include "main.h"
GtkWidget* splash_window;
GtkWidget* splash_pbar;
extern GtkWidget* editor_window;
void setup_splash()
{
splash_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_decorated(GTK_WINDOW(splash_window), false);
gtk_window_set_has_frame(GTK_WINDOW(splash_window), false);
gtk_window_set_transient_for(GTK_WINDOW(splash_window), GTK_WINDOW(editor_window));
gtk_window_set_keep_above(GTK_WINDOW(splash_window), true);
gtk_window_set_position(GTK_WINDOW(splash_window), GTK_WIN_POS_CENTER);
gtk_window_set_skip_taskbar_hint(GTK_WINDOW(splash_window), true);
// Frame
GtkWidget *frame = gtk_frame_new(NULL);
gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
// Image
GtkWidget *vbox = gtk_vbox_new(false, 0);
GtkWidget *image = gtk_image_new_from_file("res/logo.png");
gtk_widget_set_size_request(image, 589, 230);
gtk_box_pack_start(GTK_BOX(vbox), image, true, true, 0);
// Progress bar
splash_pbar = gtk_progress_bar_new();
gtk_box_pack_start(GTK_BOX(vbox), splash_pbar, false, false, 0);
gtk_container_add(GTK_CONTAINER(frame), vbox);
gtk_container_add(GTK_CONTAINER(splash_window), frame);
gtk_widget_set_size_request(splash_window, -1, splash_pbar->allocation.height + 230);
}
void splash(string message)
{
if (!splash_window)
setup_splash();
gtk_progress_bar_set_text(GTK_PROGRESS_BAR(splash_pbar), message.c_str());
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(splash_pbar), 0);
gtk_window_set_position(GTK_WINDOW(splash_window), GTK_WIN_POS_CENTER);
gtk_widget_show_all(splash_window);
gtk_window_present(GTK_WINDOW(splash_window));
wait_gtk_events();
}
void splash_hide()
{
gtk_widget_destroy(splash_window);
splash_window = NULL;
}
void splash_progress(double prog)
{
if (!splash_window)
return;
gtk_window_set_position(GTK_WINDOW(splash_window), GTK_WIN_POS_CENTER);
gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(splash_pbar), prog);
wait_gtk_events();
}
|
[
"veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be"
] |
[
[
[
1,
66
]
]
] |
aed61a6eaf0bb3c7dae1875cfcc0d175a67e70fb
|
867f5533667cce30d0743d5bea6b0c083c073386
|
/jingxian-downloader/DownloadTaskList.h
|
e6aa875bf5c17941c795349bc470cb47a8565ffc
|
[] |
no_license
|
mei-rune/jingxian-project
|
32804e0fa82f3f9a38f79e9a99c4645b9256e889
|
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
|
refs/heads/master
| 2022-08-12T18:43:37.139637 | 2009-12-11T09:30:04 | 2009-12-11T09:30:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,170 |
h
|
/***************************************************************
* Name: DownloadTaskList.h
* Purpose: Defines DownloadTaskList Class
* Author: runner.mei ([email protected])
* Created: 2008-11-15
* Copyright: runner.mei
* License:
**************************************************************/
#ifndef DOWNLOADLIST_H
#define DOWNLOADLIST_H
#include <wx/gdicmn.h>
#include <wx/font.h>
#include <wx/colour.h>
#include <wx/settings.h>
#include <wx/string.h>
#include <wx/bitmap.h>
#include <wx/image.h>
#include <wx/icon.h>
#include <wx/sizer.h>
#include <wx/panel.h>
#include <wx/listctrl.h>
#include <wx/frame.h>
class DownloadTaskList : public wxPanel
{
public:
DownloadTaskList(wxWindow *parent,
wxWindowID winid = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxTAB_TRAVERSAL | wxNO_BORDER,
const wxString& name = wxPanelNameStr);
~DownloadTaskList(void);
protected:
void on_download_list_select_changed( wxListEvent& e );
private:
wxListCtrl* m_download_list;
};
#endif //DOWNLOADLIST_H
|
[
"runner.mei@0dd8077a-353d-11de-b438-597f59cd7555"
] |
[
[
[
1,
48
]
]
] |
4430b32d18bf5f0c7a12432995d5a3b6c28b8501
|
f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae
|
/Exercises/OpenGL6/DDEngine/colladaSkeleton.cpp
|
f715bc2f1b9ab2f064d18e3030a885c1d0f1ac1f
|
[] |
no_license
|
giacomof/gameengines2010itu
|
8407be66d1aff07866d3574a03804f2f5bcdfab1
|
bc664529a429394fe5743d5a76a3d3bf5395546b
|
refs/heads/master
| 2016-09-06T05:02:13.209432 | 2010-12-12T22:18:19 | 2010-12-12T22:18:19 | 35,165,366 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,375 |
cpp
|
#include "colladaSkeleton.h"
ColladaSkeleton::ColladaSkeleton(void)
{
}
ColladaSkeleton::~ColladaSkeleton(void)
{
}
bool ColladaSkeleton::load(std::string & str)
{
// Clear the array for loading
skelJoints.clear();
// Variables to parse xml doc with
xml_document<> doc;
xml_node<> * rootNode, * libraryNode;
// Try to open the xml file
doc.parse<0>(strdup(str.c_str())); // 0 means default parse flags
// Check if the file opened succesfully
if (doc.first_node("COLLADA") != 0)
{
rootNode = doc.first_node("COLLADA");
}
else
{
std::cout << "colladaSkeleton - Could not open xml file!\n";
return false;
}
// Check if there is a skeleton library in the file
if (rootNode->first_node("library_visual_scenes") != 0)
{
libraryNode = rootNode->first_node("library_visual_scenes")->first_node("visual_scene");
// We need to find the name of the root joint node first
string skelRootName;
xml_node<>* skelRootNode;
// The name is in a subnode of the instance_controller node. We look for that
bool nodeFound = false;
xml_node<>* currentNode = libraryNode->first_node("node");
while (!nodeFound)
{
if (currentNode->first_node("instance_controller") != 0)
{
skelRootName = currentNode->first_node("instance_controller")->first_node("skeleton")->value();
nodeFound = true;
}
// Continue to next node if we haven't found it yet
if ( !nodeFound && currentNode->next_sibling() != 0)
{
currentNode = currentNode->next_sibling();
}
else if ( !nodeFound )
{
std::cout << "colladaSkeleton - Could not identify root joint!\n";
return false;
}
}
// Now we need to find the node matching the name we've found
nodeFound = false;
currentNode = libraryNode->first_node("node");
while (!nodeFound)
{
if ( currentNode->first_node("node") != 0 )
{
if ( currentNode->first_node("node")->first_attribute("id") != 0 )
{
string tempString = currentNode->first_node("node")->first_attribute("id")->value();
if ( skelRootName.compare(1, skelRootName.size() - 1, tempString) == 0)
{
skelRootNode = currentNode->first_node("node");
nodeFound = true;
}
}
}
// Continue to next node if we haven't found it yet
if ( !nodeFound && currentNode->next_sibling() != 0)
{
currentNode = currentNode->next_sibling();
}
else if ( !nodeFound )
{
std::cout << "colladaSkeleton - Could not find skeleton root node!\n";
return false;
}
}
// We have the root skeleton node now. We can now parse the tree and load it into our vector
loadSkelJoint(skelRootNode, -1);
}
else
{
std::cout << "colladaSkeleton - Could not find library_visual_scenes node!\n";
return false;
}
// Check if there is an animation library in the file
if (rootNode->first_node("library_animations") != 0)
{
libraryNode = rootNode->first_node("library_animations");
// Iterate through the joints we have loaded and load animations for each if possible
for (int i=0; i<skelJoints.size(); i++)
{
// First we need to find the animation node match our current joint
xml_node<>* currentAnimationNode = libraryNode->first_node("animation");
// Get the current joint's ID.
string currentJointName = skelJoints[i].jName;
// Search for a joint animation matching this joint ID
bool matchFound = false;
while (!matchFound)
{
string tempJointName = currentAnimationNode->first_attribute("id")->value();
// this assumes tempJointID is jointID with "-transform" appended. We could make this more robust I guess
if (tempJointName.compare(0, tempJointName.size() - 10, currentJointName) == 0)
{
matchFound = true;
}
if ( !matchFound && currentAnimationNode->next_sibling("animation") != 0)
{
currentAnimationNode = currentAnimationNode->next_sibling("animation");
}
else if ( !matchFound )
{
break;
}
}
// Only continue if we found the match
if (matchFound)
{
// Prepare variables for storing data
unsigned int currentCount;
string currentTimeArray;
string currentMatrixArray;
// Get the time array
xml_node<>* currentSource = currentAnimationNode->first_node("source");
currentTimeArray = currentSource->first_node("float_array")->value();
currentCount = atoi(currentSource->first_node("float_array")->first_attribute("count")->value());
// Utility variable
string token;
// Put in the time data
skelJoints[i].jKeyframeTime.reserve(currentCount);
std::istringstream streamTimeArray(currentTimeArray);
while ( getline(streamTimeArray, token, ' ') )
{
skelJoints[i].jKeyframeTime.push_back( atof(token.c_str()) );
}
// Generate empty matrices
skelJoints[i].jKeyframeMatrix.resize(skelJoints[i].jKeyframeTime.size());
// Go down through the matrix channels and put them into the vector
currentSource = currentSource->next_sibling("source");
for (int channel=0; channel<16; channel++)
{
currentMatrixArray = currentSource->first_node("float_array")->value();
currentCount = atoi(currentSource->first_node("float_array")->first_attribute("count")->value());
int row = (int) (channel % 4);
int col = (int) (channel / 4);
// Last channel is special case. we want to make sure it's 1
if (channel == 15)
{
for (int j=0; j<skelJoints[i].jKeyframeMatrix.size(); j++)
{
skelJoints[i].jKeyframeMatrix[j].InvMatrix.set( row, col, 1 );
}
}
// If matrix channel doesnt have a value for each frame, assume the first value is constant
else if (currentCount != skelJoints[i].jKeyframeTime.size())
{
std::istringstream streamMatrixArray(currentMatrixArray);
getline(streamMatrixArray, token, ' ');
float value = atof(token.c_str());
for (int j=0;j<skelJoints[i].jKeyframeTime.size();j++)
{
skelJoints[i].jKeyframeMatrix[j].InvMatrix.set( row, col, value);
}
}
else
{
std::istringstream streamMatrixArray(currentMatrixArray);
int j = 0;
while ( getline(streamMatrixArray, token, ' ') )
{
skelJoints[i].jKeyframeMatrix[j].InvMatrix.set( row, col, atof(token.c_str()) );
j++;
}
}
if (channel < 15)
{
currentSource = currentSource->next_sibling("source")->next_sibling("source")->next_sibling("source");
}
}
}
// Animation Node has been loaded at this point
}
// All joints have had animations loaded at this point
}
else
{
std::cout << "colladaSkeleton - Could not find library_animations node!\n";
}
return true;
}
void ColladaSkeleton::loadSkelJoint(xml_node<>* currentNode, int parentIndex)
{
// Make the joint
skelJoint currentSkelJoint;
// Save the name and ID, if applicable
currentSkelJoint.jName = currentNode->first_attribute("id")->value();
if ( currentNode->first_attribute("sid") != 0 )
currentSkelJoint.jID = currentNode->first_attribute("sid")->value();
else
currentSkelJoint.jID = "";
// Save the parent's index
currentSkelJoint.jParentIndex = parentIndex;
// Get the bind pose matrix
string token;
string matrixArray = currentNode->first_node("matrix")->value();
std::istringstream isM(matrixArray);
for (int col = 0; col < 4; col++)
{
for (int row = 0; row < 4; row++)
{
if ( getline(isM, token, ' ') )
{
currentSkelJoint.jBindPose.set(row, col, atof(token.c_str()) );
}
else
break;
}
}
// Joint should be complete at this point, add it to the array
skelJoints.push_back(currentSkelJoint);
// Search children of this node and call this function on them too
int currentIndex = skelJoints.size() - 1;
if (currentNode->first_node("node") != 0)
{
bool didChildren = false;
xml_node<>* childNode = currentNode->first_node("node");
do {
loadSkelJoint(childNode, currentIndex);
if ( childNode->next_sibling("node") != 0)
childNode = childNode->next_sibling("node");
else
didChildren = true;
} while (!didChildren);
}
}
unsigned int ColladaSkeleton::getDataSize()
{
// Incomplete, obviously
return static_cast<unsigned int> (0);
}
skelPose * ColladaSkeleton::buildSkeleton()
{
skelPose * currentSkelPose = new skelPose;
currentSkelPose->skelPoseJoints.reserve(skelJoints.size());
// Create a skelPoseJoint for each skelJoint
for (int i=0; i<skelJoints.size(); i++)
{
skelPoseJoint currentSkelPoseJoint;
currentSkelPoseJoint.pjID = skelJoints[i].jID;
currentSkelPoseJoint.pjParentIndex = skelJoints[i].jParentIndex;
currentSkelPoseJoint.pjJointTransform = skelJoints[i].jBindPose;
if (skelJoints[i].jParentIndex >= 0)
{
currentSkelPoseJoint.pjJointTransform = currentSkelPoseJoint.pjJointTransform * currentSkelPose->skelPoseJoints[skelJoints[i].jParentIndex].pjJointTransform;
}
currentSkelPose->skelPoseJoints.push_back(currentSkelPoseJoint);
}
return currentSkelPose;
}
void ColladaSkeleton::updateSkeleton(skelPose * currentPose, float currentTime)
{
for (int i=0; i<currentPose->skelPoseJoints.size(); i++)
{
if (skelJoints[i].jKeyframeTime.size() != 0)
{
int currentFrame = 0;
for (int j=0; j<skelJoints[i].jKeyframeTime.size(); j++)
{
if (currentTime < (skelJoints[i].jKeyframeTime[j]) )
{
currentFrame = j - 1;
break;
}
}
if (currentFrame < 0)
currentFrame = 0;
// Interpolate
if (true)
{
Matrix tempMatrix;
int nextFrame = (currentFrame + 1);
if (nextFrame >= skelJoints[i].jKeyframeTime.size())
nextFrame = 1;
float between = currentTime - (skelJoints[i].jKeyframeTime[currentFrame]);
between = between / ( (skelJoints[i].jKeyframeTime[nextFrame]) - (skelJoints[i].jKeyframeTime[currentFrame]) );
for (int h = 0; h<15; h++)
{
tempMatrix.set(h, ( skelJoints[i].jKeyframeMatrix[currentFrame].InvMatrix.get(h) + between * (skelJoints[i].jKeyframeMatrix[nextFrame].InvMatrix.get(h) - skelJoints[i].jKeyframeMatrix[currentFrame].InvMatrix.get(h))) );
}
tempMatrix.set(15, 1);
currentPose->skelPoseJoints[i].pjJointTransform = tempMatrix;
}
else
{
currentPose->skelPoseJoints[i].pjJointTransform = skelJoints[i].jKeyframeMatrix[currentFrame].InvMatrix;
}
}
else
{
currentPose->skelPoseJoints[i].pjJointTransform = skelJoints[i].jBindPose;
}
if (skelJoints[i].jParentIndex >= 0)
{
currentPose->skelPoseJoints[i].pjJointTransform = currentPose->skelPoseJoints[i].pjJointTransform * currentPose->skelPoseJoints[skelJoints[i].jParentIndex].pjJointTransform;
}
}
}
void ColladaSkeleton::traceSkeleton(skelPose * currentPose)
{
float tranM[16];
for (int i=0; i<currentPose->skelPoseJoints.size(); i++)
{
currentPose->skelPoseJoints[i].pjJointTransform.getMatrix(&tranM[0]);
glPushMatrix();
glMultMatrixf(&tranM[0]);
glPointSize(5.0f);
glBegin(GL_POINTS);
glVertex3f(0.0f,0.0f,0.0f);
glEnd();
glPopMatrix();
}
}
|
[
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d",
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d",
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d"
] |
[
[
[
1,
14
],
[
17,
17
],
[
21,
21
],
[
23,
23
],
[
38,
38
],
[
50,
50
],
[
52,
52
],
[
61,
61
],
[
68,
68
],
[
75,
75
],
[
77,
77
],
[
84,
85
],
[
98,
98
],
[
221,
222
],
[
228,
229
],
[
231,
232
],
[
234,
235
],
[
247,
247
],
[
249,
249
],
[
252,
252
],
[
254,
254
],
[
256,
258
],
[
260,
266
],
[
268,
269
],
[
272,
272
],
[
278,
278
],
[
309,
309
],
[
311,
311
],
[
314,
314
],
[
317,
318
],
[
320,
320
],
[
375,
376
],
[
378,
378
],
[
395,
395
]
],
[
[
15,
16
],
[
18,
20
],
[
22,
22
],
[
24,
37
],
[
39,
49
],
[
51,
51
],
[
53,
60
],
[
62,
67
],
[
69,
74
],
[
76,
76
],
[
78,
83
],
[
86,
97
],
[
99,
196
],
[
198,
215
],
[
218,
220
],
[
223,
227
],
[
230,
230
],
[
233,
233
],
[
236,
246
],
[
248,
248
],
[
250,
251
],
[
253,
253
],
[
255,
255
],
[
259,
259
],
[
267,
267
],
[
270,
271
],
[
273,
277
],
[
279,
308
],
[
310,
310
],
[
312,
313
],
[
315,
316
],
[
319,
319
],
[
321,
337
],
[
343,
343
],
[
363,
374
],
[
377,
377
],
[
379,
394
]
],
[
[
197,
197
],
[
216,
217
],
[
338,
342
],
[
344,
362
]
]
] |
1846fa9dedb5c4d42fd940bcdcff115cf39f1b7c
|
c95a83e1a741b8c0eb810dd018d91060e5872dd8
|
/Game/ObjectDLL/ObjectShared/ServerMark.cpp
|
55dd90c53658fbeaa4ccc982e5371af0c7a283e7
|
[] |
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 | 4,787 |
cpp
|
// ----------------------------------------------------------------------- //
//
// MODULE : CServerMark.cpp
//
// PURPOSE : CServerMark implementation
//
// CREATED : 1/15/99
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "ServerMark.h"
#include "WeaponMgr.h"
#include "ilttransform.h"
#include "CVarTrack.h"
CVarTrack g_cvarMarkWMShow;
CVarTrack g_cvarMarkWMFadeTime;
CVarTrack g_cvarMarkWMSolidTime;
LINKFROM_MODULE( ServerMark );
#pragma force_active on
BEGIN_CLASS(CServerMark)
END_CLASS_DEFAULT_FLAGS(CServerMark, BaseClass, NULL, NULL, CF_HIDDEN)
#pragma force_active off
// ----------------------------------------------------------------------- //
//
// ROUTINE: CServerMark::CServerMark()
//
// PURPOSE: Initialize object
//
// ----------------------------------------------------------------------- //
CServerMark::CServerMark() :
BaseClass(OT_SPRITE),
m_fElapsedTime(0.0f)
{
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CServerMark::~CServerMark()
//
// PURPOSE: Destructor
//
// ----------------------------------------------------------------------- //
CServerMark::~CServerMark()
{
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CServerMark::EngineMessageFn
//
// PURPOSE: Handle engine messages
//
// ----------------------------------------------------------------------- //
uint32 CServerMark::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData)
{
switch(messageID)
{
case MID_PARENTATTACHMENTREMOVED :
{
g_pLTServer->RemoveObject(m_hObject);
}
break;
case MID_INITIALUPDATE:
{
//make sure that our console variables are setup
if (!g_cvarMarkWMShow.IsInitted())
{
g_cvarMarkWMShow.Init(g_pLTServer, "MarkWMShow", NULL, 1.0f);
}
if (!g_cvarMarkWMFadeTime.IsInitted())
{
g_cvarMarkWMFadeTime.Init(g_pLTServer, "MarkWMFadeTime", NULL, 3.0f);
}
if (!g_cvarMarkWMSolidTime.IsInitted())
{
g_cvarMarkWMSolidTime.Init(g_pLTServer, "MarkWMSolidTime", NULL, 3.0f);
}
SetNextUpdate(m_hObject, UPDATE_NEXT_FRAME);
}
break;
case MID_UPDATE:
{
//update the time based upon the server frame time
m_fElapsedTime += g_pLTServer->GetFrameTime();
//figure out our lifespan times
float fSolidTime = g_cvarMarkWMSolidTime.GetFloat();
float fFadeTime = g_cvarMarkWMFadeTime.GetFloat();
//however, if we are disabled, set our time to 0
if(g_cvarMarkWMShow.GetFloat() < 0.99f)
{
fSolidTime = fFadeTime = 0.0f;
}
//see if we are solid
if(m_fElapsedTime < fSolidTime)
{
//we are solid, don't do anything, just don't update until we will start fading
SetNextUpdate(m_hObject, UPDATE_NEXT_FRAME);
}
else if(m_fElapsedTime < (fSolidTime + fFadeTime))
{
//we are fading out, if we are in single player update our alpha
//we don't in multiplayer because these marks could otherwise consume
//a huge amount of bandwidth
if(g_pGameServerShell->GetGameType() == eGameTypeSingle)
{
//determine what our color currently is
float fRed, fGreen, fBlue, fAlpha;
g_pLTServer->GetObjectColor(m_hObject, &fRed, &fGreen, &fBlue, &fAlpha);
//set our alpha so it will ramp down to 0
fAlpha = 1.0f - ((m_fElapsedTime - fSolidTime) / fFadeTime);
g_pLTServer->SetObjectColor(m_hObject, fRed, fGreen, fBlue, fAlpha);
}
SetNextUpdate(m_hObject, UPDATE_NEXT_FRAME);
}
else
{
//we are out of time, remove this object
g_pLTServer->RemoveObject(m_hObject);
}
}
break;
case MID_SAVEOBJECT:
{
OnSave( (ILTMessage_Write*)pData, (uint32)fData );
}
break;
case MID_LOADOBJECT:
{
OnLoad( (ILTMessage_Read*)pData, (uint32)fData );
}
break;
default : break;
}
return BaseClass::EngineMessageFn(messageID, pData, fData);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: WorldModel::OnSave
//
// PURPOSE: Save the object
//
// ----------------------------------------------------------------------- //
void CServerMark::OnSave( ILTMessage_Write *pMsg, uint32 dwSaveFlags )
{
pMsg->Writefloat(m_fElapsedTime);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: WorldModel::OnLoad
//
// PURPOSE: Load the object
//
// ----------------------------------------------------------------------- //
void CServerMark::OnLoad( ILTMessage_Read *pMsg, uint32 dwSaveFlags )
{
m_fElapsedTime = pMsg->Readfloat();
}
|
[
"[email protected]"
] |
[
[
[
1,
185
]
]
] |
110ebc3df641d1d05bc84301804648181bb1c1a0
|
3eae8bea68fd2eb7965cca5afca717b86700adb5
|
/HiroCat/Source/GSelectStageScene.h
|
7809a33b8b105c0c1dff6d2161211e67fc2835f6
|
[] |
no_license
|
mujige77/WebGame
|
c0a218ee7d23609076859e634e10e29c92bb595b
|
73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd
|
refs/heads/master
| 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 820 |
h
|
#ifndef HiroCat_GSelectStageScene_h
#define HiroCat_GSelectStageScene_h
class GnIListPageCtrl;
class GnInterfaceGroup;
class GSelectStageScene : public GScene
{
private:
GLayer* mpInterfaceLayer;
GLayer* mpBackgroundLayer;
GnIListPageCtrl* mpListPageCtrl;
GnInterfaceGroup* mpListButtonGroup;
GnMemberSlot2<GSelectStageScene, GnInterface*, GnIInputEvent*> mInputEvent;
public:
GSelectStageScene();
virtual ~GSelectStageScene();
public:
static GSelectStageScene* CreateScene(guint32 uiLastStage);
bool CreateInterface(guint32 uiLastStage);
bool CreateBackground();
public:
virtual void Update(float fTime);
virtual const gchar* GetSceneName();
protected:
void InputEvent(GnInterface* pInterface, GnIInputEvent* pEvent);
void SelectStage(gtuint uiNumStage);
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
32
]
]
] |
bc5356b14357920332d30ada86a0a8f1bf722f70
|
de0881d85df3a3a01924510134feba2fbff5b7c3
|
/apps/addonsExamples/vectorMathSpringsExample/src/particles/particle.cpp
|
030290a357da497efe11a9fc079a780032dfe645
|
[] |
no_license
|
peterkrenn/ofx-dev
|
6091def69a1148c05354e55636887d11e29d6073
|
e08e08a06be6ea080ecd252bc89c1662cf3e37f0
|
refs/heads/master
| 2021-01-21T00:32:49.065810 | 2009-06-26T19:13:29 | 2009-06-26T19:13:29 | 146,543 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 447 |
cpp
|
#include "particle.h"
particle::particle(){
pos.x = 0;
pos.y = 0;
vel.x = 0;
vel.y = 0;
bAlive = false;
bFixed = false;
}
void particle::setPropertiesAndTurnOn(float x,float y,float x_v,float y_v){
pos.x = x;
pos.y = y;
vel.x = x_v;
vel.y = y_v;
bAlive = true;
}
void particle::update(){
}
void particle::draw(){
if (bAlive == true){
glColor3f(1,1,1);
ofCircle(pos.x-2,pos.y-2,4);
}
}
|
[
"[email protected]"
] |
[
[
[
1,
34
]
]
] |
bd71ace93fa549a06051072bd13ad53132440eb7
|
fdfaf8e8449c5e80d93999ea665db48feaecccbe
|
/trunk/cg ex3/SimulationsParams.h
|
58d1840b18fe6016e56d325730435ad001569df3
|
[] |
no_license
|
BackupTheBerlios/glhuji2005-svn
|
879e60533f820d1bdcfa436fd27894774c27a0b7
|
3afe113b265704e385c94fabaf99a7d1ad1fdb02
|
refs/heads/master
| 2016-09-01T17:25:30.876585 | 2006-09-03T18:04:19 | 2006-09-03T18:04:19 | 40,673,356 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 666 |
h
|
#pragma once
class CParticleSystem;
class CSimulationsParams
{
public:
CSimulationsParams():
m_cameraPos(10,10,10),
m_cameraDir(0,0,0),
m_cameraUp(0,1,0),
m_dFovY(30),
m_dAspect(1),
m_dZNear(1),
m_dZFar(20000),
m_particleSystem(NULL),
m_clearColor(1,1,1),
m_dT(0.1),
m_dLinearAttenuation(0.05)
{}
~CSimulationsParams(void);
public:
Vector3d m_cameraPos;
Vector3d m_cameraDir;
Vector3d m_cameraUp;
Point3d m_clearColor;
double m_dFovY;
double m_dAspect;
double m_dZNear;
double m_dZFar;
double m_dT;
double m_dLinearAttenuation;
CParticleSystem* m_particleSystem;
};
|
[
"dagan@c8a6d0be-e207-0410-856a-d97b7f264bab",
"playmobil@c8a6d0be-e207-0410-856a-d97b7f264bab"
] |
[
[
[
1,
8
],
[
10,
16
],
[
18,
27
],
[
34,
37
]
],
[
[
9,
9
],
[
17,
17
],
[
28,
33
]
]
] |
59269feb877da58362d692a91d8059ac9cab4f6a
|
de98f880e307627d5ce93dcad1397bd4813751dd
|
/3libs/ut/include/OXCustomizeManager.h
|
6f5bc0cbdb31a1e5f7075f2c6ba55dc3e8fe35ba
|
[] |
no_license
|
weimingtom/sls
|
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
|
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
|
refs/heads/master
| 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 52,260 |
h
|
// ==========================================================================
// Class Specification: COXCustomizeManager
// ==========================================================================
// Header file : OXCustomizeManager.h
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
/*
Overview
COXCustomizeManager is CDialog derived class that serves as a control center that
provides customization functionality for different aspects of your application.
COXCustomizeManager is a container of customize page(s). Each customize page is
responsible for customization of a particular area of your application functionality
(e.g. customizing menus and toolbars). Refer to COXCustomizePage class overview and
overview for standard customize pages classes (like COXCustomizeCommandsPage).
COXCustomizeManager is responsible for initializing of all customize pages inserted
in the manager. It organizes all pages in groups (by default there is only one group
is defined - the one that contains standard (predefined) customize pages) and provides
navigation facilities by using shortcut bar control (COXShortcutBar class).
COXCustomizeManager is designed in the way it can be easily overridden in order
to provide support for custom-defined customize pages. It has a lot of virtual
functions that define its behavior. Those functions can be overridden in order to
provide an additional customization functionality.
Despite the fact that customize manager is easily expandable in most cases a programmer
will use a predefined set of standard customize pages (Customize Commands,
Customize Toolbars, Customize Workspace, etc.). COXCustomizeManager provides
interface functions for accessing the standard pages and their initialization
functions (refer to the class reference for details). In most cases a customization
feature will require a programmer to call only one initialization function.
COXCustomizeManager provides rich set of functions for navigating through customize
pages programmatically. These will be useful mostly for programmers who decide
to derive their own classes and provide additional functionality.
We developed a lot of predefined customize pages that should satisfy the majority
of the common needs for customization (toolbars, menus, accelerator tables, etc.).
All standard pages are documented and the entire list of them can be found in the
overview for COXCustomizePage (the base class for any customize page).
Note, that you don't have to implement your own COXCustomizeManager-derived class
in order to specify what standard pages will be included in the customize manager.
Moreover, you don't have to include the code that implements the standard pages
if you are not interested in at all by using corresponding defines. For example in
order to include support for customizing toolbars and menus you need to include the
following define in your stdafx.h file:
#define OX_CUSTOMIZE_TOOLBARS
The list of all defines that correspond to standard pages can be found in the
COXCustomizePage overview.
Below you will find the details on how you can use customize manager in your
application. (Note that some of the standard pages might require additional
initialization steps).
Usage
1) In your stdafx.h file include defines for the standard pages you are going
to use in the customize manager:
#define OX_CUSTOMIZE_TOOLBARS
#define OX_CUSTOMIZE_COMMANDS
These defines will include "Customize Toolbars" and "Customize Commands"
standard pages.
2) Declare a member variable of COXCustomizeManager class in the main window
of your application (usually CMainFrame class for SDI/MDI applications)
// customize manager
COXCustomizeManager m_customizeManager;
3) Handle WM_CREATE message for the main window and in the handler call
initialization routines for the pages included in the customize manager:
#ifdef OX_CUSTOMIZE_TOOLBARS
VERIFY(m_customizeManager.InitializeToolbars());
#endif // OX_CUSTOMIZE_TOOLBARS
#ifdef OX_CUSTOMIZE_COMMANDS
VERIFY(m_customizeManager.InitializeCommands());
#endif // OX_CUSTOMIZE_COMMANDS
This code will initialize "Customize Toolbars" and "Customize Commands"
standard pages. Note that you have to refer to the documentation for
appropriate way of initializing of any particular standard customize
routines because some of them require additional initialization step(s).
4) If you want to save the state of the pages (pages allows you to save the
changed settings in the registry) you have to handle WM_CLOSE message
for the main window and add the following line of code to this handler:
m_customizeManager.SaveWorkspaceState();
5) In order to display the customize manager (it is always displayed as modeless
window) you can use the following code:
if(!::IsWindow(m_customizeManager.GetSafeHwnd()))
{
VERIFY(m_customizeManager.Create(COXCustomizeManager::IDD,this));
}
m_customizeManager.SetActiveWindow();
m_customizeManager.ShowWindow(SW_SHOW);
That's all you need to do.
Refer to the COXCustomizePage documentation for more details on customize pages.
Note!!! COXCustomizeManager automatically recognizes if it is being used in
with docking windows framework. It behaves differently in docking
windows environment. If your application doesn't use docking framework
then you must to add the following define to your stdafx.h file:
#define OX_CUSTOMIZE_NOTSUPPORTING_DOCKING_FRAMEWORK
The best way of learning about Customize manager capabilities is to take look at the
VisualStudioLikeDemo sample that can be found in the
.\Samples\Advanced\VisualStudioLikeDemo subdirectory of your Ultimate Toolbox
directory. In the sample menu choose "View"-"Customize" in order to display the
Customize manager window.
Dependency:
#include "OXCustomizeManager.h"
Source code files:
"OXCustomizeManager.cpp"
"OXCustomizePage.cpp"
"OXLayoutManager.cpp"
"OXShortcutBar.cpp"
"OXSeparator.cpp"
"OXStatic.cpp"
Resource files:
"OXCustomizeManager.rc"
plus dependencies defined for the pages that are included in the customize manager.
Refer to the corresponding page overviews for details on their dependencies
*/
#if !defined(_OXCUSTOMIZEMANAGER_H__)
#define _OXCUSTOMIZEMANAGER_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "OXDllExt.h"
#ifndef __AFXTEMPL_H__
#include <afxtempl.h>
#define __AFXTEMPL_H__
#endif
#include "OXLayoutManager.h"
#include "OXShortcutBar.h"
#include "OXStatic.h"
#include "OXSeparator.h"
#include "OXCustomizePage.h"
#include "OXMainRes.h"
#ifndef IDR_MAINFRAME
#define IDR_MAINFRAME 128
#endif // IDR_MAINFRAME
#if defined _LINK_TO_UTB_IN_EXTDLL || defined _BUILD_UTB_INTO_EXTDLL
#ifndef OX_CUSTOMIZE_CAPTION
#define OX_CUSTOMIZE_CAPTION
#endif
#ifndef OX_CUSTOMIZE_TABBEDMDI
#define OX_CUSTOMIZE_TABBEDMDI
#endif
#ifndef OX_CUSTOMIZE_WORKSPACE_STATE
#define OX_CUSTOMIZE_WORKSPACE_STATE
#endif
#ifndef OX_CUSTOMIZE_TOOLBARS
#define OX_CUSTOMIZE_TOOLBARS
#endif
#ifndef OX_CUSTOMIZE_COMMANDS
#define OX_CUSTOMIZE_COMMANDS
#endif
#ifndef OX_CUSTOMIZE_BACKGROUND
#define OX_CUSTOMIZE_BACKGROUND
#endif
#ifndef OX_CUSTOMIZE_COOLCONTROLS
#define OX_CUSTOMIZE_COOLCONTROLS
#endif
#ifndef OX_CUSTOMIZE_TRAYICON
#define OX_CUSTOMIZE_TRAYICON
#endif
#ifndef OX_CUSTOMIZE_INSTANCE_MANAGER
#define OX_CUSTOMIZE_INSTANCE_MANAGER
#endif
#ifndef OX_CUSTOMIZE_SPLASHWINDOW
#define OX_CUSTOMIZE_SPLASHWINDOW
#endif
#ifndef OX_CUSTOMIZE_INTELLIMOUSE
#define OX_CUSTOMIZE_INTELLIMOUSE
#endif
#ifndef OX_CUSTOMIZE_SHORTKEYS
#define OX_CUSTOMIZE_SHORTKEYS
#endif
#endif
#ifndef OX_CUSTOMIZE_NOTSUPPORTING_DOCKING_FRAMEWORK
#include "OXFrameWndDock.h"
#endif // OX_CUSTOMIZE_NOTSUPPORTING_DOCKING_FRAMEWORK
#ifdef OX_CUSTOMIZE_CAPTION
#include "OXCustomizeCaptionPage.h"
#endif // OX_CUSTOMIZE_CAPTION
#ifdef OX_CUSTOMIZE_TABBEDMDI
#include "OXCustomizeTabbedMDIPage.h"
#endif // OX_CUSTOMIZE_TABBEDMDI
#ifdef OX_CUSTOMIZE_WORKSPACE_STATE
#include "OXCustomizeWorkspaceStatePage.h"
#endif // OX_CUSTOMIZE_WORKSPACE_STATE
#ifdef OX_CUSTOMIZE_TOOLBARS
#include "OXCustomizeToolbarsPage.h"
#endif // OX_CUSTOMIZE_TOOLBARS
#ifdef OX_CUSTOMIZE_COMMANDS
#include "OXCustomizeCommandsPage.h"
#endif // OX_CUSTOMIZE_COMMANDS
#ifdef OX_CUSTOMIZE_BACKGROUND
#include "OXCustomizeBackgroundPage.h"
#endif // OX_CUSTOMIZE_BACKGROUND
#ifdef OX_CUSTOMIZE_COOLCONTROLS
#include "OXCustomizeCoolControlsPage.h"
#endif // OX_CUSTOMIZE_COOLCONTROLS
#ifdef OX_CUSTOMIZE_TRAYICON
#include "OXCustomizeTrayIconPage.h"
#endif // OX_CUSTOMIZE_TRAYICON
#ifdef OX_CUSTOMIZE_INSTANCE_MANAGER
#include "OXCustomizeInstanceManagerPage.h"
#endif // OX_CUSTOMIZE_INSTANCE_MANAGER
#ifdef OX_CUSTOMIZE_SPLASHWINDOW
#include "OXCustomizeSplashWindowPage.h"
#endif // OX_CUSTOMIZE_SPLASHWINDOW
#ifdef OX_CUSTOMIZE_INTELLIMOUSE
#include "OXCustomizeIntelliMousePage.h"
#endif // OX_CUSTOMIZE_INTELLIMOUSE
#ifdef OX_CUSTOMIZE_SHORTKEYS
#include "OXCustomizeShortkeysPage.h"
#endif // OX_CUSTOMIZE_SHORTKEYS
#ifndef ID_OXCUSTOMIZE_TBIMAGE_WIDTH
#define ID_OXCUSTOMIZE_TBIMAGE_WIDTH 16
#endif // ID_OXCUSTOMIZE_TBIMAGE_WIDTH
#ifndef ID_OXCUSTOMIZE_TBIMAGE_HEIGHT
#define ID_OXCUSTOMIZE_TBIMAGE_HEIGHT 16
#endif // ID_OXCUSTOMIZE_TBIMAGE_HEIGHT
// enumerator of ids of the standard pages
enum CustomizeManagerPage { CUSTOMPAGE=-1, CAPTION_PAINTER=0, TABBEDMDI=1,
WORKSPACE_STATE=2, TOOLBARS=3, COMMANDS=4,
BACKGROUND_PAINTER=5, COOLCONTROLS=6, TRAYICON=7,
INSTANCE_MANAGER=8, SPLASHWINDOW=9, INTELLIMOUSE=10,
SHORTKEYS=11 };
typedef CMap<COXCustomizePage*,COXCustomizePage*,DWORD,DWORD> CMapPages;
typedef CMap<COXCustomizePage*,COXCustomizePage*,CString,CString> CMapPageTooltips;
class OX_CLASS_DECL COXCustomizeManager : public CDialog
{
public:
// --- In : pParent - points to parent window. If NULL is specified the
// main window of the application is used as parent
// window
// --- Out :
// --- Returns:
// --- Effect : Constructs the object
COXCustomizeManager(CWnd* pParent = NULL);
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Destructs the object
virtual ~COXCustomizeManager();
// Dialog Data
//{{AFX_DATA(COXCustomizeManager)
enum { IDD = IDD_OX_CUSTOMIZEMANAGER_DIALOG };
COXSeparator m_sepTitle;
COXSeparator m_sepBottom;
COXShortcutBar m_shb;
COXStatic m_title;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COXCustomizeManager)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
protected:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Called at the initialization stage once in order to populate
// the manager with customize pages. Advanced overridable, use
// your own implementation in the case you need to add
// non-standard pages
virtual void PopulatePages();
// --- In : page - ID of the standandard page. Can be one of the
// following:
//
// CAPTION_PAINTER - page for customizing
// caption painter settings
// TABBEDMDI - page for customizing
// Tabbed MDI interface settings
// WORKSPACE_STATE - page for customizing
// workspace state settings
// TOOLBARS - page for customizing
// toolbars appearance
// COMMANDS - page for customizing
// toolbars and menus contents
// BACKGROUND_PAINTER - page for customizing
// background painter settings
// COOLCONTROLS - page for customizing
// cool controls settings
// TRAYICON - page for customizing
// tray icon settings
// INSTANCE_MANAGER - page for customizing
// the instance manager settings
// SPLASHWINDOW - page for customizing
// splash window appearance
// INTELLIMOUSE - page for customizing
// IntelliMouse support
// SHORTKEYS - page for customizing
// shortkeys table
// --- Out :
// --- Returns: TRUE if specified page will be included in the manager;
// FALSE otherwise
// --- Effect : Called internally in order to add standard page to the manager.
// Advanced overridable, default implementation always returns TRUE.
// Use your own implementation in the case you need to prevent the
// inclusion of any standard customize page
virtual BOOL IsIncludingStandardPage(CustomizeManagerPage page)
{
UNREFERENCED_PARAMETER(page);
return TRUE;
}
// --- In : bIsOk - TRUE if the customize manager window is being closed
// as a result of pressing "OK" button; FALSE otherwise
// --- Out :
// --- Returns: TRUE if manager dialog window was successfully closed;
// FALSE otherwise
// --- Effect : Called to close active customize manager. Advanced overridable,
// use your own implementation in the case you need to handle the
// close event
virtual BOOL CloseManager(BOOL bIsOk);
public:
// --- In :
// --- Out :
// --- Returns: Pointer to the parent window for customize pages
// --- Effect : Retrieves the parent window for customize pages. Advanced
// overridable, use your own implementation in the case you need to
// specify a different parent window for customize pages
virtual CWnd* GetSite() { return this; }
// --- In : lpszGroup - the name of a group in the customize manager.
// By default it is set to DEFAULT_CUSTOMIZE_GROUP,
// the group that contains standard pages
// hGroup - handle to a group in the customize manager.
// --- Out :
// --- Returns: The number of customize pages in the specified group
// --- Effect : Retrieves the number of customize pages in the specified group.
// All standard pages are created in one group which name is
// defined as DEFAULT_CUSTOMIZE_GROUP constant
inline int GetPageCount(LPCTSTR lpszGroup=DEFAULT_CUSTOMIZE_GROUP) const
{
HSHBGROUP hGroup=m_shb.FindGroupByTitle(lpszGroup);
return GetPageCount(hGroup);
}
inline int GetPageCount(HSHBGROUP hGroup) const
{
if(hGroup==NULL)
return 0;
return m_shb.GetLCItemCount(hGroup);
}
// --- In :
// --- Out :
// --- Returns: The number of customize pages in all groups
// --- Effect : Retrieves the number of customize pages in all groups
int GetAllPageCount() const;
// --- In : pCustomizePage - pointer to a created page to be added
// to customize manager
// --- Out :
// --- Returns: TRUE if the specified page was successfully added to
// customize manager; FALSE otherwise
// --- Effect : Adds new page to customize manager. The name of the group
// the specified page belongs to is retrieve by calling corresponding
// function defined in COXCustomizePage class (the base class for
// all customize pages). When corresponding group is found the page
// is being added to the end of existing pages in the found group
inline BOOL AddPage(COXCustomizePage* pCustomizePage)
{
return InsertPage(pCustomizePage,GetPageCount(pCustomizePage->GetGroup()));
}
// --- In : pCustomizePage - pointer to a created page to be inserted
// in customize manager
// nPageIndex - position at which the specified page will be
// inserted in the corresponding group
// --- Out :
// --- Returns: TRUE if the specified page was successfully inserted in
// customize manager; FALSE otherwise
// --- Effect : Inserts new page in customize manager. The name of the group
// the specified page belongs to is retrieve by calling corresponding
// function defined in COXCustomizePage class (the base class for
// all customize pages). When corresponding group is found the page
// is being inserted at the position specified by nPageIndex
// parameter. Advanced overridable, use your own implementation in
// the case you need to handle the process of inserting new
// customize page
virtual BOOL InsertPage(COXCustomizePage* pCustomizePage, int nPageIndex);
// --- In : pCustomizePage - pointer to a page to be deleted from
// customize manager
// --- Out :
// --- Returns: TRUE if the specified page was successfully deleted from
// customize manager; FALSE otherwise
// --- Effect : Deletes a page from customize manager. Advanced overridable,
// use your own implementation if you need to handle the process
// of deleting a customize page
virtual BOOL DeletePage(COXCustomizePage* pCustomizePage);
// --- In : pageType - ID of standard page, refer to
// IsIncludingStandardPage() function
// documentation for the values this parameter
// can take
// pCustomizePage - a pointer to a customize page to find
// lpszTitle - title of a customize page to find
// lpszGroup - title of a group where the specified page
// belongs to
// --- Out : hGroupTest - group in the shortcut bar where the specified
// page icon is displayed
// nIndexTest - index of the position in the hGroupTest group
// in the shortcut bar at which the specified page
// icon is displayed
// --- Returns: TRUE if the specified page was successfully found;
// FALSE otherwise
// --- Effect : Finds the position of the specified customize page icon in the
// customize manager shortcut bar. Whenever a page is added to
// customize manager the new item that identifies this page will be
// created in the shortcut bar. Information on the name of shortcut
// bar group the page belongs to, the item icon and the item title
// will be retrieved by calling corresponding functions defined in
// the COXCustomizePage class (base class for all customize pages)
BOOL FindPage(CustomizeManagerPage pageType,
HSHBGROUP& hGroupTest, int& nIndexTest) const;
BOOL FindPage(COXCustomizePage* pCustomizePage,
HSHBGROUP& hGroupTest, int& nIndexTest) const;
BOOL FindPage(LPCTSTR lpszTitle, LPCTSTR lpszGroup,
HSHBGROUP& hGroupTest, int& nIndexTest) const;
// --- In : hGroup - group in the shortcut bar where a page icon is
// displayed
// nIndex - index of the position in the hGroupTest group
// in the shortcut bar at which a page icon is
// displayed
// --- Out :
// --- Returns: A pointer to the customize page object which icon is located
// at the specified position in the customize manager shortcut bar
// if found; NULL otherwise
// --- Effect : Finds a customize page by position of its icon in the customize
// manager shortcut bar. Whenever a page is added to
// customize manager the new item that identifies this page will be
// created in the shortcut bar. Knowing shortcut bar group and item
// index any customize page added to customize manager can be
// uniquely identified
COXCustomizePage* GetPageByLocation(HSHBGROUP hGroup, int nIndex) const;
// --- In : hGroup - group in the shortcut bar where a page icon is
// displayed
// nIndex - index of the position in the hGroupTest group
// in the shortcut bar at which a page icon is
// displayed
// --- Out :
// --- Returns: A pointer to the currently active customize page object
// --- Effect : Retrieves currently active customize page
inline COXCustomizePage* GetActivePage() const { return m_pActivePage; }
// --- In : pageType - ID of standard page, refer to
// IsIncludingStandardPage() function
// documentation for the values this parameter
// can take
// pCustomizePage - a pointer to a customize page to activate
// lpszTitle - title of a customize page to activate
// lpszGroup - title of a group where the specified page
// belongs to
// hGroup - group in the shortcut bar where a page icon is
// displayed
// nIndex - index of the position in the hGroupTest group
// in the shortcut bar at which a page icon is
// displayed
// --- Out :
// --- Returns: TRUE if the specified page was successfully activated;
// FALSE otherwise
// --- Effect : Activates the specified customize page. The corresponding item
// in the customize manager shortcut bar will be activated and the
// specified page will be loaded while previously active page
// will be unloaded. Advanced overridable, use your own implementation
// in the case you need to handle customize page activation event
BOOL ActivatePage(CustomizeManagerPage pageType);
BOOL ActivatePage(COXCustomizePage* pCustomizePage);
BOOL ActivatePage(LPCTSTR lpszTitle, LPCTSTR lpszGroup);
virtual BOOL ActivatePage(HSHBGROUP hGroup, int nIndex);
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Recalculates the rectangle within customize manager window
// that can be taken by a customize page. Call this function
// whenever the positioning of the controls in customize manager
// is changed. Automatically called from WM_SIZE handler
void RecalcPageRect();
// --- In :
// --- Out :
// --- Returns: The rectangle within customize manager window that can be taken
// by a customize page
// --- Effect : Retrieves the rectangle within customize manager window
// that can be taken by a customize page.
inline CRect GetPageRect() const {return m_rectPage; }
// --- In :
// --- Out :
// --- Returns: A pointer to internal shortcut bar control that is used to
// display all customize page icons
// --- Effect : Retrieves a pointer to internal shortcut bar control. This
// shortcut bar is populated with items that corresponds to all
// inserted customize pages.
inline COXShortcutBar* GetShortcutBar() { return &m_shb; }
// --- In :
// --- Out :
// --- Returns: A pointer to internal array of all inserted customize pages
// --- Effect : Retrieves a pointer to internal array of all inserted customize
// pages. You might need to use this array in order to iterate
// through all inserted pages and apply the same routine.
inline CMapPages* GetMapPages() { return &m_mapPages; }
// --- In :
// --- Out :
// --- Returns: A pointer to internal array of all customize page tooltips
// --- Effect : Retrieves a pointer to internal array of all customize page
// tooltips.
inline CMapPageTooltips* GetMapPageTooltips() { return &m_mapTooltips; }
// --- In : pCustomizePage - a pointer to a customize page
// --- Out :
// --- Returns: A tooltip for the specified page
// --- Effect : Retrieves a tooltip for the specified page.
inline CString GetPageTooltip(COXCustomizePage* pCustomizePage) const
{
CString sTooltip(_T(""));
m_mapTooltips.Lookup(pCustomizePage,sTooltip);
return sTooltip;
}
// --- In : pCustomizePage - a pointer to a customize page
// lpszTooltip - new tooltip for the specified page
// --- Out :
// --- Returns: TRUE if new tooltip for the specified page was set successfully;
// FALSE otherwise
// --- Effect : Sets new tooltip for the specified page.
BOOL SetPageTooltip(COXCustomizePage* pCustomizePage, LPCTSTR lpszTooltip);
// --- In :
// --- Out :
// --- Returns: TRUE if this customize manager belongs to the framework that
// supports Ultimate Toolbox Docking Windows Framework (mainframe
// window is derived from COXFrameWndSizeDock class); FALSE otherwise
// --- Effect : Retrieves the flag that specifies if customize manager belongs
// to the framework that supports Ultimate Toolbox Docking Windows
// Framework
inline BOOL IsDockingFramework() const
{
#ifndef OX_CUSTOMIZE_NOTSUPPORTING_DOCKING_FRAMEWORK
CWnd* pWnd=AfxGetMainWnd();
ASSERT(pWnd!=NULL);
return (pWnd->IsKindOf(RUNTIME_CLASS(COXFrameWndSizeDock)) ||
pWnd->IsKindOf(RUNTIME_CLASS(COXMDIFrameWndSizeDock)));
#else
return FALSE;
#endif // OX_CUSTOMIZE_NOTSUPPORTING_DOCKING_FRAMEWORK
}
// --- In :
// --- Out :
// --- Returns: TRUE if this customize manager belongs to the MDI framework;
// FALSE otherwise
// --- Effect : Retrieves the flag that specifies if customize manager belongs
// to MDI framework or not
inline BOOL IsMDIFramework() const
{
CWnd* pWnd=AfxGetMainWnd();
ASSERT(pWnd!=NULL);
return pWnd->IsKindOf(RUNTIME_CLASS(CMDIFrameWnd));
}
// --- In :
// --- Out :
// --- Returns: TRUE if the state of a framework this customize manager
// belongs was saved in the registry successfully; FALSE otherwise
// --- Effect : Saves in the registry the state of the framework this customize
// manager belongs to. Call this function before the application is
// closed. Advanced overridable, use your own implementation if you
// need to save any additional information.
virtual BOOL SaveWorkspaceState();
protected:
// image list for icons associated with pages (32x32 size)
CImageList m_ilShortcutBar;
// rectangle for the page dialog
CRect m_rectPage;
// pointer to currently active page
COXCustomizePage* m_pActivePage;
// layout manager object that can be used in order to resize child controls
// whenever size of the dialog is changed
COXLayoutManager m_LayoutManager;
// map of all created customize pages (in terms of C++ objects)
CMapPages m_mapObjects;
// map of all created customize pages (in terms of window objects)
CMapPages m_mapPages;
// map that associates customize pages with their tooltips
CMapPageTooltips m_mapTooltips;
// flag that specifies that the dialog has been completely initialized
BOOL m_bInitialized;
// pedefined pages
//
#ifdef OX_CUSTOMIZE_CAPTION
// page for caption painter settings
COXCustomizeCaptionPage m_pageCaption;
#endif // OX_CUSTOMIZE_CAPTION
#ifdef OX_CUSTOMIZE_TABBEDMDI
// page for tabbed MDI settings
COXCustomizeTabbedMDIPage m_pageTabbedMDI;
#endif // OX_CUSTOMIZE_TABBEDMDI
#ifdef OX_CUSTOMIZE_WORKSPACE_STATE
// page for caption painter settings
COXCustomizeWorkspaceStatePage m_pageWorkspaceState;
#endif // OX_CUSTOMIZE_WORKSPACE_STATE
#ifdef OX_CUSTOMIZE_TOOLBARS
// page for caption painter settings
COXCustomizeToolbarsPage m_pageToolbars;
#endif // OX_CUSTOMIZE_TOOLBARS
#ifdef OX_CUSTOMIZE_COMMANDS
// page for caption painter settings
COXCustomizeCommandsPage m_pageCommands;
#endif // OX_CUSTOMIZE_COMMANDS
#ifdef OX_CUSTOMIZE_BACKGROUND
// page for background painter settings
COXCustomizeBackgroundPage m_pageBackground;
#endif // OX_CUSTOMIZE_BACKGROUND
#ifdef OX_CUSTOMIZE_COOLCONTROLS
// page for cool controls settings
COXCustomizeCoolControlsPage m_pageCoolControls;
#endif // OX_CUSTOMIZE_COOLCONTROLS
#ifdef OX_CUSTOMIZE_TRAYICON
// page for tray icon settings
COXCustomizeTrayIconPage m_pageTrayIcon;
#endif // OX_CUSTOMIZE_TRAYICON
#ifdef OX_CUSTOMIZE_INSTANCE_MANAGER
// page for tray icon settings
COXCustomizeInstanceManagerPage m_pageInstanceManager;
#endif // OX_CUSTOMIZE_INSTANCE_MANAGER
#ifdef OX_CUSTOMIZE_SPLASHWINDOW
// page for splash window settings
COXCustomizeSplashWindowPage m_pageSplashWindow;
#endif // OX_CUSTOMIZE_SPLASHWINDOW
#ifdef OX_CUSTOMIZE_INTELLIMOUSE
// page for intelli mouse suport settings
COXCustomizeIntelliMousePage m_pageIntelliMouse;
#endif // OX_CUSTOMIZE_INTELLIMOUSE
#ifdef OX_CUSTOMIZE_SHORTKEYS
// page for shortkeys settings
COXCustomizeShortkeysPage m_pageShortkeys;
#endif // OX_CUSTOMIZE_SHORTKEYS
public:
#ifdef OX_CUSTOMIZE_CAPTION
virtual BOOL InitializeCaptionPainter(BOOL bPaintCaption=TRUE,
LPCTSTR lpszProfileName=_T("CustomizeCaptionPainter"),
BOOL bOnlyMainWindow=FALSE)
{
ASSERT(GetCaptionPage()!=NULL);
return GetCaptionPage()->
InitializeCaptionPainter(bPaintCaption,lpszProfileName,bOnlyMainWindow);
}
virtual COXCaptionPainterOrganizer* GetCaptionPainterOrganizer()
{
ASSERT(GetCaptionPage()!=NULL);
return GetCaptionPage()->GetPainterOrganizer();
}
virtual COXCustomizeCaptionPage* GetCaptionPage() { return &m_pageCaption; }
#endif // OX_CUSTOMIZE_CAPTION
#ifdef OX_CUSTOMIZE_TABBEDMDI
// --- In : dwTabCtrlStyle - tab control styles that will be
// used while creating the internal tab control.
// Refer to the Windows SDK documentation
// for list of all available styles.
// The following styles are used by
// default:
//
// TCS_MULTILINE
// TCS_BOTTOM
// TCS_HOTTRACK
// TCS_SCROLLOPPOSITE
// TCS_RIGHTJUSTIFY
//
// dwOffset - offset in points from the MDIFrame window
// client area where the tab control will be
// displayed
// lpszProfileName - the name of the hive in the registry
// where TabbedMDI settings is saved.
// If non-NULL value is set then
// settings is retrieved from the
// registry right away. These can
// overwrite the values specified in
// the previous parameters
// bSupportTabbedMDI- if TRUE then TabbedMDI will be activated
// immediately
// --- Out :
// --- Returns: TRUE if TabbedMDI was initialized successfully;
// FALSE otherwise
// --- Effect : Replaces standard MDI with TabbedMDI. TabbedMDI is initialized
// with parameters specified by this function arguments or retrieved
// from registry. Refer to TabbedMDI documentation for more details
virtual BOOL InitializeTabbedMDI(DWORD dwTabCtrlStyle=DEFAULT_TABCTRLSTYLE,
DWORD dwOffset=ID_TABOFFSET, LPCTSTR lpszProfileName=_T("CustomizeTabbedMDI"),
BOOL bSupportTabbedMDI=TRUE)
{
ASSERT(GetTabbedMDIPage()!=NULL);
return GetTabbedMDIPage()->InitializeTabbedMDI(dwTabCtrlStyle,
dwOffset,lpszProfileName,bSupportTabbedMDI);
}
// --- In :
// --- Out :
// --- Returns: A pointer to internal COXTabClientWnd object
// --- Effect : Retrieves internal COXTabClientWnd object that implements
// TabbedMDI functionality
virtual COXTabClientWnd* GetTabClientWnd()
{
ASSERT(GetTabbedMDIPage()!=NULL);
return GetTabbedMDIPage()->GetTabClientWnd();
}
// --- In :
// --- Out :
// --- Returns: A pointer to Customize TabbedMDI page
// --- Effect : Retrieves a pointer to Customize TabbedMDI page. This page
// can be used to customize the appearance of TabbedMDI interface.
// TabbedMDI is MDI extension that displays standard tab control
// in which we create an item for every MDIChild window. The window
// icon and text will be associated with the corresponding tab item.
// Using tab control you can switch very fast between MDIChild
// windows just clicking on the tab item. Refer to TabbedMDI
// documentation for more details
virtual COXCustomizeTabbedMDIPage* GetTabbedMDIPage()
{
return &m_pageTabbedMDI;
}
#endif // OX_CUSTOMIZE_TABBEDMDI
#ifdef OX_CUSTOMIZE_WORKSPACE_STATE
// --- In : bIncludeMainWnd - if TRUE then info about application's
// main window placement will be
// saved/restored
// bIncludeBars - if TRUE then info about application's
// control bar windows placement will be
// saved/restored
// bIncludeChildFrames - if TRUE then info about application's
// child windows placement will be
// saved/restored
// bIncludeSplitterPanes - if TRUE then info about application's
// splitter windows panes placement will
// be saved/restored
// lpszProfileName - the name of the hive in the registry
// where workspace state organizer
// settings are saved. If non-NULL value
// is set then settings are retrieved
// from the registry right away. These
// can overwrite the values specified in
// the previous parameters. Also it
// retrieves information on what customize
// pages must be displayed in the
// customize manager shortcut bar and what
// ones must be hidden
// --- Out :
// --- Returns: TRUE if workspace state settings were initialized successfully;
// FALSE otherwise
// --- Effect : Initializes the application's workspace state
virtual BOOL LoadWorkspaceState(BOOL bIncludeMainWnd=TRUE, BOOL bIncludeBars=TRUE,
BOOL bIncludeChildFrames=TRUE, BOOL bIncludeSplitterPanes=TRUE,
LPCTSTR lpszProfileName=_T("CustomizeWorkspaceState"));
// --- In :
// --- Out :
// --- Returns: A pointer to COXWorkspaceState object that is responsible for
// saving/loading workspace state
// --- Effect : Retrieves a pointer to internal COXWorkspaceState object
virtual COXWorkspaceState* GetWorkspaceStateObject()
{
ASSERT(GetWorkspaceStatePage()!=NULL);
return GetWorkspaceStatePage()->GetWorkspaceStateObject();
}
// --- In :
// --- Out :
// --- Returns: A pointer to Customize Workspace State page
// --- Effect : Retrieves a pointer to Customize Workspace State page. This page
// can be used to specify what aspect of application's workspace
// state must be saved/loaded. Also it allows you to specify what
// customize pages must be displayed in the customize manager
// shortcut bar and what ones must be hidden
virtual COXCustomizeWorkspaceStatePage* GetWorkspaceStatePage()
{
return &m_pageWorkspaceState;
}
#endif // OX_CUSTOMIZE_WORKSPACE_STATE
#ifdef OX_CUSTOMIZE_TOOLBARS
// --- In : bCoolLook - if TRUE the toolbars will be displayed in
// cool mode (flat buttons). By default set
// to TRUE
// bShowGripper - if TRUE a gripper will be displayed on the
// top/left side of application's toolbars.
// By default set to TRUE
// bShowTooltips - if TRUE a tooltip will be displayed for
// toolbars buttons. By default set to TRUE
// nBorderSize - the border size in pixels for toolbars.
// By default set to 0
// lpszProfileName - the name of the hive in the registry where
// toolbars' appearance settings is saved. If
// non-NULL value is set then settings are
// retrieved from the registry right away.
// These can overwrite the values specified in
// the previous parameters
// --- Out :
// --- Returns: TRUE if toolbars were initialized successfully; FALSE otherwise
// --- Effect : Initializes the settings that specifies the appearance of the
// application's toolbars
virtual BOOL InitializeToolbars(BOOL bCoolLook=TRUE, BOOL bShowGripper=TRUE,
BOOL bShowTooltips=TRUE, int nBorderSize=0,
LPCTSTR lpszProfileName=_T("CustomizeToolbars"))
{
ASSERT(GetToolbarsPage()!=NULL);
return GetToolbarsPage()->InitializeToolbars(bCoolLook,bShowGripper,
bShowTooltips,nBorderSize,lpszProfileName);
}
// --- In :
// --- Out :
// --- Returns: A pointer to Customize Toolbars page
// --- Effect : Retrieves a pointer to Customize Toolbars page. This page can
// be used to specify the appearance of the application's toolbars;
// create new toolbars; delete existing toolbars; rename existing
// toolbars; reset the contents of the toolbars to their original
// set of commands.
virtual COXCustomizeToolbarsPage* GetToolbarsPage() { return &m_pageToolbars; }
#endif // OX_CUSTOMIZE_TOOLBARS
#ifdef OX_CUSTOMIZE_COMMANDS
// --- In : nCustomImagesResourceID - ID of the bitmap that specifies
// customize images that can be
// associated with existing commands
// and displayed next to buttons in
// toolbars and menu items in menus.
// We provide predefined set of
// customize images
// lpszCustomImagesResource- resource string the defines the
// bitmap that specifies
// customize images that can be
// associated with existing commands
// and displayed next to buttons in
// toolbars and menu items in menus.
// clrMask - color of the mask for the specified
// bitmap. By default set to
// RGB(192,192,192)
// bShowIconsInMenu - if TRUE an images will be displayed
// next to menu items in menus.
// By default set to TRUE
// lpszProfileName - the name of the hive in the registry
// where commands settings is saved. If
// non-NULL value is set then settings
// is retrieved from the registry right
// away. These can overwrite the values
// specified in the previous parameters.
// Also the saved contents of the
// application's toolbars and menus will
// retrieved and applied
// --- Out :
// --- Returns: TRUE if information on the application's commands was initialized
// successfully; FALSE otherwise
// --- Effect : Initializes the information on the application's commands and
// retrieves the saved contents of the application's toolbars and
// menus and applies it
inline BOOL InitializeCommands(
UINT nCustomImagesResourceID=IDB_OX_IL_CUSTOMIZE_CUSTOM_IMAGES,
COLORREF clrMask=RGB(192,192,192), BOOL bShowIconsInMenu=TRUE,
BOOL bShowOnlyRecentlyUsedMenuItems=TRUE,
LPCTSTR lpszProfileName=_T("CustomizeCommands"))
{
return InitializeCommands(MAKEINTRESOURCE(nCustomImagesResourceID),
clrMask,bShowIconsInMenu,bShowOnlyRecentlyUsedMenuItems,lpszProfileName);
}
virtual BOOL InitializeCommands(LPCTSTR lpszCustomImagesResource,
COLORREF clrMask=RGB(192,192,192), BOOL bShowIconsInMenu=TRUE,
BOOL bShowOnlyRecentlyUsedMenuItems=TRUE,
LPCTSTR lpszProfileName=_T("CustomizeCommands"))
{
ASSERT(GetCommandsPage()!=NULL);
return GetCommandsPage()->InitializeCommands(lpszCustomImagesResource,
clrMask,bShowIconsInMenu,bShowOnlyRecentlyUsedMenuItems,lpszProfileName);
}
// --- In :
// --- Out :
// --- Returns: A pointer to Customize Commands page
// --- Effect : Retrieves a pointer to Customize Commands page. This page can
// be used to customize the contents of application's toolbars and
// menus. New items can be added, existing deleted or reallocated.
// Also the appearance of items can be customized.
virtual COXCustomizeCommandsPage* GetCommandsPage() { return &m_pageCommands; }
// --- In :
// --- Out :
// --- Returns: A pointer to internal COXBitmapMenuOrganizer object
// --- Effect : Retrieves a pointer to internal COXBitmapMenuOrganizer object.
// This object is used to handle menus in the framework.
virtual COXBitmapMenuOrganizer* GetBMOrganizer()
{
ASSERT(GetCommandsPage()!=NULL);
return GetCommandsPage()->GetBMOrganizer();
}
#endif // OX_CUSTOMIZE_COMMANDS
#ifdef OX_CUSTOMIZE_BACKGROUND
virtual BOOL InitializeBackgroundPainter(const BOOL bPaintBackground,
const BOOL bOnlyClientArea, LPCTSTR lpszDIBResourceName,
const PaintType paintType=Tile, const COLORREF clrBk=CLR_DEFAULT,
LPCTSTR lpszProfileName=_T("CustomizeBackgroundPainter"))
{
ASSERT(GetBackgroundPage()!=NULL);
return GetBackgroundPage()->InitializeBackgroundPainter(bPaintBackground,
bOnlyClientArea,lpszDIBResourceName,paintType,clrBk,lpszProfileName);
}
virtual BOOL InitializeBackgroundPainter(const BOOL bPaintBackground,
const BOOL bOnlyClientArea, const UINT nDIBResourceID,
const PaintType paintType=Tile, const COLORREF clrBk=CLR_DEFAULT,
LPCTSTR lpszProfileName=_T("CustomizeBackgroundPainter"))
{
ASSERT(GetBackgroundPage()!=NULL);
return GetBackgroundPage()->InitializeBackgroundPainter(bPaintBackground,
bOnlyClientArea,nDIBResourceID,paintType,clrBk,lpszProfileName);
}
virtual BOOL InitializeBackgroundPainter(const BOOL bPaintBackground,
const BOOL bOnlyClientArea, const CString& sDIBFileName,
const PaintType paintType=Tile, const COLORREF clrBk=CLR_DEFAULT,
LPCTSTR lpszProfileName=_T("CustomizeBackgroundPainter"))
{
ASSERT(GetBackgroundPage()!=NULL);
return GetBackgroundPage()->InitializeBackgroundPainter(bPaintBackground,
bOnlyClientArea,sDIBFileName,paintType,clrBk,lpszProfileName);
}
virtual BOOL InitializeBackgroundPainter(const BOOL bPaintBackground,
const BOOL bOnlyClientArea, const COXDIB* pDIB,
const PaintType paintType=Tile, const COLORREF clrBk=CLR_DEFAULT,
LPCTSTR lpszProfileName=_T("CustomizeBackgroundPainter"))
{
ASSERT(GetBackgroundPage()!=NULL);
return GetBackgroundPage()->InitializeBackgroundPainter(bPaintBackground,
bOnlyClientArea,pDIB,paintType,clrBk,lpszProfileName);
}
virtual COXBackgroundPainterOrganizer* GetBackgroundPainterOrganizer()
{
ASSERT(GetBackgroundPage()!=NULL);
return GetBackgroundPage()->GetBackgroundOrganizer();
}
virtual COXCustomizeBackgroundPage* GetBackgroundPage()
{
return &m_pageBackground;
}
#endif // OX_CUSTOMIZE_BACKGROUND
#ifdef OX_CUSTOMIZE_COOLCONTROLS
virtual BOOL InitializeCoolControls(BOOL bConvertToCool=FALSE,
LPCTSTR lpszProfileName=_T("CustomizeCoolControls"))
{
ASSERT(GetCoolControlsPage()!=NULL);
return GetCoolControlsPage()->
InitializeCoolControls(bConvertToCool,lpszProfileName);
}
virtual COXCoolControlOrganizer* GetCoolControlOrganizer()
{
ASSERT(GetCoolControlsPage()!=NULL);
return GetCoolControlsPage()->GetCoolControlOrganizer();
}
virtual COXCustomizeCoolControlsPage* GetCoolControlsPage()
{
return &m_pageCoolControls;
}
#endif // OX_CUSTOMIZE_COOLCONTROLS
#ifdef OX_CUSTOMIZE_TRAYICON
virtual BOOL InitializeTrayIcon(HICON hIcon, UINT nContextMenuResourceID,
LPCTSTR lpszIconTooltip=NULL, BOOL bShowTrayIcon=TRUE,
BOOL bUseRightClick=TRUE, LPCTSTR lpszIconSourceFileName=NULL,
LPCTSTR lpszProfileName=_T("CustomizeTrayIcon"))
{
ASSERT(GetTrayIconPage()!=NULL);
return GetTrayIconPage()->InitializeTrayIcon(hIcon,nContextMenuResourceID,
lpszIconTooltip,bShowTrayIcon,bUseRightClick,
lpszIconSourceFileName,lpszProfileName);
}
inline BOOL InitializeTrayIcon(UINT nIconResourceID, UINT nContextMenuResourceID,
LPCTSTR lpszIconTooltip=NULL, BOOL bShowTrayIcon=TRUE,
BOOL bUseRightClick=TRUE, LPCTSTR lpszIconSourceFileName=NULL,
LPCTSTR lpszProfileName=_T("CustomizeTrayIcon"))
{
return InitializeTrayIcon(MAKEINTRESOURCE(nIconResourceID),
nContextMenuResourceID,
lpszIconTooltip,bShowTrayIcon,bUseRightClick,
lpszIconSourceFileName,lpszProfileName);
}
inline BOOL InitializeTrayIcon(LPCTSTR lpszIconResource,
UINT nContextMenuResourceID, LPCTSTR lpszIconTooltip=NULL,
BOOL bShowTrayIcon=TRUE, BOOL bUseRightClick=TRUE,
LPCTSTR lpszIconSourceFileName=NULL,
LPCTSTR lpszProfileName=_T("CustomizeTrayIcon"))
{
HICON hIcon=::LoadIcon(AfxGetResourceHandle(),lpszIconResource);
if(hIcon==NULL)
return FALSE;
return InitializeTrayIcon(hIcon,nContextMenuResourceID,
lpszIconTooltip,bShowTrayIcon,bUseRightClick,
lpszIconSourceFileName,lpszProfileName);
}
virtual COXTaskbarIcon* GetTrayIcon()
{
ASSERT(GetTrayIconPage()!=NULL);
return GetTrayIconPage()->GetTrayIcon();
}
virtual COXCustomizeTrayIconPage* GetTrayIconPage() { return &m_pageTrayIcon; }
#endif // OX_CUSTOMIZE_TRAYICON
#ifdef OX_CUSTOMIZE_INSTANCE_MANAGER
// --- In : nMaxAllowedInstances - the maximum number of instances
// of the application allowed to run
// simultaneously (-1 means there is
// no limit)
// lpszProfileName - the name of the hive in the registry
// where instance manager settings is
// saved. If non-NULL value is set then
// settings is retrieved from the
// registry right away. These can
// overwrite the value specified in
// the previous parameter
// --- Out :
// --- Returns: TRUE if instance manager was initialized successfully;
// FALSE otherwise
// --- Effect : Initializes and retrieve settings for instance manager object
// that can be used in order to access instances of the same
// application running simultaneously
virtual BOOL InitializeInstanceManager(
int nMaxAllowedInstances=OX_MAX_NUM_INSTANCES_IN_LIST,
LPCTSTR lpszProfileName=_T("CustomizeInstanceManager"))
{
ASSERT(GetInstanceManagerPage()!=NULL);
return GetInstanceManagerPage()->
InitializeInstanceManager(nMaxAllowedInstances,lpszProfileName);
}
// --- In :
// --- Out :
// --- Returns: A pointer to internal COXInstanceManager object
// --- Effect : Retrieves internal COXInstanceManager object
virtual COXInstanceManager* GetInstanceManager()
{
ASSERT(GetInstanceManagerPage()!=NULL);
return GetInstanceManagerPage()->GetInstanceManager();
}
// --- In : bActivatePrevious - if TRUE then in the case the
// number of allowed instances
// has been reached, the last created
// instance will be activated
// --- Out :
// --- Returns: TRUE if the maximum allowed number of instances has been reached;
// FALSE otherwise
// --- Effect : Retrieves a flag that specifies if the maximum allowed number of
// instances has been reached. This function must be called in
// OnCreate() handler of main window of the application before
// calling the default implementation. In the case it returns TRUE
// you have to return -1 right away; otherwise you can go on
// with creation of the main window of the application
virtual BOOL CheckMaxAllowedInstances(BOOL bActivatePrevious=TRUE)
{
ASSERT(GetInstanceManager()!=NULL);
return GetInstanceManager()->CheckMaxAllowedInstances(bActivatePrevious);
}
// --- In :
// --- Out :
// --- Returns: A pointer to Instance Manager page
// --- Effect : Retrieves a pointer to Instance Manager page. This page can
// be used to limit the number of simultaneously running instances
// of the application. Also it lists all running instances and
// allows you to apply some standard operations to them
// ("Close","Switch to...","Bring To Front","Maximize",
// "Minimize","Restore")
virtual COXCustomizeInstanceManagerPage* GetInstanceManagerPage()
{
return &m_pageInstanceManager;
}
#endif // OX_CUSTOMIZE_INSTANCE_MANAGER
#ifdef OX_CUSTOMIZE_SPLASHWINDOW
virtual BOOL InitializeSplashWindow(UINT nBitmapResourceID,
BOOL bShowSplashWnd=TRUE, int nDisplayFor=-1,
BOOL bUserCanCancel=FALSE, COLORREF clrTransparent=CLR_DEFAULT,
LPPOINT pColorPoint=NULL, BYTE nTolerance=0,
LPCTSTR lpszProfileName=_T("CustomizeSplashWindow"))
{
ASSERT(GetSplashWindowPage()!=NULL);
return GetSplashWindowPage()->InitializeSplashWindow(nBitmapResourceID,
bShowSplashWnd,nDisplayFor,bUserCanCancel,clrTransparent,pColorPoint,
nTolerance,lpszProfileName);
}
virtual COXSplashWnd* GetSplashWindow()
{
ASSERT(GetSplashWindowPage()!=NULL);
return GetSplashWindowPage()->GetSplashWindow();
}
virtual COXCustomizeSplashWindowPage* GetSplashWindowPage() {
return &m_pageSplashWindow;
}
#endif // OX_CUSTOMIZE_SPLASHWINDOW
#ifdef OX_CUSTOMIZE_INTELLIMOUSE
virtual BOOL InitializeIntelliMouse(BOOL bSupportIntelliMouse=TRUE,
UINT nStartEventID=WM_MBUTTONDOWN, DWORD dwKeyState=0, BOOL bOnlyViews=TRUE,
LPCTSTR lpszProfileName=_T("CustomizeIntelliMouse"))
{
ASSERT(GetIntelliMousePage()!=NULL);
return GetIntelliMousePage()->InitializeIntelliMouse(bSupportIntelliMouse,
nStartEventID,dwKeyState,bOnlyViews,lpszProfileName);
}
virtual COXIntelliMouseOrganizer* GetIntelliMouseOrganizer()
{
ASSERT(GetIntelliMousePage()!=NULL);
return GetIntelliMousePage()->GetIntelliMouseOrganizer();
}
virtual COXCustomizeIntelliMousePage* GetIntelliMousePage() {
return &m_pageIntelliMouse;
}
#endif // OX_CUSTOMIZE_INTELLIMOUSE
#ifdef OX_CUSTOMIZE_SHORTKEYS
// --- In : pFrameWnd - pointer to main frame window of the
// application
// lpszProfileName - the name of the hive in the registry
// where updated accelerator tables contents
// is saved. If non-NULL value is set then
// the contents is retrieved from the registry
// and applied right away.
// --- Out :
// --- Returns: TRUE if information on the application's accelerator tables was
// initialized successfully; FALSE otherwise
// --- Effect : Initializes the information on the application's accelerator
// tables and retrieves their saved in the registry contents and
// applies it
virtual BOOL InitializeShortkeys(CFrameWnd* pFrameWnd,
LPCTSTR lpszProfileName=_T("CustomizeShortkeys"))
{
ASSERT(GetShortkeysPage()!=NULL);
return GetShortkeysPage()->InitializeShortkeys(pFrameWnd,lpszProfileName);
}
// --- In :
// --- Out :
// --- Returns: A pointer to COXShortkeysOrganizer object that is responsible for
// saving/loading accelerator table contents and applying it to the
// application
// --- Effect : Retrieves a pointer to internal COXShortkeysOrganizer object
virtual COXShortkeysOrganizer* GetShortkeysOrganizer()
{
ASSERT(GetShortkeysPage()!=NULL);
return GetShortkeysPage()->GetShortkeysOrganizer();
}
// --- In :
// --- Out :
// --- Returns: A pointer to Customize Shortkeys page
// --- Effect : Retrieves a pointer to Customize Shortkeys page. This page can
// be used to customize the contents of application's accelerator
// table. New shortkeys can be assigned to existing commands
// or removed from accelerator table.
virtual COXCustomizeShortkeysPage* GetShortkeysPage() { return &m_pageShortkeys; }
#endif // OX_CUSTOMIZE_SHORTKEYS
//
////////////////////////////////////
// Generated message map functions
protected:
//{{AFX_MSG(COXCustomizeManager)
virtual BOOL OnInitDialog();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI);
afx_msg void OnButtonApply();
virtual void OnCancel();
virtual void OnOK();
afx_msg void OnDestroy();
//}}AFX_MSG
afx_msg void OnActivateItem(NMHDR* pNotifyStruct, LRESULT* result);
afx_msg void OnGetItemInfoTip(NMHDR* pNotifyStruct, LRESULT* result);
afx_msg LRESULT OnKickIdle(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
///////////////////////////////////////////////////////////////////////
#endif // !defined(_OXCUSTOMIZEMANAGER_H__)
|
[
"[email protected]"
] |
[
[
[
1,
1351
]
]
] |
cf95aed4a29dec8a076303423d07b3378f7a0a2a
|
dd738ae41d10b95f71680d9f38e6dd31f2e6d113
|
/Controllers/Shoot.cpp
|
f937ebfce8f289ef25b85a6e452f7137a7f08a8e
|
[] |
no_license
|
mbh1100/frc2009
|
8ece016010aa170b1b34859f58d5a9d9447bad2e
|
62808972421e8823657ed69fbdf8f80367a5685e
|
refs/heads/master
| 2021-01-23T08:38:57.103159 | 2009-02-17T02:43:17 | 2009-02-17T02:43:17 | 34,929,820 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,381 |
cpp
|
#include "Shoot.h"
Shoot::Shoot(AdvMotorController* shootMotorOne, AdvMotorController* shootMotorTwo, AdvMotorController* leftHelixMotor, AdvMotorController* rightHelixMotor)
{
m_shootMotorOne = shootMotorOne;
m_shootMotorTwo = shootMotorTwo;
m_leftHelixMotor = leftHelixMotor;
m_rightHelixMotor = rightHelixMotor;
m_leftTimer = new Timer();
m_rightTimer = new Timer();
m_timer = new Timer();
m_direction = 0;
m_distance = 3;
m_ballsLeft = 0;
m_ballsRight = 0;
m_limitLeft = false;
m_limitRight = false;
m_leftPressed = false;
m_rightPressed = false;
}
Shoot::~Shoot()
{
}
void Shoot::InitialSet(int ballsLeft, int ballsRight, float direction)
{
m_ballsLeft = ballsLeft;
m_ballsRight = ballsRight;
m_direction = direction;
if (m_direction <= .5)
{
m_direction = kLeft;
}
else
{
m_direction = kRight;
}
m_timer->Start();
}
void Shoot::Update(float distance, bool limitLeft, bool limitRight)
{
m_distance = distance;
m_limitLeft = limitLeft;
m_limitRight = limitRight;
m_shootMotorOne->Set(Distance());
//m_shootMotorOne->Set(.98);
m_shootMotorTwo->Set(.98);
printf("ShooterSpeed: %lf\r\n", m_shootMotorOne->Get());
printf("Distance Value: %lf\r\n", m_distance);
SideShooting();
CountBallsLeft();
CountBallsRight();
}
float Shoot::Distance()
{
if (m_distance < 200)
{
return .17;
}
else if (m_distance < 350)
{
return .33;
}
else if (m_distance < 500)
{
return .5;
}
else if (m_distance < 650)
{
return .67;
}
else if (m_distance < 775)
{
return .83;
}
else
{
return .98f;
}
}
int Shoot::CountBallsLeft()
{
if (m_limitLeft && !m_leftPressed && m_leftHelixMotor != 0)
{
m_leftPressed = true;
m_ballsLeft--;
m_leftTimer->Reset();
m_leftTimer->Start();
}
if (m_leftPressed && m_leftTimer->Get() >= kTimePerShot)
{
m_leftPressed = false;
m_leftTimer->Stop();
}
return m_ballsLeft;
}
int Shoot::CountBallsRight()
{
if (m_limitRight && !m_rightPressed && m_rightHelixMotor != 0)
{
m_rightPressed = true;
m_ballsRight--;
m_rightTimer->Reset();
m_rightTimer->Start();
}
if (m_rightPressed && m_rightTimer->Get() >= kTimePerShot)
{
m_rightPressed = false;
m_rightTimer->Stop();
}
return m_ballsRight;
}
void Shoot::SideShooting()
{
if (m_timer->Get() < 2)
{
if (m_direction == 0)
{
if (m_ballsRight > 0)
{
m_rightHelixMotor->Set(.98);
m_leftHelixMotor->Set(0.0);
}
else if (m_ballsLeft > 0)
{
m_rightHelixMotor->Set(0.0);
m_leftHelixMotor->Set(.98);
}
else
{
m_rightHelixMotor->Set(.98);
m_leftHelixMotor->Set(.98);
}
}
else
{
if (m_ballsLeft > 0)
{
m_rightHelixMotor->Set(0.0);
m_leftHelixMotor->Set(.98);
}
else if (m_ballsRight > 0)
{
m_rightHelixMotor->Set(.98);
m_leftHelixMotor->Set(0.0);
}
else
{
m_rightHelixMotor->Set(.98);
m_leftHelixMotor->Set(.98);
}
}
}
else
{
m_rightHelixMotor->Set(.98);
m_leftHelixMotor->Set(.98);
}
}
void Shoot::Disable()
{
m_rightHelixMotor->Set(0.0);
m_leftHelixMotor->Set(0.0);
m_shootMotorOne->Set(0.0);
m_shootMotorTwo->Set(0.0);
m_timer->Stop();
m_timer->Reset();
}
|
[
"first.team1100@ddad09ec-df38-11dd-a8eb-ddf07f3c1838",
"Hunter0000@ddad09ec-df38-11dd-a8eb-ddf07f3c1838"
] |
[
[
[
1,
2
],
[
4,
190
]
],
[
[
3,
3
]
]
] |
a2fadbf2dedcd72c233e1fcff730bddbb36a853e
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/nebula2/src/shadow2/nskinnedshadowcaster2_main.cc
|
fc5a60179f00591b047d81a574873b8fdafcb1da
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 10,830 |
cc
|
#include "precompiled/pchnnebula.h"
//------------------------------------------------------------------------------
// nskinnedshadowcaster2_main.cc
// (C) 2005 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "shadow2/nskinnedshadowcaster2.h"
#include "shadow2/nshadowserver2.h"
nNebulaClass(nSkinnedShadowCaster2, "nshadowcaster2");
//------------------------------------------------------------------------------
/**
*/
nSkinnedShadowCaster2::nSkinnedShadowCaster2() :
charSkeleton(0),
charSkeletonDirty(false)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nSkinnedShadowCaster2::~nSkinnedShadowCaster2()
{
if (this->IsLoaded())
{
this->Unload();
}
}
//------------------------------------------------------------------------------
/**
This initializes all mesh resources needed by nSkinnedShadowCaster2.
*/
bool
nSkinnedShadowCaster2::LoadResource()
{
n_assert(!this->IsLoaded());
n_assert(!this->refIndexBuffer.isvalid());
n_assert(!this->refBindPoseMesh.isvalid());
n_assert(!this->refSkinnedMesh.isvalid());
nGfxServer2* gfxServer = nGfxServer2::Instance();
// load the bind pose mesh, this will reside in system memory and
// will ever only be read by the CPU as the source for skinning
nMesh2* bindPoseMesh = gfxServer->NewMesh(this->GetFilename().Get());
this->refBindPoseMesh = bindPoseMesh;
if (!bindPoseMesh->IsLoaded())
{
bindPoseMesh->SetFilename(this->GetFilename().Get());
bindPoseMesh->SetUsage(nMesh2::ReadOnly);
if (!bindPoseMesh->Load())
{
n_error("Error loading shadow skin mesh '%s'!", this->GetFilename().Get());
bindPoseMesh->Release();
return false;
}
}
// create the skinned mesh, this will be filled by the CPU with skinned
// data, properly layed out for shadow volume extrusion (which means
// vertices will be duplicated)
nString skinnedMeshName = this->GetFilename() + "s";
nMesh2* skinnedMesh = gfxServer->NewMesh(skinnedMeshName.Get());
this->refSkinnedMesh = skinnedMesh;
if (!skinnedMesh->IsLoaded())
{
skinnedMesh->SetVertexUsage(nMesh2::ReadWrite | nMesh2::NeedsVertexShader);
skinnedMesh->SetIndexUsage(nMesh2::ReadOnly);
skinnedMesh->SetVertexComponents(nMesh2::Coord4);
skinnedMesh->SetNumVertices(bindPoseMesh->GetNumVertices() * 2);
skinnedMesh->SetNumIndices(bindPoseMesh->GetNumIndices());
skinnedMesh->SetNumEdges(bindPoseMesh->GetNumEdges());
int numGroups = bindPoseMesh->GetNumGroups();
skinnedMesh->SetNumGroups(numGroups);
int groupIndex;
for (groupIndex = 0; groupIndex < numGroups; groupIndex++)
{
nMeshGroup group = bindPoseMesh->Group(groupIndex);
group.SetFirstVertex(group.GetFirstVertex() * 2);
group.SetNumVertices(group.GetNumVertices() * 2);
skinnedMesh->Group(groupIndex) = group;
}
skinnedMesh->Load();
// transfer vertices from bindPoseMesh and duplicate them on
// the way (one version for the un-extruded and one for the
// extruded position)
int numVertices = bindPoseMesh->GetNumVertices();
int srcVertexWidth = bindPoseMesh->GetVertexWidth();
float* srcVertices = bindPoseMesh->LockVertices();
float* dstVertices = skinnedMesh->LockVertices();
int vertexIndex;
for (vertexIndex = 0; vertexIndex < numVertices; vertexIndex++)
{
int srcOffset = vertexIndex * srcVertexWidth;
// write unextruded vertex
*dstVertices++ = srcVertices[srcOffset];
*dstVertices++ = srcVertices[srcOffset + 1];
*dstVertices++ = srcVertices[srcOffset + 2];
*dstVertices++ = 0.0f;
// write extruded vertex
*dstVertices++ = srcVertices[srcOffset];
*dstVertices++ = srcVertices[srcOffset + 1];
*dstVertices++ = srcVertices[srcOffset + 2];
*dstVertices++ = 1.0f;
}
bindPoseMesh->UnlockVertices();
skinnedMesh->UnlockVertices();
// transfer indices into skinned mesh and fix them according to the new vertex layout
int numIndices = bindPoseMesh->GetNumIndices();
ushort* srcIndices = bindPoseMesh->LockIndices();
ushort* dstIndices = skinnedMesh->LockIndices();
int ii;
for (ii = 0; ii < numIndices; ii++)
{
dstIndices[ii] = srcIndices[ii] * 2;
}
bindPoseMesh->UnlockIndices();
skinnedMesh->UnlockIndices();
// transfer indices into skinned mesh and fix their vertex indices according to the new vertex layout
int numEdges = bindPoseMesh->GetNumEdges();
nMesh2::Edge* srcEdges = bindPoseMesh->LockEdges();
nMesh2::Edge* dstEdges = skinnedMesh->LockEdges();
int edgeIndex;
for (edgeIndex = 0; edgeIndex < numEdges; edgeIndex++)
{
dstEdges[edgeIndex] = srcEdges[edgeIndex];
dstEdges[edgeIndex].vIndex[0] *= 2;
dstEdges[edgeIndex].vIndex[1] *= 2;
}
bindPoseMesh->UnlockEdges();
skinnedMesh->UnlockEdges();
}
// initialize parent class buffers
this->AllocateBuffers(this->refSkinnedMesh);
this->SetState(Valid);
return true;
}
//------------------------------------------------------------------------------
/**
Unload resources.
*/
void
nSkinnedShadowCaster2::UnloadResource()
{
n_assert(Unloaded != this->GetState());
// unload the skinned mesh
if (this->refSkinnedMesh.isvalid())
{
this->refSkinnedMesh->Release();
this->refSkinnedMesh.invalidate();
}
// unload the bind pose mesh
if (this->refBindPoseMesh.isvalid())
{
this->refBindPoseMesh->Release();
this->refBindPoseMesh.invalidate();
}
// unload parent class buffers
this->ReleaseBuffers();
this->SetState(Unloaded);
}
//------------------------------------------------------------------------------
/**
Setup the shadow volume for this caster. This method is called by
nShadowServer2 right before rendering the shadow volume. Implement this
method in a derived class.
*/
void
nSkinnedShadowCaster2::SetupShadowVolume(const nLight& light, const matrix44& invModelLightMatrix)
{
nShadowServer2* shadowServer = nShadowServer2::Instance();
nGfxServer2* gfxServer = nGfxServer2::Instance();
// FIXME: can we optimize all of this more through some sort of lazy evaluation?
if (this->charSkeletonDirty)
{
this->UpdateSkinning();
this->UpdateFaceNormalsAndMidpoints(this->refSkinnedMesh);
}
// split faces into lit and unlit
if (this->charSkeletonDirty || this->LightingChanged(light, invModelLightMatrix))
{
this->UpdateFaceLitFlags(light, invModelLightMatrix);
}
// write shadow volume indices
if (shadowServer->GetUseZFail())
{
this->BeginWriteIndices(this->refSkinnedMesh);
this->WriteSideIndices();
this->WriteCapIndices(true);
this->WriteCapIndices(false);
this->EndWriteIndices();
}
else
{
this->BeginWriteIndices(this->refSkinnedMesh);
this->WriteSideIndices();
this->EndWriteIndices();
}
// prepare for rendering
gfxServer->SetMesh(this->refSkinnedMesh, this->refIndexBuffer);
const nMeshGroup& meshGroup = this->refSkinnedMesh->Group(this->meshGroupIndex);
gfxServer->SetVertexRange(meshGroup.GetFirstVertex(), meshGroup.GetNumVertices());
gfxServer->SetIndexRange(0, this->GetNumDrawIndices());
// not forgetting: resetting da dirty flags!
this->charSkeletonDirty = false;
}
//------------------------------------------------------------------------------
/**
Actually render the shadow volume. This can be called 1 or 2 times by
the shadow server, depending on whether 2-sided stencil operations are
availalable.
*/
void
nSkinnedShadowCaster2::RenderShadowVolume()
{
nGfxServer2* gfxServer = nGfxServer2::Instance();
gfxServer->DrawIndexedNS(nGfxServer2::TriangleList);
}
//------------------------------------------------------------------------------
/**
This method performs the actual skinning on the cpu and writes the
skinned vertices into the refSkinnedMesh. A valid and uptodate character
skeleton must be set through
FIXME: performance optimization: convert float joint indices to integer
during load time?
*/
void
nSkinnedShadowCaster2::UpdateSkinning()
{
n_assert(this->charSkeleton);
nMesh2* srcMesh = this->refBindPoseMesh;
nMesh2* dstMesh = this->refSkinnedMesh;
const nMeshGroup& srcGroup = srcMesh->Group(this->meshGroupIndex);
const nMeshGroup& dstGroup = dstMesh->Group(this->meshGroupIndex);
int numSrcVertices = srcGroup.GetNumVertices();
N_IFDEF_ASSERTS(int numDstVertices = )dstGroup.GetNumVertices();
n_assert((2 * numSrcVertices) == numDstVertices);
float* srcVertices = srcMesh->LockVertices() + srcGroup.GetFirstVertex();
float* dstVertices = dstMesh->LockVertices() + dstGroup.GetFirstVertex();
vector3 v;
int index;
for (index = 0; index < numSrcVertices; index++)
{
// perform weighted skinning
const vector3& srcVec = *((vector3*)srcVertices);
float* weights = &srcVertices[3];
float* indices = &srcVertices[7];
v.set(0.0f, 0.0f, 0.0f);
int i;
for (i = 0; i < 4; i++)
{
if (weights[i] > 0.0f)
{
const matrix44& skinMatrix = this->charSkeleton->GetJointAt(int(indices[i])).GetSkinMatrix44();
skinMatrix.weighted_madd(srcVec, v, weights[i]);
}
}
// write skinned vertex to unextruded and extruded vertex position, note, we are filling
// a dynamic vertex buffer which will be discarded after rendering, so we NEED to write
// seeminigly constant data (the extrude weights) as well!
*dstVertices++ = v.x; *dstVertices++ = v.y; *dstVertices++ = v.z; *dstVertices++ = 0.0f;
*dstVertices++ = v.x; *dstVertices++ = v.y; *dstVertices++ = v.z; *dstVertices++ = 1.0f;
// set to next src vertex
srcVertices += 11;
}
dstMesh->UnlockVertices();
srcMesh->UnlockVertices();
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
296
]
]
] |
1102a463ca2cba76ab08e22b096d05ef1529dcf5
|
59166d9d1eea9b034ac331d9c5590362ab942a8f
|
/FrustumTerrain/DynamicGroupUpdateCallback.h
|
e70de5a49cfe1296baec6a3caa14d5336749d409
|
[] |
no_license
|
seafengl/osgtraining
|
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
|
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
|
refs/heads/master
| 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 1,143 |
h
|
#ifndef _DYNAMIC_GROUP_UPDATE_CALLBACK_H_
#define _DYNAMIC_GROUP_UPDATE_CALLBACK_H_
#include "VisiblePatchArray.h"
#include <osg/NodeCallback>
#include <osg/Geode>
#include <osg/Referenced>
#include <osg/ref_ptr>
#include <osg/Image>
#include <map>
class DynamicGroupUpdateCallback : public osg::NodeCallback
{
public:
DynamicGroupUpdateCallback();
~DynamicGroupUpdateCallback();
virtual void operator()( osg::Node* node, osg::NodeVisitor* nv );
private:
//поиск максимального размера патча
int FindMax();
//обновить коэффициенты из файла
void UpdateKof();
//обновить статистику
void UpdateStatistic();
//класс формирующий массив видимых патчей
VisiblePatchArray m_VisiblePatchArray;
//изображение содержащие индексы
osg::ref_ptr<osg::Image> m_ImageIndex;
//масштаб и смещение
double m_dAdd;
double m_dScale;
//статистика
std::map< int , int > m_Statistic;
};
#endif //_DYNAMIC_GROUP_UPDATE_CALLBACK_H_
|
[
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
] |
[
[
[
1,
46
]
]
] |
00abc5642edc50638de62b5f4792d1a530319163
|
8ce47e73afa904a145a1104fa8eaa71e3a237907
|
/Robot/controller/NXTBluetooth/temperature.h
|
e991606b87cd65a2bca18f01fa42ded1bd5af8d3
|
[] |
no_license
|
nobody/magiclegoblimps
|
bc4f1459773773599ec397bdd1a43b1c341ff929
|
d66fe634cc6727937a066118f25847fa7d71b8f6
|
refs/heads/master
| 2021-01-23T15:42:15.729310 | 2010-05-05T03:15:00 | 2010-05-05T03:15:00 | 39,790,220 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,362 |
h
|
#ifndef TEMPERATURE_SENSOR_H
#define TEMPERATURE_SENSOR_H
#include "Sensor.h"
#include "connection.h"
#include "dllexport.h"
/**
* Enumeration for different temperarure sensor modes
* @see Temperature
*/
enum Temp_mode{
CELSIUS = 21,
FAHRENHEIT = 22
};
using namespace std;
/**
* Class for RCX temperature sensor
*/
class DllExport Temperature : public Sensor{
public:
/**
* Constructor for the temperature sensor (default TEMP_MODE is celsius)
* @param port [which sensor port to use]
* @param *connection [attach a connection]
* @param mode [set the TEMP mode to either CELSIUS or FAHRENHEIT (default is CELSIUS)]
*/
Temperature(Sensor_port port, Connection* connection, Temp_mode mode = CELSIUS):Sensor(port, connection, TEMPERATURE, CELSIUS_MODE){
if(mode == FAHRENHEIT){
sensor_mode = FAHRENHEIT_MODE;
}
}
~Temperature(){};
/**
* Get the sensor reading as a string
* (init method will be called if the sensor has not been initialized)
* @return sensor reading as a string + either " Celsius" or " Fahrenheit"
*/
string print(){
if(sensor_mode == FAHRENHEIT_MODE){
return Sensor::print() + " Fahrenheit";
}
else{
return Sensor::print() + " Celsius";
}
}
};
#endif
|
[
"eXceLynX@445d4ad4-0937-11df-b996-818f58f34e26"
] |
[
[
[
1,
51
]
]
] |
db39e84b3dcd79d670e2b1144f06e64111fde8c0
|
fc4946d917dc2ea50798a03981b0274e403eb9b7
|
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10ShaderResourceView1.h
|
1f69b20b4d520e8dac32ac917b3351a0bc746efb
|
[] |
no_license
|
midnite8177/phever
|
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
|
45529e80ebf707e7299887165821ca360aa1907d
|
refs/heads/master
| 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,354 |
h
|
//Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "D3D10ShaderResourceView.h"
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D10 {
using namespace System;
/// <summary>
/// A shader-resource-view interface specifies the subresources a shader can access during rendering. Examples of shader resources include a constant buffer, a texture buffer, a texture or a sampler.
/// <para>(Also see DirectX SDK: ID3D10ShaderResourceView1)</para>
/// </summary>
public ref class ShaderResourceView1 :
public ShaderResourceView
{
public:
/// <summary>
/// Get the shader resource view's description.
/// <para>(Also see DirectX SDK: ID3D10ShaderResourceView1::GetDesc1)</para>
/// </summary>
/// <returns>A ShaderResourceViewDescription1 structure to be filled with data about the shader resource view.</returns>
property ShaderResourceViewDescription1 Description1
{
ShaderResourceViewDescription1 get();
}
internal:
ShaderResourceView1()
{ }
ShaderResourceView1(ID3D10ShaderResourceView1* pNativeID3D10ShaderResourceView1) : ShaderResourceView(pNativeID3D10ShaderResourceView1)
{ }
};
} } } }
|
[
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] |
[
[
[
1,
35
]
]
] |
ed05e10b4396726133f5b946e1900337e49ce178
|
080941f107281f93618c30a7aa8bec9e8e2d8587
|
/src/conditioners/linestrips2lines_core.cpp
|
3806511de95e65cb0ab153aaf3900c1138038b83
|
[
"MIT"
] |
permissive
|
scoopr/COLLADA_Refinery
|
6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4
|
3a5ad1a81e0359f9025953e38e425bc10b5bf6c5
|
refs/heads/master
| 2021-01-22T01:55:14.642769 | 2009-03-10T21:31:04 | 2009-03-10T21:31:04 | 194,828 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,137 |
cpp
|
/*
The MIT License
Copyright 2006 Sony Computer Entertainment Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "linestrips2lines.h"
bool Linestrips2lines::init()
{
addBoolOption( "verbose", "verbose", "verbose", true);
return true;
}
int Linestrips2lines::execute()
{
bool verbose = false;
getBoolOption("v", verbose);
int error = 0;
// How many geometry elements are there?
int geometryElementCount = (int)(_dae->getDatabase()->getElementCount(NULL, "geometry", getInput(0).c_str()));
// if(verbose) cerr<<"There are "<<geometryElementCount<<" geometry elements in this file\n";
for(int currentGeometry = 0; currentGeometry < geometryElementCount; currentGeometry++)
{
// Find the next geometry element
domGeometry *thisGeometry;
error = _dae->getDatabase()->getElement((daeElement**)&thisGeometry,currentGeometry, NULL, "geometry", getInput(0).c_str());
// Get the mesh out of the geometry
domMesh *thisMesh = thisGeometry->getMesh();
if (thisMesh == 0) continue;
// Loop over all the linestrip elements
int linestripCount = (int)(thisMesh->getLinestrips_array().getCount());
if (linestripCount == 0)
continue;
domLines *thisLines = (domLines *)thisMesh->createAndPlace("lines");
domP* lineP = (domP*) thisLines->createAndPlace("p");
// if(verbose) cerr<<"There are "<<linestripCount<<" linestrip elements in this file\n";
for(int currLinestrip = 0; currLinestrip<linestripCount; currLinestrip++)
{
// Get the linestrip out of the mesh
// Always get index 0 because every pass through this loop deletes the <linestrips> element as it finishes with it
domLinestrips *thisLinestrip = thisMesh->getLinestrips_array().get(0);
// add inputs
unsigned int offsetcount = 0;
for(unsigned int i=0; i<thisLinestrip->getInput_array().getCount(); i++)
{
unsigned int tempoffset = (unsigned int) thisLinestrip->getInput_array()[i]->getOffset();
if (offsetcount < tempoffset) offsetcount = tempoffset;
thisLines->placeElement( thisLinestrip->getInput_array()[i]->clone() );
}
offsetcount++; //offset is 1 start
// add names
if (thisLinestrip->getName())
thisLines->setName(thisLinestrip->getName());
// set materials
thisLines->setMaterial(thisLinestrip->getMaterial());
// set P
int pArrayCount = (int)thisLinestrip->getP_array().getCount();
unsigned int totalLineCount = 0;
for (int i = 0; i < pArrayCount; i++) {
domListOfUInts linestripValue = thisLinestrip->getP_array()[i]->getValue();
unsigned int lineCount = (unsigned int) thisLinestrip->getP_array()[i]->getValue().getCount()/offsetcount - 1;
for(unsigned int i=0; i<lineCount; i=i+1)
{
for(unsigned int j=0; j<offsetcount; j++)
lineP->getValue().append(linestripValue[i*offsetcount+j]);
for(unsigned int j=0; j<offsetcount; j++)
lineP->getValue().append(linestripValue[(i+1)*offsetcount+j]);
}
totalLineCount += lineCount;
}
thisLines->setCount(totalLineCount);
thisMesh->removeChildElement(thisLinestrip);
}
}
return 0;
}
Conditioner::Register<Linestrips2linesProxy> linestrips2linesProxy;
|
[
"alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"hnz@7d79dae2-2c22-0410-a73c-a02ad39e49d4"
] |
[
[
[
1,
1
],
[
23,
104
]
],
[
[
2,
22
]
],
[
[
105,
105
]
]
] |
4dec991ac372d0c83d70f8e5e7f9db9145622f72
|
b2d46af9c6152323ce240374afc998c1574db71f
|
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/numeric/conversion/test/numeric_cast_test.cpp
|
dca43be28e13a7cd306e73b0e84f4710865fc7a7
|
[] |
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 | 3,242 |
cpp
|
// boost utility cast test program -----------------------------------------//
// (C) Copyright Beman Dawes, Dave Abrahams 1999. 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 for most recent version including documentation.
// Revision History
// 28 Set 04 taken from the old cast library (Fernando Cacciola)
#include <iostream>
#include <climits>
#include <cfloat> // for DBL_MAX (Peter Schmid)
#include <boost/numeric/conversion/cast.hpp>
#include "boost/test/minimal.hpp"
# if SCHAR_MAX == LONG_MAX
# error "This test program doesn't work if SCHAR_MAX == LONG_MAX"
# endif
using namespace boost;
using std::cout;
int test_main( int argc, char * argv[] )
{
# ifdef NDEBUG
cout << "NDEBUG is defined\n";
# else
cout << "NDEBUG is not defined\n";
# endif
cout << "\nBeginning tests...\n";
// test implicit_cast and numeric_cast -------------------------------------//
// tests which should succeed
long small_value = 1;
long small_negative_value = -1;
long large_value = LONG_MAX;
long large_negative_value = LONG_MIN;
signed char c = 0;
c = large_value; // see if compiler generates warning
c = numeric_cast<signed char>( small_value );
BOOST_CHECK( c == 1 );
c = 0;
c = numeric_cast<signed char>( small_value );
BOOST_CHECK( c == 1 );
c = 0;
c = numeric_cast<signed char>( small_negative_value );
BOOST_CHECK( c == -1 );
// These tests courtesy of Joe R NWP Swatosh<[email protected]>
BOOST_CHECK( 0.0f == numeric_cast<float>( 0.0 ) );
BOOST_CHECK( 0.0 == numeric_cast<double>( 0.0 ) );
// tests which should result in errors being detected
bool caught_exception = false;
try { c = numeric_cast<signed char>( large_value ); }
catch ( numeric::bad_numeric_conversion )
{ cout<<"caught bad_numeric_cast #1\n"; caught_exception = true; }
BOOST_CHECK ( caught_exception );
caught_exception = false;
try { c = numeric_cast<signed char>( large_negative_value ); }
catch ( numeric::bad_numeric_conversion )
{ cout<<"caught bad_numeric_cast #2\n"; caught_exception = true; }
BOOST_CHECK ( caught_exception );
unsigned long ul;
caught_exception = false;
try { ul = numeric_cast<unsigned long>( large_negative_value ); }
catch ( numeric::bad_numeric_conversion )
{ cout<<"caught bad_numeric_cast #3\n"; caught_exception = true; }
BOOST_CHECK ( caught_exception );
caught_exception = false;
try { ul = numeric_cast<unsigned long>( small_negative_value ); }
catch ( numeric::bad_numeric_conversion )
{ cout<<"caught bad_numeric_cast #4\n"; caught_exception = true; }
BOOST_CHECK ( caught_exception );
caught_exception = false;
try { numeric_cast<int>( DBL_MAX ); }
catch ( numeric::bad_numeric_conversion )
{ cout<<"caught bad_numeric_cast #5\n"; caught_exception = true; }
BOOST_CHECK ( caught_exception );
return 0 ;
} // main
|
[
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] |
[
[
[
1,
97
]
]
] |
e9d72a0eab6e9870d1e57e67b0e93a8154de25d4
|
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
|
/KylinSdk/Standard/Source/AssertX.cpp
|
7e955630a831cef1da14f52b6bcb65258b4d68a2
|
[] |
no_license
|
dzw/kylin001v
|
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
|
6cec2ed2e44cea42957301ec5013d264be03ea3e
|
refs/heads/master
| 2021-01-10T12:27:26.074650 | 2011-05-30T07:11:36 | 2011-05-30T07:11:36 | 46,501,473 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 2,704 |
cpp
|
//--------------------------------------------------------------------------------
//
// Filename : Assert.cpp
//
//--------------------------------------------------------------------------------
// include files
#include "stdpch.h"
#include "Assertx.h"
#include <time.h>
#include "Utility.h"
#ifdef __LINUX__
#include <execinfo.h>
#endif
VOID __show__( const CHAR* szTemp )
{
#ifdef __LINUX__
printf("Assert:%s",szTemp);
#endif
// //保存日志
// #ifndef GAME_CLIENT
// FILE* f = fopen( "./Log/assert.log", "a" ) ;
// fwrite( szTemp, 1, strlen(szTemp), f ) ;
// fwrite( "\r\n", 1, 2, f ) ;
// fclose(f) ;
// #endif
#if defined(WIN32)
static MyLock lock ;
//if( g_Command_Assert!=1 )
{
lock.Lock() ;
INT iRet = ::MessageBoxA( NULL, szTemp, "异常", MB_OK ) ;
lock.Unlock() ;
}
#elif defined(__LINUX__)
#endif
// #ifdef _DEBUG
// throw(std::string(szTemp));
// #else
// throw(1);
// #endif
}
VOID __messagebox__(const CHAR*msg )
{
#if defined(WIN32)
::MessageBoxA( NULL, msg, "信息", MB_OK ) ;
#elif defined(__LINUX__)
#endif
}
//--------------------------------------------------------------------------------
//
// __assert__
//
//
//--------------------------------------------------------------------------------
VOID __assert__ ( const CHAR * file , UINT line , const CHAR * func , const CHAR * expr )
{
CHAR szTemp[1024] = {0};
#ifdef __LINUX__ //换个格式
sprintf( szTemp, "[%s][%d][%s][%s]\n", file, line, func, expr ) ;
#else
sprintf( szTemp, "[%s][%d][%s][%s]", file, line, func, expr ) ;
#endif
__show__(szTemp) ;
}
VOID __assertex__ ( const CHAR * file , UINT line , const CHAR * func , const CHAR * expr ,const CHAR* msg)
{
CHAR szTemp[1024] = {0};
#ifdef __LINUX__
sprintf( szTemp, "[%s][%d][%s][%s]\n[%s]\n", file, line, func, expr ,msg ) ;
#else
sprintf( szTemp, "[%s][%d][%s][%s]\n[%s]", file, line, func, expr ,msg ) ;
#endif
__show__(szTemp) ;
}
VOID __assertspecial__ ( const CHAR * file , UINT line , const CHAR * func , const CHAR * expr ,const CHAR* msg)
{
CHAR szTemp[1024] = {0};
#ifdef __LINUX__
sprintf( szTemp, "S[%s][%d][%s][%s]\n[%s]\n", file, line, func, expr ,msg ) ;
#else
sprintf( szTemp, "S[%s][%d][%s][%s]\n[%s]", file, line, func, expr ,msg ) ;
#endif
__show__(szTemp) ;
}
//--------------------------------------------------------------------------------
//
//
//--------------------------------------------------------------------------------
VOID __protocol_assert__ ( const CHAR * file , UINT line , const CHAR * func , const CHAR * expr )
{
printf( "[%s][%d][%s][%s]", file, line, func, expr ) ;
}
|
[
"[email protected]"
] |
[
[
[
1,
106
]
]
] |
f7e24bec1b0cc0b4889541ddc00f23e2329609a0
|
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
|
/projects/MainUI/GuiLib1.5/GuiLabelButton.h
|
499a0d3a0e94b78c5f0672f6115a130717eda2e3
|
[] |
no_license
|
weimingtom/httpcontentparser
|
4d5ed678f2b38812e05328b01bc6b0c161690991
|
54554f163b16a7c56e8350a148b1bd29461300a0
|
refs/heads/master
| 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,484 |
h
|
/****************************************************************************
* *
* GuiToolKit *
* (MFC extension) *
* Created by Francisco Campos G. www.beyondata.com [email protected] *
*--------------------------------------------------------------------------*
* *
* This program is free software;so you are free to use it any of your *
* applications (Freeware, Shareware, Commercial),but leave this header *
* intact. *
* *
* These files are provided "as is" without warranty of any kind. *
* *
* GuiToolKit is forever FREE CODE !!!!! *
* *
*--------------------------------------------------------------------------*
* Created by: Francisco Campos G. *
* Bug Fixes and improvements : (Add your name) *
* -Francisco Campos *
* *
****************************************************************************/
#pragma once
#include "guitoolbutton.h"
class CGuiLabelButton : public CGuiToolButton
{
DECLARE_DYNAMIC(CGuiLabelButton)
public:
CGuiLabelButton(void);
virtual ~CGuiLabelButton(void);
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
void DrawUnderLine(BOOL bDraw=TRUE){m_bDrawLine=bDraw; Invalidate(); UpdateData();};
protected:
CFont m_cfont;
BOOL m_bDrawLine;
};
|
[
"[email protected]"
] |
[
[
[
1,
39
]
]
] |
6b431ace572688e18c645efc16d47c0588bd4e08
|
23017336d25e6ec49c4a51f11c1b3a3aa10acf22
|
/csc3750/prog1/AffineTransforms.h
|
3f3fbf9f5f0695fe5a8d537b13362eff2ad187aa
|
[] |
no_license
|
tjshaffer21/School
|
5e7681c96e0c10966fc7362931412c4244507911
|
4aa5fc3a8bbbbb8d46d045244e8a7f84e71c768f
|
refs/heads/master
| 2020-05-27T19:05:06.422314 | 2011-05-17T19:55:40 | 2011-05-17T19:55:40 | 1,681,224 | 1 | 1 | null | 2017-07-29T13:35:54 | 2011-04-29T15:36:55 |
C++
|
UTF-8
|
C++
| false | false | 355 |
h
|
#if !defined (AFFINETRANSFORMS_H)
#define AFFINETRANSFORMS_H
#include "Matrix.h"
class AffineTransforms
{
private:
public:;
static Matrix* scale(double x, double y, double z);
static Matrix* windowingTransform( double width, double height );
static Matrix* aspectRatio( double width, double height );
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
16
]
]
] |
3b36f4540d27bd842163a4b0ac4b54b80c3d1d95
|
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
|
/GameBaseCode/source/myrecord.h
|
0def1b8cac43ebb22f7d38dfe2a18a4b3c13ff7a
|
[] |
no_license
|
cronoszeu/revresyksgpr
|
78fa60d375718ef789042c452cca1c77c8fa098e
|
5a8f637e78f7d9e3e52acdd7abee63404de27e78
|
refs/heads/master
| 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null |
GB18030
|
C++
| false | false | 3,164 |
h
|
// myrecords.h 用于分解出myrecordset.h中的单个记录。
// 仙剑修,2002.9.12
#pragma once
class CCriticalSection;
class CMyDatabase;
class CMyRecord : public IRecord
{
protected: // interface
virtual IRecord* CreateNewRecord(DWORD idNewKey = NEWKEY_NONE);
virtual void Release() { delete this; }
virtual DWORD InsertRecord();
virtual bool UpdateRecord();
virtual bool DeleteRecord();
virtual int LoadInt (LPCTSTR szField);
virtual void SetInt (LPCTSTR szField, int nData);
virtual UINT LoadUInt (LPCTSTR szField) { return (UINT)LoadInt(szField); }
virtual void SetUInt (LPCTSTR szField, UINT nData) { SetInt(szField, nData); }
virtual void LoadString (char* szData, LPCTSTR szField, int nSize);
virtual void SetString (LPCTSTR szField, LPCTSTR szData, int nSize);
// 新模式的接口,用于代替应用程序的DATA层。
virtual int GetInt (int idx);
virtual LPCTSTR GetStr (int idx);
virtual void SetInt (int idx, int nData);
virtual void SetStr (int idx, LPCTSTR szData, int nSize);
virtual void ClearUpdateFlags () { ClsEditFlag(); }
// 立即写库。如无共享冲突,可不提供该接口
virtual bool AddInt (LPCTSTR szField, int nData) { return AddField(szField, nData); }
public: // Constructor
CMyRecord(CMyDatabase * pMyDatabase);
virtual ~CMyRecord();
public:
#ifdef MULTITHREAD_SAFE
static CCriticalSection m_xCtrl;
#endif
#ifdef USE_NEW
static CMyHeap s_heapString;
#endif
static CMyRecord* CreateNew(CMyDatabase *pMyDatabase);
public:
MYHEAP_DECLARATION(s_heap)
public:
enum { modeEdit, modeAddNew, modeDelete };
virtual bool Open( CMyRecordset* pRes, DWORD idNewKey = 0);
virtual bool Spawn(CMyRecord *pMyRecord, DWORD idNewKey = 0);
virtual void Close();
int FieldsCount();
void AddNew();
void Edit();
bool Update();
void Delete();
bool IsOpen();
bool CanUpdate() const; // Can Edit/AddNew/Delete be called?
void ClsEditFlag();
bool AddField(LPCTSTR szField, int nData);
void SetDatabase(CMyDatabase* pDb) { m_pMyDatabase = pDb; }
bool SetTableName(LPCTSTR szName, DWORD idNewKey = 0);
CMyField Fields(char * szField);
CMyField Fields(UINT uiIndex );
CMyDatabase * m_pMyDatabase;
protected: // inside function
int UpdateFieldsCount();
void BuildUpdateSQL();
void BuildUpdateCondition();
void BuildUpdateOpration();
CMyField * GetFieldRef(UINT uiIndex);
bool Query(char * szSQL, MYSQL_RES * * res);
void GetFieldValue(UINT uiIndex);
bool FormatField(char* szFormat, const CMyField& objField);
protected:
MYSQL_FIELD* m_Fields; //? COPY的结构,table、def未复制,不可用
unsigned int m_uiFieldsCount;
char m_szKey[16];
unsigned int m_uiKeyIndex;
char m_szKeyData[256]; //paled add 可能有点大
bool * m_pbDirty;
bool m_bEdit;
bool m_bIsOpen;
int m_nEditMode;
CMyField * m_objFields;
char m_szTableName[32];
char m_szUpdateSQL[1024];
char m_szUpdateOpration[1024];
char m_szUpdateCondition[128];
bool m_bCanUpdate;
};
|
[
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
] |
[
[
[
1,
118
]
]
] |
9eca910f29ae20865a5f198faae81a2114563cae
|
8a8873b129313b24341e8fa88a49052e09c3fa51
|
/src/HandleSystemInfo.cpp
|
5109b16f63745b9804e9a9c18b042fdcbd50ce17
|
[] |
no_license
|
flaithbheartaigh/wapbrowser
|
ba09f7aa981d65df810dba2156a3f153df071dcf
|
b0d93ce8517916d23104be608548e93740bace4e
|
refs/heads/master
| 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,448 |
cpp
|
/*
============================================================================
Name : HandleSystemInfo.cpp
Author :
Version :
Copyright : Your copyright notice
Description : CHandleSystemInfo implementation
============================================================================
*/
#include "HandleSystemInfo.h"
#include "MainEngine.h"
#include "HttpObserver.h"
#include "MControlObserver.h"
#include "HttpManager.h"
#include "CoCoPreDefine.h"
CHandleSystemInfo::CHandleSystemInfo(MHandleEventObserver& aObserver,CMainEngine& aMainEngine)
:iObserver(aObserver)
,iMainEngine(aMainEngine)
,iHttpManager(*aMainEngine.GetHttpManager())
,iSystemInfo(NULL)
,iUrl(NULL)
,iTitle(NULL)
,iBuf(NULL)
{
// No implementation required
}
CHandleSystemInfo::~CHandleSystemInfo()
{
this->CancelSendRequest();
DELETE(iSystemInfo);
DELETE(iUrl);
DELETE(iTitle);
DELETE(iBuf);
}
CHandleSystemInfo* CHandleSystemInfo::NewLC(MHandleEventObserver& aObserver,CMainEngine& aMainEngine)
{
CHandleSystemInfo* self = new (ELeave)CHandleSystemInfo(aObserver,aMainEngine);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CHandleSystemInfo* CHandleSystemInfo::NewL(MHandleEventObserver& aObserver,CMainEngine& aMainEngine)
{
CHandleSystemInfo* self=CHandleSystemInfo::NewLC(aObserver,aMainEngine);
CleanupStack::Pop(); // self;
return self;
}
void CHandleSystemInfo::ConstructL()
{
iBoolNext=EFalse;
iContentError=EFalse;
TBuf8<30> tbufTemp;
iUrl=HBufC8::NewL(300);
iUrl->Des().Append(_L8("http://59.36.96.182/interface/no?m=1&n="));
tbufTemp.Zero();
tbufTemp.Copy(iMainEngine.GetIMEI());
iUrl->Des().Append(tbufTemp);
}
void CHandleSystemInfo::SendRequest()
{
iHttpManager.SendGetRequest(*this,*iUrl,EHttpSystemInfo);
}
void CHandleSystemInfo::CancelSendRequest()
{
iHttpManager.CancelTransaction(this,EHttpSystemInfo);
}
const TDesC& CHandleSystemInfo::GetSystemInfo()
{
if(!iSystemInfo)
{
iSystemInfo=HBufC::NewL(0);
}
return *iSystemInfo;
}
const TDesC& CHandleSystemInfo::GetInfo()
{
if(!iBuf)
{
iBuf=HBufC::NewL(0);
}
return *iBuf;
}
const TDesC& CHandleSystemInfo::GetTitle()
{
if(!iTitle)
{
iTitle=HBufC::NewL(0);
}
return *iTitle;
}
//From MOperationObserver
void CHandleSystemInfo::OperationEvent(TInt aEventType,const TDesC& aEventData,TInt aType)
{
if(aEventType==EHttpNoError)
{
if(aType==EHttpSystemInfo)
{
TInt post=aEventData.Find(_L("|"));
if(post<0)
{
iBoolNext=EFalse;
iTitle=iMainEngine.GetDesById(ETurkeyTextRes_Setting_SystemMsg).Alloc();
iSystemInfo=aEventData.Alloc();
}
else
{
if(aEventData.Left(post).Compare(_L("0"))==0)
{
iBoolNext=EFalse;
}
else
{
iBoolNext=ETrue;
}
TInt postl=aEventData.Right(aEventData.Length()-1-post).Find(_L("|"));
if(post<0)
{
iTitle=iMainEngine.GetDesById(ETurkeyTextRes_Setting_SystemMsg).Alloc();
iSystemInfo=aEventData.Right(aEventData.Length()-1-post).Alloc();
}
else
{
iTitle=aEventData.Left(post+postl+1).Right(postl).Alloc();
iSystemInfo=aEventData.Right(aEventData.Length()-post-postl-2).Alloc();
}
}
}
}
else
{
iBuf=HBufC::NewL(aEventData.Length());
iBuf->Des().Copy(aEventData);
}
iObserver.HandleResponseEvent(aEventType,aType);
}
|
[
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
] |
[
[
[
1,
150
]
]
] |
b7b3d8ec5197d6bf441adae11de4f7ba0c5978a1
|
ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2
|
/ edge2d --username [email protected]/include/EdgeFont.h
|
ecb4a10dc048eeab7918b0d0895a771f41255f82
|
[] |
no_license
|
ratalaika/edge2d
|
11189c41b166960d5d7d5dbcf9bfaf833a41c079
|
79470a0fa6e8f5ea255df1696da655145bbf83ff
|
refs/heads/master
| 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,720 |
h
|
/*
-----------------------------------------------------------------------------
This source file is part of EDGE
(A very object-oriented and plugin-based 2d game engine)
For the latest info, see http://edge2d.googlecode.com
Copyright (c) 2007-2008 The EDGE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef EDGE_FONT_H
#define EDGE_FONT_H
#include "EdgeCompile.h"
#include "EdgeSharedPtr.h"
#include "EdgeColor.h"
#include "EdgeDataStream.h"
#include <string>
#include <map>
using std::wstring;
using std::map;
using std::string;
namespace Edge
{
class FontFactory;
/**
* FontParam, contains the information to create a font
* @remarks it's an abstract structure, when you want to create a font, you usually
* need to create a FontParam structure to specify some properties. But you need to
* create a TTFontParam instead FontParam.
*/
struct FontParam
{
virtual ~FontParam() {}
};
/**
* TTFontParam, describes a true type font/ system font information
*
*/
struct TTFontParam : public FontParam
{
/// specifies the typeface name of the font.
string mFaceName;
/// i.e -12, the logic height of the font
long mHeight;
/// usually canbe 0.
long mWidth;
long mWeight;
/// whether italic
bool mItalic;
/// whether underline.
bool mUnderLine;
TTFontParam() : mFaceName( "System" )
{
mHeight = -18;
mWidth = 0;
mWeight = 0;
mItalic = false;
mUnderLine = false;
}
void setHeight( long height ) { mHeight = height; }
void setWidth( long width ) { mWidth = width; }
void setWeight( long weight ) { mWeight = weight; }
void setItalic( bool italic ) { mItalic = italic; }
void setUnderline( bool ul ) { mUnderLine = ul; }
void setFaceName( const string &name){ mFaceName = name; }
};
/**
* Font, use font to render text.
* @remarks this class is an abstract class.And you donot need to create a font yourslef.
* You can call FontFactory::createFont to create a font for you.
*
*/
class EDGE_EXPORT Font
{
public:
/**
* text align
*
*/
enum ETextAlign
{
ETA_LEFT = 0x00,
ETA_RIGHT = 0x01,
ETA_TOP = 0x00,
ETA_BOTTOM = 0x02,
ETA_CENTER = 0x04, /// center in horizontal
ETA_MIDDLE = 0x08, /// center in veri
ETA_DEFAULT = ETA_LEFT | ETA_TOP
};
public:
/**
* Constructor
*
*/
Font( FontFactory *parent, const string &name ) : mParent( parent ), mName( name )
{
mScale = 1.0f;
mSpacing = 0.0f;
mLineSpacing = 0.0f;
}
/**
* Destructor
*
*/
virtual ~Font() {}
/**
* create
*
*/
virtual bool create( const FontParam ¶m ) = 0;
virtual bool create( const DataStreamPtr &stream ) = 0;
/**
* release, automatically called by destructor
*
*/
virtual void release() = 0;
/**
* scale the font
*
*/
virtual void setScale( float scale ) { mScale = scale; }
/**
* set the spacing between characters
*
*/
virtual void setSpacing( float spacing ) { mSpacing = spacing; }
/**
* set the spacing between lines
*
*/
virtual void setLineSpacing( float linespace ) { mLineSpacing = linespace; }
/**
* get a string's width
*
*/
virtual float getStringWidth( const wstring &str ) { return 0.0f; }
/**
* get the font's height
*
*/
virtual float getHeight() { return 0.0f ;}
/**
* get the current font scaling
*
*/
virtual float getScale() { return mScale; }
/**
* get the current spacing between characters
*
*/
virtual float getSpacing() { return mSpacing; }
/**
* get the current spacing between lines
*
*/
virtual float getLineSpacing() { return mLineSpacing; }
/**
* render, render some texts
*
*/
virtual void render( float x, float y, const wstring &text, const Color &color = Color(), int align = 0 ) = 0;
/**
* render format strings
*
*/
virtual void render( float x, float y, int align, const Color &color, const wchar_t *format, ... ) = 0;
string &getName() { return mName; }
protected:
/// name
string mName;
/// scale
float mScale;
/// spacing between characters
float mSpacing;
/// spacing between lines
float mLineSpacing;
/// parent, when the object is destroyed, it will notify its parent
FontFactory *mParent;
};
/// font ptr
typedef shared_ptr<Font> FontPtr;
/**
* FontFactory, it can create a font, and store a font.
* @remarks usually you want to create a font to render some texts, you need to use this
* class to create a font for you.
*
*/
class EDGE_EXPORT FontFactory
{
public:
/**
* Constructor
*
*/
FontFactory();
/**
* Destructor
*
*/
virtual ~FontFactory() ;
/**
* initiate, initiate the factory
*
*/
virtual bool initiate() { return true; }
/**
* release, it will be called automatically by constructor
*
*/
virtual void release() {}
/**
* createFont
* this function will save the pointer, and you should specify an unique
* name for the Font.And later you can get the Font by its name.
*/
virtual Font *createFont( const string &name, const FontParam ¶m ) = 0;
/**
* You can write a font config file to specify a FontParam, so you can create
* a font from a font config file.
*
*
*/
virtual Font *createFont( const string &name, const string &file ) = 0;
/**
* getFont
*
* get a font you have created before.
* @warning if the font is not exist, this function will throw an exception.
*/
Font* getFont( const string &name );
/**
* removeFont
* this function will remove the Font in the list and also will destroy the
* Font object from memory
*
*/
void removeFont( const string &name );
/**
*
*
*/
void removeFont( Font *font );
/**
* removeAllFonts, called by the destructor.
*
*/
void removeAllFonts();
/**
* notify a child's death, when some children of this factory are destroyed, this function
* will be called
*
*/
virtual void notifyDeath( const Font *font ) {}
protected:
/**
*
* selfGetFont, this class will use it to check whether the font is already exist.
*/
Font *_selfGetFont( const string &name );
/**
* saveFont, save the font object in the list
*
*/
void _saveFont( const string &name, Font *font )
{
mFonts[ name ] = font;
}
/**
*
*
*/
void _modifyName( string &name );
protected:
///
typedef map<string, Font*> FontMap;
protected:
FontMap mFonts;
};
}
#endif
|
[
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
] |
[
[
[
1,
340
]
]
] |
3b2813954fc83abcb7cd5c5f6cdf81b4f195dfae
|
a36d7a42310a8351aa0d427fe38b4c6eece305ea
|
/core_billiard/EffectShaderFeederNull.hpp
|
5e26f02033e6aa3554d87662e9d6a58d13084a96
|
[] |
no_license
|
newpolaris/mybilliard01
|
ca92888373c97606033c16c84a423de54146386a
|
dc3b21c63b5bfc762d6b1741b550021b347432e8
|
refs/heads/master
| 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 416 |
hpp
|
#pragma once
namespace my_render {
NULL_OBJECT( EffectShaderFeeder ) {
virtual void setEffectShader( EffectShader * ) OVERRIDE {}
virtual EffectShader * getEffectShader() OVERRIDE { return NULL; }
virtual void updateModelMatrix( const RowMajorMatrix44f & matWorld ) OVERRIDE {}
virtual bool displayWithEffect( EffectShaderCallBack * calBack ) OVERRIDE { return false; }
};
}
|
[
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
] |
[
[
[
1,
17
]
]
] |
2730b0e527aa2e8230fe21f8885e7c631f94991a
|
bef7d0477a5cac485b4b3921a718394d5c2cf700
|
/dingus/dingus/gfx/gui/Gui.cpp
|
26f04f778a1b5f8760fe6edd3b6778def111fe92
|
[
"MIT"
] |
permissive
|
TomLeeLive/aras-p-dingus
|
ed91127790a604e0813cd4704acba742d3485400
|
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
|
refs/heads/master
| 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 106,004 |
cpp
|
// --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#include "stdafx.h"
#include "Gui.h"
#include "../../resource/TextureBundle.h"
using namespace dingus;
// --------------------------------------------------------------------------
// Constants
// Some things aren't always defined...
#ifndef WM_XBUTTONDOWN
#define WM_XBUTTONDOWN 0x020B
#endif
#ifndef WM_XBUTTONUP
#define WM_XBUTTONUP 0x020C
#endif
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WHEEL_DELTA
#define WHEEL_DELTA 120
#endif
#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES 104
#endif
#define V(x) { hr = x; }
#define V_RETURN(x) { hr = x; if( FAILED(hr) ) { return hr; } }
// Minimum scrollbar thumb size
const float SCROLLBAR_MINTHUMBSIZE = 8;
// Maximum scrollbar thumb size
const float SCROLLBAR_MAXTHUMBSIZE = 32;
// Delay and repeat period when clicking on the scroll bar arrows
const float SCROLLBAR_ARROWCLICK_DELAY = 0.33f;
const float SCROLLBAR_ARROWCLICK_REPEAT = 0.05f;
// --------------------------------------------------------------------------
// Global/Static Members
CUIResourceManager* CUIResourceManager::mSingleInstance = 0;
double CUIDialog::sTimeRefresh = 0.0f;
CUIControl* CUIDialog::sCtrlFocus = NULL; // The control which has focus
CUIControl* CUIDialog::sCtrlPressed = NULL; // The control currently pressed
struct SUIScreenVertex {
float x, y, z, h;
D3DCOLOR color;
float tu, tv;
static DWORD FVF;
};
DWORD SUIScreenVertex::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1;
static inline int rectWidth( const RECT &rc ) { return ( (rc).right - (rc).left ); }
static inline int rectHeight( const RECT &rc ) { return ( (rc).bottom - (rc).top ); }
// --------------------------------------------------------------------------
// CUIDialog class
// --------------------------------------------------------------------------
CUIDialog::CUIDialog()
: mHasCaption(false), mMinimized(false), mDragging(false),
mX(0), mY(0), mWidth(0), mHeight(0), mCaptionHeight(18),
mColorUL(0), mColorUR(0), mColorDL(0), mColorDR(0),
mCallbackEvent(NULL), mDefaultTexture(NULL),
mRenderCallback(NULL),
mDefaultCtrlID(0xFFFF), mTimeLastRefresh(0),
mCtrlMouseOver(NULL)
{
mCaption[0] = 0;
mNextDlg = this;
mPrevDlg = this;
mDoNonUserEvents = false;
mDoKeyboardInput = false;
mDoMouseInput = true;
initDefaultElements();
}
CUIDialog::~CUIDialog()
{
removeAllControls();
mFonts.clear();
for( size_t i = 0; i < mDefaultElements.size(); ++i ) {
safeDelete( mDefaultElements[i] );
}
mDefaultElements.clear();
}
void CUIDialog::removeControl( int cid )
{
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[ i ];
if( ctrl->getID() == cid ) {
// Clear focus first
clearFocus();
// clear references to this control
if( sCtrlFocus == ctrl ) sCtrlFocus = NULL;
if( sCtrlPressed == ctrl ) sCtrlPressed = NULL;
if( mCtrlMouseOver == ctrl ) mCtrlMouseOver = NULL;
safeDelete( ctrl );
mControls.erase( mControls.begin() + i );
return;
}
}
}
void CUIDialog::removeAllControls()
{
if( sCtrlFocus && sCtrlFocus->mDialog == this )
sCtrlFocus = NULL;
if( sCtrlPressed && sCtrlPressed->mDialog == this )
sCtrlPressed = NULL;
mCtrlMouseOver = NULL;
for( size_t i = 0; i < mControls.size(); ++i )
safeDelete( mControls[i] );
mControls.clear();
}
void CUIDialog::refresh()
{
if( sCtrlFocus )
sCtrlFocus->onFocusOut();
if( mCtrlMouseOver )
mCtrlMouseOver->onMouseLeave();
sCtrlFocus = NULL;
sCtrlPressed = NULL;
mCtrlMouseOver = NULL;
size_t n = mControls.size();
for( size_t i=0; i < n; ++i ) {
mControls[i]->refresh();
}
if( mDoKeyboardInput )
focusDefaultControl();
}
namespace {
// single flag for error checking - because we really want just one
// dialog to be rendering at a time
static bool gUIDlgInsideRenderBegin = false;
};
void CUIDialog::renderBegin( bool renderDlgBackground )
{
assert( !gUIDlgInsideRenderBegin );
gUIDlgInsideRenderBegin = true;
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
IDirect3DDevice9* device = &dx.getDevice();
// set up a state block here and restore it when finished drawing all the controls
resmgr.mStateBlock->Capture();
device->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
device->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
device->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
device->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
device->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
device->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
device->SetVertexShader( NULL );
device->SetPixelShader( NULL );
device->SetRenderState( D3DRS_ZENABLE, FALSE );
if( renderDlgBackground && !mMinimized ) {
device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 );
device->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
device->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
device->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
float x1 = resmgr.xToBB( mX, dx.getBackBufferWidth() ) - 0.5f;
float x2 = resmgr.xToBB( mX+mWidth, dx.getBackBufferWidth() ) - 0.5f;
float y1 = resmgr.yToBB( mY, dx.getBackBufferHeight() ) - 0.5f;
float y2 = resmgr.yToBB( mY+mHeight, dx.getBackBufferHeight() ) - 0.5f;
SUIScreenVertex vertices[4] = {
x1, y1, 0.5f, 1.0f, mColorUL, 0.0f, 0.5f,
x1, y2, 0.5f, 1.0f, mColorDL, 1.0f, 0.5f,
x2, y2, 0.5f, 1.0f, mColorDR, 1.0f, 1.0f,
x2, y1, 0.5f, 1.0f, mColorUR, 0.0f, 1.0f,
};
device->SetFVF( SUIScreenVertex::FVF );
device->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices, sizeof(SUIScreenVertex) );
}
device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
device->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
device->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
device->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
device->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
device->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
device->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
assert( mDefaultTexture );
device->SetTexture( 0, mDefaultTexture->getObject() );
resmgr.mSprite->Begin( D3DXSPRITE_DONOTSAVESTATE );
}
void CUIDialog::renderEnd()
{
assert( gUIDlgInsideRenderBegin );
gUIDlgInsideRenderBegin = false;
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
resmgr.mSprite->End();
resmgr.mStateBlock->Apply();
}
void CUIDialog::onRender( float dt )
{
// See if the dialog needs to be refreshed
if( mTimeLastRefresh < sTimeRefresh ) {
mTimeLastRefresh = CSystemTimer::getInstance().getTimeS();
refresh();
}
renderBegin( true );
IDirect3DDevice9* device = &CD3DDevice::getInstance().getDevice();
// call render callback
if( mRenderCallback ) {
mRenderCallback( *this );
}
// render the caption if it's enabled.
if( mHasCaption ) {
// drawSprite will offset the rect down by mCaptionHeight, so
// adjust the rect higher here to negate the effect.
SFRect rc( 0, -mCaptionHeight, mWidth, 0 );
drawSprite( &mCaptionElement, &rc );
rc.left += 5; // Make a left margin
char output[256];
strncpy( output, mCaption, 256 );
output[255] = 0;
if( mMinimized )
strncat( output, " (Minimized)", 256 - strlen( output ) );
drawText( output, &mCaptionElement, &rc, !mCaptionElement.darkFont );
}
// If the dialog is minimized, skip rendering its controls.
if( !mMinimized ) {
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[i];
// Focused control is drawn last
if( ctrl == sCtrlFocus )
continue;
ctrl->render( device, dt );
}
if( sCtrlFocus != NULL && sCtrlFocus->mDialog == this )
sCtrlFocus->render( device, dt );
}
renderEnd();
}
void CUIDialog::sendEvent( UINT evt, bool userTriggered, CUIControl* ctrl )
{
// If no callback has been registered there's nowhere to send the event to
if( mCallbackEvent == NULL )
return;
// Discard events triggered programatically if these types of events
// haven't been enabled
if( !userTriggered && !mDoNonUserEvents )
return;
mCallbackEvent( evt, ctrl->getID(), ctrl );
}
void CUIDialog::setFont( size_t index, const char* facename, LONG height, LONG weight )
{
// Make sure the list is at least as large as the index being set
for( size_t i = (int)mFonts.size(); i <= index; ++i )
mFonts.push_back( (size_t)-1 );
size_t fontIdx = CUIResourceManager::getInstance().addFont( facename, height, weight );
mFonts[index] = fontIdx;
}
SUIFontNode* CUIDialog::getFont( size_t index ) const
{
assert( index >= 0 && index < mFonts.size() );
return CUIResourceManager::getInstance().getFontNode( mFonts[ index ] );
}
bool CUIDialog::msgProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
bool handled = false;
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& uiresmgr = CUIResourceManager::getInstance();
POINT mousePoint;
mousePoint.x = uiresmgr.bbToX( short(LOWORD(lParam)), dx.getBackBufferWidth() );
mousePoint.y = uiresmgr.bbToY( short(HIWORD(lParam)), dx.getBackBufferHeight() );
// If caption is enabled, check for clicks in the caption area.
if( mHasCaption ) {
if( msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK ) {
if( mousePoint.x >= mX && mousePoint.x < mX + mWidth &&
mousePoint.y >= mY && mousePoint.y < mY + mCaptionHeight )
{
mDragging = true;
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
return true;
}
} else if( msg == WM_LBUTTONUP && mDragging ) {
if( mousePoint.x >= mX && mousePoint.x < mX + mWidth &&
mousePoint.y >= mY && mousePoint.y < mY + mCaptionHeight )
{
ReleaseCapture();
mDragging = false;
mMinimized = !mMinimized;
return true;
}
}
}
// If the dialog is minimized, don't send any messages to controls.
if( mMinimized )
return false;
// Give the first chance at handling the message to the focused control.
bool isFocus = hasFocusControl();
if( isFocus ) {
// If the control handles it, then we're done.
if( sCtrlFocus->msgProc( msg, wParam, lParam ) )
return true;
}
switch( msg ) {
case WM_ACTIVATEAPP:
// Call onFocusIn()/onFocusOut() of the control that currently
// has the focus as the application is activated/deactivated.
// This matches the Windows behavior.
if( isFocus ) {
if( wParam )
sCtrlFocus->onFocusIn();
else
sCtrlFocus->onFocusOut();
}
break;
// Keyboard messages
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
{
// Give first chance to the focused control.
if( isFocus ) {
if( sCtrlFocus->handleKeyb( msg, wParam, lParam ) )
return true;
}
// Not yet handled, see if this matches a control's hotkey
// [Activate the hotkey if the focus doesn't belong to an edit box.]
if( msg == WM_KEYUP ) {
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[ i ];
if( ctrl->isEnabled() && ctrl->getHotkey() == wParam ) {
ctrl->onHotkey();
return true;
}
}
}
// Not yet handled, check for focus messages
if( msg == WM_KEYDOWN ) {
// If keyboard input is not enabled, this message should be ignored
if( !mDoKeyboardInput )
return false;
switch( wParam ) {
case VK_RIGHT:
case VK_DOWN:
if( sCtrlFocus != NULL ) {
onCycleFocus( true );
return true;
}
break;
case VK_LEFT:
case VK_UP:
if( sCtrlFocus != NULL ) {
onCycleFocus( false );
return true;
}
break;
case VK_TAB:
if( sCtrlFocus == NULL ) {
focusDefaultControl();
} else {
bool shiftDown = ((GetAsyncKeyState( VK_SHIFT ) & 0x8000) != 0);
onCycleFocus( !shiftDown );
}
return true;
}
}
break;
}
// Mouse messages
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_MOUSEWHEEL:
{
// If not accepting mouse input, return false to indicate the
// message should still be handled by the application
// (usually to move the camera).
if( !mDoMouseInput )
return false;
mousePoint.x -= (LONG)mX;
mousePoint.y -= (LONG)mY;
// If caption is enabled, offset the Y coordinate by the
// negative of its height.
if( mHasCaption )
mousePoint.y -= (LONG)mCaptionHeight;
// Give first chance to the focused control.
if( isFocus ) {
if( sCtrlFocus->handleMouse( msg, mousePoint, wParam, lParam ) )
return true;
}
// Not yet handled, see if the mouse is over any controls
CUIControl* ctrl = getControlAtPoint( mousePoint );
if( ctrl != NULL && ctrl->isEnabled() ) {
handled = ctrl->handleMouse( msg, mousePoint, wParam, lParam );
if( handled )
return true;
} else {
// Mouse not over any controls in this dialog, if there was
// a control which had focus it just lost it
if( msg == WM_LBUTTONDOWN && sCtrlFocus && sCtrlFocus->mDialog == this ) {
sCtrlFocus->onFocusOut();
sCtrlFocus = NULL;
}
}
// Still not handled, hand this off to the dialog. Return false
// to indicate the message should still be handled by the
// application (usually to move the camera).
switch( msg ) {
case WM_MOUSEMOVE:
onMouseMove( mousePoint );
return false;
}
break;
}
case WM_CAPTURECHANGED:
// The application has lost mouse capture. The dialog object may
// not have received a WM_MOUSEUP when capture changed. Reset
// mDragging so that the dialog does not mistakenly
// think the mouse button is still held down.
if( (HWND)lParam != hwnd )
mDragging = false;
break;
}
// Not handled
return false;
}
CUIControl* CUIDialog::getControlAtPoint( POINT pt )
{
// Search through all child controls for the first one which
// contains the mouse point
size_t n = mControls.size();
for( size_t i=0; i < n; ++i ) {
CUIControl* ctrl = mControls[i];
assert( ctrl );
//if( ctrl == NULL )
// continue;
// We only return the current control if it is visible
// and enabled. Because getControlAtPoint() is used to do mouse
// hittest, it makes sense to perform this filtering.
if( ctrl->containsPoint( pt ) && ctrl->isEnabled() && ctrl->isVisible() )
return ctrl;
}
return NULL;
}
bool CUIDialog::isControlEnabled( int cid )
{
CUIControl* ctrl = getControl( cid );
if( ctrl == NULL )
return false;
return ctrl->isEnabled();
}
void CUIDialog::setControlEnabled( int cid, bool enabled )
{
CUIControl* ctrl = getControl( cid );
if( ctrl == NULL )
return;
ctrl->setEnabled( enabled );
}
void CUIDialog::onMouseUp( POINT pt )
{
sCtrlPressed = NULL;
mCtrlMouseOver = NULL;
}
void CUIDialog::onMouseMove( POINT pt )
{
// Figure out which control the mouse is over now
CUIControl* ctrl = getControlAtPoint( pt );
// If the mouse is still over the same control, nothing needs to be done
if( ctrl == mCtrlMouseOver )
return;
// Handle mouse leaving the old control
if( mCtrlMouseOver )
mCtrlMouseOver->onMouseLeave();
// Handle mouse entering the new control
mCtrlMouseOver = ctrl;
if( ctrl != NULL )
mCtrlMouseOver->onMouseEnter();
}
HRESULT CUIDialog::setDefaultElement( eUIControlType ctrlType, size_t index, SUIElement* element )
{
// If this element type already exist in the list, simply update the stored element
size_t n = mDefaultElements.size();
for( size_t i = 0; i < n; ++i ) {
SElementHolder* holder = mDefaultElements[ i ];
if( holder->ctrlType == ctrlType && holder->index == index ) {
holder->element = *element;
return S_OK;
}
}
// Otherwise, add a new entry
SElementHolder* newHolder;
newHolder = new SElementHolder;
if( newHolder == NULL )
return E_OUTOFMEMORY;
newHolder->ctrlType = ctrlType;
newHolder->index = index;
newHolder->element = *element;
mDefaultElements.push_back( newHolder );
return S_OK;
}
SUIElement* CUIDialog::getDefaultElement( eUIControlType ctrlType, size_t index )
{
size_t n = mDefaultElements.size();
for( size_t i = 0; i < n; ++i ) {
SElementHolder* holder = mDefaultElements[ i ];
if( holder->ctrlType == ctrlType && holder->index == index )
return &holder->element;
}
return NULL;
}
// --------------------------------------------------------------------------
HRESULT CUIDialog::addStatic( int cid, const char* text, int x, int y, int width, int height, bool isDefault, CUIStatic** created )
{
HRESULT hr = S_OK;
CUIStatic* ctrl = new CUIStatic( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and list index
ctrl->setID( cid );
ctrl->setText( text );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->mDefault = isDefault;
return S_OK;
}
HRESULT CUIDialog::addImage( int cid, int x, int y, int width, int height, CD3DTexture& tex, int u0, int v0, int u1, int v1, CUIImage** created )
{
HRESULT hr = S_OK;
CUIImage* ctrl = new CUIImage( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
ctrl->setTexture( tex, u0, v0, u1, v1 );
// set the cid and list index
ctrl->setID( cid );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->mDefault = false;
return S_OK;
}
HRESULT CUIDialog::addButton( int cid, const char* text, int x, int y, int width, int height, UINT hotkey, bool isDefault, CUIButton** created )
{
HRESULT hr = S_OK;
CUIButton* ctrl = new CUIButton( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and list index
ctrl->setID( cid );
ctrl->setText( text );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->setHotkey( hotkey );
ctrl->mDefault = isDefault;
return S_OK;
}
HRESULT CUIDialog::addCheckBox( int cid, const char* text, int x, int y, int width, int height, bool chk, UINT hotkey, bool isDefault, CUICheckBox** created )
{
HRESULT hr = S_OK;
CUICheckBox* ctrl = new CUICheckBox( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and list index
ctrl->setID( cid );
ctrl->setText( text );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->setHotkey( hotkey );
ctrl->mDefault = isDefault;
ctrl->setChecked( chk );
return S_OK;
}
HRESULT CUIDialog::addRollout( int cid, const char* text, int x, int y, int width, int height, int rollHeight, bool expanded, UINT hotkey, bool isDefault, CUIRollout** created )
{
HRESULT hr = S_OK;
CUIRollout* ctrl = new CUIRollout( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
ctrl->setID( cid );
ctrl->setText( text );
ctrl->setRolloutHeight( float(rollHeight) );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->setHotkey( hotkey );
ctrl->mDefault = isDefault;
ctrl->setExpanded( expanded );
return S_OK;
}
HRESULT CUIDialog::addRadioButton( int cid, UINT group, const char* text, int x, int y, int width, int height, bool chk, UINT hotkey, bool isDefault, CUIRadioButton** created )
{
HRESULT hr = S_OK;
CUIRadioButton* ctrl = new CUIRadioButton( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and list index
ctrl->setID( cid );
ctrl->setText( text );
ctrl->setButtonGroup( group );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->setHotkey( hotkey );
ctrl->setChecked( chk );
ctrl->mDefault = isDefault;
ctrl->setChecked( chk );
return S_OK;
}
HRESULT CUIDialog::addComboBox( int cid, int x, int y, int width, int height, UINT hotkey, bool isDefault, CUIComboBox** created )
{
HRESULT hr = S_OK;
CUIComboBox* ctrl = new CUIComboBox( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and list index
ctrl->setID( cid );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->setHotkey( hotkey );
ctrl->mDefault = isDefault;
return S_OK;
}
HRESULT CUIDialog::addSlider( int cid, int x, int y, int width, int height, int min, int max, int value, bool isDefault, CUISlider** created )
{
HRESULT hr = S_OK;
CUISlider* ctrl = new CUISlider( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and list index
ctrl->setID( cid );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->mDefault = isDefault;
ctrl->setRange( min, max );
ctrl->setValue( value );
ctrl->updateRects();
return S_OK;
}
HRESULT CUIDialog::addListBox( int cid, int x, int y, int width, int height, DWORD style, CUIListBox** created )
{
HRESULT hr = S_OK;
CUIListBox *ctrl = new CUIListBox( this );
if( created != NULL )
*created = ctrl;
if( ctrl == NULL )
return E_OUTOFMEMORY;
hr = addControl( ctrl );
if( FAILED(hr) )
return hr;
// set the cid and position
ctrl->setID( cid );
ctrl->setLocation( float(x), float(y) );
ctrl->setSize( float(width), float(height) );
ctrl->setStyle( style );
return S_OK;
}
HRESULT CUIDialog::initControl( CUIControl* ctrl )
{
HRESULT hr;
if( ctrl == NULL )
return E_INVALIDARG;
ctrl->mIndex = mControls.size();
// Look for a default element entries
for( size_t i=0; i < mDefaultElements.size(); i++ ) {
SElementHolder* holder = mDefaultElements[ i ];
if( holder->ctrlType == ctrl->getType() )
ctrl->setElement( holder->index, &holder->element );
}
V_RETURN( ctrl->onInit() );
return S_OK;
}
HRESULT CUIDialog::addControl( CUIControl* ctrl )
{
HRESULT hr = S_OK;
hr = initControl( ctrl );
if( FAILED(hr) ) {
ASSERT_FAIL_MSG( "CUIDialog::initControl" );
return hr;
}
// add to the list
mControls.push_back( ctrl );
return S_OK;
}
CUIControl* CUIDialog::getControl( int cid )
{
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[ i ];
if( ctrl->getID() == cid )
return ctrl;
}
return NULL;
}
CUIControl* CUIDialog::getControl( int cid, eUIControlType ctrlType )
{
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[ i ];
if( ctrl->getID() == cid && ctrl->getType() == ctrlType )
return ctrl;
}
return NULL;
}
CUIControl* CUIDialog::getNextControl( CUIControl* ctrl )
{
size_t index = ctrl->mIndex + 1;
CUIDialog* dialog = ctrl->mDialog;
// Cycle through dialogs in the loop to find the next control. Note
// that if only one control exists in all looped dialogs it will
// be the returned 'next' control.
while( index >= (int)dialog->mControls.size() ) {
dialog = dialog->mNextDlg;
index = 0;
}
return dialog->mControls[ index ];
}
CUIControl* CUIDialog::getPrevControl( CUIControl* ctrl )
{
size_t index = ctrl->mIndex - 1;
CUIDialog* dialog = ctrl->mDialog;
// Cycle through dialogs in the loop to find the next control. Note
// that if only one control exists in all looped dialogs it will
// be the returned 'previous' control.
while( index < 0 ) {
dialog = dialog->mPrevDlg;
if( dialog == NULL )
dialog = ctrl->mDialog;
index = dialog->mControls.size() - 1;
}
return dialog->mControls[ index ];
}
// --------------------------------------------------------------------------
void CUIDialog::clearRadioButtonGroup( int group )
{
// Find all radio buttons with the given group number
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[ i ];
if( ctrl->getType() == UICTRL_RADIOBUTTON ) {
CUIRadioButton* rctrl = (CUIRadioButton*) ctrl;
if( rctrl->getButtonGroup() == group )
rctrl->setChecked( false, false );
}
}
}
void CUIDialog::clearComboBox( int cid )
{
CUIComboBox* ctrl = getComboBox( cid );
if( ctrl == NULL )
return;
ctrl->removeAllItems();
}
void CUIDialog::requestFocus( CUIControl* ctrl )
{
if( sCtrlFocus == ctrl )
return;
if( !ctrl->canHaveFocus() )
return;
if( sCtrlFocus )
sCtrlFocus->onFocusOut();
ctrl->onFocusIn();
sCtrlFocus = ctrl;
}
// --------------------------------------------------------------------------
HRESULT CUIDialog::drawRect( const SFRect* rect, D3DCOLOR color )
{
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
SFRect rcScreen = *rect;
rcScreen.offset( mX, mY );
// If caption is enabled, offset the Y position by its height.
if( mHasCaption )
rcScreen.offset( 0, mCaptionHeight );
float x1 = resmgr.xToBB( rcScreen.left, dx.getBackBufferWidth() ) - 0.5f;
float x2 = resmgr.xToBB( rcScreen.right, dx.getBackBufferWidth() ) - 0.5f;
float y1 = resmgr.yToBB( rcScreen.top, dx.getBackBufferHeight() ) - 0.5f;
float y2 = resmgr.yToBB( rcScreen.bottom, dx.getBackBufferHeight() ) - 0.5f;
SUIScreenVertex vertices[4] = {
x1, y1, 0.5f, 1.0f, color, 0, 0,
x2, y1, 0.5f, 1.0f, color, 0, 0,
x2, y2, 0.5f, 1.0f, color, 0, 0,
x1, y2, 0.5f, 1.0f, color, 0, 0,
};
IDirect3DDevice9* device = &dx.getDevice();
// Since we're doing our own drawing here we need to flush the sprites
resmgr.mSprite->Flush();
IDirect3DVertexDeclaration9 *decl = NULL;
device->GetVertexDeclaration( &decl ); // Preserve the sprite's current vertex decl
device->SetFVF( SUIScreenVertex::FVF );
device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 );
device->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 );
device->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices, sizeof(SUIScreenVertex) );
device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
device->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
// Restore the vertex decl
device->SetVertexDeclaration( decl );
decl->Release();
return S_OK;
}
/*
HRESULT CUIDialog::drawPolyLine( const POINT* points, size_t pointCount, D3DCOLOR color )
{
SUIScreenVertex* vertices = new SUIScreenVertex[ pointCount ];
if( vertices == NULL )
return E_OUTOFMEMORY;
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
SUIScreenVertex* vtx = vertices;
const POINT* pt = points;
for( size_t i = 0; i < pointCount; ++i ) {
vtx->x = resmgr.xToBB( mX + pt->x, dx.getBackBufferWidth() );
vtx->y = resmgr.yToBB( mY + pt->y, dx.getBackBufferHeight() );
vtx->z = 0.5f;
vtx->h = 1.0f;
vtx->color = color;
vtx->tu = 0.0f;
vtx->tv = 0.0f;
vtx++;
pt++;
}
IDirect3DDevice9* device = &dx.getDevice();
// Since we're doing our own drawing here we need to flush the sprites
resmgr.mSprite->Flush();
IDirect3DVertexDeclaration9 *decl = NULL;
device->GetVertexDeclaration( &decl ); // Preserve the sprite's current vertex decl
device->SetFVF( SUIScreenVertex::FVF );
device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 );
device->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 );
device->DrawPrimitiveUP( D3DPT_LINESTRIP, pointCount - 1, vertices, sizeof(SUIScreenVertex) );
device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
device->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
// Restore the vertex decl
device->SetVertexDeclaration( decl );
decl->Release();
safeDeleteArray( vertices );
return S_OK;
}
*/
HRESULT CUIDialog::drawSprite( SUIElement* element, const SFRect* dest )
{
SFRect destScr = *dest;
destScr.offset( mX, mY );
// If caption is enabled, offset the Y position by its height.
if( mHasCaption )
destScr.offset( 0, mCaptionHeight );
return imDrawSprite( element->colorTexture.current, element->textureRect, element->texture, destScr );
}
/*
HRESULT CUIDialog::calcTextRect( const char* text, SUIElement* element, SFRect* dest, int count )
{
HRESULT hr = S_OK;
SUIFontNode* fontNode = getFont( element->fontIdx );
DWORD textFormat = element->textFormat | DT_CALCRECT;
// Since we are only computing the rectangle, we don't need a sprite.
hr = fontNode->font->DrawText( NULL, text, count, dest, textFormat, element->colorFont.current );
if( FAILED(hr) )
return hr;
return S_OK;
}
*/
HRESULT CUIDialog::drawText( const char* text, SUIElement* element, const SFRect* dest, bool shadow, int count )
{
SFRect destScr = *dest;
destScr.offset( mX, mY );
// If caption is enabled, offset the Y position by its height.
if( mHasCaption )
destScr.offset( 0, mCaptionHeight );
return imDrawText( text, element->fontIdx, element->textFormat, element->colorFont.current, destScr, shadow, count );
}
HRESULT CUIDialog::drawText( const wchar_t* text, SUIElement* element, const SFRect* dest, bool shadow, int count )
{
SFRect destScr = *dest;
destScr.offset( mX, mY );
// If caption is enabled, offset the Y position by its height.
if( mHasCaption )
destScr.offset( 0, mCaptionHeight );
return imDrawText( text, element->fontIdx, element->textFormat, element->colorFont.current, destScr, shadow, count );
}
// --------------------------------------------------------------------------
HRESULT CUIDialog::imDrawSprite( const D3DXCOLOR& color, const RECT& texRect, CD3DTexture* tex, const SFRect& destScr )
{
// No need to draw fully transparent layers
if( color.a == 0 )
return S_OK;
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
float x1 = resmgr.xToBB( destScr.left, dx.getBackBufferWidth() );
float x2 = resmgr.xToBB( destScr.right, dx.getBackBufferWidth() );
float y1 = resmgr.yToBB( destScr.top, dx.getBackBufferHeight() );
float y2 = resmgr.yToBB( destScr.bottom, dx.getBackBufferHeight() );
float scaleX = (x2-x1) / rectWidth( texRect );
float scaleY = (y2-y1) / rectHeight( texRect );
D3DXMATRIXA16 matrix;
D3DXMatrixScaling( &matrix, scaleX, scaleY, 1.0f );
resmgr.mSprite->SetTransform( &matrix );
D3DXVECTOR3 pos( x1/scaleX, y1/scaleY, 0.0f );
return resmgr.mSprite->Draw( tex->getObject(), &texRect, NULL, &pos, color );
}
HRESULT CUIDialog::imDrawText( const char* text, size_t fontIdx, DWORD format, const D3DXCOLOR& color, const SFRect& destScr, bool shadow, int count )
{
HRESULT hr = S_OK;
// No need to draw fully transparent layers
if( color.a == 0 )
return S_OK;
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
SFRect rcScreen;
rcScreen.left = resmgr.xToBB( destScr.left, dx.getBackBufferWidth() );
rcScreen.right = resmgr.xToBB( destScr.right, dx.getBackBufferWidth() );
rcScreen.top = resmgr.yToBB( destScr.top, dx.getBackBufferHeight() );
rcScreen.bottom = resmgr.yToBB( destScr.bottom, dx.getBackBufferHeight() );
D3DXMATRIXA16 matrix;
D3DXMatrixIdentity( &matrix );
resmgr.mSprite->SetTransform( &matrix );
SUIFontNode* fontNode = getFont( fontIdx );
RECT drawRC;
rcScreen.toRect( drawRC );
if( shadow ) {
RECT rcShadow = drawRC;
OffsetRect( &rcShadow, 1, 1 );
hr = fontNode->font->DrawText( resmgr.mSprite, text, count, &rcShadow, format, D3DCOLOR_ARGB(DWORD(color.a * 255), 0, 0, 0) );
if( FAILED(hr) )
return hr;
}
hr = fontNode->font->DrawText( resmgr.mSprite, text, count, &drawRC, format, color );
if( FAILED(hr) )
return hr;
return S_OK;
}
HRESULT CUIDialog::imDrawText( const wchar_t* text, size_t fontIdx, DWORD format, const D3DXCOLOR& color, const SFRect& destScr, bool shadow, int count )
{
HRESULT hr = S_OK;
// No need to draw fully transparent layers
if( color.a == 0 )
return S_OK;
CD3DDevice& dx = CD3DDevice::getInstance();
CUIResourceManager& resmgr = CUIResourceManager::getInstance();
SFRect rcScreen;
rcScreen.left = resmgr.xToBB( destScr.left, dx.getBackBufferWidth() );
rcScreen.right = resmgr.xToBB( destScr.right, dx.getBackBufferWidth() );
rcScreen.top = resmgr.yToBB( destScr.top, dx.getBackBufferHeight() );
rcScreen.bottom = resmgr.yToBB( destScr.bottom, dx.getBackBufferHeight() );
D3DXMATRIXA16 matrix;
D3DXMatrixIdentity( &matrix );
resmgr.mSprite->SetTransform( &matrix );
SUIFontNode* fontNode = getFont( fontIdx );
RECT drawRC;
rcScreen.toRect( drawRC );
if( shadow ) {
RECT rcShadow = drawRC;
OffsetRect( &rcShadow, 1, 1 );
hr = fontNode->font->DrawTextW( resmgr.mSprite, text, count, &rcShadow, format, D3DCOLOR_ARGB(DWORD(color.a * 255), 0, 0, 0) );
if( FAILED(hr) )
return hr;
}
hr = fontNode->font->DrawTextW( resmgr.mSprite, text, count, &drawRC, format, color );
if( FAILED(hr) )
return hr;
return S_OK;
}
// --------------------------------------------------------------------------
void CUIDialog::setBackgroundColors( D3DCOLOR colorUL, D3DCOLOR colorUR, D3DCOLOR colorDL, D3DCOLOR colorDR )
{
mColorUL = colorUL;
mColorUR = colorUR;
mColorDL = colorDL;
mColorDR = colorDR;
}
void CUIDialog::setNextDialog( CUIDialog* nextDlg )
{
if( nextDlg == NULL )
nextDlg = this;
mNextDlg = nextDlg;
mNextDlg->mPrevDlg = this;
}
void CUIDialog::clearFocus()
{
if( sCtrlFocus ) {
sCtrlFocus->onFocusOut();
sCtrlFocus = NULL;
}
ReleaseCapture();
}
void CUIDialog::focusDefaultControl()
{
// Check for default control in this dialog
size_t n = mControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl* ctrl = mControls[ i ];
if( ctrl->mDefault ) {
// remove focus from the current control
clearFocus();
// Give focus to the default control
sCtrlFocus = ctrl;
sCtrlFocus->onFocusIn();
return;
}
}
}
void CUIDialog::onCycleFocus( bool forward )
{
// This should only be handled by the dialog which owns the focused
// control, and only if a control currently has focus
if( sCtrlFocus == NULL || sCtrlFocus->mDialog != this )
return;
CUIControl* ctrl = sCtrlFocus;
for( int i=0; i < 0xFFFF; i++ ) {
ctrl = (forward) ? getNextControl( ctrl ) : getPrevControl( ctrl );
// If we've gone in a full circle then focus doesn't change
if( ctrl == sCtrlFocus )
return;
// If the dialog accepts keybord input and the control can have focus then
// move focus
if( ctrl->mDialog->mDoKeyboardInput && ctrl->canHaveFocus() ) {
if( sCtrlFocus )
sCtrlFocus->onFocusOut();
sCtrlFocus = ctrl;
sCtrlFocus->onFocusIn();
return;
}
}
// If we reached this point, the chain of dialogs didn't form a complete loop
ASSERT_FAIL_MSG( "CUIDialog: Multiple dialogs are improperly chained together" );
}
void CUIDialog::onMouseEnter( CUIControl* ctrl )
{
if( ctrl == NULL )
return;
// TBD - implementation?
//ctrl->mMouseOver = true;
}
void CUIDialog::onMouseLeave( CUIControl* ctrl )
{
if( ctrl == NULL )
return;
// TBD - implementation?
//ctrl->mMouseOver = false;
}
// --------------------------------------------------------------------------
const D3DCOLOR colINormal = 0xC0ffffff;
const D3DCOLOR colIPressed = 0xF0e0e0d0;
const D3DCOLOR colIHover = 0xF0ffffe0;
const D3DCOLOR colIFocus = 0xE0ffffe0;
const D3DCOLOR colIDisable = 0x80808080;
const D3DCOLOR colHidden = 0x00000000;
const D3DCOLOR colTDNormal = 0xE0000000;
const D3DCOLOR colTDPress = 0xF0202020;
const D3DCOLOR colTDHover = 0xFF202000;
const D3DCOLOR colTDFocus = 0xFF202000;
const D3DCOLOR colTDDisable= 0x80404040;
const D3DCOLOR colTLNormal = 0xE0ffffff;
const D3DCOLOR colTLPress = 0xF0e0e0d0;
const D3DCOLOR colTLHover = 0xFFffffe0;
const D3DCOLOR colTLFocus = 0xFFffffe0;
const D3DCOLOR colTLDisable= 0x80808080;
void CUIDialog::initDefaultElements()
{
CD3DTexture* tex = RGET_TEX("guiskin");
setDefaultTexture( *tex );
setFont( 0, "Tahoma", 12, FW_NORMAL );
SUIElement element;
RECT textureRect;
// -------------------------------------
// element for the caption
SetRect( &textureRect, 17, 269, 241, 287 );
mCaptionElement.setTexture( tex, &textureRect );
//mCaptionElement.colorTexture.colors[ UISTATE_NORMAL ] = D3DCOLOR_ARGB(255, 255, 255, 255);
mCaptionElement.setFont( 0, false, DT_LEFT | DT_VCENTER );
// Pre-blend as we don't need to transition the state
mCaptionElement.colorTexture.blend( UISTATE_NORMAL, 10.0f );
mCaptionElement.colorFont.blend( UISTATE_NORMAL, 10.0f );
// -------------------------------------
// CUIStatic
element.setFont( 0, false, DT_LEFT | DT_VCENTER );
element.colorFont.colors[ UISTATE_DISABLED ] = 0xA0a0a0a0;
setDefaultElement( UICTRL_STATIC, 0, &element );
// -------------------------------------
// CUIImage
SetRect( &textureRect, 0, 0, 512, 512 );
element.setTexture( tex, &textureRect );
element.colorTexture.colors[ UISTATE_NORMAL ] = 0xFFffffff;
setDefaultElement( UICTRL_IMAGE, 0, &element );
// -------------------------------------
// CUIButton
// Button
SetRect( &textureRect, 0, 320, 136, 394 );
element.setTexture( tex, &textureRect );
element.setFont( 0, true );
setDefaultElement( UICTRL_BUTTON, 0, &element );
// -------------------------------------
// CUICheckBox
// Box
SetRect( &textureRect, 19, 394, 38, 413 );
element.setTexture( tex, &textureRect );
element.setFont( 0, false, DT_LEFT | DT_VCENTER );
setDefaultElement( UICTRL_CHECKBOX, 0, &element );
// Check
SetRect( &textureRect, 0, 394, 19, 413 );
element.setTexture( tex, &textureRect );
setDefaultElement( UICTRL_CHECKBOX, 1, &element );
// -------------------------------------
// CUIRollout
// Box
SetRect( &textureRect, 0, 24, 256, 49 );
element.setTexture( tex, &textureRect );
element.setFont( 0, true, DT_CENTER | DT_VCENTER );
setDefaultElement( UICTRL_ROLLOUT, 0, &element );
// Rollout
SetRect( &textureRect, 0, 106, 256, 320 );
element.setTexture( tex, &textureRect );
element.colorTexture.colors[UISTATE_MOUSEOVER] = colIFocus;
setDefaultElement( UICTRL_ROLLOUT, 1, &element );
// -------------------------------------
// CUISlider
// Track
SetRect( &textureRect, 0, 0, 256, 24 );
element.setTexture( tex, &textureRect );
//element.colorTexture.colors[ UISTATE_NORMAL ] = D3DCOLOR_ARGB(150, 255, 255, 255);
//element.colorTexture.colors[ UISTATE_FOCUS ] = D3DCOLOR_ARGB(200, 255, 255, 255);
//element.colorTexture.colors[ UISTATE_DISABLED ] = D3DCOLOR_ARGB(70, 255, 255, 255);
setDefaultElement( UICTRL_SLIDER, 0, &element );
// Button
SetRect( &textureRect, 135, 54, 162, 81 );
element.setTexture( tex, &textureRect );
setDefaultElement( UICTRL_SLIDER, 1, &element );
// -------------------------------------
// CUIRadioButton
// Box
SetRect( &textureRect, 54, 54, 81, 81 );
element.setTexture( tex, &textureRect );
element.setFont( 0, false, DT_LEFT | DT_VCENTER );
setDefaultElement( UICTRL_RADIOBUTTON, 0, &element );
// Check
SetRect( &textureRect, 81, 54, 108, 81 );
element.setTexture( tex, &textureRect );
setDefaultElement( UICTRL_RADIOBUTTON, 1, &element );
// -------------------------------------
// CUIComboBox
// main
SetRect( &textureRect, 0, 24, 256, 49 );
//SetRect( &textureRect, 7, 81, 247, 123 );
element.setTexture( tex, &textureRect );
element.setFont( 0, true );
setDefaultElement( UICTRL_COMBOBOX, 0, &element );
// button
SetRect( &textureRect, 38, 394, 57, 413 );
//SetRect( &textureRect, 272, 0, 325, 49 );
element.setTexture( tex, &textureRect );
//element.colorTexture.colors[ UISTATE_NORMAL ] = D3DCOLOR_ARGB(150, 255, 255, 255);
//element.colorTexture.colors[ UISTATE_PRESSED ] = D3DCOLOR_ARGB(255, 150, 150, 150);
//element.colorTexture.colors[ UISTATE_FOCUS ] = D3DCOLOR_ARGB(200, 255, 255, 255);
//element.colorTexture.colors[ UISTATE_DISABLED ] = D3DCOLOR_ARGB(70, 255, 255, 255);
setDefaultElement( UICTRL_COMBOBOX, 1, &element );
// dropdown
SetRect( &textureRect, 0, 106, 256, 320 );
//SetRect( &textureRect, 7, 123, 241, 265 );
element.setTexture( tex, &textureRect );
element.setFont( 0, true, DT_LEFT | DT_TOP );
element.colorTexture.colors[ UISTATE_NORMAL ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_FOCUS ] |= 0xFF000000;
setDefaultElement( UICTRL_COMBOBOX, 2, &element );
// selection
SetRect( &textureRect, 0, 444, 256, 460 );
element.setTexture( tex, &textureRect );
element.setFont( 0, false, DT_LEFT | DT_TOP );
//element.colorTexture.colors[ UISTATE_NORMAL ] = 0x80000000;
//element.colorTexture.colors[ UISTATE_FOCUS ] = 0x80000000;
//element.colorTexture.colors[ UISTATE_PRESSED ] = 0x80000000;
setDefaultElement( UICTRL_COMBOBOX, 3, &element );
// -------------------------------------
// CUIScrollBar
// track
SetRect( &textureRect, 256, 96, 272, 130 );
element.setTexture( tex, &textureRect );
element.colorTexture.colors[ UISTATE_NORMAL ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_FOCUS ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_DISABLED ] |= 0xFF000000;
setDefaultElement( UICTRL_SCROLLBAR, 0, &element );
// up arrow
SetRect( &textureRect, 256, 81, 272, 96 );
element.setTexture( tex, &textureRect );
element.colorTexture.colors[ UISTATE_NORMAL ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_FOCUS ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_DISABLED ] |= 0xFF000000;
setDefaultElement( UICTRL_SCROLLBAR, 1, &element );
// down arrow
SetRect( &textureRect, 256, 130, 272, 145 );
element.setTexture( tex, &textureRect );
element.colorTexture.colors[ UISTATE_NORMAL ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_FOCUS ] |= 0xFF000000;
element.colorTexture.colors[ UISTATE_DISABLED ] |= 0xFF000000;
setDefaultElement( UICTRL_SCROLLBAR, 2, &element );
// button
SetRect( &textureRect, 256, 146, 272, 178 );
element.setTexture( tex, &textureRect );
//element.colorTexture.colors[ UISTATE_NORMAL ] |= 0xFF000000;
//element.colorTexture.colors[ UISTATE_FOCUS ] |= 0xFF000000;
//element.colorTexture.colors[ UISTATE_DISABLED ] |= 0xFF000000;
setDefaultElement( UICTRL_SCROLLBAR, 3, &element );
// -------------------------------------
// CUIListBox
// Main
SetRect( &textureRect, 13, 124, 241, 265 );
element.setTexture( tex, &textureRect );
element.setFont( 0, true, DT_LEFT | DT_TOP );
setDefaultElement( UICTRL_LISTBOX, 0, &element );
// Selection
SetRect( &textureRect, 17, 269, 241, 287 );
element.setTexture( tex, &textureRect );
element.setFont( 0, false, DT_LEFT | DT_TOP );
setDefaultElement( UICTRL_LISTBOX, 1, &element );
}
// --------------------------------------------------------------------------
// CUIResourceManager class
// --------------------------------------------------------------------------
CUIResourceManager::CUIResourceManager( int screenX, int screenY )
: mStateBlock(NULL), mSprite(NULL),
mScreenX( screenX ), mScreenY( screenY ),
mInvScreenX( 1.0f/screenX ), mInvScreenY( 1.0f/screenY )
{
}
CUIResourceManager::~CUIResourceManager()
{
for( size_t i = 0; i < mFontCache.size(); ++i )
safeDelete( mFontCache[i] );
mFontCache.clear();
}
void CUIResourceManager::createResource()
{
HRESULT hr = S_OK;
/*
for( int i = 0; i < mFontCache.size(); ++i ) {
hr = createFont( i );
assert( SUCCEEDED(hr) );
}
*/
V( D3DXCreateSprite( &CD3DDevice::getInstance().getDevice(), &mSprite ) );
assert( SUCCEEDED(hr) );
}
void CUIResourceManager::activateResource()
{
HRESULT hr = S_OK;
for( size_t i = 0; i < mFontCache.size(); ++i ) {
hr = createFont( i );
assert( SUCCEEDED(hr) );
//SUIFontNode* fontNode = mFontCache[ i ];
//if( fontNode->font )
// fontNode->font->OnResetDevice();
}
if( mSprite )
mSprite->OnResetDevice();
V( CD3DDevice::getInstance().getDevice().CreateStateBlock( D3DSBT_ALL, &mStateBlock ) );
assert( SUCCEEDED(hr) );
}
void CUIResourceManager::passivateResource()
{
for( size_t i = 0; i < mFontCache.size(); ++i ) {
//SUIFontNode* fontNode = mFontCache[ i ];
//if( fontNode->font )
// fontNode->font->OnLostDevice();
safeRelease( mFontCache[ i ]->font );
}
if( mSprite )
mSprite->OnLostDevice();
safeRelease( mStateBlock );
}
void CUIResourceManager::deleteResource()
{
// Release the resources but don't clear the cache, as these will need
// to be recreated if the device is recreated
//for( int i = 0; i < mFontCache.size(); ++i )
// safeRelease( mFontCache[ i ]->font );
safeRelease( mSprite );
}
int CUIResourceManager::addFont( const char* facename, LONG height, LONG weight )
{
// See if this font already exists
for( size_t i=0; i < mFontCache.size(); i++ ) {
SUIFontNode* fontNode = mFontCache[i];
if( 0 == _strnicmp( fontNode->facename, facename, MAX_PATH-1 ) &&
fontNode->height == height &&
fontNode->weight == weight )
{
return (int)i;
}
}
// add a new font and try to create it
SUIFontNode* newFontNode = new SUIFontNode();
if( newFontNode == NULL )
return -1;
ZeroMemory( newFontNode, sizeof(SUIFontNode) );
strncpy( newFontNode->facename, facename, MAX_PATH-1 );
newFontNode->height = height;
newFontNode->weight = weight;
mFontCache.push_back( newFontNode );
size_t fontIdx = mFontCache.size()-1;
// If a device is available, try to create immediately
if( CD3DDevice::getInstance().isDevice() )
createFont( fontIdx );
return (int)fontIdx;
}
HRESULT CUIResourceManager::createFont( size_t fontIdx )
{
HRESULT hr = S_OK;
SUIFontNode* fontNode = mFontCache[ fontIdx ];
safeRelease( fontNode->font );
int height = (int)xToBB( float(fontNode->height), CD3DDevice::getInstance().getBackBufferWidth() );
V_RETURN( D3DXCreateFont( &CD3DDevice::getInstance().getDevice(), height, 0, fontNode->weight, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
fontNode->facename, &fontNode->font ) );
return S_OK;
}
// ---------------------------------------------------------------------------
// CUIControl class
// ---------------------------------------------------------------------------
CUIControl::CUIControl( CUIDialog *dialog )
: mVisible(true), mMouseOver(false), mHasFocus(false), mDefault(false),
mX(0), mY(0), mWidth(0), mHeight(0),
mDialog(/*dialog*/NULL), mIndex(0),
mID(0), mType(UICTRL_BUTTON), mHotkey(0), mUserData(NULL), mEnabled(true)
{
ZeroMemory( &mBBox, sizeof( mBBox ) );
}
CUIControl::~CUIControl()
{
stl_utils::wipe( mElements );
}
void CUIControl::setTextColor( D3DCOLOR color )
{
SUIElement* element = mElements[ 0 ];
if( element )
element->colorFont.colors[UISTATE_NORMAL] = color;
}
HRESULT CUIControl::setElement( size_t index, SUIElement* element )
{
if( element == NULL )
return E_INVALIDARG;
// Make certain the array is this large
for( size_t i = mElements.size(); i <= index; ++i ) {
SUIElement* newElem = new SUIElement();
if( newElem == NULL )
return E_OUTOFMEMORY;
mElements.push_back( newElem );
}
// Update the data
*mElements[index] = *element;
return S_OK;
}
void CUIControl::refresh()
{
mMouseOver = false;
mHasFocus = false;
size_t n = mElements.size();
for( size_t i = 0; i < n; ++i )
mElements[i]->refresh();
}
void CUIControl::updateRects()
{
mBBox.set( mX, mY, mX + mWidth, mY + mHeight );
}
// --------------------------------------------------------------------------
// CUIStatic class
// --------------------------------------------------------------------------
CUIStatic::CUIStatic( CUIDialog *dialog )
{
mType = UICTRL_STATIC;
mDialog = dialog;
ZeroMemory( &mText, sizeof(mText) );
size_t n = mElements.size();
for( size_t i=0; i < n; ++i )
safeDelete( mElements[i] );
mElements.clear();
}
void CUIStatic::render( IDirect3DDevice9* device, float dt )
{
if( !mVisible )
return;
eUIControlState state = UISTATE_NORMAL;
if( !mEnabled )
state = UISTATE_DISABLED;
SUIElement* element = mElements[ 0 ];
element->colorFont.blend( state, dt );
mDialog->drawText( mText, element, &mBBox, !element->darkFont );
}
HRESULT CUIStatic::getTextCopy( char* strDest, size_t bufferCount )
{
// Validate incoming parameters
if( strDest == NULL || bufferCount == 0 )
return E_INVALIDARG;
// Copy the window text
strncpy( strDest, mText, bufferCount );
strDest[bufferCount-1] = 0;
return S_OK;
}
HRESULT CUIStatic::setText( const char* text )
{
if( text == NULL ) {
mText[0] = 0;
return S_OK;
}
strncpy( mText, text, MAX_PATH-1 );
return S_OK;
}
// --------------------------------------------------------------------------
// CUIImage class
// --------------------------------------------------------------------------
CUIImage::CUIImage( CUIDialog *dialog )
{
mType = UICTRL_IMAGE;
mDialog = dialog;
size_t n = mElements.size();
for( size_t i=0; i < n; ++i )
safeDelete( mElements[i] );
mElements.clear();
}
void CUIImage::render( IDirect3DDevice9* device, float dt )
{
if( !mVisible )
return;
eUIControlState state = UISTATE_NORMAL;
SUIElement* element = mElements[ 0 ];
element->colorTexture.current = element->colorTexture.colors[state];
mDialog->drawSprite( element, &mBBox );
}
// --------------------------------------------------------------------------
// CUIButton class
// --------------------------------------------------------------------------
CUIButton::CUIButton( CUIDialog *dialog )
{
mType = UICTRL_BUTTON;
mDialog = dialog;
mPressed = false;
mHotkey = 0;
}
bool CUIButton::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg ) {
case WM_KEYDOWN: {
switch( wParam ) {
case VK_SPACE:
mPressed = true;
return true;
}
}
case WM_KEYUP: {
switch( wParam ) {
case VK_SPACE:
if( mPressed ) {
mPressed = false;
mDialog->sendEvent( UIEVENT_BUTTON_CLICKED, true, this );
}
return true;
}
}
}
return false;
}
bool CUIButton::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg ) {
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
if( containsPoint( pt ) ) {
// Pressed while inside the control
mPressed = true;
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
if( !mHasFocus )
mDialog->requestFocus( this );
return true;
}
break;
}
case WM_LBUTTONUP:
{
if( mPressed ) {
mPressed = false;
ReleaseCapture();
if( !mDialog->mDoKeyboardInput )
mDialog->clearFocus();
// Button click
if( containsPoint( pt ) )
mDialog->sendEvent( UIEVENT_BUTTON_CLICKED, true, this );
return true;
}
break;
}
};
return false;
}
void CUIButton::render( IDirect3DDevice9* device, float dt )
{
int nOffsetX = 0;
int nOffsetY = 0;
eUIControlState state = getState();
if( mVisible && mEnabled && mPressed ) {
nOffsetX = 1;
nOffsetY = 1;
}
// Background fill layer
// TODO: remove magic numbers
SUIElement* element = mElements[ 0 ];
float blendRate = ( state == UISTATE_PRESSED ) ? 0.0f : 0.8f;
SFRect rcWindow = mBBox;
rcWindow.offset( float(nOffsetX), float(nOffsetY) );
// blend current color
element->colorTexture.blend( state, dt, blendRate );
element->colorFont.blend( state, dt, blendRate );
mDialog->drawSprite( element, &rcWindow );
mDialog->drawText( mText, element, &rcWindow, !element->darkFont );
// Main button
/*
element = mElements[ 1 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
element->colorFont.blend( state, dt, blendRate );
mDialog->drawSprite( element, &rcWindow );
mDialog->drawText( mText, element, &rcWindow, !element.darkFont );
*/
}
eUIControlState CUIButton::getState() const
{
eUIControlState state = UISTATE_NORMAL;
if( !mVisible )
state = UISTATE_HIDDEN;
else if( !mEnabled )
state = UISTATE_DISABLED;
else if( mPressed )
state = UISTATE_PRESSED;
else if( mMouseOver )
state = UISTATE_MOUSEOVER;
else if( mHasFocus )
state = UISTATE_FOCUS;
return state;
}
// --------------------------------------------------------------------------
// CUICheckBox class
// --------------------------------------------------------------------------
CUICheckBox::CUICheckBox( CUIDialog *dialog )
{
mType = UICTRL_CHECKBOX;
mDialog = dialog;
mChecked = false;
}
bool CUICheckBox::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg ) {
case WM_KEYDOWN:
{
switch( wParam ) {
case VK_SPACE:
mPressed = true;
return true;
}
}
case WM_KEYUP:
{
switch( wParam ) {
case VK_SPACE:
if( mPressed ) {
mPressed = false;
setCheckedInternal( !mChecked, true );
}
return true;
}
}
}
return false;
}
bool CUICheckBox::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg ) {
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
if( containsPoint( pt ) ) {
// Pressed while inside the control
mPressed = true;
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
if( !mHasFocus && mDialog->mDoKeyboardInput )
mDialog->requestFocus( this );
return true;
}
break;
}
case WM_LBUTTONUP:
{
if( mPressed ) {
mPressed = false;
ReleaseCapture();
// Button click
if( containsPoint( pt ) )
setCheckedInternal( !mChecked, true );
return true;
}
break;
}
};
return false;
}
void CUICheckBox::setCheckedInternal( bool chk, bool fromInput )
{
bool changed = (chk != mChecked);
mChecked = chk;
if( changed )
mDialog->sendEvent( UIEVENT_CHECKBOX_CHANGED, fromInput, this );
}
bool CUICheckBox::containsPoint( const POINT& pt ) const
{
return mBBox.containsPoint( pt ) || mRectButton.containsPoint( pt );
}
void CUICheckBox::updateRects()
{
CUIButton::updateRects();
mRectButton = mBBox;
mRectButton.right = mRectButton.left + mRectButton.getHeight();
mRectText = mBBox;
mRectText.left += 1.25f * mRectButton.getWidth();
}
void CUICheckBox::render( IDirect3DDevice9* device, float dt )
{
eUIControlState state = getState();
//debug
//mDialog->drawRect( &mBBox, D3DCOLOR_ARGB(255, 255, 255, 0) );
//mDialog->drawRect( &mRectButton, D3DCOLOR_ARGB(255, 0, 255, 255) );
//TODO: remove magic numbers
SUIElement* element = mElements[ 0 ];
float blendRate = ( state == UISTATE_PRESSED ) ? 0.0f : 0.8f;
element->colorTexture.blend( state, dt, blendRate );
element->colorFont.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectButton );
mDialog->drawText( mText, element, &mRectText, !element->darkFont );
if( !mChecked )
state = UISTATE_HIDDEN;
element = mElements[ 1 ];
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectButton );
}
// --------------------------------------------------------------------------
// CUIRollout class
// --------------------------------------------------------------------------
CUIRollout::CUIRollout( CUIDialog *dialog )
{
mType = UICTRL_ROLLOUT;
mDialog = dialog;
mChecked = false;
mChildControls.reserve( 8 );
}
void CUIRollout::setCheckedInternal( bool chk, bool fromInput )
{
bool changed = (chk != mChecked);
mChecked = chk;
updateRects();
if( changed ) {
mDialog->sendEvent( UIEVENT_CHECKBOX_CHANGED, fromInput, this );
// set visibility for child controls
size_t n = mChildControls.size();
for( size_t i = 0; i < n; ++i ) {
mChildControls[i]->setVisible( mChecked );
}
}
}
void CUIRollout::offsetPos( float dx, float dy )
{
setLocation( mX + dx, mY + dy );
size_t n = mChildControls.size();
for( size_t i = 0; i < n; ++i ) {
CUIControl& ctrl = *mChildControls[i];
ctrl.setLocation( ctrl.mX + dx, ctrl.mY + dy );
}
}
bool CUIRollout::containsPoint( const POINT& pt ) const
{
return mBBox.containsPoint( pt ) || mRectText.containsPoint( pt );
}
void CUIRollout::updateRects()
{
CUIButton::updateRects();
mRectButton = mBBox;
float shiftup = mBBox.getHeight() / 8;
mRectText = mBBox;
mRectText.top = mBBox.bottom - shiftup;
mRectText.bottom = mBBox.bottom + (mChecked ? mRolloutHeight : 0);
}
void CUIRollout::render( IDirect3DDevice9* device, float dt )
{
eUIControlState state = getState();
// TODO: remove magic numbers
float blendRate = ( state == UISTATE_PRESSED ) ? 0.0f : 0.4f;
SUIElement* element = mElements[ 1 ];
element->colorTexture.blend( !isExpanded() ? UISTATE_HIDDEN : state, dt, blendRate );
if( isExpanded() )
mDialog->drawSprite( element, &mRectText );
element = mElements[ 0 ];
element->colorTexture.blend( state, dt, blendRate );
element->colorFont.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectButton );
mDialog->drawText( mText, element, &mRectButton, !element->darkFont );
}
// --------------------------------------------------------------------------
// CUIRadioButton class
// --------------------------------------------------------------------------
CUIRadioButton::CUIRadioButton( CUIDialog *dialog )
{
mType = UICTRL_RADIOBUTTON;
mDialog = dialog;
}
bool CUIRadioButton::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg ) {
case WM_KEYDOWN:
{
switch( wParam ) {
case VK_SPACE:
mPressed = true;
return true;
}
}
case WM_KEYUP:
{
switch( wParam ) {
case VK_SPACE:
if( mPressed ) {
mPressed = false;
mDialog->clearRadioButtonGroup( mButtonGroup );
mChecked = !mChecked;
mDialog->sendEvent( UIEVENT_RADIOBUTTON_CHANGED, true, this );
}
return true;
}
}
}
return false;
}
bool CUIRadioButton::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg ) {
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
if( containsPoint( pt ) ) {
// Pressed while inside the control
mPressed = true;
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
if( !mHasFocus && mDialog->mDoKeyboardInput )
mDialog->requestFocus( this );
return true;
}
break;
}
case WM_LBUTTONUP:
{
if( mPressed ) {
mPressed = false;
ReleaseCapture();
// Button click
if( containsPoint( pt ) ) {
mDialog->clearRadioButtonGroup( mButtonGroup );
mChecked = !mChecked;
mDialog->sendEvent( UIEVENT_RADIOBUTTON_CHANGED, true, this );
}
return true;
}
break;
}
};
return false;
}
void CUIRadioButton::setCheckedInternal( bool chk, bool clearGroup, bool fromInput )
{
if( chk && clearGroup )
mDialog->clearRadioButtonGroup( mButtonGroup );
mChecked = chk;
mDialog->sendEvent( UIEVENT_RADIOBUTTON_CHANGED, fromInput, this );
}
// --------------------------------------------------------------------------
// CUIComboBox class
// --------------------------------------------------------------------------
CUIComboBox::CUIComboBox( CUIDialog *dialog )
: mScrollBar( dialog )
{
mType = UICTRL_COMBOBOX;
mDialog = dialog;
mDropHeight = 75;
mSBWidth = 12;
mOpened = false;
mSelected = -1;
mFocused = -1;
}
CUIComboBox::~CUIComboBox()
{
removeAllItems();
}
void CUIComboBox::setTextColor( D3DCOLOR color )
{
SUIElement* element = mElements[ 0 ];
if( element )
element->colorFont.colors[UISTATE_NORMAL] = color;
element = mElements[ 2 ];
if( element )
element->colorFont.colors[UISTATE_NORMAL] = color;
}
void CUIComboBox::updateRects()
{
CUIButton::updateRects();
mRectButton = mBBox;
mRectButton.left = mRectButton.right - mRectButton.getHeight();
mRectText = mBBox;
//mRectText.right = mRectButton.left;
mRectDropdown = mRectText;
mRectDropdown.offset( 0, 0.90f * mRectText.getHeight() );
mRectDropdown.bottom += mDropHeight;
mRectDropdown.right -= mSBWidth;
float hgt = mBBox.getHeight();
mRectDropdownText = mRectDropdown;
mRectDropdownText.left += hgt/4;
mRectDropdownText.right -= hgt/4;
mRectDropdownText.top += hgt/4;
mRectDropdownText.bottom -= hgt/4;
// Update the scrollbar's rects
mScrollBar.setLocation( mRectDropdown.right, mRectDropdown.top+2 );
mScrollBar.setSize( mSBWidth, mRectDropdown.getHeight() - 2 );
SUIFontNode* fontNode = CUIResourceManager::getInstance().getFontNode( mElements[ 2 ]->fontIdx );
if( fontNode && fontNode->height ) {
mScrollBar.setPageSize( int(mRectDropdownText.getHeight() / fontNode->height) );
// The selected item may have been scrolled off the page.
// Ensure that it is in page again.
mScrollBar.showItem( mSelected );
}
}
void CUIComboBox::onFocusOut()
{
CUIButton::onFocusOut();
mOpened = false;
}
bool CUIComboBox::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
const DWORD REPEAT_MASK = (0x40000000);
if( !mEnabled || !mVisible )
return false;
// Let the scroll bar have a chance to handle it first
if( mScrollBar.handleKeyb( msg, wParam, lParam ) )
return true;
switch( msg ) {
case WM_KEYDOWN:
{
switch( wParam ) {
case VK_RETURN:
if( mOpened ) {
if( mSelected != mFocused ) {
mSelected = mFocused;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
}
mOpened = false;
if( !mDialog->mDoKeyboardInput )
mDialog->clearFocus();
return true;
}
break;
case VK_F4:
// Filter out auto-repeats
if( lParam & REPEAT_MASK )
return true;
mOpened = !mOpened;
if( !mOpened ) {
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
if( !mDialog->mDoKeyboardInput )
mDialog->clearFocus();
}
return true;
case VK_LEFT:
case VK_UP:
if( mFocused > 0 ) {
mFocused--;
mSelected = mFocused;
if( !mOpened )
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
}
return true;
case VK_RIGHT:
case VK_DOWN:
if( mFocused+1 < (int)getItemCount() ) {
++mFocused;
mSelected = mFocused;
if( !mOpened )
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
}
return true;
}
break;
}
}
return false;
}
bool CUIComboBox::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
// Let the scroll bar handle it first.
if( mOpened && mScrollBar.handleMouse( msg, pt, wParam, lParam ) )
return true;
switch( msg ) {
case WM_MOUSEMOVE:
{
if( mOpened && mRectDropdown.containsPoint( pt ) ) {
// Determine which item has been selected
for( int i=0; i < (int)mItems.size(); i++ ) {
SUIComboItem* item = mItems[ i ];
if( item -> vis && item->activeRect.containsPoint( pt ) ) {
mFocused = i;
}
}
return true;
}
break;
}
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
if( containsPoint( pt ) ) {
// Pressed while inside the control
mPressed = true;
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
if( !mHasFocus )
mDialog->requestFocus( this );
// Toggle dropdown
if( mHasFocus ) {
mOpened = !mOpened;
if( !mOpened ) {
if( !mDialog->mDoKeyboardInput )
mDialog->clearFocus();
}
}
return true;
}
// Perhaps this click is within the dropdown
if( mOpened && mRectDropdown.containsPoint( pt ) ) {
// Determine which item has been selected
for( int i = mScrollBar.getTrackPos(); i < (int)mItems.size(); i++ ) {
SUIComboItem* item = mItems[ i ];
if( item -> vis && item->activeRect.containsPoint( pt ) ) {
mFocused = mSelected = i;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
mOpened = false;
if( !mDialog->mDoKeyboardInput )
mDialog->clearFocus();
break;
}
}
return true;
}
// Mouse click not on main control or in dropdown, fire an event if needed
if( mOpened ) {
mFocused = mSelected;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
mOpened = false;
}
// Make sure the control is no longer in a pressed state
mPressed = false;
// Release focus if appropriate
if( !mDialog->mDoKeyboardInput ) {
mDialog->clearFocus();
}
break;
}
case WM_LBUTTONUP:
{
if( mPressed && containsPoint( pt ) ) {
// Button click
mPressed = false;
ReleaseCapture();
return true;
}
break;
}
case WM_MOUSEWHEEL:
{
int zDelta = (short) HIWORD(wParam) / WHEEL_DELTA;
if( mOpened ) {
UINT lines;
SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &lines, 0 );
mScrollBar.scroll( -zDelta * lines );
} else {
if( zDelta > 0 ) {
if( mFocused > 0 ) {
mFocused--;
mSelected = mFocused;
if( !mOpened )
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
}
} else {
if( mFocused+1 < (int)getItemCount() ) {
mFocused++;
mSelected = mFocused;
if( !mOpened )
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
}
}
}
return true;
}
};
return false;
}
void CUIComboBox::onHotkey()
{
if( mOpened )
return;
if( mSelected == -1 )
return;
mSelected++;
if( mSelected >= (int) mItems.size() )
mSelected = 0;
mFocused = mSelected;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, true, this );
}
void CUIComboBox::render( IDirect3DDevice9* device, float dt )
{
eUIControlState state = UISTATE_NORMAL;
if( !mOpened )
state = UISTATE_HIDDEN;
//
// dropdown box
SUIElement* element = mElements[ 2 ];
// If we have not initialized the scroll bar page size, do that now.
static bool sbInit;
if( !sbInit ) {
// Update the page size of the scroll bar
if( CUIResourceManager::getInstance().getFontNode( element->fontIdx )->height )
mScrollBar.setPageSize( int(mRectDropdownText.getHeight() / CUIResourceManager::getInstance().getFontNode( element->fontIdx )->height) );
else
mScrollBar.setPageSize( int(mRectDropdownText.getHeight()) );
sbInit = true;
}
// scroll bar
if( mOpened )
mScrollBar.render( device, dt );
// blend current color
element->colorTexture.blend( state, dt );
element->colorFont.blend( state, dt );
mDialog->drawSprite( element, &mRectDropdown );
//
// selection outline
SUIElement* selElement = mElements[ 3 ];
//selElement->colorTexture.current = element->colorTexture.current;
selElement->colorTexture.current = selElement->colorTexture.colors[ UISTATE_NORMAL ];
selElement->colorFont.current = selElement->colorFont.colors[ UISTATE_NORMAL ];
SUIFontNode* font = mDialog->getFont( element->fontIdx );
float curY = mRectDropdownText.top;
float nRemainingHeight = mRectDropdownText.getHeight();
for( size_t i = mScrollBar.getTrackPos(); i < mItems.size(); ++i ) {
SUIComboItem* item = mItems[ i ];
// Make sure there's room left in the dropdown
nRemainingHeight -= font->height;
if( nRemainingHeight < 0 ) {
item->vis = false;
continue;
}
item->activeRect.set( mRectDropdownText.left, curY, mRectDropdownText.right, curY + font->height );
curY += font->height;
//debug
//int blue = 50 * i;
//mDialog->drawRect( &item->activeRect, 0xFFFF0000 | blue );
item->vis = true;
if( mOpened ) {
if( (int)i == mFocused ) {
SFRect rc;
rc.set( mRectDropdown.left, item->activeRect.top-2, mRectDropdown.right, item->activeRect.bottom+2 );
mDialog->drawSprite( selElement, &rc );
mDialog->drawText( item->text, selElement, &item->activeRect, !selElement->darkFont );
} else {
mDialog->drawText( item->text, element, &item->activeRect, !element->darkFont );
}
}
}
//
// main & button
int nOffsetX = 0;
int nOffsetY = 0;
state = UISTATE_NORMAL;
if( !mVisible )
state = UISTATE_HIDDEN;
else if( !mEnabled )
state = UISTATE_DISABLED;
else if( mPressed ) {
state = UISTATE_PRESSED;
nOffsetX = 1;
nOffsetY = 1;
} else if( mMouseOver ) {
state = UISTATE_MOUSEOVER;
//nOffsetX = -1;
//nOffsetY = -1;
} else if( mHasFocus )
state = UISTATE_FOCUS;
float blendRate = ( state == UISTATE_PRESSED ) ? 0.0f : 0.8f;
// main box
if( mOpened )
state = UISTATE_PRESSED;
element = mElements[ 0 ];
element->colorTexture.blend( state, dt, blendRate );
element->colorFont.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectText);
if( mSelected >= 0 && mSelected < (int) mItems.size() ) {
SUIComboItem* item = mItems[ mSelected ];
if( item != NULL ) {
mDialog->drawText( item->text, element, &mRectText, !element->darkFont );
}
}
// button
element = mElements[ 1 ];
element->colorTexture.blend( state, dt, blendRate );
SFRect rcWindow = mRectButton;
rcWindow.offset( float(nOffsetX), float(nOffsetY) );
mDialog->drawSprite( element, &rcWindow );
}
HRESULT CUIComboBox::addItem( const char* text, const void* data, bool updateSelectionIf1st )
{
// Validate parameters
if( text== NULL )
return E_INVALIDARG;
// Create a new item and set the data
SUIComboItem* item = new SUIComboItem;
if( item == NULL ) {
ASSERT_FAIL_MSG( "new" );
return E_OUTOFMEMORY;
}
ZeroMemory( item, sizeof(SUIComboItem) );
strncpy( item->text, text, 255 );
item->data = data;
mItems.push_back( item );
// Update the scroll bar with new range
mScrollBar.setTrackRange( 0, (int)mItems.size() );
// If this is the only item in the list, it's selected
if( updateSelectionIf1st && getItemCount() == 1 ) {
mSelected = 0;
mFocused = 0;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, false, this );
}
return S_OK;
}
void CUIComboBox::removeItem( size_t index )
{
SUIComboItem* item = mItems[ index ];
safeDelete( item );
mItems.erase( mItems.begin() + index );
mScrollBar.setTrackRange( 0, (int)mItems.size() );
if( mSelected >= (int)mItems.size() )
mSelected = (int)mItems.size() - 1;
}
void CUIComboBox::removeAllItems()
{
for( size_t i=0; i < mItems.size(); i++ )
safeDelete( mItems[i] );
mItems.clear();
mScrollBar.setTrackRange( 0, 1 );
mFocused = mSelected = -1;
}
bool CUIComboBox::containsItem( const char* text, size_t start ) const
{
return ( -1 != findItem( text, start ) );
}
int CUIComboBox::findItem( const char* text, size_t start ) const
{
if( text == NULL )
return -1;
for( size_t i = start; i < mItems.size(); i++ ) {
SUIComboItem* item = mItems[i];
if( 0 == strcmp( item->text, text ) ) {
return (int)i;
}
}
return -1;
}
const void* CUIComboBox::getSelectedData()
{
if( mSelected < 0 )
return NULL;
SUIComboItem* item = mItems[ mSelected ];
return item->data;
}
SUIComboItem* CUIComboBox::getSelectedItem()
{
if( mSelected < 0 )
return NULL;
return mItems[ mSelected ];
}
const void* CUIComboBox::getItemData( const char* text )
{
int index = findItem( text );
if( index == -1 )
return NULL;
SUIComboItem* item = mItems[index];
if( item == NULL ) {
ASSERT_FAIL_MSG( "" );
return NULL;
}
return item->data;
}
HRESULT CUIComboBox::setSelectedByIndex( int index )
{
if( index >= (int)getItemCount() )
return E_INVALIDARG;
mFocused = mSelected = index;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, false, this );
return S_OK;
}
HRESULT CUIComboBox::setSelectedByText( const char* text )
{
if( text == NULL )
return E_INVALIDARG;
int index = findItem( text );
if( index == -1 )
return E_FAIL;
mFocused = mSelected = index;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, false, this );
return S_OK;
}
HRESULT CUIComboBox::setSelectedByData( const void* data )
{
for( int i=0; i < (int)mItems.size(); i++ ) {
SUIComboItem* item = mItems[i];
if( item->data == data ) {
mFocused = mSelected = i;
mDialog->sendEvent( UIEVENT_COMBOBOX_SELECTION_CHANGED, false, this );
return S_OK;
}
}
return E_FAIL;
}
// --------------------------------------------------------------------------
// CUISlider control
// --------------------------------------------------------------------------
CUISlider::CUISlider( CUIDialog *dialog )
{
mType = UICTRL_SLIDER;
mDialog = dialog;
mMin = 0;
mMax = 100;
mValue = 50;
mPressed = false;
}
bool CUISlider::containsPoint( const POINT& pt ) const
{
return mBBox.containsPoint( pt ) || mRectButton.containsPoint( pt );
}
void CUISlider::updateRects()
{
CUIControl::updateRects();
mRectButton = mBBox;
mRectButton.right = mRectButton.left + mRectButton.getHeight();
mRectButton.offset( -mRectButton.getWidth()/2, 0 );
mButtonX = ( (mValue - mMin) * mBBox.getWidth() / (mMax - mMin) );
mRectButton.offset( mButtonX, 0 );
}
int CUISlider::getValueFromPos( int x )
{
float valPerCoord = (float)(mMax - mMin) / mBBox.getWidth();
return (int) (0.5f + mMin + valPerCoord * (x - mBBox.left));
}
bool CUISlider::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg )
{
case WM_KEYDOWN:
{
switch( wParam )
{
case VK_HOME:
setValueInternal( mMin, true );
return true;
case VK_END:
setValueInternal( mMax, true );
return true;
case VK_PRIOR:
case VK_LEFT:
case VK_UP:
setValueInternal( mValue - 1, true );
return true;
case VK_NEXT:
case VK_RIGHT:
case VK_DOWN:
setValueInternal( mValue + 1, true );
return true;
}
break;
}
}
return false;
}
//--------------------------------------------------------------------------------------
bool CUISlider::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
switch( msg )
{
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
if( mRectButton.containsPoint( pt ) ) {
// Pressed while inside the control
mPressed = true;
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
mDragStartX = pt.x;
//m_nDragY = pt.y;
mDragOffset = (int)mButtonX - mDragStartX;
//m_nDragValue = mValue;
if( !mHasFocus )
mDialog->requestFocus( this );
return true;
}
if( mBBox.containsPoint( pt ) ) {
if( pt.x > mButtonX + mX ) {
setValueInternal( mValue + 1, true );
return true;
}
if( pt.x < mButtonX + mX ) {
setValueInternal( mValue - 1, true );
return true;
}
}
break;
}
case WM_LBUTTONUP:
{
if( mPressed )
{
mPressed = false;
ReleaseCapture();
mDialog->sendEvent( UIEVENT_SLIDER_VALUE_CHANGED, true, this );
return true;
}
break;
}
case WM_MOUSEMOVE:
{
if( mPressed )
{
setValueInternal( getValueFromPos( (int)mX + pt.x + mDragOffset ), true );
return true;
}
break;
}
};
return false;
}
void CUISlider::setRange( int vmin, int vmax )
{
mMin = vmin;
mMax = vmax;
setValueInternal( mValue, false );
}
void CUISlider::setValueInternal( int value, bool fromInput )
{
// Clamp to range
value = max( mMin, value );
value = min( mMax, value );
if( value == mValue )
return;
mValue = value;
updateRects();
mDialog->sendEvent( UIEVENT_SLIDER_VALUE_CHANGED, fromInput, this );
}
void CUISlider::render( IDirect3DDevice9* device, float dt )
{
int nOffsetX = 0;
int nOffsetY = 0;
eUIControlState state = UISTATE_NORMAL;
if( !mVisible )
{
state = UISTATE_HIDDEN;
}
else if( !mEnabled )
{
state = UISTATE_DISABLED;
}
else if( mPressed )
{
state = UISTATE_PRESSED;
nOffsetX = 1;
nOffsetY = 2;
}
else if( mMouseOver )
{
state = UISTATE_MOUSEOVER;
nOffsetX = -1;
nOffsetY = -2;
}
else if( mHasFocus )
{
state = UISTATE_FOCUS;
}
float blendRate = ( state == UISTATE_PRESSED ) ? 0.0f : 0.8f;
SUIElement* element = mElements[ 0 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mBBox );
//TODO: remove magic numbers
element = mElements[ 1 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectButton );
}
//--------------------------------------------------------------------------------------
// CUIScrollBar class
//--------------------------------------------------------------------------------------
CUIScrollBar::CUIScrollBar( CUIDialog *dialog )
: mDragging(false)
{
mType = UICTRL_SCROLLBAR;
mDialog = dialog;
mShowThumb = true;
mRectUp.set( 0, 0, 0, 0 );
mRectDown.set( 0, 0, 0, 0 );
mRectTrack.set( 0, 0, 0, 0 );
mRectThumb.set( 0, 0, 0, 0 );
mPosition = 0;
mPageSize = 1;
mStart = 0;
mEnd = 1;
mArrows = CLEAR;
mLastArrowTime = 0.0;
}
CUIScrollBar::~CUIScrollBar()
{
}
void CUIScrollBar::updateRects()
{
CUIControl::updateRects();
// Make the buttons square
mRectUp.set( mBBox.left, mBBox.top, mBBox.right, mBBox.top + mBBox.getWidth() );
mRectDown.set( mBBox.left, mBBox.bottom - mBBox.getWidth(), mBBox.right, mBBox.bottom );
mRectTrack.set( mRectUp.left, mRectUp.bottom, mRectDown.right, mRectDown.top );
mRectThumb.left = mRectUp.left;
mRectThumb.right = mRectUp.right;
updateThumbRect();
}
void CUIScrollBar::updateThumbRect()
{
if( mEnd - mStart > mPageSize ) {
float nThumbHeight = max( mRectTrack.getHeight() * mPageSize / ( mEnd - mStart ), SCROLLBAR_MINTHUMBSIZE );
nThumbHeight = min( nThumbHeight, SCROLLBAR_MAXTHUMBSIZE );
int nMaxPosition = mEnd - mStart - mPageSize;
mRectThumb.top = mRectTrack.top + ( mPosition - mStart ) * ( mRectTrack.getHeight() - nThumbHeight ) / nMaxPosition;
mRectThumb.bottom = mRectThumb.top + nThumbHeight;
mShowThumb = true;
} else {
// No content to scroll
mRectThumb.top = mRectTrack.top;
mRectThumb.bottom = mRectThumb.top;
mShowThumb = false;
}
}
// scroll() scrolls by delta items. A positive value scrolls down, while
// a negative value scrolls up.
void CUIScrollBar::scroll( int delta )
{
// Perform scroll
mPosition += delta;
// capPosition position
capPosition();
// Update thumb position
updateThumbRect();
}
void CUIScrollBar::showItem( int index )
{
// capPosition the index
if( index < 0 )
index = 0;
if( index >= mEnd )
index = mEnd - 1;
// Adjust position
if( mPosition > index )
mPosition = index;
else
if( mPosition + mPageSize <= index )
mPosition = index - mPageSize + 1;
updateThumbRect();
}
bool CUIScrollBar::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
return false;
}
bool CUIScrollBar::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
static int ThumbOffsetY;
mLastMouse = pt;
switch( msg )
{
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
// Check for click on up button
if( mRectUp.containsPoint( pt ) ) {
if( mPosition > mStart )
--mPosition;
updateThumbRect();
mArrows = CLICKED_UP;
mLastArrowTime = CSystemTimer::getInstance().getTimeS();
return true;
}
// Check for click on down button
if( mRectDown.containsPoint( pt ) ) {
if( mPosition + mPageSize < mEnd )
++mPosition;
updateThumbRect();
mArrows = CLICKED_DOWN;
mLastArrowTime = CSystemTimer::getInstance().getTimeS();
return true;
}
// Check for click on thumb
if( mRectThumb.containsPoint( pt ) ) {
mDragging = true;
ThumbOffsetY = pt.y - (int)mRectThumb.top;
return true;
}
// Check for click on track
if( mRectThumb.left <= pt.x && mRectThumb.right > pt.x ) {
if( mRectThumb.top > pt.y && mRectTrack.top <= pt.y ) {
scroll( -( mPageSize - 1 ) );
return true;
} else if( mRectThumb.bottom <= pt.y && mRectTrack.bottom > pt.y ) {
scroll( mPageSize - 1 );
return true;
}
}
break;
}
case WM_LBUTTONUP: {
mDragging = false;
ReleaseCapture();
updateThumbRect();
mArrows = CLEAR;
break;
}
case WM_MOUSEMOVE: {
if( mDragging ) {
mRectThumb.bottom += pt.y - ThumbOffsetY - mRectThumb.top;
mRectThumb.top = float( pt.y - ThumbOffsetY );
if( mRectThumb.top < mRectTrack.top )
mRectThumb.offset( 0, mRectTrack.top - mRectThumb.top );
else if( mRectThumb.bottom > mRectTrack.bottom )
mRectThumb.offset( 0, mRectTrack.bottom - mRectThumb.bottom );
// Compute first item index based on thumb position
int nMaxFirstItem = mEnd - mStart - mPageSize; // Largest possible index for first item
int nMaxThumb = int( mRectTrack.getHeight() - mRectThumb.getHeight() ); // Largest possible thumb position from the top
mPosition = mStart + int(
( mRectThumb.top - mRectTrack.top +
nMaxThumb / ( nMaxFirstItem * 2 ) ) * // Shift by half a row to avoid last row covered by only one pixel
nMaxFirstItem / nMaxThumb );
return true;
}
break;
}
}
return false;
}
bool CUIScrollBar::msgProc( UINT msg, WPARAM wparam, LPARAM lparam )
{
if( WM_CAPTURECHANGED == msg )
{
// The application just lost mouse capture. We may not have gotten
// the WM_MOUSEUP message, so reset mDragging here.
if( (HWND)lparam != CD3DDevice::getInstance().getDeviceWindow() )
mDragging = false;
}
return false;
}
void CUIScrollBar::render( IDirect3DDevice9* device, float dt )
{
// Check if the arrow button has been held for a while.
// If so, update the thumb position to simulate repeated
// scroll.
if( mArrows != CLEAR )
{
double dCurrTime = CSystemTimer::getInstance().getTimeS();
if( mRectUp.containsPoint( mLastMouse ) ) {
switch( mArrows )
{
case CLICKED_UP:
if( SCROLLBAR_ARROWCLICK_DELAY < dCurrTime - mLastArrowTime )
{
scroll( -1 );
mArrows = HELD_UP;
mLastArrowTime = dCurrTime;
}
break;
case HELD_UP:
if( SCROLLBAR_ARROWCLICK_REPEAT < dCurrTime - mLastArrowTime )
{
scroll( -1 );
mLastArrowTime = dCurrTime;
}
break;
}
} else if( mRectDown.containsPoint( mLastMouse ) ) {
switch( mArrows ) {
case CLICKED_DOWN:
if( SCROLLBAR_ARROWCLICK_DELAY < dCurrTime - mLastArrowTime )
{
scroll( 1 );
mArrows = HELD_DOWN;
mLastArrowTime = dCurrTime;
}
break;
case HELD_DOWN:
if( SCROLLBAR_ARROWCLICK_REPEAT < dCurrTime - mLastArrowTime )
{
scroll( 1 );
mLastArrowTime = dCurrTime;
}
break;
}
}
}
eUIControlState state = UISTATE_NORMAL;
if( !mVisible )
state = UISTATE_HIDDEN;
else if( !mEnabled || mShowThumb == false )
state = UISTATE_DISABLED;
else if( mMouseOver )
state = UISTATE_MOUSEOVER;
else if( mHasFocus )
state = UISTATE_FOCUS;
float blendRate = ( state == UISTATE_PRESSED ) ? 0.0f : 0.8f;
// Background track layer
SUIElement* element = mElements[ 0 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectTrack );
// Up Arrow
element = mElements[ 1 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectUp );
// Down Arrow
element = mElements[ 2 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectDown );
// Thumb button
element = mElements[ 3 ];
// blend current color
element->colorTexture.blend( state, dt, blendRate );
mDialog->drawSprite( element, &mRectThumb );
}
//--------------------------------------------------------------------------------------
void CUIScrollBar::setTrackRange( int start, int end )
{
mStart = start; mEnd = end;
capPosition();
updateThumbRect();
}
//--------------------------------------------------------------------------------------
void CUIScrollBar::capPosition() // Clips position at boundaries. Ensures it stays within legal range.
{
if( mPosition < mStart ||
mEnd - mStart <= mPageSize )
{
mPosition = mStart;
}
else
if( mPosition + mPageSize > mEnd )
mPosition = mEnd - mPageSize;
}
//--------------------------------------------------------------------------------------
// CUIListBox class
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
CUIListBox::CUIListBox( CUIDialog *dialog )
: mScrollBar( dialog )
, mDragging(false)
{
mType = UICTRL_LISTBOX;
mDialog = dialog;
mStyle = 0;
mSBWidth = 16;
mSelected = -1;
mSelStart = 0;
mBorder = 6;
mMargin = 5;
mTextHeight = 0;
}
CUIListBox::~CUIListBox()
{
removeAllItems();
}
void CUIListBox::updateRects()
{
CUIControl::updateRects();
mRectSelection = mBBox;
mRectSelection.right -= mSBWidth;
mRectSelection.inflate( -mBorder, -mBorder );
mRectText = mRectSelection;
mRectText.inflate( -mMargin, 0 );
// Update the scrollbar's rects
mScrollBar.setLocation( mBBox.right - mSBWidth, mBBox.top );
mScrollBar.setSize( mSBWidth, mHeight );
SUIFontNode* fontNode = CUIResourceManager::getInstance().getFontNode( mElements[ 0 ]->fontIdx );
if( fontNode && fontNode->height ) {
mScrollBar.setPageSize( int(mRectText.getHeight() / fontNode->height) );
// The selected item may have been scrolled off the page.
// Ensure that it is in page again.
mScrollBar.showItem( mSelected );
}
}
// --------------------------------------------------------------------------
HRESULT CUIListBox::addItem( const char *text, const void *data )
{
SUIListItem *pNewItem = new SUIListItem;
if( !pNewItem )
return E_OUTOFMEMORY;
strncpy( pNewItem->text, text, 256 );
pNewItem->text[255] = L'\0';
pNewItem->data = data;
pNewItem->activeRect.set( 0, 0, 0, 0 );
pNewItem->selected = false;
mItems.push_back( pNewItem );
mScrollBar.setTrackRange( 0, (int)mItems.size() );
return S_OK;
}
// --------------------------------------------------------------------------
HRESULT CUIListBox::insertItem( int index, const char *text, const void *data )
{
SUIListItem *pNewItem = new SUIListItem;
if( !pNewItem )
return E_OUTOFMEMORY;
strncpy( pNewItem->text, text, 256 );
pNewItem->text[255] = L'\0';
pNewItem->data = data;
pNewItem->activeRect.set( 0, 0, 0, 0 );
pNewItem->selected = false;
mItems.insert( mItems.begin() + index, pNewItem );
mScrollBar.setTrackRange( 0, (int)mItems.size() );
return S_OK;
}
//--------------------------------------------------------------------------------------
void CUIListBox::removeItem( int index )
{
if( index < 0 || index >= (int)mItems.size() )
return;
SUIListItem *item = mItems[ index ];
delete item;
mItems.erase( mItems.begin() + index );
mScrollBar.setTrackRange( 0, (int)mItems.size() );
if( mSelected >= (int)mItems.size() )
mSelected = (int)mItems.size() - 1;
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
}
void CUIListBox::removeItemByText( const char *text )
{
// TBD - implementation?
}
void CUIListBox::removeItemByData( const void *data )
{
// TBD - implementation?
}
void CUIListBox::removeAllItems()
{
for( size_t i = 0; i < mItems.size(); ++i )
{
SUIListItem *item = mItems[ i ];
delete item;
}
mItems.clear();
mScrollBar.setTrackRange( 0, 1 );
}
SUIListItem *CUIListBox::getItem( int index )
{
if( index < 0 || index >= (int)mItems.size() )
return NULL;
return mItems[index];
}
//--------------------------------------------------------------------------------------
// For single-selection listbox, returns the index of the selected item.
// For multi-selection, returns the first selected item after the prevSelected position.
// To search for the first selected item, the app passes -1 for prevSelected. For
// subsequent searches, the app passes the returned index back to getSelectedIndex as.
// prevSelected.
// Returns -1 on error or if no item is selected.
int CUIListBox::getSelectedIndex( int prevSelected ) const
{
if( prevSelected < -1 )
return -1;
if( mStyle & MULTISELECTION )
{
// Multiple selection enabled. Search for the next item with the selected flag.
for( int i = prevSelected + 1; i < (int)mItems.size(); ++i )
{
SUIListItem *item = mItems[ i ];
if( item->selected )
return i;
}
return -1;
}
else
{
// Single selection
return mSelected;
}
}
//--------------------------------------------------------------------------------------
void CUIListBox::selectItem( int newIndex )
{
// If no item exists, do nothing.
if( mItems.size() == 0 )
return;
int nOldSelected = mSelected;
// Adjust mSelected
mSelected = newIndex;
// Perform capping
if( mSelected < 0 )
mSelected = 0;
if( mSelected >= (int)mItems.size() )
mSelected = (int)mItems.size() - 1;
if( nOldSelected != mSelected )
{
if( mStyle & MULTISELECTION )
{
mItems[mSelected]->selected = true;
}
// Update selection start
mSelStart = mSelected;
// Adjust scroll bar
mScrollBar.showItem( mSelected );
}
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
}
//--------------------------------------------------------------------------------------
bool CUIListBox::handleKeyb( UINT msg, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
// Let the scroll bar have a chance to handle it first
if( mScrollBar.handleKeyb( msg, wParam, lParam ) )
return true;
switch( msg )
{
case WM_KEYDOWN:
switch( wParam )
{
case VK_UP:
case VK_DOWN:
case VK_NEXT:
case VK_PRIOR:
case VK_HOME:
case VK_END:
// If no item exists, do nothing.
if( mItems.size() == 0 )
return true;
int nOldSelected = mSelected;
// Adjust mSelected
switch( wParam )
{
case VK_UP: --mSelected; break;
case VK_DOWN: ++mSelected; break;
case VK_NEXT: mSelected += mScrollBar.getPageSize() - 1; break;
case VK_PRIOR: mSelected -= mScrollBar.getPageSize() - 1; break;
case VK_HOME: mSelected = 0; break;
case VK_END: mSelected = (int)mItems.size() - 1; break;
}
// Perform capping
if( mSelected < 0 )
mSelected = 0;
if( mSelected >= (int)mItems.size() )
mSelected = (int)mItems.size() - 1;
if( nOldSelected != mSelected )
{
if( mStyle & MULTISELECTION )
{
// Multiple selection
// clear all selection
for( int i = 0; i < (int)mItems.size(); ++i )
{
SUIListItem *item = mItems[i];
item->selected = false;
}
if( GetKeyState( VK_SHIFT ) < 0 )
{
// Select all items from mSelStart to
// mSelected
int end = max( mSelStart, mSelected );
for( int n = min( mSelStart, mSelected ); n <= end; ++n )
mItems[n]->selected = true;
}
else
{
mItems[mSelected]->selected = true;
// Update selection start
mSelStart = mSelected;
}
} else
mSelStart = mSelected;
// Adjust scroll bar
mScrollBar.showItem( mSelected );
// Send notification
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
}
return true;
}
break;
}
return false;
}
//--------------------------------------------------------------------------------------
bool CUIListBox::handleMouse( UINT msg, POINT pt, WPARAM wParam, LPARAM lParam )
{
if( !mEnabled || !mVisible )
return false;
// First acquire focus
if( WM_LBUTTONDOWN == msg )
if( !mHasFocus )
mDialog->requestFocus( this );
// Let the scroll bar handle it first.
if( mScrollBar.handleMouse( msg, pt, wParam, lParam ) )
return true;
switch( msg )
{
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
// Check for clicks in the text area
if( mItems.size() > 0 && mRectSelection.containsPoint( pt ) ) {
// Compute the index of the clicked item
int nClicked;
if( mTextHeight )
nClicked = mScrollBar.getTrackPos() + int(( pt.y - mRectText.top ) / mTextHeight);
else
nClicked = -1;
// Only proceed if the click falls on top of an item.
if( nClicked >= mScrollBar.getTrackPos() &&
nClicked < (int)mItems.size() &&
nClicked < mScrollBar.getTrackPos() + mScrollBar.getPageSize() )
{
SetCapture( CD3DDevice::getInstance().getDeviceWindow() );
mDragging = true;
// If this is a double click, fire off an event and exit
// since the first click would have taken care of the selection
// updating.
if( msg == WM_LBUTTONDBLCLK )
{
mDialog->sendEvent( UIEVENT_LISTBOX_ITEM_DBLCLK, true, this );
return true;
}
mSelected = nClicked;
if( !( wParam & MK_SHIFT ) )
mSelStart = mSelected;
// If this is a multi-selection listbox, update per-item
// selection data.
if( mStyle & MULTISELECTION )
{
// Determine behavior based on the state of Shift and Ctrl
SUIListItem *pSelItem = mItems[ mSelected ];
if( ( wParam & (MK_SHIFT|MK_CONTROL) ) == MK_CONTROL )
{
// Control click. Reverse the selection of this item.
pSelItem->selected = !pSelItem->selected;
} else
if( ( wParam & (MK_SHIFT|MK_CONTROL) ) == MK_SHIFT )
{
// Shift click. set the selection for all items
// from last selected item to the current item.
// clear everything else.
int nBegin = min( mSelStart, mSelected );
int end = max( mSelStart, mSelected );
int i;
for( i = 0; i < nBegin; ++i )
{
SUIListItem *item = mItems[ i ];
item->selected = false;
}
for( i = end + 1; i < (int)mItems.size(); ++i )
{
SUIListItem *item = mItems[ i ];
item->selected = false;
}
for( i = nBegin; i <= end; ++i )
{
SUIListItem *item = mItems[ i ];
item->selected = true;
}
} else
if( ( wParam & (MK_SHIFT|MK_CONTROL) ) == ( MK_SHIFT|MK_CONTROL ) )
{
// Control-Shift-click.
// The behavior is:
// set all items from mSelStart to mSelected to
// the same state as mSelStart, not including mSelected.
// set mSelected to selected.
int nBegin = min( mSelStart, mSelected );
int end = max( mSelStart, mSelected );
// The two ends do not need to be set here.
bool bLastSelected = mItems[ mSelStart ]->selected;
for( int i = nBegin + 1; i < end; ++i )
{
SUIListItem *item = mItems[ i ];
item->selected = bLastSelected;
}
pSelItem->selected = true;
// Restore mSelected to the previous value
// This matches the Windows behavior
mSelected = mSelStart;
} else
{
// Simple click. clear all items and select the clicked
// item.
for( int i = 0; i < (int)mItems.size(); ++i )
{
SUIListItem *item = mItems[ i ];
item->selected = false;
}
pSelItem->selected = true;
}
} // End of multi-selection case
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
}
return true;
}
break;
case WM_LBUTTONUP:
{
ReleaseCapture();
mDragging = false;
if( mSelected != -1 )
{
// set all items between mSelStart and mSelected to
// the same state as mSelStart
int end = max( mSelStart, mSelected );
for( int n = min( mSelStart, mSelected ) + 1; n < end; ++n )
mItems[n]->selected = mItems[mSelStart]->selected;
mItems[mSelected]->selected = mItems[mSelStart]->selected;
// If mSelStart and mSelected are not the same,
// the user has dragged the mouse to make a selection.
// Notify the application of this.
if( mSelStart != mSelected )
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
}
return false;
}
case WM_MOUSEMOVE:
if( mDragging )
{
// Compute the index of the item below cursor
int nItem;
if( mTextHeight )
nItem = mScrollBar.getTrackPos() + int(( pt.y - mRectText.top ) / mTextHeight);
else
nItem = -1;
// Only proceed if the cursor is on top of an item.
if( nItem >= (int)mScrollBar.getTrackPos() &&
nItem < (int)mItems.size() &&
nItem < mScrollBar.getTrackPos() + mScrollBar.getPageSize() )
{
mSelected = nItem;
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
} else
if( nItem < (int)mScrollBar.getTrackPos() )
{
// User drags the mouse above window top
mScrollBar.scroll( -1 );
mSelected = mScrollBar.getTrackPos();
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
} else
if( nItem >= mScrollBar.getTrackPos() + mScrollBar.getPageSize() )
{
// User drags the mouse below window bottom
mScrollBar.scroll( 1 );
mSelected = min( (int)mItems.size(), mScrollBar.getTrackPos() + mScrollBar.getPageSize() ) - 1;
mDialog->sendEvent( UIEVENT_LISTBOX_SELECTION, true, this );
}
}
break;
case WM_MOUSEWHEEL:
{
UINT lines;
SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &lines, 0 );
int nScrollAmount = int((short)HIWORD(wParam)) / WHEEL_DELTA * lines;
mScrollBar.scroll( -nScrollAmount );
return true;
}
}
return false;
}
bool CUIListBox::msgProc( UINT msg, WPARAM wparam, LPARAM lparam )
{
if( WM_CAPTURECHANGED == msg )
{
// The application just lost mouse capture. We may not have gotten
// the WM_MOUSEUP message, so reset mDragging here.
if( (HWND)lparam != CD3DDevice::getInstance().getDeviceWindow() )
mDragging = false;
}
return false;
}
//--------------------------------------------------------------------------------------
void CUIListBox::render( IDirect3DDevice9* device, float dt )
{
if( !mVisible )
return;
SUIElement* element = mElements[ 0 ];
element->colorTexture.blend( UISTATE_NORMAL, dt );
element->colorFont.blend( UISTATE_NORMAL, dt );
SUIElement* selElement = mElements[ 1 ];
selElement->colorTexture.blend( UISTATE_NORMAL, dt );
selElement->colorFont.blend( UISTATE_NORMAL, dt );
mDialog->drawSprite( element, &mBBox );
// render the text
if( mItems.size() > 0 ) {
// Find out the height of a single line of text
SFRect rc = mRectText;
SFRect rcSel = mRectSelection;
rc.bottom = rc.top + CUIResourceManager::getInstance().getFontNode( element->fontIdx )->height;
// Update the line height formation
mTextHeight = rc.bottom - rc.top;
static bool sbInit;
if( !sbInit ) {
// Update the page size of the scroll bar
if( mTextHeight )
mScrollBar.setPageSize( int(mRectText.getHeight() / mTextHeight) );
else
mScrollBar.setPageSize( int(mRectText.getHeight()) );
sbInit = true;
}
rc.right = mRectText.right;
for( int i = mScrollBar.getTrackPos(); i < (int)mItems.size(); ++i )
{
if( rc.bottom > mRectText.bottom )
break;
SUIListItem *item = mItems[ i ];
// Determine if we need to render this item with the
// selected element.
bool bSelectedStyle = false;
if( !( mStyle & MULTISELECTION ) && i == mSelected )
bSelectedStyle = true;
else
if( mStyle & MULTISELECTION )
{
if( mDragging &&
( ( i >= mSelected && i < mSelStart ) ||
( i <= mSelected && i > mSelStart ) ) )
bSelectedStyle = mItems[mSelStart]->selected;
else
if( item->selected )
bSelectedStyle = true;
}
if( bSelectedStyle )
{
rcSel.top = rc.top; rcSel.bottom = rc.bottom;
mDialog->drawSprite( selElement, &rcSel );
mDialog->drawText( item->text, selElement, &rc, !selElement->darkFont );
}
else
mDialog->drawText( item->text, element, &rc, !element->darkFont );
rc.offset( 0, mTextHeight );
}
}
// render the scroll bar
mScrollBar.render( device, dt );
}
// --------------------------------------------------------------------------
void SBlendColor::init( bool font, bool darkFont )
{
D3DCOLOR cnormal = font ? (darkFont ? colTDNormal : colTLNormal) : colINormal;
for( int i=0; i < UI_MAX_CTRL_STATES; ++i )
colors[ i ] = cnormal;
if( font ) {
colors[ UISTATE_PRESSED ] = darkFont ? colTDPress : colTLPress;
colors[ UISTATE_MOUSEOVER ] = darkFont ? colTDHover : colTLHover;
colors[ UISTATE_FOCUS ] = darkFont ? colTDFocus : colTLFocus;
colors[ UISTATE_DISABLED ] = darkFont ? colTDDisable : colTLDisable;
} else {
colors[ UISTATE_PRESSED ] = colIPressed;
colors[ UISTATE_MOUSEOVER ] = colIHover;
colors[ UISTATE_FOCUS ] = colIFocus;
colors[ UISTATE_DISABLED ] = colIDisable;
}
colors[ UISTATE_HIDDEN ] = colHidden;
current = colHidden;
}
void SBlendColor::blend( UINT state, float dt, float rate )
{
D3DXCOLOR destColor = colors[ state ];
D3DXColorLerp( ¤t, ¤t, &destColor, 1.0f - powf( rate, 30 * dt ) );
}
// --------------------------------------------------------------------------
void SUIElement::setTexture( CD3DTexture* tex, const RECT* texRect )
{
texture = tex;
if( texRect )
textureRect = *texRect;
else
SetRectEmpty( &textureRect );
colorTexture.init( false );
}
void SUIElement::setFont( size_t fIdx, bool dark, DWORD textFmt )
{
fontIdx = fIdx;
textFormat = textFmt;
darkFont = dark;
colorFont.init( true, darkFont );
}
void SUIElement::refresh()
{
colorTexture.current = colorTexture.colors[ UISTATE_HIDDEN ];
colorFont.current = colorFont.colors[ UISTATE_HIDDEN ];
}
|
[
"[email protected]"
] |
[
[
[
1,
4092
]
]
] |
5a7d18f44233722e2be38a8564cce96356e255dd
|
3e69b159d352a57a48bc483cb8ca802b49679d65
|
/tags/release-2006-01-18/pcbnew/editrout.cpp
|
a1d3797bd6210b3da3b4474037941ad2badb970c
|
[] |
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 | 4,343 |
cpp
|
/***************************************************************/
/* Edition des pistes: Routines de modification de dimensions: */
/* Modif de largeurs de segment, piste, net , zone et diam Via */
/***************************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "protos.h"
/* Routines Locales */
/*********************************************************************/
int WinEDA_PcbFrame::Edit_TrackSegm_Width(wxDC * DC, TRACK * pt_segm)
/*********************************************************************/
/* Routine de modification de la largeur d'un segment ( ou via) de piste
Routine de base utilisee par les autres routines
*/
{
int errdrc = OK_DRC;
int old_w, consigne ;
pt_segm->Draw(DrawPanel, DC, GR_XOR) ; // effacement a l'ecran
/* Test DRC et mise a la largeur */
old_w = pt_segm->m_Width;
consigne = pt_segm->m_Width = g_DesignSettings.m_CurrentTrackWidth;
if( pt_segm->m_StructType == TYPEVIA )
{
consigne = pt_segm->m_Width = g_DesignSettings.m_CurrentViaSize;
}
if ( old_w < consigne) /* DRC utile puisque augm de dimension */
{
if(Drc_On) errdrc = Drc(this, DC, pt_segm, m_Pcb->m_Track,1);
if(errdrc == BAD_DRC) pt_segm->m_Width = old_w;
else GetScreen()->SetModify();
}
else GetScreen()->SetModify(); /* Correction systematiquement faite si reduction */
pt_segm->Draw(DrawPanel, DC, GR_OR) ;
return(errdrc);
}
/*****************************************************************/
void WinEDA_PcbFrame::Edit_Track_Width(wxDC * DC,TRACK * pt_segm)
/*****************************************************************/
{
int ii;
TRACK * pt_track;
int errdrc;
int nb_segm, nb_segm_modifies = 0, nb_segm_non_modifies = 0;
if( pt_segm == NULL) return;
pt_track = Marque_Une_Piste(this, DC, pt_segm, &nb_segm, 0);
for(ii = 0; ii < nb_segm; ii++, pt_track = (TRACK*) pt_track->Pnext)
{
pt_track->SetState(BUSY,OFF);
errdrc = Edit_TrackSegm_Width(DC, pt_track);
if(errdrc == BAD_DRC) nb_segm_non_modifies++;
else nb_segm_modifies++;
}
}
/***********************************************************/
void WinEDA_PcbFrame::Edit_Net_Width(wxDC * DC, int Netcode)
/***********************************************************/
{
TRACK *pt_segm;
int errdrc;
int nb_segm_modifies = 0;
int nb_segm_non_modifies = 0;
if (Netcode <= 0 ) return;
if( ! IsOK(this, "Change largeur NET ?") ) return;
/* balayage des segments */
for( pt_segm = m_Pcb->m_Track; pt_segm != NULL; pt_segm = (TRACK*) pt_segm->Pnext )
{
if ( Netcode != pt_segm->m_NetCode ) /* mauvaise piste */
continue ;
/* piste d'un net trouvee */
errdrc = Edit_TrackSegm_Width(DC, pt_segm);
if(errdrc == BAD_DRC) nb_segm_non_modifies++;
else nb_segm_modifies++;
}
}
/*************************************************************************/
bool WinEDA_PcbFrame::Resize_Pistes_Vias(wxDC * DC, bool Track, bool Via)
/*************************************************************************/
/* remet a jour la largeur des pistes et/ou le diametre des vias
Si piste == 0 , pas de cht sur les pistes
Si via == 0 , pas de cht sur les vias
*/
{
TRACK * pt_segm ;
int errdrc;
int nb_segm_modifies = 0;
int nb_segm_non_modifies = 0;
if ( Track && Via)
{
if( ! IsOK(this, _("Edit All Tracks and Vias Sizes")) ) return FALSE;
}
else if ( Via )
{
if( ! IsOK(this, _("Edit All Via Sizes")) ) return FALSE;
}
else if( Track )
{
if( ! IsOK(this, _("Edit All Track Sizes")) ) return FALSE;
}
pt_segm = m_Pcb->m_Track ;
for ( ; pt_segm != NULL; pt_segm = (TRACK*) pt_segm->Pnext )
{
if( pt_segm->m_StructType == TYPEVIA ) /* mise a jour du diametre de la via */
{
if ( Via )
{
errdrc = Edit_TrackSegm_Width(DC, pt_segm);
if(errdrc == BAD_DRC) nb_segm_non_modifies++;
else nb_segm_modifies++;
}
}
else /* mise a jour de la largeur du segment */
{
if ( Track )
{
errdrc = Edit_TrackSegm_Width(DC, pt_segm);
if(errdrc == BAD_DRC) nb_segm_non_modifies++;
else nb_segm_modifies++;
}
}
}
if ( nb_segm_modifies ) return TRUE;
return FALSE;
}
|
[
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] |
[
[
[
1,
155
]
]
] |
b903336a0e0e9f06ce298ff15483a9f248a9cfdf
|
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
|
/SMDK/Limn/LimnDW/LimnDW/LimnDW.cpp
|
4b391fe2b4ee66ebc1782db0d4294d230d90f371
|
[] |
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 | 1,459 |
cpp
|
//================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#define __LIMNDW_CPP
#include "LimnDW.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
#include "scdmacros.h"
#include "md_headers.h"
#pragma LIBCOMMENT("..\\..\\..\\Bin\\", "\\DevLib" )
#pragma LIBCOMMENT("..\\..\\..\\Bin\\", "\\scdlib" )
#pragma LIBCOMMENT("..\\..\\..\\Bin\\", "\\scexec" )
//#pragma LIBCOMMENT("..\\LimnDWG\\", "\\LimnDWG")
//#pragma LIBCOMMENT("..\\LimnDWM\\", "\\LimnDWM")
//===========================================================================
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
/*if (!MakeVersionOK("LimnDW.DLL", _MAKENAME, SCD_VERINFO_V0, SCD_VERINFO_V1, SCD_VERINFO_V2, SCD_VERINFO_V3))
return FALSE;*/
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//===========================================================================
extern "C" __declspec(dllexport) BOOL IsSMDKLibDLL()
{
return TRUE;
}
//===========================================================================
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
33
],
[
36,
53
]
],
[
[
34,
35
]
]
] |
594b7952dd59e174b0ca5cebf8cfdf1ab40a4587
|
8f1601062c4a5452f2bdd0f75f3d12a79b98ba62
|
/lib/timer/timer_win32.cpp
|
b2b256ba8570f036c46f32acff7c7f6f445c0479
|
[] |
no_license
|
chadaustin/isugamedev
|
200a54f55a2581cd2c62c94eb96b9e238abcf3dd
|
d3008ada042d2dd98c6e05711773badf6f1fd85c
|
refs/heads/master
| 2016-08-11T17:59:38.504631 | 2005-01-25T23:17:11 | 2005-01-25T23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 480 |
cpp
|
#include <windows.h>
#include <mmsystem.h>
#include "timer.hpp"
u64 GetNow() {
// get frequency of the performance counter
LARGE_INTEGER frequency;
if (QueryPerformanceFrequency(&frequency) && frequency.QuadPart != 0) {
LARGE_INTEGER now;
if (QueryPerformanceCounter(&now)) {
return 1000000 * u64(now.QuadPart) / frequency.QuadPart;
}
}
// no performance counter, so use the Win32 multimedia timer
return timeGetTime() * 1000;
}
|
[
"aegis@84b32ba4-53c3-423c-be69-77cca6335494"
] |
[
[
[
1,
18
]
]
] |
bfe22bb4bdfd569f4901fe0e71bbc147e7c8a1f0
|
3eae1d8c99d08bca129aceb7c2269bd70e106ff0
|
/trunk/Codes/CLR/Libraries/CorLib/corlib_native_System_Reflection_RuntimeFieldInfo.cpp
|
19a3277863075412b34de4d7f794583ac2416377
|
[] |
no_license
|
yuaom/miniclr
|
9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082
|
4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1
|
refs/heads/master
| 2023-06-07T09:10:33.703929 | 2010-12-27T14:41:18 | 2010-12-27T14:41:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,962 |
cpp
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CorLib.h"
HRESULT Library_corlib_native_System_Reflection_RuntimeFieldInfo::get_Name___STRING( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_FieldDef_Instance fd; if(GetFieldDescriptor( stack, stack.Arg0(), fd ) == false) TINYCLR_SET_AND_LEAVE(CLR_E_NULL_REFERENCE);
TINYCLR_SET_AND_LEAVE(CLR_RT_HeapBlock_String::CreateInstance( stack.PushValue(), fd.m_target->name, fd.m_assm ));
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_RuntimeFieldInfo::get_DeclaringType___SystemType( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_FieldDef_Instance fd;
CLR_RT_TypeDef_Instance cls;
if(GetFieldDescriptor( stack, stack.Arg0(), fd ) == false) TINYCLR_SET_AND_LEAVE(CLR_E_NULL_REFERENCE);
if(cls.InitializeFromField( fd ) == false) TINYCLR_SET_AND_LEAVE(CLR_E_WRONG_TYPE);
{
CLR_RT_HeapBlock& top = stack.PushValue();
top.SetReflection( cls );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_RuntimeFieldInfo::get_FieldType___SystemType( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_TypeDescriptor desc;
CLR_RT_FieldDef_Instance fd;
if(GetFieldDescriptor( stack, stack.Arg0(), fd ) == false) TINYCLR_SET_AND_LEAVE(CLR_E_NULL_REFERENCE);
TINYCLR_CHECK_HRESULT(desc.InitializeFromFieldDefinition( fd ));
stack.PushValue().SetReflection( desc.m_handlerCls );
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_RuntimeFieldInfo::GetValue___OBJECT__OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_HeapBlock* argObj = &stack.Arg1();
CLR_RT_FieldDef_Instance instFD;
CLR_RT_TypeDef_Instance instTD;
const CLR_RECORD_FIELDDEF* fd;
CLR_RT_HeapBlock* obj;
CLR_RT_HeapBlock dst;
TINYCLR_CHECK_HRESULT(Library_corlib_native_System_Reflection_FieldInfo::Initialize( stack, instFD, instTD, obj ));
fd = instFD.m_target;
if(fd->flags & CLR_RECORD_FIELDDEF::FD_NoReflection) // don't allow reflection for fields with NoReflection attribute
{
TINYCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED);
}
{
dst.Assign( *obj );
#if defined(TINYCLR_APPDOMAINS)
//Marshal if necessary.
if(argObj->IsTransparentProxy())
{
_ASSERTE(argObj->DataType() == DATATYPE_OBJECT);
argObj = argObj->Dereference();
_ASSERTE(argObj != NULL && argObj->DataType() == DATATYPE_TRANSPARENT_PROXY);
TINYCLR_CHECK_HRESULT(argObj->TransparentProxyValidate());
TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.GetCurrentAppDomain()->MarshalObject( *obj, dst, argObj->TransparentProxyAppDomain() ));
}
#endif
CLR_RT_HeapBlock& res = stack.PushValueAndAssign( dst );
TINYCLR_CHECK_HRESULT(res.PerformBoxingIfNeeded());
}
TINYCLR_NOCLEANUP();
}
//--//
bool Library_corlib_native_System_Reflection_RuntimeFieldInfo::GetFieldDescriptor( CLR_RT_StackFrame& stack, CLR_RT_HeapBlock& arg, CLR_RT_FieldDef_Instance& inst )
{
NATIVE_PROFILE_CLR_CORE();
return CLR_RT_ReflectionDef_Index::Convert( arg, inst );
}
|
[
"[email protected]"
] |
[
[
[
1,
111
]
]
] |
964690d570f53dbcf68a7b1313a8f7c0e4f196a1
|
655fe8fa2c95def8ab819d480d66dfb2c3d5f9b4
|
/utility/exception.hpp
|
865a7e72dc422dda38eb5c1ec77644b9da851891
|
[] |
no_license
|
PatrickRABEL/dicomlib
|
66a2608ca215930270adab5611830c2842c207f1
|
c85cd617833f801959d61c268fd970ed0ff0ca46
|
refs/heads/master
| 2016-08-12T15:10:29.968444 | 2011-12-05T02:45:12 | 2011-12-05T02:45:12 | 55,343,371 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 734 |
hpp
|
#include <exception>
#include <string>
namespace utility
{
//!root exception class
/*!
Microsoft's library differs from the standard in that it provides
a constructor that takes a a string argument.
To make our libraries cross platform, we provide our own base
exception class that follows Microsoft's approach.
Use this in place of std::exception and we should be OK.
*/
class exception : public std::exception
{
protected:
std::string what_;
public:
//!no reference, just a description
exception(std::string what): what_(what)
{}
//!g++ needs this
virtual ~exception() throw(){}
virtual const char* what() const throw()
{
return what_.c_str();
}
};
}
|
[
"trevor@localhost"
] |
[
[
[
1,
33
]
]
] |
6250407319c869db99b4bb01c60d55818a46b76e
|
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
|
/Code/TootleNeuralNetwork/TLNeuralNetwork.cpp
|
3e1927e18012857e39c11e84e2b852209f40c373
|
[] |
no_license
|
SoylentGraham/Tootle
|
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
|
17002da0936a7af1f9b8d1699d6f3e41bab05137
|
refs/heads/master
| 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,494 |
cpp
|
#include "TLNeuralNetwork.h"
using namespace TLNeuralNetwork;
TNeuron::TNeuron(void)
{
}
void TNeuron::Update()
{
// Sum all of the inputs.
float fSum = 0.0f;
for(u32 uIndex = 0; uIndex < m_fInputs.GetSize(); uIndex++)
{
fSum += m_fInputs.ElementAt(uIndex);
}
fSum /= m_fInputs.GetSize();
//If greater than the threashold then perform activation
if(fSum > m_fThreshold)
{
// Perform action by sending message to allsubscribers
TLMessaging::TMessage Message("PULSE");
// TODO: Cater for prohibitive neurons here
//Message.SetSenderRef(GetNeuronID());
Message.Write(1.0f);
PublishMessage(Message);
}
/*
// Reduce/clear the input data values
for(u32 uIndex = 0; uIndex < m_fInputs.GetSize(); uIndex++)
{
m_fInputs.ElementAt(uIndex) = 0.0f;
}
*/
// Remove the inputs - not needed anymore
m_fInputs.Empty();
}
/*
*/
void TNeuron::ProcessMessage(TLMessaging::TMessage& Message)
{
// Check the message coming in and if it is a pulse then add the pulse to our inputs
if(Message.GetMessageRef() == "PULSE")
{
float fInput = 0.0f;
if(Message.Read(fInput))
m_fInputs.Add(fInput);
}
}
Bool TNeuron::Activate()
{
return FALSE;
}
/*
Neural network class
*/
TNeuralNetwork::TNeuralNetwork(TRef refNeuralNetworkID) :
m_refNeuralNetworkID(refNeuralNetworkID)
{
}
TNeuralNetwork::~TNeuralNetwork(void)
{
RemoveAllNeurons();
}
/*
Removes all neurons from the neural netowrk and clears the input buffer
*/
void TNeuralNetwork::RemoveAllNeurons()
{
// Remove all of the input neurons first (these will be in the main neuron list as well)
for(u32 uIndex = 0; uIndex < m_InputNeurons.GetSize(); uIndex++)
m_InputNeurons.ElementAt(uIndex) = NULL;
m_InputNeurons.Empty();
// Clean up the input buffer
m_fInputBuffer.Empty();
// Now remove all of the neurons themselves
for(u32 uIndex = 0; uIndex < m_Neurons.GetSize(); uIndex++)
m_Neurons.ElementAt(uIndex) = NULL;
m_Neurons.Empty();
}
void TNeuralNetwork::Update()
{
for(u32 uIndex = 0; uIndex < m_Neurons.GetSize(); uIndex++)
{
TPtr<TNeuron> pNeuron = m_Neurons.ElementAt(uIndex);
if(pNeuron.IsValid() && pNeuron->HasInput())
pNeuron->Update();
}
}
/*
Adds a new neuron and automatically links it to the specified neuron
*/
TPtr<TNeuron> TNeuralNetwork::AddInputNeuron()
{
TPtr<TNeuron> pNeuron = AddNeuron();
if(pNeuron.IsValid())
{
// add a new data member to the input buffer
m_fInputBuffer.Add(0.0f);
// Add to the list of input neurons
m_InputNeurons.Add(pNeuron);
}
return pNeuron;
}
/*
Adds n number of input neurons and returns them in a list
*/
Bool TNeuralNetwork::AddInputNeurons(u32 uNumberOfNeurons, TPtrArray<TNeuron>& NeuronList)
{
for(u32 uIndex = 0; uIndex < uNumberOfNeurons; uIndex++)
{
TPtr<TNeuron> pNeuron = AddInputNeuron();
// Failed to add a neuron??
if(!pNeuron.IsValid())
return FALSE;
NeuronList.Add(pNeuron);
}
// All done
return TRUE;
}
/*
Adds a new neuron and automatically links it to the specified neuron
*/
TPtr<TNeuron> TNeuralNetwork::AddNeuron(TPtr<TNeuron> pNeuronTo)
{
TPtr<TNeuron> pNeuron = new TNeuron();
if(pNeuron.IsValid())
{
m_Neurons.Add(pNeuron);
// Connect the neurons with an axon
if(pNeuronTo.IsValid())
Connect(pNeuron, pNeuronTo);
}
return pNeuron;
}
/*
Adds a new list of neurons and automatically links them to the specified neuron
*/
Bool TNeuralNetwork::AddNeurons(u32 uNumberOfNeurons, TPtrArray<TNeuron>& NeuronList, TPtr<TNeuron> pNeuronTo)
{
for(u32 uIndex = 0; uIndex < uNumberOfNeurons; uIndex++)
{
TPtr<TNeuron> pNeuron = AddNeuron();
// Failed to add a neuron??
if(!pNeuron.IsValid())
return FALSE;
NeuronList.Add(pNeuron);
// Connect the neurons with an axon
if(pNeuronTo.IsValid())
{
TPtr<TAxon> pAxon = Connect(pNeuron, pNeuronTo);
// Failed to connect the neurons??
if(!pAxon.IsValid())
return FALSE;
}
}
return TRUE;
}
/*
Removes a neuron removing all links to and from the neuron
*/
void TNeuralNetwork::RemoveNeuron(TPtr<TNeuron> pNeuron)
{
// Check for if the neuron is an input neuron
for(u32 uIndex = 0; uIndex < m_InputNeurons.GetSize(); uIndex++)
{
TPtr<TNeuron> pTemp = m_InputNeurons.ElementAt(uIndex);
if(pTemp == pNeuron)
{
// Remove the node fromt he list
m_InputNeurons.RemoveAt(uIndex);
// remove the last input buffer value - preserve the order of the buffer by not removing the one at the same index
m_fInputBuffer.RemoveLast();
break;
}
}
// Now find the neuron in the main list and remove it
for(u32 uIndex = 0; uIndex < m_Neurons.GetSize(); uIndex++)
{
TPtr<TNeuron> pTemp = m_Neurons.ElementAt(uIndex);
if(pTemp == pNeuron)
{
// Remove the node fromt he list
m_Neurons.RemoveAt(uIndex);
break;
}
}
}
/*
Adds a new neuron and connects it to the list of neurons
*/
TPtr<TNeuron> TNeuralNetwork::AddNeuron(TPtrArray<TNeuron>& pNeuronsTo)
{
TPtr<TNeuron> pNeuron = AddNeuron();
if(pNeuron.IsValid())
{
// Connect the neuron to the specified list of neurons
for(u32 uIndex = 0; uIndex < pNeuronsTo.GetSize(); uIndex++)
{
TPtr<TNeuron> pTemp = pNeuronsTo.ElementAt(uIndex);
if(pTemp.IsValid())
{
Connect(pNeuron, pTemp);
}
}
}
return pNeuron;
}
/*
Adds a new list of neurons and connects them to the list of neurons
*/
Bool TNeuralNetwork::AddNeurons(u32 uNumberOfNeurons, TPtrArray<TNeuron>& NeuronList, TPtrArray<TNeuron>& pNeuronsTo)
{
for(u32 uIndex = 0; uIndex < uNumberOfNeurons; uIndex++)
{
TPtr<TNeuron> pNeuron = AddNeuron();
// Failed to add a neuron??
if(!pNeuron.IsValid())
return FALSE;
NeuronList.Add(pNeuron);
// Connect the neurons with an axon to all of the neurons in the list
for(u32 uIndex2 = 0; uIndex2 < pNeuronsTo.GetSize(); uIndex2++)
{
TPtr<TNeuron> pNeuronTo = pNeuronsTo.ElementAt(uIndex2);
if(!pNeuronTo.IsValid())
return FALSE;
TPtr<TAxon> pAxon = Connect(pNeuron, pNeuronTo);
// Failed to connect the neurons??
if(!pAxon.IsValid())
return FALSE;
}
}
return TRUE;
}
/*
Connect neuron A to neuron B. This is done via an axon which stores a weight for when processing input values
before data is passed onto neuron b
*/
TPtr<TAxon> TNeuralNetwork::Connect(TPtr<TNeuron> pNeuronA, TPtr<TNeuron> pNeuronB)
{
TPtr<TAxon> pAxon = new TAxon(1.0f);
if(pAxon.IsValid())
{
// Subscribe the axon to neuron A
pAxon->SubscribeTo(pNeuronA);
// Subscribe neuron B to the axon
pNeuronB->SubscribeTo(pAxon);
}
return pAxon;
}
/*
Disconnects the specified neuron from all links to and from the neuron
*/
void TNeuralNetwork::Disconnect(TPtr<TNeuron> pNeuron)
{
}
/*
Disconnect neuron A from neuron B
*/
void TNeuralNetwork::Disconnect(TPtr<TNeuron> pNeuronA, TPtr<TNeuron> pNeuronB)
{
}
/*
Gets the axon connection between two neurons
*/
TPtr<TAxon> TNeuralNetwork::GetConnection(TPtr<TNeuron> pNeuronA, TPtr<TNeuron> pNeuronB)
{
TPtr<TAxon> pAxon = NULL;
return pAxon;
}
/*
Sets the weight between two neurons A and B
*/
void TNeuralNetwork::SetConnectionWeight(TPtr<TNeuron> pNeuronA, TPtr<TNeuron> pNeuronB, float fWeight)
{
}
|
[
"[email protected]"
] |
[
[
[
1,
350
]
]
] |
544c1430e2b0d3bf381808f5c695b90393e4e2eb
|
feef66ddf56e93a373234792bfdf6af2c6e0726e
|
/datatypes.h
|
7d56527fd1ef4c3e7765af4cea4c7ad6e2af742e
|
[] |
no_license
|
BackupTheBerlios/managedinogl-svn
|
2091df44218a5e7498117e70e997967617beafb3
|
4bed2100c4068a16df3aa517aad5460df61bbce6
|
refs/heads/master
| 2016-09-16T12:42:31.230750 | 2005-05-13T13:32:33 | 2005-05-13T13:32:33 | 40,802,900 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,849 |
h
|
#ifndef DATA_TYPES_H_
#define DATA_TYPES_H_
#include <string>
#include <vector>
class DynamicProperty
{
public:
DynamicProperty(void){};
~DynamicProperty(void){};
std::string getName(){ return name_; };
void setName(std::string name){ name_ = name; };
std::string getDescription(){ return description_; };
void setDescription(std::string description){ description_ = description; };
std::string getValue(){ return value_; };
void setValue(std::string value){ value_ = value; };
private:
std::string name_;
std::string description_;
std::string value_;
};
class ResourceType
{
public:
ResourceType(void){};
~ResourceType(void){};
std::string getName(){ return name_; };
void setName(std::string name){};
int getID(){ return id_; };
void setID(int id){};
std::vector<DynamicProperty> getAllProperties(){ return properties_; };
DynamicProperty getPropertyAt(unsigned int index){ return properties_[index]; };
void deletePropertyAt(unsigned int index){};
unsigned int getPropertyCount(){ return static_cast<unsigned int>(properties_.size()); };
void addProperty(DynamicProperty property){};
private:
std::string name_;
int id_;
std::vector<DynamicProperty> properties_;
};
class Resource
{
public:
Resource(void){};
~Resource(void){};
std::string getName(){ return name_; };
void setName(std::string name){};
std::string getDescription(){ return description_; };
void setDescription(std::string description){};
time_t getAvailableFrom(){ return available_from_; };
void setAvailableFrom(time_t time){};
time_t getAvailableUntil(){ return available_until_; };
void setAvailableUntil(time_t time){};
unsigned int getMaximumUsage(){ return max_usage_; };
void setMaximusUsage(unsigned int usage){};
ResourceType getResourceType(){ return resource_type_; };
void setResourceType(ResourceType resource_type){};
private:
std::string name_;
std::string description_;
time_t available_from_;
time_t available_until_;
unsigned int max_usage_;
ResourceType resource_type_;
};
class Task
{
public:
Task(void){};
~Task(void){};
std::string getName(){ return name_; };
void setName(std::string name){};
std::string getDescription(){ return description_; };
void setDescription(std::string description){};
time_t getStartTime(){ return start_time_; };
void setStartTime(time_t time){};
time_t getEndTime(){ return end_time_; };
void setEndTime(time_t time){};
std::vector<Resource> getAllResources(){ return resources_; };
Resource getResourceAt(unsigned int index){ return resources_[index]; };
void deleteResourceAt(unsigned int index){};
unsigned int getResourceCount(){ return static_cast<unsigned int>(resources_.size()); };
void addResource(Resource resource){};
private:
std::string name_;
std::string description_;
time_t start_time_;
time_t end_time_;
std::vector<Resource> resources_;
};
class Project
{
public:
Project(void){};
~Project(void){};
std::string getName(){ return name_; };
void setName(std::string name){};
std::string getDescription(){ return description_; };
void setDescription(std::string description){};
time_t getStartTime(){ return start_time_; };
void setStartTime(time_t time){};
time_t getEndTime(){ return end_time_; };
void setEndTime(time_t time){};
std::vector<Task> getAllTasks(){ return tasks_; };
Task getTaskAt(unsigned int index){ return tasks_[index]; };
void deleteTaskAt(unsigned int index){};
unsigned int getTaskCount(){ return static_cast<unsigned int>(tasks_.size()); };
void addTask(Task task){};
private:
std::string name_;
std::string description_;
time_t start_time_;
time_t end_time_;
std::vector<Task> tasks_;
};
#endif DATA_TYPES_H_
|
[
"patrickhofmann@acfc4149-aaf6-0310-bffb-82d883f3e4cc"
] |
[
[
[
1,
153
]
]
] |
a2292d105988625c9ee857b9b3ac290d2bac4740
|
0d32d7cd4fb22b60c4173b970bdf2851808c0d71
|
/src/hancock/hancock/MergeDlg.h
|
abae60ea39ad3db8960d5bfe3696c67361dc226e
|
[] |
no_license
|
kanakb/cs130-hancock
|
a6eaef9a44955846d486ee2330bec61046cb91bd
|
d1f77798d90c42074c7a26b03eb9d13925c6e9d7
|
refs/heads/master
| 2021-01-18T13:04:25.582562 | 2009-06-12T03:49:56 | 2009-06-12T03:49:56 | 32,226,524 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,000 |
h
|
#pragma once
#include "afxwin.h"
#include "Scheduler.h"
#include <string>
#include <list>
// MergeDlg dialog
class MergeDlg : public CDialog
{
DECLARE_DYNAMIC(MergeDlg)
public:
MergeDlg(Scheduler *sched, CWnd* pParent = NULL); // standard constructor
virtual ~MergeDlg();
// Dialog Data
enum { IDD = IDD_MERGEMODEL };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedBtnCrcfg();
afx_msg void OnBnClickedBtnEcfg();
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedBtnSelinp1();
afx_msg void OnBnClickedSeldep1();
afx_msg void OnBnClickedBtnSelinp2();
afx_msg void OnBnClickedSeldep2();
afx_msg void OnBnClickedBtnSelmodout();
private:
CEdit m_input1;
CEdit m_path1;
CEdit m_input2;
CEdit m_path2;
CEdit m_output;
CButton m_eCFG;
CButton m_start;
std::string m_cfgname;
Scheduler *m_sched;
std::list<Scheduler::actData*> m_deps;
};
|
[
"kanakb@1f8f3222-2881-11de-bcab-dfcfbda92187"
] |
[
[
[
1,
45
]
]
] |
35420f833dea363e1610e077341b89728c5f954d
|
619941b532c6d2987c0f4e92b73549c6c945c7e5
|
/Stellar_/code/Render/coregraphics/d3d9/d3d9shadervariation.cc
|
096ba060ef2af1114903dce1bf21f334784e559c
|
[] |
no_license
|
dzw/stellarengine
|
2b70ddefc2827be4f44ec6082201c955788a8a16
|
2a0a7db2e43c7c3519e79afa56db247f9708bc26
|
refs/heads/master
| 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,189 |
cc
|
//------------------------------------------------------------------------------
// d3d9shadervariation.cc
// (C) 2007 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "coregraphics/d3d9/d3d9shadervariation.h"
#include "coregraphics/shaderserver.h"
namespace Direct3D9
{
ImplementClass(Direct3D9::D3D9ShaderVariation, 'D9SV', Base::ShaderVariationBase);
using namespace CoreGraphics;
//------------------------------------------------------------------------------
/**
*/
D3D9ShaderVariation::D3D9ShaderVariation() :
d3d9Effect(0),
hTechnique(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
D3D9ShaderVariation::~D3D9ShaderVariation()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
D3D9ShaderVariation::Setup(ID3DXEffect* effect, D3DXHANDLE handle)
{
s_assert(0 != effect);
s_assert(0 != handle);
s_assert(0 == this->d3d9Effect);
s_assert(0 == this->hTechnique);
s_assert(0 == this->featureMask);
s_assert(0 == this->numPasses);
this->d3d9Effect = effect;
this->hTechnique = handle;
// setup name and feature mask
D3DXTECHNIQUE_DESC desc;
HRESULT hr = this->d3d9Effect->GetTechniqueDesc(this->hTechnique, &desc);
s_assert(SUCCEEDED(hr));
this->SetName(Name(desc.Name));
this->SetNumPasses(desc.Passes);
// generate the feature mask from the "Mask" annotation
D3DXHANDLE hFeatureAnnotation = this->d3d9Effect->GetAnnotationByName(this->hTechnique, "Mask");
if (NULL != hFeatureAnnotation)
{
LPCSTR strPtr = 0;
hr = this->d3d9Effect->GetString(hFeatureAnnotation, &strPtr);
s_assert(SUCCEEDED(hr));
ShaderFeature::Mask mask = ShaderServer::Instance()->FeatureStringToMask(strPtr);
this->SetFeatureMask(mask);
}
else
{
// issue a warning
s_warning("No Features annotation in technique '%s'!\n", this->GetName().Value().c_str());
}
}
} // namespace Direct3D9
|
[
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
] |
[
[
[
1,
73
]
]
] |
79c1103aa3328dda74df628249da65c28a2635ca
|
5efdf4f304c39c1aa8a24ab5a9690afad3340c00
|
/src/GLCairoSurface.h
|
c6d137f6aed5da6e3cf08bf119d2230be7f33d73
|
[] |
no_license
|
asquared/hockeyboard
|
286f57d8bea282e74425cbe77d915d692398f722
|
06480cb228dcd6d4792964837e20a1dddea89d1b
|
refs/heads/master
| 2016-09-06T11:16:20.947224 | 2011-01-09T21:23:16 | 2011-01-09T21:23:16 | 1,236,086 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,928 |
h
|
#ifndef _glcairosurface_h_
#define _glcairosurface_h_
#define MAX_ALT 4
// required libraries
#ifdef WINDOWS
#pragma comment(lib, "pango-1.0.lib")
#pragma comment(lib, "pangocairo-1.0.lib")
#pragma comment(lib, "libcairo.lib")
#pragma comment(lib, "gobject-2.0.lib")
#pragma comment(lib, "opengl32")
#endif
#include <pango/pangocairo.h>
#include <pango/pango-font.h>
#ifdef WINDOWS
#include <windows.h>
#endif
#include <GL/gl.h>
#include <string>
#include <iostream>
using std::string;
class GLCairoSurface {
private:
cairo_surface_t* cs;
cairo_t* ct;
PangoFontDescription* pfd;
PangoFontDescription* pfda[MAX_ALT];
PangoFontMap* pm;
PangoCairoFontMap* pfm;
PangoContext* pc;
int norm_size;
int X_glyph; // index of 'X' glyph in font
int X_glyph_a[MAX_ALT]; // index of 'X' glyph for alternate fonts
public:
GLCairoSurface(int width, int height);
GLCairoSurface(const string& pngfilename);
~GLCairoSurface();
void common_constructor();
int width();
int height();
void clear();
void fill(int r, int g, int b, int a);
void fill_match_a(int r, int g, int b, int a);
void drawrect(double x_l, double x_h, double y_l, double y_h);
void paintgl(float x, float y);
void painton(GLCairoSurface* glcs2, int x, int y, double alpha);
void mixfrom(GLCairoSurface* s1, GLCairoSurface* s2, double alpha);
void color(int r, int g, int b);
bool setfontface(const string& face, bool bold, bool italic, bool smallcaps, int X);
bool setfontfacealt(unsigned int index, const string& face, bool bold, bool italic, bool smallcaps, int X);
bool setfontsize(int size);
bool setaa(bool mode);
bool writetext(const string& text, int x, int y, int align);
bool writetext(const string& text, int x, int y, int align, int maxwidth);
bool writetextshrink(const string& text, int x, int y_c, int align, int maxwidth);
};
#endif
|
[
"pymlofy@4cf78214-6c29-4fb8-b038-d2ccc4421ee9",
"[email protected]"
] |
[
[
[
1,
6
],
[
8,
12
],
[
14,
16
],
[
19,
19
],
[
23,
71
]
],
[
[
7,
7
],
[
13,
13
],
[
17,
18
],
[
20,
22
],
[
72,
72
]
]
] |
728e50c379323a5db363cac712b51128be7bd150
|
dd5c8920aa0ea96607f2498701c81bb1af2b3c96
|
/multicrewcore/fsuipc.cpp
|
e0fa427e8532722ae3e194b49b0a9e51b64163b7
|
[] |
no_license
|
BackupTheBerlios/multicrew-svn
|
913279401e9cf886476a3c912ecd3d2b8d28344c
|
5087f07a100f82c37d2b85134ccc9125342c58d1
|
refs/heads/master
| 2021-01-23T13:36:03.990862 | 2005-06-10T16:52:32 | 2005-06-10T16:52:32 | 40,747,367 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,196 |
cpp
|
/*
Multicrew
Copyright (C) 2004,2005 Stefan Schimanski
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 "common.h"
#include <windows.h>
#include "fsuipc/FSUIPC_User.h"
#include "../multicrewgauge/gauges.h"
#include "fsuipc.h"
#include "log.h"
#include "shared.h"
char *gFsuipcErrors[] = {
"Okay",
"Attempt to Open when already Open",
"Cannot link to FSUIPC or WideClient",
"Failed to Register common message with Windows",
"Failed to create Atom for mapping filename",
"Failed to create a file mapping object",
"Failed to open a view to the file map",
"Incorrect version of FSUIPC, or not FSUIPC",
"Sim is not version requested",
"Call cannot execute, link not Open",
"Call cannot execute: no requests accumulated",
"IPC timed out all retries",
"IPC sendmessage failed all retries",
"IPC request contains bad data",
"Maybe running on WideClient, but FS not running on Server, or wrong FSUIPC",
"Read or Write request cannot be added, memory for Process is full",
};
/***************************************************************/
struct Fsuipc::Data {
CRITICAL_SECTION critSect;
unsigned char mem[256];
};
static Fsuipc *gFsuipc = 0;
Fsuipc::Fsuipc() {
d = new Data;
InitializeCriticalSection( &d->critSect );
// connect to FSUIPC
DWORD res;
if( !FSUIPC_Open2( SIM_FS2K4, &res, d->mem, 256 ) ) {
derr << "Cannot connect to FSUIPC: "
<< gFsuipcErrors[res]
<< std::endl;
}
// register with freeware key
begin();
char *key = "E09XMDV8JQZ0multicrewcore.dll";
bool ok1 = write( 0x8001, strlen(key)+1, key );
bool ok2 = end();
if( !ok1 || !ok2 ) {
derr << "Cannot register Multicrew at FSUIPC with freeware key:"
<< gFsuipcErrors[res]
<< std::endl;
}
}
Fsuipc::~Fsuipc() {
// disconnect from FSUIPC
FSUIPC_Close();
if( gFsuipc==this ) gFsuipc = 0;
DeleteCriticalSection( &d->critSect );
delete d;
}
SmartPtr<Fsuipc> Fsuipc::fsuipc() {
if( gFsuipc==0 ) gFsuipc = new Fsuipc();
return gFsuipc;
}
void Fsuipc::begin() {
EnterCriticalSection( &d->critSect );
}
bool Fsuipc::read( WORD id, unsigned size, void *data ) {
DWORD res;
return FSUIPC_Read( id, size, data, &res )==TRUE;
}
bool Fsuipc::write( WORD id, unsigned size, void *data ) {
DWORD res;
return FSUIPC_Write( id, size, data, &res )==TRUE;
}
bool Fsuipc::end() {
DWORD res;
bool ok = FSUIPC_Process( &res )==TRUE;
LeaveCriticalSection( &d->critSect );
return ok;
}
|
[
"schimmi@cb9ff89a-abed-0310-8fc6-a4cabe7d48c9"
] |
[
[
[
1,
128
]
]
] |
21b6bf9fed4daf3240cd7f624086bbfe580d137b
|
208475bcab65438eed5d8380f26eacd25eb58f70
|
/SoftPack/Mkimage.cpp
|
b5207b1c574ec49db369671e503106d7bbd29aa1
|
[] |
no_license
|
awzhang/MyWork
|
83b3f0b9df5ff37330c0e976310d75593f806ec4
|
075ad5d0726c793a0c08f9158080a144e0bb5ea5
|
refs/heads/master
| 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,642 |
cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, char* argv[])
{
int i;
int iRet = 0;
FILE *hOFile = NULL;
FILE *hIFile[8] = {NULL};
struct stat objIFileStat[8] = {0};
int iIFileNum;
char szBufRead[4*1024] = {0xff};
char szOFilePath[256];
char szIFilePath[8][256];
unsigned long dwStartPos[8], dwEndPos[8];
unsigned long dwCount;
if( strcmp(argv[1],"M")==0 )
{
mkdir( "../M_bin", 0 );
iIFileNum = 8;
strcpy(szOFilePath, "../M_bin/M_image.bin");
strcpy(szIFilePath[0], "../M_bin/M_boot.bin");
strcpy(szIFilePath[1], "../M_bin/M_env.bin");
strcpy(szIFilePath[2], "../M_bin/M_kernel.bin");
strcpy(szIFilePath[3], "../M_bin/M_root.bin");
strcpy(szIFilePath[4], "../M_bin/M_update.bin");
strcpy(szIFilePath[5], "../M_bin/M_black.bin");
strcpy(szIFilePath[6], "../M_bin/M_app.bin");
strcpy(szIFilePath[7], "../M_bin/M_config.bin");
dwStartPos[0] = 0;
dwStartPos[1] = 0x00040000;
dwStartPos[2] = 0x00100000;
dwStartPos[3] = 0x00300000;
dwStartPos[4] = 0x01000000;
dwStartPos[5] = 0x01500000;
dwStartPos[6] = 0x01800000;
dwStartPos[7] = 0x01f00000;
dwEndPos[0] = 0x00040000;
dwEndPos[1] = 0x00100000;
dwEndPos[2] = 0x00300000;
dwEndPos[3] = 0x01000000;
dwEndPos[4] = 0x01500000;
dwEndPos[5] = 0x01800000;
dwEndPos[6] = 0x01f00000;
dwEndPos[7] = 0x02000000;
}
else if( strcmp(argv[1],"V8")==0 )
{
mkdir( "../V8_bin", 0 );
iIFileNum = 7;
strcpy(szOFilePath, "../V8_bin/V8_image.bin");
strcpy(szIFilePath[0], "../V8_bin/V8_boot.bin");
strcpy(szIFilePath[1], "../V8_bin/V8_kernel.bin");
strcpy(szIFilePath[2], "../V8_bin/V8_root.bin");
strcpy(szIFilePath[3], "../V8_bin/V8_update.bin");
strcpy(szIFilePath[4], "../V8_bin/V8_black.bin");
strcpy(szIFilePath[5], "../V8_bin/V8_app.bin");
strcpy(szIFilePath[6], "../V8_bin/V8_config.bin");
dwStartPos[0] = 0;
dwStartPos[1] = 0x00100000;
dwStartPos[2] = 0x00300000;
dwStartPos[3] = 0x01000000;
dwStartPos[4] = 0x01500000;
dwStartPos[5] = 0x01800000;
dwStartPos[6] = 0x01f00000;
dwEndPos[0] = 0x00100000;
dwEndPos[1] = 0x00300000;
dwEndPos[2] = 0x01000000;
dwEndPos[3] = 0x01500000;
dwEndPos[4] = 0x01800000;
dwEndPos[5] = 0x01f00000;
dwEndPos[6] = 0x02000000;
}
hOFile = fopen(szOFilePath, "w+b");
if( hOFile==NULL )
{
printf("Open Output File %s Fail!\n", szOFilePath);
goto MERGE_END;
}
for(i = 0; i < iIFileNum; i++)
{
if( access(szIFilePath[i], F_OK) )
{
printf("Input File %s Lack!\n", szIFilePath[i]);
for(dwCount = 0; dwCount < (dwEndPos[i]-dwStartPos[i])/sizeof(szBufRead); dwCount++)
{
memset(szBufRead, 0xff, sizeof(szBufRead));
fwrite(szBufRead, 1, sizeof(szBufRead), hOFile);
}
}
else
{
stat(szIFilePath[i], &objIFileStat[i]);
if( !objIFileStat[i].st_size )
{
printf("Input File %s Empty!\n", szIFilePath[i]);
goto MERGE_END;
}
hIFile[i] = fopen(szIFilePath[i], "r+");
if( hIFile[i]==NULL )
{
printf("Open Input File %s Fail!\n", szIFilePath[i]);
goto MERGE_END;
}
for(dwCount = 0; dwCount < (dwEndPos[i]-dwStartPos[i])/sizeof(szBufRead); dwCount++)
{
memset(szBufRead, 0xff, sizeof(szBufRead));
fread(szBufRead, 1, sizeof(szBufRead), hIFile[i]);
fwrite(szBufRead, 1, sizeof(szBufRead), hOFile);
}
}
}
MERGE_END:
for(i=0; i<iIFileNum; i++)
{
if(hIFile[i])
fclose(hIFile[i]);
}
if(hOFile)
fclose(hOFile);
}
|
[
"[email protected]"
] |
[
[
[
1,
142
]
]
] |
6d6c3af156c859a32d38cce222ed4d57bf1f86fa
|
5e755d27b668f647bb29218987a03c9eaa6a6d0b
|
/CADBiS_winservice/BillingService/BillingService.cpp
|
b08d97a432a7be74ed0d6e8fe2dc02a098535689
|
[] |
no_license
|
xtps1987225/cadbis
|
0672ae5b00fd04fa7ce0722190110ab1466a04ac
|
ffd2f41d87df438d6276b748129dca4dc49d2055
|
refs/heads/master
| 2021-01-20T02:17:18.865466 | 2008-07-23T09:32:21 | 2008-07-23T09:32:21 | 33,819,572 | 0 | 0 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 9,503 |
cpp
|
// BillingService.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "BillingService.h"
#include "BalloonMess.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
#include "EnsureCleanup.h"
#include "ServiceStatus.h"
#include "IOCP.h"
TCHAR g_szServiceName[] = TEXT("BS_WinClient");
TCHAR g_szShowName[] = TEXT("Биллинг система");
const int g_ncPort(12001);
#define SERVICESTATUS_IMPL
CServiceStatus g_ssSpy;
enum COMPKEY
{
CK_SERVICECONTROL,
CK_VOID //reserved for removed acess=)
};
void fInstallService() {
//открываем диспетчер служб на локальном компьютереx
CEnsureCloseServiceHandle hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
TCHAR szModulePathname[_MAX_PATH * 2];
//узнаем имя файла откуда были запущены
::GetModuleFileName(NULL, szModulePathname,
sizeof(szModulePathname)/sizeof(szModulePathname[0]));
//добавляем
::lstrcat(szModulePathname, TEXT(" /service"));
//создаем наш сервис
CEnsureCloseServiceHandle
hService = ::CreateService(hSCM, //диспетчер сервисов
g_szServiceName, //имя сервиса
g_szShowName, //отображемое имя
SERVICE_CHANGE_CONFIG|SERVICE_ENUMERATE_DEPENDENTS|GENERIC_READ, //права сервиса
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,//тип сервиса
SERVICE_AUTO_START,//само запуск
SERVICE_ERROR_IGNORE,//забиваем на ошибки
szModulePathname,//чего запускать и откуда
NULL, //все остальные по умолч
NULL,
NULL,
NULL,
NULL);
//описание
SERVICE_DESCRIPTION sd = {TEXT("Windows клент для биллинговой системы кафедры САПРиУ")};
//изменяем описание сервисов
::ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sd);
//принудительно запускаем его
if(hService) StartService(hService,0,NULL);
}
//удаление сервиса
void fRemoveService()
{
//открыли диспетчер
CEnsureCloseServiceHandle hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
//закрыли сервис путем его открыванием...
CEnsureCloseServiceHandle hService = ::OpenService(hSCM, g_szServiceName, DELETE);
//...и убили :-((
::DeleteService(hService);
}
DWORD WINAPI TimeHandlerEx(DWORD dwControl, DWORD dwEventType, PVOID pvEventData, PVOID pvContext)
{
DWORD dwReturn = ERROR_CALL_NOT_IMPLEMENTED;
BOOL fPostControlToServiceThread = FALSE;
switch (dwControl)
{
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
g_ssSpy.SetUltimateState(SERVICE_STOPPED, 2000);
fPostControlToServiceThread = TRUE;
break;
case SERVICE_CONTROL_PAUSE:
g_ssSpy.SetUltimateState(SERVICE_PAUSED, 2000);
fPostControlToServiceThread = TRUE;
break;
case SERVICE_CONTROL_CONTINUE:
g_ssSpy.SetUltimateState(SERVICE_RUNNING, 2000);
fPostControlToServiceThread = TRUE;
break;
case SERVICE_CONTROL_INTERROGATE:
g_ssSpy.ReportStatus();
break;
case SERVICE_CONTROL_PARAMCHANGE:
break;
case SERVICE_CONTROL_DEVICEEVENT:
case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
case SERVICE_CONTROL_POWEREVENT:
break;
}
if (fPostControlToServiceThread) {
CIOCP* piocp = (CIOCP*) pvContext;
piocp->PostStatus(CK_SERVICECONTROL, dwControl);
dwReturn = NO_ERROR;
}
return(dwReturn);
}
bool fSocketCreate(SOCKET& ListenSocket)
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR)return false;
//----------------------
// Create a SOCKET for listening for
// incoming connection requests.
//SOCKET ListenSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ListenSocket == INVALID_SOCKET) {
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port =12001;
if (bind( ListenSocket,
(SOCKADDR*) &service,
sizeof(service)) == SOCKET_ERROR) {
printf("bind() failed.\n");
closesocket(ListenSocket);
return 0;
}
//----------------------
// Listen for incoming connection requests.
// on the created socket
if (listen( ListenSocket, 1 ) == SOCKET_ERROR)
return false;
}
void fSocketKill(SOCKET& AcceptSocket)
{
shutdown(AcceptSocket,0);
closesocket(AcceptSocket);
WSACleanup();
}
DWORD WINAPI TPAcceptSocket(LPVOID lpParameter)
{
SOCKET* lpListenSocket=static_cast<SOCKET*>(lpParameter);
SOCKET AcceptSocket;
for(;;)
{
while(1) {
AcceptSocket = SOCKET_ERROR;
while( AcceptSocket == SOCKET_ERROR ) {
AcceptSocket = accept(*lpListenSocket, NULL, NULL );
}
//MessageBox(NULL,TEXT("Клиент подключился"),TEXT("Lanservice"),MB_OK);
break;
}
size_t len(0);
char buf[100];
do{
len=recv(AcceptSocket,buf,100,0);
buf[len]='\0';
if (strlen(buf))
{
//MessageBox(NULL,TEXT(buf),TEXT("Сообщение"),MB_OK);
CBalloonMess _bm;
_bm.DoModal(CString(buf));
}
}
while(len);
}
return 0;
}
void BeginAccept(SOCKET& AcceptSocket,HANDLE &hthread)
{
hthread=::CreateThread(NULL,0,TPAcceptSocket,&AcceptSocket,0,NULL);
}
VOID WINAPI LanServiceMain(DWORD dwArgc,LPTSTR* lpszArgv)
{
DWORD dwControl = SERVICE_CONTROL_CONTINUE;
OVERLAPPED *po;
DWORD dwNumBytes;
CIOCP iocp(0);
ULONG_PTR CompKey = CK_SERVICECONTROL;
SOCKET AcceptSocket;
HANDLE hthread(NULL);
//связываем СServiceStatus и наш сервис
g_ssSpy.Initialize(g_szServiceName, TimeHandlerEx, (PVOID) &iocp, TRUE, TRUE);
//останавливаем дотступ к процессу
g_ssSpy.AcceptControls(SERVICE_ACCEPT_STOP);
//указатели на функции установки и деустновки
//если подключилась
//делаем это
fSocketCreate(AcceptSocket);
BeginAccept(AcceptSocket,hthread);
do
{
switch (CompKey)
{
case CK_SERVICECONTROL:
//в зависимости от состояния сервиса, т.е. в зависимости от того что он делает
switch (dwControl)
{
//если просто работает
case SERVICE_CONTROL_CONTINUE:
//видимо переволи в состояние работы
g_ssSpy.ReportUltimateState();
break;
//если (при)остановлен
//то сохраняем то что собрали и удалемся
case SERVICE_CONTROL_PAUSE:
g_ssSpy.ReportUltimateState();
break;
//
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
fSocketKill(AcceptSocket);
TerminateThread(hthread,0);
g_ssSpy.ReportUltimateState();
break;
}
break;
case CK_VOID: //забито под отправку отчётов по сети.
break;
}
//если сервис не остановлен то получаем его статус
if (g_ssSpy != SERVICE_STOPPED) {
iocp.GetStatus(&CompKey, &dwNumBytes, &po);
dwControl = dwNumBytes;
}
//пока сервис не остановится
} while (g_ssSpy != SERVICE_STOPPED);
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
for (int it(0);it<argc;++it)
{
std::wcout<<argv[it];
std::cout<<std::endl;
}
//char c;
//std::cin>>c;
if(argc>1)
{
if ((argv[1][0] == TEXT('-')) || (argv[1][0] == TEXT('/')))
{
//если устанавливается
if (lstrcmpi(&argv[1][1], TEXT("install")) == 0)
{
fInstallService();
}
//если удаляется
if (lstrcmpi(&argv[1][1], TEXT("remove")) == 0)
{
fRemoveService();
}
//если в отладке
if (lstrcmpi(&argv[1][1], TEXT("debug")) == 0)
{
//
}
if (lstrcmpi(&argv[1][1], TEXT("test")) == 0)
{
MessageBox(NULL,argv[1],TEXT("MessageBox"),MB_OK);
//
}
//напрямую не вызывается, вызывается через /install
if (lstrcmpi(&argv[1][1], TEXT("service")) == 0)
{
SERVICE_TABLE_ENTRY ServiceTable[] =
{
//связываем созданнй процесс с функцией
{ g_szServiceName, LanServiceMain },
//нулы нужны чтобы знать сколько элементов
{ NULL, NULL }
};
//непосредственое свзывание процесса и функции
::StartServiceCtrlDispatcher(ServiceTable);
}
}
}
return 0;
}
return nRetCode;
}
|
[
"smecsia@254517df-764a-0410-b743-7361b4a10c92"
] |
[
[
[
1,
359
]
]
] |
c8f61c714f517d2efd587609c635e3e8161191ff
|
f77f105963cd6447d0f392b9ee7d923315a82ac6
|
/Box2DandOgre/include/GameObject/KinematicObject.h
|
a1bc25b2df3e431bc496223be1980d789aed2905
|
[] |
no_license
|
GKimGames/parkerandholt
|
8bb2b481aff14cf70a7a769974bc2bb683d74783
|
544f7afa462c5a25c044445ca9ead49244c95d3c
|
refs/heads/master
| 2016-08-07T21:03:32.167272 | 2010-08-26T03:01:35 | 2010-08-26T03:01:35 | 32,834,451 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,312 |
h
|
/*=============================================================================
KinematicObject.h
Author: Matt King
NOT USED IN THE GAME RIGHT NOW.
=============================================================================*/
#ifndef KINEMATICOBJECT_H
#define KINEMATICOBJECT_H
#include "GameObjectOgreBox2D.h"
typedef std::vector<b2Vec2> Path;
/// This is a kinematic object that moves at a certain speed a long a path.
class KinematicObject : public GameObjectOgreBox2D
{
public:
KinematicObject();
bool Update(double timeSinceLastFrame);
bool Initialize();
/// Called when two fixtures begin to touch.
/// Contact fixture is the fixture in this Object's body.
/// Collided fixture is the fixture that hit this Object's body.
virtual void BeginContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture);
/// Called when two fixtures cease to touch.
/// Contact fixture is the fixture in this Object's body.
/// Collided fixture is the fixture that hit this Object's body.
virtual void EndContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture);
void Disable() { disabled_ = true; }
void Enable() { disabled_ = false; }
const bool IsDisabled() { return disabled_; }
virtual void CreatePhysics();
/// Send out a message to all the Objects in messageList_.
virtual void SendOnMessageToList(boost::any pUserData = 0);
/// Send out a message to all the Objects in messageList_.
virtual void SendOffMessageToList(boost::any pUserData = 0);
/// Send out a message to all the Objects in messageList_.
virtual void SendToMessageList(KGBMessageType message, boost::any pUserData = 0);
/// Add an Object to the message list
void AddToMessageList(GameObjectId Id, KGBMessageType messageOn = MESSAGE_NULL, KGBMessageType messageOff = MESSAGE_NULL);
/// Remove an Object from the message list
void RemoveFromMessageList(GameObjectId Id);
void SetDefaultOnMessage(KGBMessageType onMessage){ defaultMessageOn_ = onMessage; }
void SetDefaultOffMessage(KGBMessageType offMessage){ defaultMessageOff_ = offMessage; }
protected:
KGBMessageType startReachedMessage_;
KGBMessageType endReachedMessage_;
bool isDisabled_;
Path path_;
};
|
[
"mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce"
] |
[
[
[
1,
71
]
]
] |
53d79cece8e19780ddf9af5a75514ea0c53aba16
|
8aa65aef3daa1a52966b287ffa33a3155e48cc84
|
/Source/3rdparty/Bullet/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp
|
ba9e2176af098e898e4f9a09c10348215387faf6
|
[
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
jitrc/p3d
|
da2e63ef4c52ccb70023d64316cbd473f3bd77d9
|
b9943c5ee533ddc3a5afa6b92bad15a864e40e1e
|
refs/heads/master
| 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 41,780 |
cpp
|
/*
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.
*/
//#define COMPUTE_IMPULSE_DENOM 1
//It is not necessary (redundant) to refresh contact manifolds, this refresh has been moved to the collision algorithms.
#include "btSequentialImpulseConstraintSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "btContactConstraint.h"
#include "btSolve2LinearConstraint.h"
#include "btContactSolverInfo.h"
#include "LinearMath/btIDebugDraw.h"
#include "btJacobianEntry.h"
#include "LinearMath/btMinMax.h"
#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
#include <new>
#include "LinearMath/btStackAlloc.h"
#include "LinearMath/btQuickprof.h"
#include "btSolverBody.h"
#include "btSolverConstraint.h"
#include "LinearMath/btAlignedObjectArray.h"
#include <string.h> //for memset
btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver()
:m_btSeed2(0)
{
}
btSequentialImpulseConstraintSolver::~btSequentialImpulseConstraintSolver()
{
}
#ifdef USE_SIMD
#include <emmintrin.h>
#define vec_splat(x, e) _mm_shuffle_ps(x, x, _MM_SHUFFLE(e,e,e,e))
static inline __m128 _vmathVfDot3( __m128 vec0, __m128 vec1 )
{
__m128 result = _mm_mul_ps( vec0, vec1);
return _mm_add_ps( vec_splat( result, 0 ), _mm_add_ps( vec_splat( result, 1 ), vec_splat( result, 2 ) ) );
}
#endif//USE_SIMD
// Project Gauss Seidel or the equivalent Sequential Impulse
void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGenericSIMD(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
{
#ifdef USE_SIMD
__m128 cpAppliedImp = _mm_set1_ps(c.m_appliedImpulse);
__m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
__m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
__m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse),_mm_set1_ps(c.m_cfm)));
__m128 deltaVel1Dotn = _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.m_deltaLinearVelocity.mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.m_deltaAngularVelocity.mVec128));
__m128 deltaVel2Dotn = _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.m_deltaAngularVelocity.mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.m_deltaLinearVelocity.mVec128));
deltaImpulse = _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel1Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
deltaImpulse = _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel2Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
btSimdScalar sum = _mm_add_ps(cpAppliedImp,deltaImpulse);
btSimdScalar resultLowerLess,resultUpperLess;
resultLowerLess = _mm_cmplt_ps(sum,lowerLimit1);
resultUpperLess = _mm_cmplt_ps(sum,upperLimit1);
__m128 lowMinApplied = _mm_sub_ps(lowerLimit1,cpAppliedImp);
deltaImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse) );
c.m_appliedImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum) );
__m128 upperMinApplied = _mm_sub_ps(upperLimit1,cpAppliedImp);
deltaImpulse = _mm_or_ps( _mm_and_ps(resultUpperLess, deltaImpulse), _mm_andnot_ps(resultUpperLess, upperMinApplied) );
c.m_appliedImpulse = _mm_or_ps( _mm_and_ps(resultUpperLess, c.m_appliedImpulse), _mm_andnot_ps(resultUpperLess, upperLimit1) );
__m128 linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,_mm_set1_ps(body1.m_invMass));
__m128 linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,_mm_set1_ps(body2.m_invMass));
__m128 impulseMagnitude = deltaImpulse;
body1.m_deltaLinearVelocity.mVec128 = _mm_add_ps(body1.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
body1.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body1.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
body2.m_deltaLinearVelocity.mVec128 = _mm_sub_ps(body2.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
body2.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body2.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
#else
resolveSingleConstraintRowGeneric(body1,body2,c);
#endif
}
// Project Gauss Seidel or the equivalent Sequential Impulse
void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
{
btScalar deltaImpulse = c.m_rhs-btScalar(c.m_appliedImpulse)*c.m_cfm;
const btScalar deltaVel1Dotn = c.m_contactNormal.dot(body1.m_deltaLinearVelocity) + c.m_relpos1CrossNormal.dot(body1.m_deltaAngularVelocity);
const btScalar deltaVel2Dotn = -c.m_contactNormal.dot(body2.m_deltaLinearVelocity) + c.m_relpos2CrossNormal.dot(body2.m_deltaAngularVelocity);
const btScalar delta_rel_vel = deltaVel1Dotn-deltaVel2Dotn;
deltaImpulse -= deltaVel1Dotn*c.m_jacDiagABInv;
deltaImpulse -= deltaVel2Dotn*c.m_jacDiagABInv;
const btScalar sum = btScalar(c.m_appliedImpulse) + deltaImpulse;
if (sum < c.m_lowerLimit)
{
deltaImpulse = c.m_lowerLimit-c.m_appliedImpulse;
c.m_appliedImpulse = c.m_lowerLimit;
}
else if (sum > c.m_upperLimit)
{
deltaImpulse = c.m_upperLimit-c.m_appliedImpulse;
c.m_appliedImpulse = c.m_upperLimit;
}
else
{
c.m_appliedImpulse = sum;
}
if (body1.m_invMass)
body1.applyImpulse(c.m_contactNormal*body1.m_invMass,c.m_angularComponentA,deltaImpulse);
if (body2.m_invMass)
body2.applyImpulse(-c.m_contactNormal*body2.m_invMass,c.m_angularComponentB,deltaImpulse);
}
void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimitSIMD(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
{
#ifdef USE_SIMD
__m128 cpAppliedImp = _mm_set1_ps(c.m_appliedImpulse);
__m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
__m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
__m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse),_mm_set1_ps(c.m_cfm)));
__m128 deltaVel1Dotn = _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.m_deltaLinearVelocity.mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.m_deltaAngularVelocity.mVec128));
__m128 deltaVel2Dotn = _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.m_deltaAngularVelocity.mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.m_deltaLinearVelocity.mVec128));
deltaImpulse = _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel1Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
deltaImpulse = _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel2Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
btSimdScalar sum = _mm_add_ps(cpAppliedImp,deltaImpulse);
btSimdScalar resultLowerLess,resultUpperLess;
resultLowerLess = _mm_cmplt_ps(sum,lowerLimit1);
resultUpperLess = _mm_cmplt_ps(sum,upperLimit1);
__m128 lowMinApplied = _mm_sub_ps(lowerLimit1,cpAppliedImp);
deltaImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse) );
c.m_appliedImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum) );
__m128 linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,_mm_set1_ps(body1.m_invMass));
__m128 linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,_mm_set1_ps(body2.m_invMass));
__m128 impulseMagnitude = deltaImpulse;
body1.m_deltaLinearVelocity.mVec128 = _mm_add_ps(body1.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
body1.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body1.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
body2.m_deltaLinearVelocity.mVec128 = _mm_sub_ps(body2.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
body2.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body2.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
#else
resolveSingleConstraintRowLowerLimit(body1,body2,c);
#endif
}
// Project Gauss Seidel or the equivalent Sequential Impulse
void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
{
btScalar deltaImpulse = c.m_rhs-btScalar(c.m_appliedImpulse)*c.m_cfm;
const btScalar deltaVel1Dotn = c.m_contactNormal.dot(body1.m_deltaLinearVelocity) + c.m_relpos1CrossNormal.dot(body1.m_deltaAngularVelocity);
const btScalar deltaVel2Dotn = -c.m_contactNormal.dot(body2.m_deltaLinearVelocity) + c.m_relpos2CrossNormal.dot(body2.m_deltaAngularVelocity);
deltaImpulse -= deltaVel1Dotn*c.m_jacDiagABInv;
deltaImpulse -= deltaVel2Dotn*c.m_jacDiagABInv;
const btScalar sum = btScalar(c.m_appliedImpulse) + deltaImpulse;
if (sum < c.m_lowerLimit)
{
deltaImpulse = c.m_lowerLimit-c.m_appliedImpulse;
c.m_appliedImpulse = c.m_lowerLimit;
}
else
{
c.m_appliedImpulse = sum;
}
if (body1.m_invMass)
body1.applyImpulse(c.m_contactNormal*body1.m_invMass,c.m_angularComponentA,deltaImpulse);
if (body2.m_invMass)
body2.applyImpulse(-c.m_contactNormal*body2.m_invMass,c.m_angularComponentB,deltaImpulse);
}
unsigned long btSequentialImpulseConstraintSolver::btRand2()
{
m_btSeed2 = (1664525L*m_btSeed2 + 1013904223L) & 0xffffffff;
return m_btSeed2;
}
//See ODE: adam's all-int straightforward(?) dRandInt (0..n-1)
int btSequentialImpulseConstraintSolver::btRandInt2 (int n)
{
// seems good; xor-fold and modulus
const unsigned long un = static_cast<unsigned long>(n);
unsigned long r = btRand2();
// note: probably more aggressive than it needs to be -- might be
// able to get away without one or two of the innermost branches.
if (un <= 0x00010000UL) {
r ^= (r >> 16);
if (un <= 0x00000100UL) {
r ^= (r >> 8);
if (un <= 0x00000010UL) {
r ^= (r >> 4);
if (un <= 0x00000004UL) {
r ^= (r >> 2);
if (un <= 0x00000002UL) {
r ^= (r >> 1);
}
}
}
}
}
return (int) (r % un);
}
void btSequentialImpulseConstraintSolver::initSolverBody(btSolverBody* 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();
} else
{
solverBody->m_invMass = 0.f;
solverBody->m_originalBody = 0;
solverBody->m_angularFactor = 1.f;
}
}
int gNumSplitImpulseRecoveries = 0;
btScalar btSequentialImpulseConstraintSolver::restitutionCurve(btScalar rel_vel, btScalar restitution)
{
btScalar rest = restitution * -rel_vel;
return rest;
}
void applyAnisotropicFriction(btCollisionObject* colObj,btVector3& frictionDirection);
void applyAnisotropicFriction(btCollisionObject* colObj,btVector3& frictionDirection)
{
if (colObj && colObj->hasAnisotropicFriction())
{
// transform to local coordinates
btVector3 loc_lateral = frictionDirection * colObj->getWorldTransform().getBasis();
const btVector3& friction_scaling = colObj->getAnisotropicFriction();
//apply anisotropic friction
loc_lateral *= friction_scaling;
// ... and transform it back to global coordinates
frictionDirection = colObj->getWorldTransform().getBasis() * loc_lateral;
}
}
btSolverConstraint& btSequentialImpulseConstraintSolver::addFrictionConstraint(const btVector3& normalAxis,int solverBodyIdA,int solverBodyIdB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation)
{
btRigidBody* body0=btRigidBody::upcast(colObj0);
btRigidBody* body1=btRigidBody::upcast(colObj1);
btSolverConstraint& solverConstraint = m_tmpSolverContactFrictionConstraintPool.expand();
memset(&solverConstraint,0xff,sizeof(btSolverConstraint));
solverConstraint.m_contactNormal = normalAxis;
solverConstraint.m_solverBodyIdA = solverBodyIdA;
solverConstraint.m_solverBodyIdB = solverBodyIdB;
solverConstraint.m_frictionIndex = frictionIndex;
solverConstraint.m_friction = cp.m_combinedFriction;
solverConstraint.m_originalContactPoint = 0;
solverConstraint.m_appliedImpulse = 0.f;
// solverConstraint.m_appliedPushImpulse = 0.f;
{
btVector3 ftorqueAxis1 = rel_pos1.cross(solverConstraint.m_contactNormal);
solverConstraint.m_relpos1CrossNormal = ftorqueAxis1;
solverConstraint.m_angularComponentA = body0 ? body0->getInvInertiaTensorWorld()*ftorqueAxis1*body0->getAngularFactor() : btVector3(0,0,0);
}
{
btVector3 ftorqueAxis1 = rel_pos2.cross(-solverConstraint.m_contactNormal);
solverConstraint.m_relpos2CrossNormal = ftorqueAxis1;
solverConstraint.m_angularComponentB = body1 ? body1->getInvInertiaTensorWorld()*ftorqueAxis1*body1->getAngularFactor() : btVector3(0,0,0);
}
#ifdef COMPUTE_IMPULSE_DENOM
btScalar denom0 = rb0->computeImpulseDenominator(pos1,solverConstraint.m_contactNormal);
btScalar denom1 = rb1->computeImpulseDenominator(pos2,solverConstraint.m_contactNormal);
#else
btVector3 vec;
btScalar denom0 = 0.f;
btScalar denom1 = 0.f;
if (body0)
{
vec = ( solverConstraint.m_angularComponentA).cross(rel_pos1);
denom0 = body0->getInvMass() + normalAxis.dot(vec);
}
if (body1)
{
vec = ( -solverConstraint.m_angularComponentB).cross(rel_pos2);
denom1 = body1->getInvMass() + normalAxis.dot(vec);
}
#endif //COMPUTE_IMPULSE_DENOM
btScalar denom = relaxation/(denom0+denom1);
solverConstraint.m_jacDiagABInv = denom;
#ifdef _USE_JACOBIAN
solverConstraint.m_jac = btJacobianEntry (
rel_pos1,rel_pos2,solverConstraint.m_contactNormal,
body0->getInvInertiaDiagLocal(),
body0->getInvMass(),
body1->getInvInertiaDiagLocal(),
body1->getInvMass());
#endif //_USE_JACOBIAN
{
btScalar rel_vel;
btScalar vel1Dotn = solverConstraint.m_contactNormal.dot(body0?body0->getLinearVelocity():btVector3(0,0,0))
+ solverConstraint.m_relpos1CrossNormal.dot(body0?body0->getAngularVelocity():btVector3(0,0,0));
btScalar vel2Dotn = -solverConstraint.m_contactNormal.dot(body1?body1->getLinearVelocity():btVector3(0,0,0))
+ solverConstraint.m_relpos2CrossNormal.dot(body1?body1->getAngularVelocity():btVector3(0,0,0));
rel_vel = vel1Dotn+vel2Dotn;
btScalar positionalError = 0.f;
btSimdScalar velocityError = - rel_vel;
btSimdScalar velocityImpulse = velocityError * btSimdScalar(solverConstraint.m_jacDiagABInv);
solverConstraint.m_rhs = velocityImpulse;
solverConstraint.m_cfm = 0.f;
solverConstraint.m_lowerLimit = 0;
solverConstraint.m_upperLimit = 1e10f;
}
return solverConstraint;
}
int btSequentialImpulseConstraintSolver::getOrInitSolverBody(btCollisionObject& body)
{
int solverBodyIdA = -1;
if (body.getCompanionId() >= 0)
{
//body has already been converted
solverBodyIdA = body.getCompanionId();
} else
{
btRigidBody* rb = btRigidBody::upcast(&body);
if (rb && rb->getInvMass())
{
solverBodyIdA = m_tmpSolverBodyPool.size();
btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
initSolverBody(&solverBody,&body);
body.setCompanionId(solverBodyIdA);
} else
{
return 0;//assume first one is a fixed solver body
}
}
return solverBodyIdA;
}
#include <stdio.h>
void btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold* manifold,const btContactSolverInfo& infoGlobal)
{
btCollisionObject* colObj0=0,*colObj1=0;
colObj0 = (btCollisionObject*)manifold->getBody0();
colObj1 = (btCollisionObject*)manifold->getBody1();
int solverBodyIdA=-1;
int solverBodyIdB=-1;
if (manifold->getNumContacts())
{
solverBodyIdA = getOrInitSolverBody(*colObj0);
solverBodyIdB = getOrInitSolverBody(*colObj1);
}
///avoid collision response between two static objects
if (!solverBodyIdA && !solverBodyIdB)
return;
btVector3 rel_pos1;
btVector3 rel_pos2;
btScalar relaxation;
for (int j=0;j<manifold->getNumContacts();j++)
{
btManifoldPoint& cp = manifold->getContactPoint(j);
if (cp.getDistance() <= manifold->getContactProcessingThreshold())
{
const btVector3& pos1 = cp.getPositionWorldOnA();
const btVector3& pos2 = cp.getPositionWorldOnB();
rel_pos1 = pos1 - colObj0->getWorldTransform().getOrigin();
rel_pos2 = pos2 - colObj1->getWorldTransform().getOrigin();
relaxation = 1.f;
btScalar rel_vel;
btVector3 vel;
int frictionIndex = m_tmpSolverContactConstraintPool.size();
{
btSolverConstraint& solverConstraint = m_tmpSolverContactConstraintPool.expand();
btRigidBody* rb0 = btRigidBody::upcast(colObj0);
btRigidBody* rb1 = btRigidBody::upcast(colObj1);
solverConstraint.m_solverBodyIdA = solverBodyIdA;
solverConstraint.m_solverBodyIdB = solverBodyIdB;
solverConstraint.m_originalContactPoint = &cp;
btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB);
solverConstraint.m_angularComponentA = rb0 ? rb0->getInvInertiaTensorWorld()*torqueAxis0*rb0->getAngularFactor() : btVector3(0,0,0);
btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB);
solverConstraint.m_angularComponentB = rb1 ? rb1->getInvInertiaTensorWorld()*-torqueAxis1*rb1->getAngularFactor() : btVector3(0,0,0);
{
#ifdef COMPUTE_IMPULSE_DENOM
btScalar denom0 = rb0->computeImpulseDenominator(pos1,cp.m_normalWorldOnB);
btScalar denom1 = rb1->computeImpulseDenominator(pos2,cp.m_normalWorldOnB);
#else
btVector3 vec;
btScalar denom0 = 0.f;
btScalar denom1 = 0.f;
if (rb0)
{
vec = ( solverConstraint.m_angularComponentA).cross(rel_pos1);
denom0 = rb0->getInvMass() + cp.m_normalWorldOnB.dot(vec);
}
if (rb1)
{
vec = ( -solverConstraint.m_angularComponentB).cross(rel_pos2);
denom1 = rb1->getInvMass() + cp.m_normalWorldOnB.dot(vec);
}
#endif //COMPUTE_IMPULSE_DENOM
btScalar denom = relaxation/(denom0+denom1);
solverConstraint.m_jacDiagABInv = denom;
}
solverConstraint.m_contactNormal = cp.m_normalWorldOnB;
solverConstraint.m_relpos1CrossNormal = rel_pos1.cross(cp.m_normalWorldOnB);
solverConstraint.m_relpos2CrossNormal = rel_pos2.cross(-cp.m_normalWorldOnB);
btVector3 vel1 = rb0 ? rb0->getVelocityInLocalPoint(rel_pos1) : btVector3(0,0,0);
btVector3 vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
vel = vel1 - vel2;
rel_vel = cp.m_normalWorldOnB.dot(vel);
btScalar penetration = cp.getDistance()+infoGlobal.m_linearSlop;
solverConstraint.m_friction = cp.m_combinedFriction;
btScalar restitution = 0.f;
if (cp.m_lifeTime>infoGlobal.m_restingContactRestitutionThreshold)
{
restitution = 0.f;
} else
{
restitution = restitutionCurve(rel_vel, cp.m_combinedRestitution);
if (restitution <= btScalar(0.))
{
restitution = 0.f;
};
}
///warm starting (or zero if disabled)
if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
{
solverConstraint.m_appliedImpulse = cp.m_appliedImpulse * infoGlobal.m_warmstartingFactor;
if (rb0)
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse(solverConstraint.m_contactNormal*rb0->getInvMass(),solverConstraint.m_angularComponentA,solverConstraint.m_appliedImpulse);
if (rb1)
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse(solverConstraint.m_contactNormal*rb1->getInvMass(),-solverConstraint.m_angularComponentB,-solverConstraint.m_appliedImpulse);
} else
{
solverConstraint.m_appliedImpulse = 0.f;
}
// solverConstraint.m_appliedPushImpulse = 0.f;
{
btScalar rel_vel;
btScalar vel1Dotn = solverConstraint.m_contactNormal.dot(rb0?rb0->getLinearVelocity():btVector3(0,0,0))
+ solverConstraint.m_relpos1CrossNormal.dot(rb0?rb0->getAngularVelocity():btVector3(0,0,0));
btScalar vel2Dotn = -solverConstraint.m_contactNormal.dot(rb1?rb1->getLinearVelocity():btVector3(0,0,0))
+ solverConstraint.m_relpos2CrossNormal.dot(rb1?rb1->getAngularVelocity():btVector3(0,0,0));
rel_vel = vel1Dotn+vel2Dotn;
btScalar positionalError = 0.f;
positionalError = -penetration * infoGlobal.m_erp/infoGlobal.m_timeStep;
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_cfm = 0.f;
solverConstraint.m_lowerLimit = 0;
solverConstraint.m_upperLimit = 1e10f;
}
/////setup the friction constraints
if (1)
{
solverConstraint.m_frictionIndex = m_tmpSolverContactFrictionConstraintPool.size();
if (!(infoGlobal.m_solverMode & SOLVER_ENABLE_FRICTION_DIRECTION_CACHING) || !cp.m_lateralFrictionInitialized)
{
cp.m_lateralFrictionDir1 = vel - cp.m_normalWorldOnB * rel_vel;
btScalar lat_rel_vel = cp.m_lateralFrictionDir1.length2();
if (!(infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION) && lat_rel_vel > SIMD_EPSILON)
{
cp.m_lateralFrictionDir1 /= btSqrt(lat_rel_vel);
applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir1);
applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir1);
addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
if((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
cp.m_lateralFrictionDir2 = cp.m_lateralFrictionDir1.cross(cp.m_normalWorldOnB);
cp.m_lateralFrictionDir2.normalize();//??
applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir2);
applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir2);
addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
}
cp.m_lateralFrictionInitialized = true;
} else
{
//re-calculate friction direction every frame, todo: check if this is really needed
btPlaneSpace1(cp.m_normalWorldOnB,cp.m_lateralFrictionDir1,cp.m_lateralFrictionDir2);
applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir1);
applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir1);
addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir2);
applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir2);
addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
}
cp.m_lateralFrictionInitialized = true;
}
} else
{
addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
}
if (infoGlobal.m_solverMode & SOLVER_USE_FRICTION_WARMSTARTING)
{
{
btSolverConstraint& frictionConstraint1 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex];
if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
{
frictionConstraint1.m_appliedImpulse = cp.m_appliedImpulseLateral1 * infoGlobal.m_warmstartingFactor;
if (rb0)
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse(frictionConstraint1.m_contactNormal*rb0->getInvMass(),frictionConstraint1.m_angularComponentA,frictionConstraint1.m_appliedImpulse);
if (rb1)
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse(frictionConstraint1.m_contactNormal*rb1->getInvMass(),-frictionConstraint1.m_angularComponentB,-frictionConstraint1.m_appliedImpulse);
} else
{
frictionConstraint1.m_appliedImpulse = 0.f;
}
}
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
btSolverConstraint& frictionConstraint2 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex+1];
if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
{
frictionConstraint2.m_appliedImpulse = cp.m_appliedImpulseLateral2 * infoGlobal.m_warmstartingFactor;
if (rb0)
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse(frictionConstraint2.m_contactNormal*rb0->getInvMass(),frictionConstraint2.m_angularComponentA,frictionConstraint2.m_appliedImpulse);
if (rb1)
m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse(frictionConstraint2.m_contactNormal*rb1->getInvMass(),-frictionConstraint2.m_angularComponentB,-frictionConstraint2.m_appliedImpulse);
} else
{
frictionConstraint2.m_appliedImpulse = 0.f;
}
}
} else
{
btSolverConstraint& frictionConstraint1 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex];
frictionConstraint1.m_appliedImpulse = 0.f;
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
btSolverConstraint& frictionConstraint2 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex+1];
frictionConstraint2.m_appliedImpulse = 0.f;
}
}
}
}
}
}
}
btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** /*bodies */,int /*numBodies */,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc)
{
BT_PROFILE("solveGroupCacheFriendlySetup");
(void)stackAlloc;
(void)debugDrawer;
if (!(numConstraints + numManifolds))
{
// printf("empty\n");
return 0.f;
}
if (1)
{
int j;
for (j=0;j<numConstraints;j++)
{
btTypedConstraint* constraint = constraints[j];
constraint->buildJacobian();
}
}
btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
initSolverBody(&fixedBody,0);
//btRigidBody* rb0=0,*rb1=0;
//if (1)
{
{
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;
}
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();
btRigidBody& rbB = constraint->getRigidBodyB();
int solverBodyIdA = getOrInitSolverBody(rbA);
int solverBodyIdB = getOrInitSolverBody(rbB);
btSolverBody* bodyAPtr = &m_tmpSolverBodyPool[solverBodyIdA];
btSolverBody* bodyBPtr = &m_tmpSolverBodyPool[solverBodyIdB];
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
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;
}
}
}
}
}
{
int i;
btPersistentManifold* manifold = 0;
btCollisionObject* colObj0=0,*colObj1=0;
for (i=0;i<numManifolds;i++)
{
manifold = manifoldPtr[i];
convertContact(manifold,infoGlobal);
}
}
}
btContactSolverInfo info = infoGlobal;
int numConstraintPool = m_tmpSolverContactConstraintPool.size();
int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
///@todo: use stack allocator for such temporarily memory, same for solver bodies/constraints
m_orderTmpConstraintPool.resize(numConstraintPool);
m_orderFrictionConstraintPool.resize(numFrictionPool);
{
int i;
for (i=0;i<numConstraintPool;i++)
{
m_orderTmpConstraintPool[i] = i;
}
for (i=0;i<numFrictionPool;i++)
{
m_orderFrictionConstraintPool[i] = i;
}
}
return 0.f;
}
btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyIterations(btCollisionObject** /*bodies */,int /*numBodies*/,btPersistentManifold** /*manifoldPtr*/, int /*numManifolds*/,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* /*debugDrawer*/,btStackAlloc* /*stackAlloc*/)
{
BT_PROFILE("solveGroupCacheFriendlyIterations");
int numConstraintPool = m_tmpSolverContactConstraintPool.size();
int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
//should traverse the contacts random order...
int iteration;
{
for ( iteration = 0;iteration<infoGlobal.m_numIterations;iteration++)
{
int j;
if (infoGlobal.m_solverMode & SOLVER_RANDMIZE_ORDER)
{
if ((iteration & 7) == 0) {
for (j=0; j<numConstraintPool; ++j) {
int tmp = m_orderTmpConstraintPool[j];
int swapi = btRandInt2(j+1);
m_orderTmpConstraintPool[j] = m_orderTmpConstraintPool[swapi];
m_orderTmpConstraintPool[swapi] = tmp;
}
for (j=0; j<numFrictionPool; ++j) {
int tmp = m_orderFrictionConstraintPool[j];
int swapi = btRandInt2(j+1);
m_orderFrictionConstraintPool[j] = m_orderFrictionConstraintPool[swapi];
m_orderFrictionConstraintPool[swapi] = tmp;
}
}
}
if (infoGlobal.m_solverMode & SOLVER_SIMD)
{
///solve all joint constraints, using SIMD, if available
for (j=0;j<m_tmpSolverNonContactConstraintPool.size();j++)
{
btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[j];
resolveSingleConstraintRowGenericSIMD(m_tmpSolverBodyPool[constraint.m_solverBodyIdA],m_tmpSolverBodyPool[constraint.m_solverBodyIdB],constraint);
}
for (j=0;j<numConstraints;j++)
{
int bodyAid = getOrInitSolverBody(constraints[j]->getRigidBodyA());
int bodyBid = getOrInitSolverBody(constraints[j]->getRigidBodyB());
btSolverBody& bodyA = m_tmpSolverBodyPool[bodyAid];
btSolverBody& bodyB = m_tmpSolverBodyPool[bodyBid];
constraints[j]->solveConstraintObsolete(bodyA,bodyB,infoGlobal.m_timeStep);
}
///solve all contact constraints using SIMD, if available
int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
for (j=0;j<numPoolConstraints;j++)
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
resolveSingleConstraintRowLowerLimitSIMD(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA],m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
}
///solve all friction constraints, using SIMD, if available
int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
for (j=0;j<numFrictionPoolConstraints;j++)
{
btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
if (totalImpulse>btScalar(0))
{
solveManifold.m_lowerLimit = -(solveManifold.m_friction*totalImpulse);
solveManifold.m_upperLimit = solveManifold.m_friction*totalImpulse;
resolveSingleConstraintRowGenericSIMD(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
}
}
} else
{
///solve all joint constraints
for (j=0;j<m_tmpSolverNonContactConstraintPool.size();j++)
{
btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[j];
resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[constraint.m_solverBodyIdA],m_tmpSolverBodyPool[constraint.m_solverBodyIdB],constraint);
}
for (j=0;j<numConstraints;j++)
{
int bodyAid = getOrInitSolverBody(constraints[j]->getRigidBodyA());
int bodyBid = getOrInitSolverBody(constraints[j]->getRigidBodyB());
btSolverBody& bodyA = m_tmpSolverBodyPool[bodyAid];
btSolverBody& bodyB = m_tmpSolverBodyPool[bodyBid];
constraints[j]->solveConstraintObsolete(bodyA,bodyB,infoGlobal.m_timeStep);
}
///solve all contact constraints
int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
for (j=0;j<numPoolConstraints;j++)
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
resolveSingleConstraintRowLowerLimit(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA],m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
}
///solve all friction constraints
int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
for (j=0;j<numFrictionPoolConstraints;j++)
{
btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
if (totalImpulse>btScalar(0))
{
solveManifold.m_lowerLimit = -(solveManifold.m_friction*totalImpulse);
solveManifold.m_upperLimit = solveManifold.m_friction*totalImpulse;
resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
}
}
}
}
}
return 0.f;
}
/// btSequentialImpulseConstraintSolver Sequentially applies impulses
btScalar btSequentialImpulseConstraintSolver::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);
int i;
solveGroupCacheFriendlySetup( bodies, numBodies, manifoldPtr, numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
solveGroupCacheFriendlyIterations(bodies, numBodies, manifoldPtr, numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
int j;
for (j=0;j<numPoolConstraints;j++)
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[j];
btManifoldPoint* pt = (btManifoldPoint*) solveManifold.m_originalContactPoint;
btAssert(pt);
pt->m_appliedImpulse = solveManifold.m_appliedImpulse;
if (infoGlobal.m_solverMode & SOLVER_USE_FRICTION_WARMSTARTING)
{
pt->m_appliedImpulseLateral1 = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
pt->m_appliedImpulseLateral2 = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex+1].m_appliedImpulse;
}
//do a callback here?
}
if (infoGlobal.m_splitImpulse)
{
for ( i=0;i<m_tmpSolverBodyPool.size();i++)
{
m_tmpSolverBodyPool[i].writebackVelocity(infoGlobal.m_timeStep);
}
} else
{
for ( i=0;i<m_tmpSolverBodyPool.size();i++)
{
m_tmpSolverBodyPool[i].writebackVelocity();
}
}
m_tmpSolverBodyPool.resize(0);
m_tmpSolverContactConstraintPool.resize(0);
m_tmpSolverNonContactConstraintPool.resize(0);
m_tmpSolverContactFrictionConstraintPool.resize(0);
return 0.f;
}
void btSequentialImpulseConstraintSolver::reset()
{
m_btSeed2 = 0;
}
|
[
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
] |
[
[
[
1,
1031
]
]
] |
154b45962da2ca073a69c396c51986a2886bd605
|
f9351a01f0e2dec478e5b60c6ec6445dcd1421ec
|
/itl/boost/itl_xt/typed_episode.hpp
|
bf69dcb1e87f017f8f287ec77b542c3469c19228
|
[
"BSL-1.0"
] |
permissive
|
WolfgangSt/itl
|
e43ed68933f554c952ddfadefef0e466612f542c
|
6609324171a96565cabcf755154ed81943f07d36
|
refs/heads/master
| 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,012 |
hpp
|
/*----------------------------------------------------------------------------+
Copyright (c) 2007-2008: Joachim Faulhaber
+-----------------------------------------------------------------------------+
Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin
+-----------------------------------------------------------------------------+
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+----------------------------------------------------------------------------*/
#ifndef __itl_typed_episode_hpp_JOFA_011015_H__
#define __itl_typed_episode_hpp_JOFA_011015_H__
#include <boost/itl/interval.hpp>
#include <boost/itl_xt/ordered_type.hpp>
namespace boost{namespace itl
{
/// Serves as a base class for the decomposition of histories in episodes
/**
<b>Episoden-Intercace</b>
Eine Episode besitzt ein Intervall.
@author Joachim Faulhaber
*/
template <class TimeT>
class episode_interface
{
public:
/// virtual dtor: cave leakem
virtual ~episode_interface(){}
/// das Intervall der Episode
virtual itl::interval<TimeT> interval()const=0;
};
/// typed_episode is an episode that can be ordered wrt. it's type
/**
<b>ein Episode mit Typ dazu</b>
Die Klasse typed_episode ist nach Typ sortierbar, denn sie
implementiert \ref ordered_type. Ausserdem ist es eine Episode, denn
sie implementiert \ref episode_interface.
@author Joachim Faulhaber
*/
template <class TimeT, class TypeDomain>
class typed_episode : public ordered_type_base<TypeDomain>, public episode_interface<TimeT>
{
};
}} // namespace itl boost
#endif // __itl_typed_episode_hpp_JOFA_011015_H__
|
[
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
] |
[
[
[
1,
79
]
]
] |
9619e5db3202f8164802e5f1e673449d921d8465
|
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
|
/CommonSources/TagLib/ape/apefooter.cpp
|
183cfc38e6ab08fc3f786dbf7ed19d8bdbff762f
|
[] |
no_license
|
outcast1000/Jaangle
|
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
|
18feb537068f1f3be6ecaa8a4b663b917c429e3d
|
refs/heads/master
| 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,770 |
cpp
|
/***************************************************************************
copyright : (C) 2004 by Allan Sandfeld Jensen
(C) 2002 - 2008 by Scott Wheeler (id3v2header.cpp)
email : [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 version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <iostream>
#include <bitset>
#include <tstring.h>
#include <tdebug.h>
#include "apefooter.h"
using namespace TagLib;
using namespace APE;
class Footer::FooterPrivate
{
public:
FooterPrivate() : version(0),
footerPresent(true),
headerPresent(false),
isHeader(false),
itemCount(0),
tagSize(0) {}
~FooterPrivate() {}
uint version;
bool footerPresent;
bool headerPresent;
bool isHeader;
uint itemCount;
uint tagSize;
static const uint size = 32;
};
////////////////////////////////////////////////////////////////////////////////
// static members
////////////////////////////////////////////////////////////////////////////////
TagLib::uint Footer::size()
{
return FooterPrivate::size;
}
ByteVector Footer::fileIdentifier()
{
return ByteVector::fromCString("APETAGEX");
}
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
Footer::Footer()
{
d = new FooterPrivate;
}
Footer::Footer(const ByteVector &data)
{
d = new FooterPrivate;
parse(data);
}
Footer::~Footer()
{
delete d;
}
TagLib::uint Footer::version() const
{
return d->version;
}
bool Footer::headerPresent() const
{
return d->headerPresent;
}
bool Footer::footerPresent() const
{
return d->footerPresent;
}
bool Footer::isHeader() const
{
return d->isHeader;
}
void Footer::setHeaderPresent(bool b) const
{
d->headerPresent = b;
}
TagLib::uint Footer::itemCount() const
{
return d->itemCount;
}
void Footer::setItemCount(uint s)
{
d->itemCount = s;
}
TagLib::uint Footer::tagSize() const
{
return d->tagSize;
}
TagLib::uint Footer::completeTagSize() const
{
if(d->headerPresent)
return d->tagSize + d->size;
else
return d->tagSize;
}
void Footer::setTagSize(uint s)
{
d->tagSize = s;
}
void Footer::setData(const ByteVector &data)
{
parse(data);
}
ByteVector Footer::renderFooter() const
{
return render(false);
}
ByteVector Footer::renderHeader() const
{
if (!d->headerPresent) return ByteVector();
return render(true);
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void Footer::parse(const ByteVector &data)
{
if(data.size() < size())
return;
// The first eight bytes, data[0..7], are the File Identifier, "APETAGEX".
// Read the version number
d->version = data.mid(8, 4).toUInt(false);
// Read the tag size
d->tagSize = data.mid(12, 4).toUInt(false);
// Read the item count
d->itemCount = data.mid(16, 4).toUInt(false);
// Read the flags
std::bitset<32> flags(data.mid(20, 4).toUInt(false));
d->headerPresent = flags[31];
d->footerPresent = !flags[30];
d->isHeader = flags[29];
}
ByteVector Footer::render(bool isHeader) const
{
ByteVector v;
// add the file identifier -- "APETAGEX"
v.append(fileIdentifier());
// add the version number -- we always render a 2.000 tag regardless of what
// the tag originally was.
v.append(ByteVector::fromUInt(2000, false));
// add the tag size
v.append(ByteVector::fromUInt(d->tagSize, false));
// add the item count
v.append(ByteVector::fromUInt(d->itemCount, false));
// render and add the flags
std::bitset<32> flags;
flags[31] = d->headerPresent;
flags[30] = false; // footer is always present
flags[29] = isHeader;
v.append(ByteVector::fromUInt(flags.to_ulong(), false));
// add the reserved 64bit
v.append(ByteVector::fromLongLong(0));
return v;
}
|
[
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] |
[
[
[
1,
236
]
]
] |
0617d40d047075b141fab9a6f22361f9e64d5cca
|
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
|
/Projects/elastix/elastix_sources_v4/src/Components/Metrics/AdvancedMattesMutualInformation/itkParzenWindowMutualInformationImageToImageMetric.hxx
|
449da3f351350e4665920cdaae88c20a6d3e92ed
|
[] |
no_license
|
mijc/Diploma
|
95fa1b04801ba9afb6493b24b53383d0fbd00b33
|
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
|
refs/heads/master
| 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 35,219 |
hxx
|
/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef _itkParzenWindowMutualInformationImageToImageMetric_HXX__
#define _itkParzenWindowMutualInformationImageToImageMetric_HXX__
#include "itkParzenWindowMutualInformationImageToImageMetric.h"
#include "itkImageLinearConstIteratorWithIndex.h"
#include "vnl/vnl_math.h"
#include "itkMatrix.h"
#include "vnl/vnl_inverse.h"
#include "vnl/vnl_det.h"
namespace itk
{
/**
* ********************* Constructor ******************************
*/
template < class TFixedImage, class TMovingImage >
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::ParzenWindowMutualInformationImageToImageMetric()
{
this->m_UseJacobianPreconditioning = false;
} // end constructor
/**
* ********************* InitializeHistograms ******************************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::InitializeHistograms( void )
{
/** Call Superclass implementation. */
this->Superclass::InitializeHistograms();
/** Allocate small amount of memory for the m_PRatioArray. */
if ( !this->GetUseExplicitPDFDerivatives() )
{
this->m_PRatioArray.SetSize(
this->GetNumberOfFixedHistogramBins(),
this->GetNumberOfMovingHistogramBins() );
}
} // end InitializeHistograms()
/**
* ************************** GetValue **************************
* Get the match Measure.
*/
template < class TFixedImage, class TMovingImage >
typename ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::MeasureType
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::GetValue( const ParametersType& parameters ) const
{
/** Construct the JointPDF and Alpha. */
this->ComputePDFs( parameters );
/** Normalize the pdfs: p = alpha h. */
this->NormalizeJointPDF( this->m_JointPDF, this->m_Alpha );
/** Compute the fixed and moving marginal pdfs, by summing over the joint pdf. */
this->ComputeMarginalPDF( this->m_JointPDF, this->m_FixedImageMarginalPDF, 0 );
this->ComputeMarginalPDF( this->m_JointPDF, this->m_MovingImageMarginalPDF, 1 );
/** Compute the metric by double summation over histogram. */
/** Setup iterators */
typedef ImageLinearConstIteratorWithIndex<JointPDFType> JointPDFIteratorType;
typedef typename MarginalPDFType::const_iterator MarginalPDFIteratorType;
JointPDFIteratorType jointPDFit(
this->m_JointPDF, this->m_JointPDF->GetLargestPossibleRegion() );
jointPDFit.SetDirection(0);
jointPDFit.GoToBegin();
MarginalPDFIteratorType fixedPDFit = this->m_FixedImageMarginalPDF.begin();
const MarginalPDFIteratorType fixedPDFend = this->m_FixedImageMarginalPDF.end();
MarginalPDFIteratorType movingPDFit = this->m_MovingImageMarginalPDF.begin();
const MarginalPDFIteratorType movingPDFend = this->m_MovingImageMarginalPDF.end();
/** Loop over histogram. */
double MI = 0.0;
while ( fixedPDFit != fixedPDFend )
{
const double fixedImagePDFValue = *fixedPDFit;
movingPDFit = this->m_MovingImageMarginalPDF.begin();
while ( movingPDFit != movingPDFend )
{
const double movingImagePDFValue = *movingPDFit;
const double fixPDFmovPDF = fixedImagePDFValue * movingImagePDFValue;
const double jointPDFValue = jointPDFit.Get();
/** Check for non-zero bin contribution. */
if( jointPDFValue > 1e-16 && fixPDFmovPDF > 1e-16 )
{
MI += jointPDFValue * vcl_log( jointPDFValue / fixPDFmovPDF );
}
++movingPDFit;
++jointPDFit;
} // end while-loop over moving index
++fixedPDFit;
jointPDFit.NextLine();
} // end while-loop over fixed index
return static_cast<MeasureType>( -1.0 * MI );
} // end GetValue()
/**
* ******************** GetValueAndAnalyticDerivative *******************
* Get both the Value and the Derivative of the Measure.
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::GetValueAndAnalyticDerivative(
const ParametersType& parameters,
MeasureType& value,
DerivativeType& derivative ) const
{
/** Low memory variant. */
if ( !this->GetUseExplicitPDFDerivatives() )
{
this->GetValueAndAnalyticDerivativeLowMemory(
parameters, value, derivative );
return;
}
/** Initialize some variables. */
value = NumericTraits< MeasureType >::Zero;
derivative = DerivativeType( this->GetNumberOfParameters() );
derivative.Fill( NumericTraits<double>::Zero );
/** Construct the JointPDF, JointPDFDerivatives, Alpha and its derivatives. */
this->ComputePDFsAndPDFDerivatives( parameters );
/** Normalize the pdfs: p = alpha h. */
this->NormalizeJointPDF( this->m_JointPDF, this->m_Alpha );
/** Compute the fixed and moving marginal pdf by summing over the histogram. */
this->ComputeMarginalPDF( this->m_JointPDF, this->m_FixedImageMarginalPDF, 0 );
this->ComputeMarginalPDF( this->m_JointPDF, this->m_MovingImageMarginalPDF, 1 );
/** Compute the metric and derivatives by double summation over histogram. */
/** Setup iterators .*/
typedef ImageLinearConstIteratorWithIndex<
JointPDFType > JointPDFIteratorType;
typedef ImageLinearConstIteratorWithIndex<
JointPDFDerivativesType> JointPDFDerivativesIteratorType;
typedef typename MarginalPDFType::const_iterator MarginalPDFIteratorType;
typedef typename DerivativeType::iterator DerivativeIteratorType;
typedef typename DerivativeType::const_iterator DerivativeConstIteratorType;
JointPDFIteratorType jointPDFit(
this->m_JointPDF, this->m_JointPDF->GetLargestPossibleRegion() );
jointPDFit.SetDirection(0);
jointPDFit.GoToBegin();
JointPDFDerivativesIteratorType jointPDFDerivativesit(
this->m_JointPDFDerivatives, this->m_JointPDFDerivatives->GetLargestPossibleRegion() );
jointPDFDerivativesit.SetDirection(0);
jointPDFDerivativesit.GoToBegin();
MarginalPDFIteratorType fixedPDFit = this->m_FixedImageMarginalPDF.begin();
const MarginalPDFIteratorType fixedPDFend = this->m_FixedImageMarginalPDF.end();
MarginalPDFIteratorType movingPDFit = this->m_MovingImageMarginalPDF.begin();
const MarginalPDFIteratorType movingPDFend = this->m_MovingImageMarginalPDF.end();
DerivativeIteratorType derivit = derivative.begin();
const DerivativeIteratorType derivbegin = derivative.begin();
const DerivativeIteratorType derivend = derivative.end();
/** Loop over the joint histogram. */
double MI = 0.0;
while ( fixedPDFit != fixedPDFend )
{
const double fixedImagePDFValue = *fixedPDFit;
movingPDFit = this->m_MovingImageMarginalPDF.begin();
while ( movingPDFit != movingPDFend )
{
const double movingImagePDFValue = *movingPDFit;
const double fixPDFmovPDF = fixedImagePDFValue * movingImagePDFValue;
const double jointPDFValue = jointPDFit.Get();
/** Check for non-zero bin contribution. */
if( jointPDFValue > 1e-16 && fixPDFmovPDF > 1e-16 )
{
derivit = derivbegin;
const double pRatio = vcl_log( jointPDFValue / fixPDFmovPDF );
const double pRatioAlpha = this->m_Alpha * pRatio;
MI += jointPDFValue * pRatio;
while ( derivit != derivend )
{
/** Ref: eq 23 of Thevenaz & Unser paper [3]. */
(*derivit) -= jointPDFDerivativesit.Get() * pRatioAlpha;
++derivit;
++jointPDFDerivativesit;
} // end while-loop over parameters
} // end if-block to check non-zero bin contribution
++movingPDFit;
++jointPDFit;
jointPDFDerivativesit.NextLine();
} // end while-loop over moving index
++fixedPDFit;
jointPDFit.NextLine();
} // end while-loop over fixed index
value = static_cast<MeasureType>( -1.0 * MI );
} // end GetValueAndAnalyticDerivative()
/**
* ******************** GetValueAndAnalyticDerivativeLowMemory *******************
* Get both the Value and the Derivative of the Measure.
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::GetValueAndAnalyticDerivativeLowMemory(
const ParametersType& parameters,
MeasureType& value,
DerivativeType& derivative ) const
{
/** Initialize some variables. */
value = NumericTraits< MeasureType >::Zero;
derivative = DerivativeType( this->GetNumberOfParameters() );
derivative.Fill( NumericTraits<double>::Zero );
/** Construct the JointPDF and Alpha.
* This function contains a loop over the samples.
*/
this->ComputePDFs( parameters );
/** Normalize the joint histogram by alpha. */
this->NormalizeJointPDF( this->m_JointPDF, this->m_Alpha );
/** Compute the fixed and moving marginal pdf by summing over the histogram. */
this->ComputeMarginalPDF( this->m_JointPDF, this->m_FixedImageMarginalPDF, 0 );
this->ComputeMarginalPDF( this->m_JointPDF, this->m_MovingImageMarginalPDF, 1 );
// \todo: the last three loops over the joint histogram can be done in
// one loop, maybe also include the next loop to generate m_PRatioArray.
// The effort is probably not worth the gain in performance.
/** Compute the metric and the intermediate m_PRatioArray
* by summation over the joint histogram.
*/
/** Another loop over the joint histogram to compute the intermediate
* m_PRatioArray. Also the MI is computed.
*/
double MI = 0.0;
this->ComputeValueAndPRatioArray( MI );
/** We can compute the mutual information measure now. */
value = static_cast<MeasureType>( -1.0 * MI );
// NOW A SECOND PASS OVER THE SAMPLES to compute the derivative
/** Array that stores dM(x)/dmu, and the sparse jacobian+indices. */
NonZeroJacobianIndicesType nzji( this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices() );
DerivativeType imageJacobian( nzji.size() );
TransformJacobianType jacobian;
/** Arrays for Jacobian preconditioning */
DerivativeType jacobianPreconditioner( nzji.size() );
DerivativeType preconditioningDivisor( this->GetNumberOfParameters() );
preconditioningDivisor.Fill( 0.0 );
/** Get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator fiter;
typename ImageSampleContainerType::ConstIterator fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator fend = sampleContainer->End();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for ( fiter = fbegin; fiter != fend; ++fiter )
{
/** Read fixed coordinates and create some variables. */
const FixedImagePointType & fixedPoint = (*fiter).Value().m_ImageCoordinates;
RealType movingImageValue;
MovingImageDerivativeType movingImageDerivative;
MovingImagePointType mappedPoint;
/** Transform point and check if it is inside the B-spline support region. */
bool sampleOk = this->TransformPoint( fixedPoint, mappedPoint );
/** Check if the point is inside the moving mask. */
if ( sampleOk )
{
sampleOk = this->IsInsideMovingMask( mappedPoint );
}
/** Compute the moving image value, its derivative, and check
* if the point is inside the moving image buffer.
*/
if ( sampleOk )
{
sampleOk = this->EvaluateMovingImageValueAndDerivative(
mappedPoint, movingImageValue, &movingImageDerivative );
}
if ( sampleOk )
{
/** Get the fixed image value. */
RealType fixedImageValue = static_cast<RealType>( (*fiter).Value().m_ImageValue );
/** Make sure the values fall within the histogram range. */
fixedImageValue = this->GetFixedImageLimiter()
->Evaluate( fixedImageValue );
movingImageValue = this->GetMovingImageLimiter()
->Evaluate( movingImageValue, movingImageDerivative );
/** Get the transform Jacobian dT/dmu. */
this->EvaluateTransformJacobian( fixedPoint, jacobian, nzji );
/** Compute the inner product (dM/dx)^T (dT/dmu). */
this->EvaluateTransformJacobianInnerProduct(
jacobian, movingImageDerivative, imageJacobian );
/** If desired, apply the technique introduced by Tustison */
if ( this->GetUseJacobianPreconditioning() )
{
this->ComputeJacobianPreconditioner( jacobian, nzji,
jacobianPreconditioner, preconditioningDivisor );
DerivativeValueType * imjacit = imageJacobian.begin();
DerivativeValueType * jacprecit = jacobianPreconditioner.begin();
for ( unsigned int i = 0; i < nzji.size(); ++i )
while ( imjacit != imageJacobian.end() )
{
(*imjacit) *= (*jacprecit);
++imjacit;
++jacprecit;
}
}
/** Compute this sample's contribution to the joint distributions. */
this->UpdateDerivativeLowMemory(
fixedImageValue, movingImageValue, imageJacobian, nzji, derivative );
} // end sampleOk
} // end loop over sample container
/** If desired, apply the technique introduced by Tustison */
if ( this->GetUseJacobianPreconditioning() )
{
DerivativeValueType * derivit = derivative.begin();
DerivativeValueType * divisit = preconditioningDivisor.begin();
/** This normalization was not in the Tustison paper, but it helps,
* especially for localized mutual information */
const double normalizationFactor = preconditioningDivisor.mean();
while( derivit != derivative.end() )
{
(*derivit) *= normalizationFactor / ( (*divisit) + 1e-14 );
++derivit;
++divisit;
}
}
} // end GetValueAndAnalyticDerivativeLowMemory()
/**
* ******************* ComputePRatioArray *******************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::ComputeValueAndPRatioArray( double & MI ) const
{
/** Setup iterators. */
typedef ImageLinearConstIteratorWithIndex<
JointPDFType > JointPDFIteratorType;
typedef typename MarginalPDFType::const_iterator MarginalPDFIteratorType;
JointPDFIteratorType jointPDFit(
this->m_JointPDF, this->m_JointPDF->GetLargestPossibleRegion() );
jointPDFit.SetDirection( 0 );
jointPDFit.GoToBegin();
MarginalPDFIteratorType fixedPDFit = this->m_FixedImageMarginalPDF.begin();
const MarginalPDFIteratorType fixedPDFend = this->m_FixedImageMarginalPDF.end();
MarginalPDFIteratorType movingPDFit;
const MarginalPDFIteratorType movingPDFbegin = this->m_MovingImageMarginalPDF.begin();
const MarginalPDFIteratorType movingPDFend = this->m_MovingImageMarginalPDF.end();
/** Initialize */
this->m_PRatioArray.Fill( itk::NumericTraits<PRatioType>::Zero );
/** Loop over the joint histogram. */
MI = 0.0;
unsigned int fixedIndex = 0;
unsigned int movingIndex = 0;
while ( fixedPDFit != fixedPDFend )
{
const double fixedPDFValue = *fixedPDFit;
double logFixedPDFValue = 0.0;
if ( fixedPDFValue > 1e-16 )
{
logFixedPDFValue = vcl_log( fixedPDFValue );
}
movingPDFit = movingPDFbegin;
movingIndex = 0;
while ( movingPDFit != movingPDFend )
{
const double movingPDFValue = *movingPDFit; //returns float actually
const double jointPDFValue = jointPDFit.Get();
/** Check for non-zero bin contribution. */
if ( jointPDFValue > 1e-16 && movingPDFValue > 1e-16 )
{
const double pRatio = vcl_log( jointPDFValue / movingPDFValue );
// bETTER with ITERATORS TOO
this->m_PRatioArray[ fixedIndex ][ movingIndex ] = static_cast<PRatioType>(
this->m_Alpha * pRatio );
if ( fixedPDFValue > 1e-16 )
{
MI += jointPDFValue * ( pRatio - logFixedPDFValue );
}
} // end if-block to check non-zero bin contribution
/** Update iterators. */
++movingPDFit;
++jointPDFit;
++movingIndex;
} // end while-loop over moving index
/** Update iterators. */
++fixedPDFit;
jointPDFit.NextLine();
++fixedIndex;
} // end while-loop over fixed index
} // end ComputePRatioArray()
/**
* ******************* UpdateDerivativeLowMemory *******************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::UpdateDerivativeLowMemory(
const RealType & fixedImageValue,
const RealType & movingImageValue,
const DerivativeType & imageJacobian,
const NonZeroJacobianIndicesType & nzji,
DerivativeType & derivative ) const
{
/** In this function we need to do (see eq. 24 of Thevenaz [3]):
* derivative -= constant * imageJacobian *
* \sum_i \sum_k PRatio(i,k) * dB/dxi(xi,i,k),
* with i, k, the fixed and moving histogram bins,
* PRatio the precomputed log(p(i,k)/p(i),
* dB/dxi the B-spline derivative.
*
* Note (1) that we only have to loop over i,k within the support
* of the B-spline Parzen-window.
* Note (2) that imageJacobian may be sparse.
*/
/** Determine the affected region. */
/** Determine Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double fixedImageParzenWindowTerm =
fixedImageValue / this->m_FixedImageBinSize - this->m_FixedImageNormalizedMin;
const double movingImageParzenWindowTerm =
movingImageValue / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
/** The lowest bin numbers affected by this pixel: */
const int fixedParzenWindowIndex =
static_cast<int>( vcl_floor(
fixedImageParzenWindowTerm + this->m_FixedParzenTermToIndexOffset ) );
const int movingParzenWindowIndex =
static_cast<int>( vcl_floor(
movingImageParzenWindowTerm + this->m_MovingParzenTermToIndexOffset ) );
/** The Parzen values. */
ParzenValueContainerType fixedParzenValues( this->m_JointPDFWindow.GetSize()[ 1 ] );
ParzenValueContainerType movingParzenValues( this->m_JointPDFWindow.GetSize()[ 0 ] );
this->EvaluateParzenValues(
fixedImageParzenWindowTerm, fixedParzenWindowIndex,
this->m_FixedKernel, fixedParzenValues );
/** Compute the derivatives of the moving Parzen window. */
ParzenValueContainerType derivativeMovingParzenValues(
this->m_JointPDFWindow.GetSize()[ 0 ] );
this->EvaluateParzenValues(
movingImageParzenWindowTerm, movingParzenWindowIndex,
this->m_DerivativeMovingKernel, derivativeMovingParzenValues );
/** Get the moving image bin size. */
const double et = static_cast<double>( this->m_MovingImageBinSize );
/** Loop over the Parzen window region and increment sum. */
double sum = 0.0;
for ( unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f )
{
const double fv_et = fixedParzenValues[ f ] / et;
for ( unsigned int m = 0; m < movingParzenValues.GetSize(); ++m )
{
sum += this->m_PRatioArray[ f + fixedParzenWindowIndex ][ m + movingParzenWindowIndex ]
* fv_et * derivativeMovingParzenValues[ m ];
}
}
/** Now compute derivative -= sum * imageJacobian. */
//typedef typename DerivativeType::iterator DerivativeIteratorType;
//DerivativeIteratorType itDerivative( derivative );
if ( nzji.size() == this->GetNumberOfParameters() )
{
/** Loop over all Jacobians. */
//typename DerivativeType::const_iterator imjac = imageJacobian.begin();
for ( unsigned int mu = 0; mu < this->GetNumberOfParameters(); ++mu )
{
derivative[ mu ] += static_cast<DerivativeValueType>(
imageJacobian[ mu ] * sum ); // \todo: iterators?
}
}
else
{
/** Loop only over the non-zero Jacobians. */
for ( unsigned int i = 0; i < imageJacobian.GetSize(); ++i )
{
const unsigned int mu = nzji[ i ];
derivative[ mu ] += static_cast<DerivativeValueType>(
imageJacobian[ i ] * sum ); // \todo: iterators?
}
}
} // end UpdateDerivativeLowMemory()
/**
* ******************** GetValueAndFiniteDifferenceDerivative *******************
* Get both the Value and the Derivative of the Measure.
* Compute the derivative using a finite difference approximation
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::GetValueAndFiniteDifferenceDerivative(
const ParametersType& parameters,
MeasureType& value,
DerivativeType& derivative ) const
{
/** Initialize some variables. */
value = NumericTraits< MeasureType >::Zero;
derivative = DerivativeType( this->GetNumberOfParameters() );
derivative.Fill( NumericTraits<double>::Zero );
/** Construct the JointPDF, JointPDFDerivatives, Alpha and its derivatives. */
this->ComputePDFsAndIncrementalPDFs( parameters );
/** Compute the fixed and moving marginal pdf by summing over the histogram. */
this->ComputeMarginalPDF( this->m_JointPDF, this->m_FixedImageMarginalPDF, 0 );
this->ComputeMarginalPDF( this->m_JointPDF, this->m_MovingImageMarginalPDF, 1 );
/** Compute the fixed and moving incremental marginal pdfs by summing over the
* incremental histogram. Do it for Right and Left.
*/
this->ComputeIncrementalMarginalPDFs( this->m_IncrementalJointPDFRight,
this->m_FixedIncrementalMarginalPDFRight, this->m_MovingIncrementalMarginalPDFRight );
this->ComputeIncrementalMarginalPDFs( this->m_IncrementalJointPDFLeft,
this->m_FixedIncrementalMarginalPDFLeft, this->m_MovingIncrementalMarginalPDFLeft );
/** Compute the metric and derivatives by double summation over histogram. */
/** Setup iterators */
typedef ImageLinearConstIteratorWithIndex<
JointPDFType > JointPDFIteratorType;
typedef ImageLinearConstIteratorWithIndex<
JointPDFDerivativesType> IncrementalJointPDFIteratorType;
typedef typename MarginalPDFType::const_iterator MarginalPDFIteratorType;
typedef ImageLinearConstIteratorWithIndex<
IncrementalMarginalPDFType > IncrementalMarginalPDFIteratorType;
typedef typename DerivativeType::iterator DerivativeIteratorType;
typedef typename DerivativeType::const_iterator DerivativeConstIteratorType;
JointPDFIteratorType jointPDFit(
this->m_JointPDF, this->m_JointPDF->GetLargestPossibleRegion() );
jointPDFit.GoToBegin();
IncrementalJointPDFIteratorType jointIncPDFRightit( this->m_IncrementalJointPDFRight,
this->m_IncrementalJointPDFRight->GetLargestPossibleRegion() );
IncrementalJointPDFIteratorType jointIncPDFLeftit( this->m_IncrementalJointPDFLeft,
this->m_IncrementalJointPDFLeft->GetLargestPossibleRegion() );
jointIncPDFRightit.GoToBegin();
jointIncPDFLeftit.GoToBegin();
MarginalPDFIteratorType fixedPDFit = this->m_FixedImageMarginalPDF.begin();
const MarginalPDFIteratorType fixedPDFend = this->m_FixedImageMarginalPDF.end();
MarginalPDFIteratorType movingPDFit = this->m_MovingImageMarginalPDF.begin();
const MarginalPDFIteratorType movingPDFend = this->m_MovingImageMarginalPDF.end();
IncrementalMarginalPDFIteratorType fixedIncPDFRightit(
this->m_FixedIncrementalMarginalPDFRight,
this->m_FixedIncrementalMarginalPDFRight->GetLargestPossibleRegion() );
IncrementalMarginalPDFIteratorType movingIncPDFRightit(
this->m_MovingIncrementalMarginalPDFRight,
this->m_MovingIncrementalMarginalPDFRight->GetLargestPossibleRegion() );
IncrementalMarginalPDFIteratorType fixedIncPDFLeftit(
this->m_FixedIncrementalMarginalPDFLeft,
this->m_FixedIncrementalMarginalPDFLeft->GetLargestPossibleRegion() );
IncrementalMarginalPDFIteratorType movingIncPDFLeftit(
this->m_MovingIncrementalMarginalPDFLeft,
this->m_MovingIncrementalMarginalPDFLeft->GetLargestPossibleRegion() );
fixedIncPDFRightit.GoToBegin();
movingIncPDFRightit.GoToBegin();
fixedIncPDFLeftit.GoToBegin();
movingIncPDFLeftit.GoToBegin();
DerivativeIteratorType derivit = derivative.begin();
const DerivativeIteratorType derivbegin = derivative.begin();
const DerivativeIteratorType derivend = derivative.end();
DerivativeConstIteratorType perturbedAlphaRightit = this->m_PerturbedAlphaRight.begin();
const DerivativeConstIteratorType perturbedAlphaRightbegin = this->m_PerturbedAlphaRight.begin();
DerivativeConstIteratorType perturbedAlphaLeftit = this->m_PerturbedAlphaLeft.begin();
const DerivativeConstIteratorType perturbedAlphaLeftbegin = this->m_PerturbedAlphaLeft.begin();
double MI = 0.0;
while ( fixedPDFit != fixedPDFend )
{
const double fixedPDFValue = *fixedPDFit;
while ( movingPDFit != movingPDFend )
{
const double movingPDFValue = *movingPDFit;
const double jointPDFValue = jointPDFit.Get();
const double fixPDFmovPDFAlpha =
fixedPDFValue * movingPDFValue * this->m_Alpha;
/** Check for non-zero bin contribution and update the mutual information value. */
if( jointPDFValue > 1e-16 && fixPDFmovPDFAlpha > 1e-16 )
{
MI += this->m_Alpha * jointPDFValue * vcl_log( jointPDFValue / fixPDFmovPDFAlpha );
}
/** Update the derivative. */
derivit = derivbegin;
perturbedAlphaRightit = perturbedAlphaRightbegin;
perturbedAlphaLeftit = perturbedAlphaLeftbegin;
while ( derivit != derivend )
{
/** Initialize. */
double contrib = 0.0;
/** For clarity, get some values and give them a name.
* \todo Does this cost a lot of computation time?
*/
const double jointIncPDFRightValue = jointIncPDFRightit.Get();
const double fixedIncPDFRightValue = fixedIncPDFRightit.Get();
const double movingIncPDFRightValue = movingIncPDFRightit.Get();
const double perturbedAlphaRightValue = *perturbedAlphaRightit;
/** Compute the contribution of the Right-perturbation to the derivative. */
const double perturbedJointPDFRightValue = jointIncPDFRightValue + jointPDFValue;
const double perturbedFixedPDFRightValue = fixedPDFValue + fixedIncPDFRightValue;
const double perturbedMovingPDFRightValue = movingPDFValue + movingIncPDFRightValue;
const double perturbedfixPDFmovPDFAlphaRight =
perturbedFixedPDFRightValue * perturbedMovingPDFRightValue * perturbedAlphaRightValue;
if ( perturbedJointPDFRightValue > 1e-16 && perturbedfixPDFmovPDFAlphaRight > 1e-16 )
{
contrib += perturbedAlphaRightValue * perturbedJointPDFRightValue *
vcl_log( perturbedJointPDFRightValue / perturbedfixPDFmovPDFAlphaRight );
}
/** For clarity, get some values and give them a name. */
const double jointIncPDFLeftValue = jointIncPDFLeftit.Get();
const double fixedIncPDFLeftValue = fixedIncPDFLeftit.Get();
const double movingIncPDFLeftValue = movingIncPDFLeftit.Get();
const double perturbedAlphaLeftValue = *perturbedAlphaLeftit;
/** Compute the contribution of the Left-perturbation to the derivative. */
const double perturbedJointPDFLeftValue = jointIncPDFLeftValue + jointPDFValue;
const double perturbedFixedPDFLeftValue = fixedPDFValue + fixedIncPDFLeftValue;
const double perturbedMovingPDFLeftValue = movingPDFValue + movingIncPDFLeftValue;
const double perturbedfixPDFmovPDFAlphaLeft =
perturbedFixedPDFLeftValue * perturbedMovingPDFLeftValue * perturbedAlphaLeftValue;
if ( perturbedJointPDFLeftValue > 1e-16 && perturbedfixPDFmovPDFAlphaLeft > 1e-16 )
{
contrib -= perturbedAlphaLeftValue * perturbedJointPDFLeftValue *
vcl_log( perturbedJointPDFLeftValue / perturbedfixPDFmovPDFAlphaLeft );
}
/** Update the derivative component. */
(*derivit) += contrib;
/** Move the iterators to the next parameter. */
++derivit;
++perturbedAlphaRightit;
++perturbedAlphaLeftit;
++jointIncPDFRightit;
++jointIncPDFLeftit;
++fixedIncPDFRightit;
++movingIncPDFRightit;
++fixedIncPDFLeftit;
++movingIncPDFLeftit;
} // end while-loop over parameters
++jointPDFit; // next moving bin
++movingPDFit; // next moving bin
jointIncPDFRightit.NextLine(); // next moving bin
jointIncPDFLeftit.NextLine(); // next moving bin
fixedIncPDFRightit.GoToBeginOfLine(); // same fixed bin
fixedIncPDFLeftit.GoToBeginOfLine(); // same fixed bin
movingIncPDFRightit.NextLine(); // next moving bin
movingIncPDFLeftit.NextLine(); // next moving bin
} // end while-loop over moving index
jointPDFit.NextLine(); // next fixed bin
++fixedPDFit; // next fixed bin
movingPDFit = this->m_MovingImageMarginalPDF.begin(); // first moving bin
fixedIncPDFRightit.NextLine(); // next fixed bin
fixedIncPDFLeftit.NextLine(); // next fixed bin
movingIncPDFRightit.GoToBegin(); // first moving bin
movingIncPDFLeftit.GoToBegin(); // first moving bin
} // end while-loop over fixed index
value = static_cast<MeasureType>( -1.0 * MI );
/** Divide the derivative by -delta*2. */
const double delta2 = - 1.0 / ( this->GetFiniteDifferencePerturbation() * 2.0 );
derivit = derivative.begin();
while ( derivit != derivend )
{
(*derivit) *= delta2;
++derivit;
}
} // end GetValueAndFiniteDifferenceDerivative
/**
* ******************** ComputeJacobianPreconditioner *******************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowMutualInformationImageToImageMetric<TFixedImage,TMovingImage>
::ComputeJacobianPreconditioner(
const TransformJacobianType & jac,
const NonZeroJacobianIndicesType & nzji,
DerivativeType & preconditioner,
DerivativeType & divisor ) const
{
typedef typename TransformJacobianType::ValueType TransformJacobianValueType;
const unsigned int M = nzji.size();
typedef Matrix<double, MovingImageDimension, MovingImageDimension> MatrixType;
MatrixType jacjact;
/** Compute jac * jac' */
for (unsigned int drow = 0; drow < MovingImageDimension; ++drow)
{
for (unsigned int dcol = drow; dcol < MovingImageDimension; ++dcol)
{
const TransformJacobianValueType * jacit1 = jac[drow];
const TransformJacobianValueType * jacit2 = jac[dcol];
double sum = 0.0;
for (unsigned int mu = 0; mu < M; ++mu )
{
sum += (*jacit1) * (*jacit2);
++jacit1;
++jacit2;
}
jacjact( drow, dcol ) = sum;
jacjact( dcol, drow ) = sum;
}
}
/** Invert */
const double addtodiag = 1e-10;
for (unsigned int drow = 0; drow < MovingImageDimension; ++drow)
{
jacjact(drow,drow) += addtodiag;
}
jacjact = vnl_inverse( jacjact.GetVnlMatrix() );
/** Compute preconditioner = diag( jac' * m * jac ),
* with m = inv(jacjact)
* implementation:
* preconditioner = sum_dr sum_dc m(dr,dc) jac(dr,:) * jac(dc,:) */
preconditioner.Fill(0.0);
for (unsigned int drow = 0; drow < MovingImageDimension; ++drow)
{
for (unsigned int dcol = drow; dcol < MovingImageDimension; ++dcol)
{
DerivativeValueType * precondit = preconditioner.begin();
const TransformJacobianValueType * jacit1 = jac[drow];
const TransformJacobianValueType * jacit2 = jac[dcol];
/** count twice if off-diagonal */
const double fac = drow == dcol ? 1.0 : 2.0;
const double m = fac * jacjact(drow, dcol);
for (unsigned int mu = 0; mu < M; ++mu )
{
*precondit += m* (*jacit1) * (*jacit2);
++precondit;
++jacit1;
++jacit2;
}
}
}
/** Update divisor = sum_samples diag(jac'*jac) */
DerivativeType temp(M);
temp.Fill(0.0);
/** Compute this sample's contribution */
for (unsigned int drow = 0; drow < MovingImageDimension; ++drow)
{
DerivativeValueType * tempit = temp.begin();
const TransformJacobianValueType * jacit1 = jac[drow];
for (unsigned int mu = 0; mu < M; ++mu )
{
*tempit += vnl_math_sqr( *jacit1 );
++tempit;
++jacit1;
}
}
/** Update divisor */
for (unsigned int mu = 0; mu < M; ++mu )
{
divisor[ nzji[mu] ] += temp[mu];
}
} // end ComputeJacobianPreconditioner
} // end namespace itk
#endif // end #ifndef _itkParzenWindowMutualInformationImageToImageMetric_HXX__
|
[
"[email protected]"
] |
[
[
[
1,
871
]
]
] |
5e9b1ef562c780911775bead9b43cdbbed6998b9
|
27d5670a7739a866c3ad97a71c0fc9334f6875f2
|
/CPP/Modules/include/UiCtrl.h
|
067972e60b6c2d728389dd0109f8f3980e898c2e
|
[
"BSD-3-Clause"
] |
permissive
|
ravustaja/Wayfinder-S60-Navigator
|
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
|
14d1b729b2cea52f726874687e78f17492949585
|
refs/heads/master
| 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 30,896 |
h
|
/*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef UI_CONTROL_H
#define UI_CONTROL_H
#include <deque>
#include <utility>
#include "NavRequestType.h"
class NavCtrlMMIMessage; // forward declaration.
//MN: Do we really need these ones?
/** Timeout for sending data messages. in milliseconds.*/
#define DS_BUSY_TIMEOUT 1000
#define DS_IDLE_TIMEOUT 1000
/** The value of this timeout influences both
* how often positions are sent to the GUI
* and for how long the GUI requests not taken
* care of directly are stored.
*/
#define DS_DEFAULT_TIMEOUT 1000
#define LOST_PDA_MAX_TIMEOUTS 5
/// Max size of m_pending
#define MAX_PENDING 10
namespace isab{
class GuiCtrl; // forward declaration.
class AudioCtrl; // forward declaration.
class AudioCtrlLanguage; // forward declaration.
namespace UiCtrlInternal {
struct GpsData;
struct UiCtrlParams;
}
/**
* Controls the user interface.
*
*/
class UiCtrl : public Module,
public SerialConsumerInterface,
public NavTaskConsumerInterface,
public CtrlHubAttachedInterface,
public NavServerComConsumerInterface,
public ParameterConsumerInterface,
public DestinationsConsumerInterface,
public ErrorProviderInterface
{
friend class GuiCtrl;
friend class AudioCtrl;
public:
/**
* Constructor that takes an SerialProviderPublic.
*
* @param spp The SerialProviderPublic.
* @param httpProto If talking HTTP to server.
* @param useIAPProxy If to use proxy setting of IAP.
* @param hardIapProxyHost The hardcoded IAP proxy host, used if
* useIAPProxy and not NULL.
* @param hardIapProxyPort The hardcoded IAP proxy port, see
* hardIapProxyHost.
* @param userClipString transform the web username by clipping
* the string from the beginning.
*/
UiCtrl(SerialProviderPublic* spp,
Nav2Error::Nav2ErrorTable * errorTable,
AudioCtrlLanguage * audioSyntax,
const char *serialNumber,
bool httpProto = false,
bool useIAPProxy = false,
const char* hardIapProxyHost = NULL,
uint16 hardIapProxyPort = 0,
const char* userClipString = NULL);
/**
* Destructor.
*/
virtual ~UiCtrl();
/**
* Tells whether the GUI has connected.
*/
bool connectedToGui();
/**
* Module functions
*/
//@{
/**
* Called when shutdown starts.
*/
virtual void decodedShutdownNow(int16 upperTimeout);
/**
* Called when shutdown is complete and no further calls will
* be made.
*/
virtual void treeIsShutdown();
/**
* Called when the status of the connection to the GUI
* is changed.
*/
virtual void decodedConnectionNotify(enum ConnectionNotify,
enum ConnectionNotifyReason,
uint32 src);
/**
* Called when timer has expired.
*
* @param timerid The id of the timer that has expired.
*/
virtual void decodedExpiredTimer( uint16 timerid );
/**
* Called when startup is done and module is ready.
*/
virtual void decodedStartupComplete();
/**
* All error messages that causes request to other modules in
* Nav2 to fail, ends up here.
*
* @param err The error causing the request to fail.
* @param src Address and message id from the module sending
* the error.
* @param dst Address and message id of the request that
* failed.
*/
virtual void decodedSolicitedError( const ErrorObj& err,
uint32 src, uint32 dst );
/**
* Creates a new CtrlHubAttachedPublic object used to connect
* this module to the CtrlHub.
*
* @return A new CtrlHubAttachedPublic object connected to the
* queue.
*/
inline CtrlHubAttachedPublic* newPublicCtrlHub();
//@}
/**
* Error provider functions.
*/
//@{
/**
* This method is called when one of the other modules
* sends an unsolicited error.
*
* @param err The error sent by the module.
* @param src The address of the sending module.
*/
virtual void decodedUnsolicitedError( const ErrorObj& err,
uint32 src );
//@}
/**
* NavServerCom functions
*/
//@{
/**
* Called when sync destination reply has been decoded.
* XXX: Implement.
*/
virtual void decodedSyncDestinationsReply(std::vector<Favorite*>& fvs,
std::vector<uint32>& rmd,
uint32 src, uint32 dst);
/**
* Called when binary upload has been received by ...
* XXX: Implement
*
* @param src The id of the module?
* @param dst The id of the request.
*/
virtual void decodedBinaryUploadReply( uint32 src, uint32 dst );
/**
* Called when binary download has been received by ...
* XXX: Implement
*
* @param data The data downloaded, is valid for this method.
* @param length The length of the data.
* @param src The id of the module?
* @param dst The id of the request.
*/
virtual void decodedBinaryDownload( const uint8* data,
size_t length,
uint32 src, uint32 dst );
/**
* Called when a where an I reply has been received.
* XXX: Implement
*
* @param country String with the name of the country where you
* are.
* @param municipal String with the name of the municipal where
* you are.
* @param city String with the name of the city where you are.
* @param district String with the name of the district in the
* city where you are.
* @param streetname String with the name of the street where you
* are.
* @param lat The latitude of your current position.
* @param lon The longitude of your current position.
* @param src The id of the module?
* @param dst The id of the request.
*/
virtual void decodedWhereAmIReply( const char* country,
const char* municipal,
const char* city,
const char* district,
const char* streetname,
int32 lat, int32 lon,
uint32 src, uint32 dst );
virtual void decodedSearchReply(unsigned nAreas,
const SearchArea* const* a,
unsigned nItems,
const FullSearchItem*const* fsi,
uint16 begindex, uint16 total,
uint32 src, uint32 dst);
virtual void decodedSearchInfoReply(uint16 num, const char* const* id,
const unsigned* index,
unsigned numInfo,
const AdditionalInfo*const* info,
uint32 src, uint32 dst);
virtual void decodedMessageReply(const uint8* data, unsigned length,
uint32 src, uint32 dst);
virtual void decodedLicenseReply(bool keyOk, bool phoneOk, bool regionOk,
bool nameOk, bool emailOk,
GuiProtEnums::WayfinderType type,
uint32 src, uint32 dst);
/**
* Called when a route reply is received.
*
* @param src The id of the module?
* @param dst The id of the request that this is a reply for?
* DEPRECATED!
*/
virtual void decodedRouteReply( uint32 src, uint32 dst );
virtual void decodedMapReply(const BoxBox& bb, uint32 realWorldWidth,
uint32 realWorldHeight, uint16 imageWidth,
uint16 imageHeight,
enum MapEnums::ImageFormat imageType,
uint32 imageBufferSize,
const uint8* imageBuffer, uint32 dst);
virtual void decodedVectorMapReply(const char* /*request*/, uint32 /*size*/,
const uint8* /*data*/, uint32 /*dst*/)
{
//This function temporarily left blank
}
virtual void decodedMulitVectorMapReply(uint32 size,
const uint8* data, uint32 dst);
virtual void decodedForceFeedMuliVectorMapReply(
uint32 size, const uint8* data, uint32 dst );
virtual void decodedCellConfirm(uint32 size, const uint8* data,
uint32 dst);
/**
* Called when a progres message is received.
*
* @param status The status of the communication.
* @param type The type of message that the progress is for.
* @param done The number of sent bytes?
* @param of The total amount of bytes?
* @param src The id of the module?
* @param dst The id of the request that this is progress message
* for
*/
virtual void decodedProgressMessage( NavServerComEnums::ComStatus status,
GuiProtEnums::ServerActionType type,
uint32 done, uint32 of,
uint32 src, uint32 dst );
virtual void decodedLatestNews(uint32 checksum, const uint8* data,
unsigned length, uint32 src,
uint32 dst);
virtual void decodedParamSyncReply(GuiProtEnums::WayfinderType wft,
uint32 src, uint32 dst);
virtual void decodedReply(
navRequestType::RequestType type, NParamBlock& params,
uint8 requestVer, uint8 statusCode, const char* statusMessage,
uint32 src, uint32 dst );
//@}
/**
* Serial Consumer functions.
*/
//@{
/**
* Called when data is received.
*
* @param length The length of data.
* @param data The data received.
* @param src The id of the module?
*/
virtual void decodedReceiveData( int length, const uint8 *data,
uint32 src );
//@}
/**
* NavTask functions.
*/
//@{
/**
* Called when a position state has been received.
*
* @param p The new PositionState.
* @param src The id of the module?
*/
virtual void decodedPositionState(
const struct PositionState& p, uint32 src );
/**
* Set the nearest route coord.
*
* @param lat The latitude of the route coordinate.
* @param lon The longitude of the route coordinate.
*/
virtual void setRouteCoordinate( int32 lat, int32 lon, int8 dir );
/**
* Called when satellite info is available.
*
*/
virtual void decodedGpsSatelliteInfo(class GpsSatInfoHolder *v,
uint32 src);
/**
* Called when NavTask wishes to send a File operation
* message to the GUI.
*/
virtual void decodedFileOperation(class GuiFileOperation *op,
uint32 src);
/**
* Called when route info is received from NavTask.
*
* @param r The RouteInfo with data.
* @param src The id of the module?
*/
virtual void decodedRouteInfo(
const RouteInfo& r,
uint32 src );
/**
* Called when a route list is received from NavTask.
*
* @param buf A buffer containing the route list. Can be expanded by
* creating a new RouteList(buf)
* @param src The id of the module?
*/
virtual void decodedRouteList(
Buffer *buf,
uint32 src, uint32 dst );
/**
* Called when a route reply is received. (From NavTask)
*
* @param src The id of the module?
* @param dst The id of the request that this is a reply for?
*/
virtual void decodedNTRouteReply(int64 routeid, uint32 src,
uint32 dst );
/**
* Called whenever a new route has been downloaded, and
* we're following that route instead.
*/
virtual void decodedInvalidateRoute(bool newRouteAvailable,
int64 routeid,
int32 tLat, int32 lLon,
int32 bLat, int32 rLon,
int32 oLat, int32 oLon,
int32 dLat, int32 dLon,
uint32 src);
//@}
/**
* ParameterConsumer functions.
*/
//@{
virtual void decodedParamNoValue(uint32 paramId,
uint32 src,
uint32 dst);
virtual void decodedParamValue(uint32 paramId,
const int32 * data,
int32 numEntries,
uint32 src,
uint32 dst);
virtual void decodedParamValue(uint32 paramId,
const float * data,
int32 numEntries,
uint32 src,
uint32 dst);
virtual void decodedParamValue(uint32 paramId,
const char * const * data,
int32 numEntries,
uint32 src,
uint32 dst);
virtual void decodedParamValue(uint32 paramId,
const uint8* data,
int size,
uint32 src,
uint32 dst);
//@}
/**
* Destinations modlule methods.
*/
//@{
virtual void decodedGetFavoritesReply( std::vector<GuiFavorite*>& guiFavorites,
uint32 src, uint32 dst );
virtual void decodedGetFavoritesAllDataReply( std::vector<Favorite*>& favorites,
uint32 src, uint32 dst );
virtual void decodedGetFavoriteInfoReply( Favorite* favorite,
uint32 src, uint32 dst );
virtual void decodedFavoritesChanged( uint32 src, uint32 dst );
virtual void decodedDestRequestOk( uint32 src, uint32 dst );
//@}
enum calledGPSConnectionMode_t {
ConnectToGPSCalled,
DisconnectToGPSCalled,
nothingCalled
};
calledGPSConnectionMode_t getcalledGPSConnectionMode() const {
return m_calledGPSConnectionMode;
}
void setcalledGPSConnectionMode( calledGPSConnectionMode_t m ) {
m_calledGPSConnectionMode = m;
}
protected:
/**
* Constants.
*/
//@{
/**
* This value multiplicated with m_guiPositionUpdateTimeOut
* is the time before non handled Gui messages are timed out
* in milliseconds.
*/
enum { GUI_MESS_TIMEOUT = 30 };
//@}
// XXX move these to parameter module.
const char* getVersionString();
uint32 getSerialNo();
const char* getSoftwareVersion();
/**
* Called by hub when message is sent to this module?
*
* @param buf The request Msg?
* @return MsgBuffer with the reply?
*/
virtual class MsgBuffer* dispatch(class MsgBuffer* buf );
/**
* Internal functions.
*/
//@{
/**
* Checks if all params have been received from the
* parameter module.
*
* If this method returns true for the first time,
* it calls handleWaitingMessages before returning.
*
* @param print If this parameter is set to true,
* an not all parameter have been received,
* the method prints an info message
* telling what parameter(s) that has not
* been received yet.
*/
bool allParamsReceived(bool print = false);
/**
* Call this method to indicate that a parameter has
* been received from parameter module. It will _NOT_ notify
* the GUI.
*/
void paramReceivedNotSimpleParam(enum ParameterEnums::ParamIds paramId);
/**
* Call this method to indicate that a parameter has
* been received from parameter module. It will notify
* the GUI.
*/
void paramReceived(enum ParameterEnums::ParamIds paramId,
const class GuiProtEnums::ParameterTypeHolder& guiParamId);
/**
* Goes through the waiting messages queue and sends them
* one at a time ot m_guiCtrl->messageReceived.
*/
void handleWaitingMessages();
/**
* Initializes the IAP parameter to IMEI:-1
*/
void SendDefaultIAP();
/**
* Throws away to old Gui messages and responds to the
* Gui with a request failed message.
*/
void checkWaitingMessagesTimeOut();
/**
* Sends an ExtendedError message to the NavClient.
*
* @param errorCode A value from the NavErrorType enum.
* @param errorID The ID of the request that caused an error.
* @param errorString an error message.
*/
void sendExtendedError( uint16 errorCode, uint16 errorID,
const char* errorMessage = NULL );
//@}
private:
// communicate with the serial provider.
SerialProviderPublic* m_provider;
// communicate with navtask
NavTaskProviderPublic * m_navTaskProvider;
// communicate with the parameter module.
ParameterProviderPublic * m_paramProvider;
/// The interface to nav server com
NavServerComProviderPublic* m_serverProvider;
/// Interface to the destinations module.
DestinationsProviderPublic* m_destProvider;
// decoders.
SerialConsumerDecoder m_serialDecoder; // XXX: not set!
NavTaskConsumerDecoder m_navTaskDecoder; // XXX: not set
NavServerComConsumerDecoder m_nscDecoder; // XXX: not set!
CtrlHubAttachedDecoder m_hubDecoder; // XXX: not set!
ParameterConsumerDecoder m_paramDecoder; // XXX: not set!
DestinationsConsumerDecoder m_destDecoder;
ErrorProviderDecoder m_errorDecoder;
/**
* This helper object is used for handling messages sent to and
* from the GUI. It also cashes data used by the GUI.
*
* It has the roll NavCtrl had in the PDA.
*/
GuiCtrl* m_guiCtrl;
/**
* This helper object is used for handling the audio
* messages and streaming them correctly.
*/
AudioCtrl* m_audioCtrl;
/// Sequence id to send next to display.
uint16 m_navSeqID;
/// Expected id from display next.
uint16 m_pdaSeqID;
/**
* The current timeout time for the timer.
*
* The value of this timer also influences
* for how long the GUI requests not taken
* care of directly are stored.
*/
uint16 m_guiPositionUpdateTimeOut;
/// The id of the timer
uint16 m_guiPositionUpdateTimerId;
//MN: Remove these when communication goes directly to GUI.
//@{
/// If contact with display
bool m_gotPda;
/// If display is subscribing, to route info.
bool m_subscribing;
/// Counter for waiting for reply from display.
uint16 m_noPda;
//@}
/// Parameters cached here:
//@{
char* m_dataPhoneNo;
char* m_voicePhoneNo;
char* m_userID;
char* m_passwd;
char* m_serverHostname;
//@}
/**
* Is set to true when all parameters hav been received
* from the parameter module.
*/
bool m_allParamsReceived;
/**
* Stores messages until they can be dealt with.
*
* The uint32 member of the pair is counted down
* until it reaches 0. Then it times out. Initially,
* this member is set to GUI_MESS_TIMEOUT.
*/
//@{
std::deque<std::pair<GuiProtMess*, uint32>* >* m_waitingMessages;
#ifdef USE_THINCLIENT
// Remove this one when we have stopped using
// the ThinClient GUI prot.
std::deque<std::pair<NavCtrlMMIMessage*, uint32>* >* m_waitingNavCtrlMessages;
#endif
//@}
/** Buffer to store unparsed data in. */
Buffer* m_parseBuffer;
/**
* Allocates src if needed and copies name to it.
*
* @param src The string to copy to.
* @param name The string to copy.
*/
void setCharValue(char*& src, const char* name);
/// If module is shuting down.
bool m_shutdown;
bool m_connectedToGui;
/**
* Oustanding requests to Nav2.
*
* Table describes the use of request list in UiCtrl.
*
* Request | ThinClient GUI | Nav2 GUI
* Memeber | Protocol | Protocol
* --------------------------------------------
* request | ThinClientGuiPr\ | GuiProtEnums::
* | otEnums:: | MessageType
* | PacketNumber_t |
* | |
* reqID | ???????????????? | GUI sequence id.
* | |
* src | Nav2 message id | Nav2 message id.
* | |
* status | 1 if NavTask |
* | invalidate route |
* | or NavServerCom |
* | route downloaded |
* | has been |
* | received. |
* | Otherwise 0. |
*
* RequestList::dequeue(uint16 requestID) returns
* the item with the right reqID member.
*
* RequestList::dequeue(uint32 requestID) returns
* the item with the right src member.
*/
class RequestList *m_pending;
//MN: Is this one needed? Constructor?
/// GPS position data.
struct UiCtrlInternal::GpsData *m_lastGpsData;
/** Temporary hack - FIXME
* This is used to cached the last route list so that
* playSoundForCrossing() has access to the information.
*/
class RouteList *m_lastRouteList;
/**
* List with the parameters ids UiCtrl should
* ask from the paramter module.
*
* UiCtrlParams also has a member telling if
* a parameter has been received.
*/
struct UiCtrlInternal::UiCtrlParams* m_uiCtrlParams;
/**
* Size of m_uiCtrlParams.
*/
uint32 m_uiCtrlParamsSize;
/**
* Handle requests from other part of UiCtrl for
* the sound for a specific crossing.
* See AudioCtrl.
*/
void playSoundForCrossing(uint16 crossingNo);
/**
* Methods used for keeping track of requests to Nav2
*/
//@{
/**
* NB! See commment on m_pending for how the request list is used.
*
* Checks if a request already with the same GUI sequence id is
* pending then silently discards it.
*
* If not pending then try to allocate a new RequestListItem. If
* that fails send error reply.
*
* @param guiSequenceID The id set in the request by the GUI.
*
* @return An allocated request, or NULL if a request with the
* guiSequenceID already exists or allocation failed for
* any reason.
*/
class RequestListItem* checkForRequestAndCreate( uint32 guiMessageType, uint16 guiMessageId );
/**
* NB! See commment on m_pending for how the request list is used.
*
* Method used by ThinClient GUI protocol.
* XXX Remove it when the ThinClient protocol is no longer used!
*
* @return An allocated request or NULL if allocation
* did not succeed.
*/
class RequestListItem* checkForRequestAndCreate();
/**
* NB! See commment on m_pending for how the request list is used.
*
* Adds an request. If ID is MAX_UINT16 then an error is sent.
* Used by messageReceived.
*
* @param nav2messageId The value returned by ModulePublic methods.
* Also called src sometimes.
*
* @param req The request to add. The src member of the
* request is set by this method.
*/
void addRequest( uint32 nav2messageId, class RequestListItem* req );
//@}
/**
* Debug methods and variables.
*/
//@{
/**
* Keeps track of if a position has been printed.
*/
bool m_printedPos;
/**
* Prints the data of a favorite.
*/
void dumpFavorite(GuiFavorite* guiFav);
void dumpFavorite(Favorite* fav);
//@}
/**
* Variables used for status messages to the GUI.
*/
//@{
NavServerComEnums::ComStatus m_previousStatus;
NavServerComEnums::MessageType m_previousMessage;
//@}
/// The type of Serverlist used. Nav or Http.
enum ParameterEnums::ParamIds m_serverListParam;
enum calledGPSConnectionMode_t m_calledGPSConnectionMode;
public:
Nav2Error::Nav2ErrorTable * m_errorTable;
char *m_serialNumber;
}; // UiCtrl
// ===================================================================
// Implementation of the inlined methods =
inline CtrlHubAttachedPublic *UiCtrl::newPublicCtrlHub()
{
return new CtrlHubAttachedPublic(m_queue);
}
inline const char* UiCtrl::getVersionString()
{
return "Navigator";
}
inline uint32 UiCtrl::getSerialNo()
{
return 0xdeadbeef;
}
inline const char* UiCtrl::getSoftwareVersion()
{
return "2.5.0";
}
} //namespace isab
#endif // UI_CONTROL_H
|
[
"[email protected]"
] |
[
[
[
1,
873
]
]
] |
738e41ae7c365e0e0413908b28e45041bfd3ddd1
|
709cd826da3ae55945fd7036ecf872ee7cdbd82a
|
/Term/WildMagic2/Applications/Imagics/ImViewer/ImViewer.h
|
19a73e0820165ad3be60622a38dd71e8ea77c146
|
[] |
no_license
|
argapratama/kucgbowling
|
20dbaefe1596358156691e81ccceb9151b15efb0
|
65e40b6f33c5511bddf0fa350c1eefc647ace48a
|
refs/heads/master
| 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,410 |
h
|
// Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef IMVIEWER_H
#define IMVIEWER_H
#include "WmlApplication2.h"
class ImViewer : public Application2
{
public:
ImViewer ();
virtual ~ImViewer ();
virtual bool OnPrecreate ();
virtual bool OnInitialize ();
virtual void OnTerminate ();
virtual void OnKeyDown (unsigned char ucKey, int iX, int iY);
virtual void OnSpecialKeyDown (int iKey, int iX, int iY);
virtual void OnMouseClick (int iButton, int iState, int iX, int iY,
unsigned int uiModifiers);
virtual void OnMotion (int iX, int iY, unsigned int uiModifiers);
virtual void ScreenOverlay ();
protected:
bool LoadImage ();
void CopySliceToScreen ();
void ReadPixelValue (int iX, int iY);
void WritePixelString ();
int m_iDimensions, m_iQuantity, m_iSliceQuantity;
int* m_aiBound;
float* m_afData;
Color* m_akData;
float m_fMin, m_fMax, m_fRange, m_fInvRange;
int m_iZ;
char m_acPixelStr[256];
bool m_bMouseDown;
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
48
]
]
] |
48fea21ee36679f86bf676113d3761b718443025
|
7f6fe18cf018aafec8fa737dfe363d5d5a283805
|
/ntk/interface/src/scintilla.cpp
|
9dff1d04f210166d9f549024852dfdc61e11b95e
|
[] |
no_license
|
snori/ntk
|
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
|
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
|
refs/heads/master
| 2020-05-18T05:28:49.149912 | 2009-08-04T16:47:12 | 2009-08-04T16:47:12 | 268,861 | 2 | 0 | null | null | null | null |
SHIFT_JIS
|
C++
| false | false | 8,995 |
cpp
|
/******************************************************************************
The NTK Library
Copyright (C) 1998-2003 Noritaka Suzuki
$Id: scintilla.cpp,v 1.9 2003/11/11 12:07:08 nsuzuki Exp $
******************************************************************************/
#include <ntk/config.h>
#ifdef NTK_ENABLE_SCINTILLA
#define NTK_BUILD
#include "ntk/interface/scintilla.h"
#include <assert.h>
#include <boost/scoped_array.hpp>
#include <ntk/windows/windows.h>
#include <richedit.h>
#include <ntk/support/status.h>
#include <ntk/interface/gdiobject.h>
#include <ntk/misc/scintilla/scintilla.h>
#define for if(false); else for
namespace ntk {
//########################################################
namespace {
HMODULE g_scintilla_module = NULL;
int g_ref_count = 0;
String
scintilla_window_class()
{
if(g_ref_count == 0)
{
g_scintilla_module = ::LoadLibrary("Scintilla.dll");
if(g_scintilla_module == NULL)
{
error(status_t(st::SYSTEM_ERROR).message() + "['Scintilla.dll']");
return "";
}
}
g_ref_count++;
return "Scintilla";
}
void
clean_up_scintilla()
{return;
g_ref_count--;
if(g_ref_count == 0)
{
::FreeLibrary(g_scintilla_module);
g_scintilla_module = NULL;
}
}
}// anonymous namespace
//########################################################
// public methods
Scintilla::Scintilla(const Rect& frame, const String& name, const String& text, uint mode, uint flags, const RGBColor& color, uint style, uint ex_style)
: Control(scintilla_window_class(), frame, name, text, NULL, mode, flags, transparent_color(), style, ex_style)
{
set_flags(flags);// コンストラクタの中では仮想関数が正しく動作しない為
send_message_(SCI_SETVSCROLLBAR, style & WS_VSCROLL);
send_message_(SCI_SETHSCROLLBAR, style & WS_HSCROLL);
set_tab_width(2);
set_font(Font("MS ゴシック", 10));
set_view_color(color);
set_text_color(RGBColor(0, 0, 0));
send_message_(SCI_SETTABINDENTS, true);
send_message_(SCI_SETMARGINWIDTHN, 1, 0);
send_message_(SCI_STYLESETBACK, STYLE_LINENUMBER, (view_color() - 25).ref());
send_message_(SCI_STYLESETFORE, STYLE_LINENUMBER, (ntk::white_color() - (view_color() - 25)).ref());
}
Scintilla::~Scintilla()
{
clean_up_scintilla();
}
void
Scintilla::insert(const String& text)
{
// int start, finish;
// get_selection(&start, &finish);
// select(start);
send_message_(EM_REPLACESEL, 0, reinterpret_cast<LPARAM>(text.c_str()));
}
void
Scintilla::insert(const String& text, int length)
{
insert(String(text.c_str(), text.length() < length ? text.length() : length));
}
void
Scintilla::insert(int offset, const String& text, int length)
{
select(offset);
insert(text, length);
}
void
Scintilla::erase()
{
send_message_(EM_REPLACESEL, 0, reinterpret_cast<LPARAM>(""));
}
void
Scintilla::erase(int start, int finish)
{
select(start, finish);
erase();
}
void
Scintilla::go_to_line(int line_no)
{
send_message_(SCI_GOTOLINE, line_no);
}
void
Scintilla::cut(Clipboard* clipboard)
{
send_message_(SCI_CUT);
}
void
Scintilla::copy(Clipboard* clipboard) const
{
send_message_(SCI_COPY);
}
void
Scintilla::paste(Clipboard* clipboard)
{
send_message_(SCI_PASTE);
}
void
Scintilla::clear()
{
send_message_(SCI_CLEAR);
}
bool
Scintilla::accepts_paste(Clipboard* clipboard) const
{
return send_message_(SCI_CANPASTE) != FALSE;
}
bool
Scintilla::accepts_drop(const Message& message) const
{
return false;
}
bool
Scintilla::undoable() const
{
return send_message_(SCI_CANUNDO) != FALSE;
}
void
Scintilla::undo()
{
send_message_(SCI_UNDO);
}
void
Scintilla::redo()
{
send_message_(SCI_REDO);
}
void
Scintilla::zoom_in()
{
send_message_(SCI_ZOOMIN);
}
void
Scintilla::zoom_out()
{
send_message_(SCI_ZOOMOUT);
}
int
Scintilla::zoom_factor() const
{
return send_message_(SCI_GETZOOM);
}
void
Scintilla::set_zoom(int factor)
{
send_message_(SCI_SETZOOM, factor);
}
void
Scintilla::search_next(const String& word)
{
int a = anchor_pos();
int c = current_pos();
OutputDebugString(format_string("[%d-%d]\n", a, c).c_str());
select(anchor_pos());
send_message_(SCI_SEARCHANCHOR);
send_message_(SCI_SEARCHNEXT, SCFIND_MATCHCASE, reinterpret_cast<LPARAM>(word.c_str()));
send_message_(SCI_SCROLLCARET);
}
void
Scintilla::search_prev(const String& word)
{
int a = anchor_pos();
int c = current_pos();
OutputDebugString(format_string("[%d-%d] (reverse)\n", a, c).c_str());
select(current_pos() -1);
send_message_(SCI_SEARCHANCHOR);
send_message_(SCI_SEARCHPREV, SCFIND_MATCHCASE, reinterpret_cast<LPARAM>(word.c_str()));
send_message_(SCI_SCROLLCARET);
}
//--------------------------------------------------------
// public accessors and manipulators
String
Scintilla::text() const
{
int len = text_length() +1;
boost::scoped_array<char_t> buf(new char_t[len]);
send_message_(SCI_GETTEXT, len, reinterpret_cast<LPARAM>(&buf[0]));
return &buf[0];
}
String
Scintilla::text(int offset, int length) const
{
length += 1;
boost::scoped_array<char_t> buf(new char_t[length]);
get_text(offset, length, &buf[0]);
return &buf[0];
}
void
Scintilla::get_text(int offset, int length, char_t* buffer) const
{
int start, finish;
get_selection(&start, &finish);
const_cast<Scintilla*>(this)->select(offset, offset + length);
send_message_(SCI_GETSELTEXT, 0, reinterpret_cast<LPARAM>(buffer));
const_cast<Scintilla*>(this)->select(start, finish);
}
void
Scintilla::set_text(const char_t* text)
{
send_message_(SCI_SETTEXT, 0, reinterpret_cast<LPARAM>(text));
}
void
Scintilla::set_text(const String& text)
{
set_text(text.c_str());
}
int
Scintilla::text_length() const
{
return send_message_(SCI_GETTEXTLENGTH);
}
int
Scintilla::count_lines() const
{
return send_message_(SCI_GETLINECOUNT);
}
int
Scintilla::current_line() const
{
return send_message_(SCI_LINEFROMPOSITION, send_message_(SCI_GETCURRENTPOS));
}
int
Scintilla::anchor_pos() const
{
return send_message_(SCI_GETANCHOR);
}
void
Scintilla::set_anchor_pos(int pos)
{
send_message_(SCI_SETANCHOR, pos);
}
int
Scintilla::current_pos() const
{
return send_message_(SCI_GETCURRENTPOS);
}
void
Scintilla::set_current_pos(int pos)
{
send_message_(SCI_SETCURRENTPOS, pos);
}
void
Scintilla::get_selection(int* start, int* finish) const
{
*start = anchor_pos();
*finish = current_pos();
}
void
Scintilla::select(int start, int finish)
{
if(start < 0)
start = END_OF_BUFFER;
set_anchor_pos(start);
if(finish == SAME_AS_START)
finish = start;
else if(finish < 0)
finish = END_OF_BUFFER;
set_current_pos(finish);
}
void
Scintilla::select_all()
{
send_message_(SCI_SELECTALL);
}
int
Scintilla::tab_width() const
{
return send_message_(SCI_GETTABWIDTH);
}
void
Scintilla::set_tab_width(int width)
{
send_message_(SCI_SETTABWIDTH, width);
}
const Font&
Scintilla::font() const
{
return m_font;
}
void
Scintilla::set_font(const Font& font)
{
m_font = font;
send_message_(SCI_STYLESETFONT, STYLE_DEFAULT, reinterpret_cast<LPARAM>(m_font.face().c_str()));
for(int i=0; i<=STYLE_MAX; ++i)
{
send_message_(SCI_STYLESETFONT, i, reinterpret_cast<LPARAM>(m_font.face().c_str()));
send_message_(SCI_STYLESETSIZE, i, font.size());
send_message_(SCI_STYLESETCHARACTERSET, i, static_cast<LPARAM>(SHIFTJIS_CHARSET));
}
}
const RGBColor&
Scintilla::view_color() const
{
return m_view_color;
}
void
Scintilla::set_view_color(const RGBColor& color)
{
m_view_color = color;
for(int i=0; i<=STYLE_MAX; ++i)
send_message_(SCI_STYLESETBACK, i, static_cast<LPARAM>(color.ref()));
}
const RGBColor&
Scintilla::text_color() const
{
return m_text_color;
}
void
Scintilla::set_text_color(const RGBColor& color)
{
m_text_color = color;
for(int i=0; i<=STYLE_MAX; ++i)
send_message_(SCI_STYLESETFORE, i, static_cast<LPARAM>(color.ref()));
}
bool
Scintilla::is_modified() const
{
return send_message_(SCI_GETMODIFY) != 0;
}
void
Scintilla::clear_modification_flag()//bool flag)
{
// if(flag == false)
send_message_(SCI_SETSAVEPOINT);
// else
// send_message_();
}
void
Scintilla::set_flags(uint flags)
{
Control::set_flags(flags);
if(flags & SHOW_LINE_NUMBER)
send_message_(SCI_SETMARGINWIDTHN, 0, 56);
else
send_message_(SCI_SETMARGINWIDTHN, 0, 0);
}
//--------------------------------------------------------
// functions
LRESULT
Scintilla::send_message_(UINT message, WPARAM wp, LPARAM lp) const
{
return SendMessage(hwnd(), message, wp, lp);
}
//########################################################
}// namespace ntk
#endif// NTK_ENABLE_SCINTILLA
|
[
"[email protected]"
] |
[
[
[
1,
469
]
]
] |
794c35c1515f1459ea5938efc4519ab60c7212c5
|
f0c08b3ddefc91f1fa342f637b0e947a9a892556
|
/branches/develop/cppreflect/src/Type.cpp
|
ee4fc4e02f15aeb1023380432358b4b97f3c5c1e
|
[] |
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 | 2,120 |
cpp
|
#include "Type.hpp"
#include "Field.hpp"
namespace reflect {
Type::Type(const std::string& name)
: _name(name)
{
}
Type::~Type()
{
}
bool Type::operator==(const Type& type) const
{
return this == &type;
}
const std::string& Type::name() const
{
return _name;
}
bool Type::isClassType() const
{
return false;
}
const ClassType& Type::asClassType() const
{
throw ClassTypeCastException();
}
ClassType::ClassType(const std::string& name)
: Type(name)
{
}
bool ClassType::isClassType() const
{
return true;
}
const ClassType& ClassType::asClassType() const
{
return * static_cast<const ClassType*>(this);
}
bool ClassType::addField(const Field& field)
{
if (_fields.insert(std::make_pair(field.name(), &field)).second)
return true;
return false;
}
const Field& ClassType::findField(const std::string& fieldName) const
{
FieldMap::const_iterator resFind = _fields.find(fieldName);
return *resFind->second;
}
ClassType::FieldsIterator::FieldsIterator(const FieldMap::const_iterator& internalIterator)
: _internalIterator(internalIterator)
{
}
bool ClassType::FieldsIterator::operator == (const FieldsIterator& fieldsIterator) const
{
return _internalIterator == fieldsIterator._internalIterator;
}
bool ClassType::FieldsIterator::operator != (const FieldsIterator& fieldsIterator) const
{
return _internalIterator != fieldsIterator._internalIterator;
}
ClassType::FieldsIterator& ClassType::FieldsIterator::operator ++ ()
{
++_internalIterator;
return *this;
}
ClassType::FieldsIterator& ClassType::FieldsIterator::operator ++ (int)
{
_internalIterator++;
return *this;
}
const Field& ClassType::FieldsIterator::operator * () const
{
return *_internalIterator->second;
}
const Field* ClassType::FieldsIterator::operator -> () const
{
return _internalIterator->second;
}
ClassType::FieldsIterator ClassType::fieldsBegin() const
{
return _fields.begin();
}
ClassType::FieldsIterator ClassType::fieldsEnd() const
{
return _fields.end();
}
} // namespace reflect
|
[
"fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb"
] |
[
[
[
1,
115
]
]
] |
4546ed5134dca1a2e974d73757c481438d9a3bf6
|
9433cf978aa6b010903c134d77c74719f22efdeb
|
/src/svl/Mat3.cpp
|
6701b8033ab1f2c8daedec1e274a01028d5d9ce0
|
[] |
no_license
|
brandonagr/gpstracktime
|
4666575cb913db2c9b3b8aa6b40a3ba1a3defb2f
|
842bfd9698ec48debb6756a9acb2f40fd6041f9c
|
refs/heads/master
| 2021-01-20T07:10:58.579764 | 2008-09-24T05:44:56 | 2008-09-24T05:44:56 | 32,090,265 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,054 |
cpp
|
/*
File: Mat3.cpp
Function: Implements Mat3.h
Author(s): Andrew Willmott
Copyright: (c) 1995-2001, Andrew Willmott
*/
#include "svl/Mat3.h"
#include "svl/Vec4.h"
#include <cctype>
#include <iomanip>
Mat3::Mat3(Real a, Real b, Real c,
Real d, Real e, Real f,
Real g, Real h, Real i)
{
row[0][0] = a; row[0][1] = b; row[0][2] = c;
row[1][0] = d; row[1][1] = e; row[1][2] = f;
row[2][0] = g; row[2][1] = h; row[2][2] = i;
}
Mat3::Mat3(const Mat3 &m)
{
row[0] = m[0];
row[1] = m[1];
row[2] = m[2];
}
Mat3 &Mat3::operator = (const Mat3 &m)
{
row[0] = m[0];
row[1] = m[1];
row[2] = m[2];
return(SELF);
}
Mat3 &Mat3::operator += (const Mat3 &m)
{
row[0] += m[0];
row[1] += m[1];
row[2] += m[2];
return(SELF);
}
Mat3 &Mat3::operator -= (const Mat3 &m)
{
row[0] -= m[0];
row[1] -= m[1];
row[2] -= m[2];
return(SELF);
}
Mat3 &Mat3::operator *= (const Mat3 &m)
{
SELF = SELF * m;
return(SELF);
}
Mat3 &Mat3::operator *= (Real s)
{
row[0] *= s;
row[1] *= s;
row[2] *= s;
return(SELF);
}
Mat3 &Mat3::operator /= (Real s)
{
row[0] /= s;
row[1] /= s;
row[2] /= s;
return(SELF);
}
Bool Mat3::operator == (const Mat3 &m) const
{
return(row[0] == m[0] && row[1] == m[1] && row[2] == m[2]);
}
Bool Mat3::operator != (const Mat3 &m) const
{
return(row[0] != m[0] || row[1] != m[1] || row[2] != m[2]);
}
Mat3 Mat3::operator + (const Mat3 &m) const
{
Mat3 result;
result[0] = row[0] + m[0];
result[1] = row[1] + m[1];
result[2] = row[2] + m[2];
return(result);
}
Mat3 Mat3::operator - (const Mat3 &m) const
{
Mat3 result;
result[0] = row[0] - m[0];
result[1] = row[1] - m[1];
result[2] = row[2] - m[2];
return(result);
}
Mat3 Mat3::operator - () const
{
Mat3 result;
result[0] = -row[0];
result[1] = -row[1];
result[2] = -row[2];
return(result);
}
Mat3 Mat3::operator * (const Mat3 &m) const
{
#define N(x,y) row[x][y]
#define M(x,y) m[x][y]
#define R(x,y) result[x][y]
Mat3 result;
R(0,0) = N(0,0) * M(0,0) + N(0,1) * M(1,0) + N(0,2) * M(2,0);
R(0,1) = N(0,0) * M(0,1) + N(0,1) * M(1,1) + N(0,2) * M(2,1);
R(0,2) = N(0,0) * M(0,2) + N(0,1) * M(1,2) + N(0,2) * M(2,2);
R(1,0) = N(1,0) * M(0,0) + N(1,1) * M(1,0) + N(1,2) * M(2,0);
R(1,1) = N(1,0) * M(0,1) + N(1,1) * M(1,1) + N(1,2) * M(2,1);
R(1,2) = N(1,0) * M(0,2) + N(1,1) * M(1,2) + N(1,2) * M(2,2);
R(2,0) = N(2,0) * M(0,0) + N(2,1) * M(1,0) + N(2,2) * M(2,0);
R(2,1) = N(2,0) * M(0,1) + N(2,1) * M(1,1) + N(2,2) * M(2,1);
R(2,2) = N(2,0) * M(0,2) + N(2,1) * M(1,2) + N(2,2) * M(2,2);
return(result);
#undef N
#undef M
#undef R
}
Mat3 Mat3::operator * (Real s) const
{
Mat3 result;
result[0] = row[0] * s;
result[1] = row[1] * s;
result[2] = row[2] * s;
return(result);
}
Mat3 Mat3::operator / (Real s) const
{
Mat3 result;
result[0] = row[0] / s;
result[1] = row[1] / s;
result[2] = row[2] / s;
return(result);
}
Mat3 trans(const Mat3 &m)
{
#define M(x,y) m[x][y]
#define R(x,y) result[x][y]
Mat3 result;
R(0,0) = M(0,0); R(0,1) = M(1,0); R(0,2) = M(2,0);
R(1,0) = M(0,1); R(1,1) = M(1,1); R(1,2) = M(2,1);
R(2,0) = M(0,2); R(2,1) = M(1,2); R(2,2) = M(2,2);
return(result);
#undef M
#undef R
}
Mat3 adj(const Mat3 &m)
{
Mat3 result;
result[0] = cross(m[1], m[2]);
result[1] = cross(m[2], m[0]);
result[2] = cross(m[0], m[1]);
return(result);
}
Real trace(const Mat3 &m)
{
return(m[0][0] + m[1][1] + m[2][2]);
}
Real det(const Mat3 &m)
{
return(dot(m[0], cross(m[1], m[2])));
}
Mat3 inv(const Mat3 &m)
{
Real mDet;
Mat3 adjoint;
Mat3 result;
adjoint = adj(m);
mDet = dot(adjoint[0], m[0]);
Assert(mDet != 0, "(Mat3::inv) matrix is non-singular");
result = trans(adjoint);
result /= mDet;
return(result);
}
Mat3 oprod(const Vec3 &a, const Vec3 &b)
// returns outerproduct of a and b: a * trans(b)
{
Mat3 result;
result[0] = a[0] * b;
result[1] = a[1] * b;
result[2] = a[2] * b;
return(result);
}
Void Mat3::MakeZero()
{
Int i;
for (i = 0; i < 9; i++)
((Real*) row)[i] = vl_zero;
}
Void Mat3::MakeDiag(Real k)
{
Int i, j;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
if (i == j)
row[i][j] = k;
else
row[i][j] = vl_zero;
}
Void Mat3::MakeBlock(Real k)
{
Int i;
for (i = 0; i < 9; i++)
((Real *) row)[i] = k;
}
ostream &operator << (ostream &s, const Mat3 &m)
{
Int w = s.width();
return(s << '[' << m[0] << endl << setw(w) << m[1] << endl << setw(w)
<< m[2] << ']' << endl);
}
istream &operator >> (istream &s, Mat3 &m)
{
Mat3 result;
Char c;
// Expected format: [[1 2 3] [4 5 6] [7 8 9]]
// Each vector is a column of the matrix.
while (s >> c && isspace(c)) // ignore leading white space
;
if (c == '[')
{
s >> result[0] >> result[1] >> result[2];
if (!s)
{
cerr << "Expected number while reading matrix\n";
return(s);
}
while (s >> c && isspace(c))
;
if (c != ']')
{
s.clear(ios::failbit);
cerr << "Expected ']' while reading matrix\n";
return(s);
}
}
else
{
s.clear(ios::failbit);
cerr << "Expected '[' while reading matrix\n";
return(s);
}
m = result;
return(s);
}
Mat3 &Mat3::MakeRot(const Vec4 &q)
{
Real i2 = 2 * q[0],
j2 = 2 * q[1],
k2 = 2 * q[2],
ij = i2 * q[1],
ik = i2 * q[2],
jk = j2 * q[2],
ri = i2 * q[3],
rj = j2 * q[3],
rk = k2 * q[3];
i2 *= q[0];
j2 *= q[1];
k2 *= q[2];
#if VL_ROW_ORIENT
row[0][0] = 1 - j2 - k2; row[0][1] = ij + rk ; row[0][2] = ik - rj;
row[1][0] = ij - rk ; row[1][1] = 1 - i2 - k2; row[1][2] = jk + ri;
row[2][0] = ik + rj ; row[2][1] = jk - ri ; row[2][2] = 1 - i2 - j2;
#else
row[0][0] = 1 - j2 - k2; row[0][1] = ij - rk ; row[0][2] = ik + rj;
row[1][0] = ij + rk ; row[1][1] = 1 - i2 - k2; row[1][2] = jk - ri;
row[2][0] = ik - rj ; row[2][1] = jk + ri ; row[2][2] = 1 - i2 - j2;
#endif
return(SELF);
}
Mat3 &Mat3::MakeRot(const Vec3 &axis, Real theta)
{
Real s;
Vec4 q;
theta /= 2.0;
s = sin(theta);
q[0] = s * axis[0];
q[1] = s * axis[1];
q[2] = s * axis[2];
q[3] = cos(theta);
MakeRot(q);
return(SELF);
}
Mat3 &Mat3::MakeScale(const Vec3 &s)
{
MakeZero();
row[0][0] = s[0];
row[1][1] = s[1];
row[2][2] = s[2];
return(SELF);
}
Mat3 &Mat3::MakeHRot(Real theta)
{
Real c, s;
MakeDiag();
s = sin(theta);
c = cos(theta);
#ifdef VL_ROW_ORIENT
row[0][0] = c; row[0][1] = s;
row[1][0] = -s; row[1][1] = c;
#else
row[0][0] = c; row[0][1] = -s;
row[1][0] = s; row[1][1] = c;
#endif
return(SELF);
}
Mat3 &Mat3::MakeHScale(const Vec2 &s)
{
MakeDiag();
row[0][0] = s[0];
row[1][1] = s[1];
return(SELF);
}
Mat3 &Mat3::MakeHTrans(const Vec2 &t)
{
MakeDiag();
#ifdef VL_ROW_ORIENT
row[2][0] = t[0];
row[2][1] = t[1];
#else
row[0][2] = t[0];
row[1][2] = t[1];
#endif
return(SELF);
}
|
[
"BrandonAGr@0fd8bb18-9850-0410-888e-21b4c4172e3e"
] |
[
[
[
1,
428
]
]
] |
3a14984314a79371be5fe45327c3d09bfba73abe
|
413d5224c2cc2c710e047cdd9cf87e509cfb6a36
|
/zad7.cpp
|
5f8a52b36cfc4ba8f8f0aebd6633e6f239800a67
|
[] |
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 | 2,318 |
cpp
|
#include <iostream>
#include <cstring>
#include <cstdlib> //free && mallock w cstdlib
//las
using namespace std;
class Person {
char* name; //private
public:
friend class Couple;
friend ostream& operator<<(ostream& str, const Person& os)
{
str<<os.name;
};
Person(const char* n)
{
name = (char*)n;
cout<<"konstr1 "<<name<<endl;
};
Person(const Person& os)
{
name = os.name;
cout<<"konstr 2 "<<name<<endl;
};
Person& operator=(const Person& os)
{
this->name = os.name;
return *this; //this to wskaznik na aktualny obiekt
};
~Person()
{
free(name); //funkcja zwalniajaca pamiec
cout<<"destr"<<endl;
};
char* getName(){
return name;
};
};
class Couple {
Person *husb, *wife;
public:
friend ostream& operator<<(ostream& str, const Couple& p)
{
str<<"He: "<<*p.husb<<", She: "<<*p.wife;
};
Couple(const char* m, const char* z)
{
husb = new Person(m);
wife = new Person(z);
cout<<"coup1"<<endl;
};
Couple(const Couple& p)
{
husb = new Person(*p.husb);
wife = new Person(*p.wife);
cout<<"coup2"<<endl;
};
Couple& operator=(const Couple& p)
{
this->husb = new Person(*p.husb);
this->wife = new Person(*p.wife);
return *this;
};
~Couple()
{
free(husb->name);
free(wife->name);
free(husb);
free(wife);
};
};
int main(void) {
Couple *c1 = new Couple("John","Sue");
Couple c2("Bert","Elsa");
*c1 = c2;
Couple c3(*c1);
delete c1;
cout << c3 << endl;
/*
Person person1("naaapis");
Person person2(person1);
Person person3("Waldek");
cout<<person1<<" "<<person2<<endl;
person1 = person3;
cout<<person1<<endl;
Couple c2("Bert","Elsa");
Couple c3(c2);
Couple c4("Benny","Ann");
c3 = c4;
cout<<c3<<endl;
*/
//system("PAUSE");
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
129
]
]
] |
dd56350e0deacde9c32d9280628b5969fd9adfc7
|
3970f1a70df104f46443480d1ba86e246d8f3b22
|
/imebra/src/imebra/include/dicomDict.h
|
25779021477afa83e5fe57317453d136934ab7cb
|
[] |
no_license
|
zhan2016/vimrid
|
9f8ea8a6eb98153300e6f8c1264b2c042c23ee22
|
28ae31d57b77df883be3b869f6b64695df441edb
|
refs/heads/master
| 2021-01-20T16:24:36.247136 | 2009-07-28T18:32:31 | 2009-07-28T18:32:31 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,946 |
h
|
/*
0.0.46
Imebra: a C++ dicom library.
Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU AFFERO GENERAL PUBLIC LICENSE Version 3 for more details.
You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
along with this program; If not, see http://www.gnu.org/licenses/
-------------------
If you want to use Imebra commercially then you have to buy the commercial
license available at http://puntoexe.com
After you buy the commercial license then you can use Imebra according
to the terms described in the Imebra Commercial License Version 1.
A copy of the Imebra Commercial License Version 1 is available in the
documentation pages.
Imebra is available at http://puntoexe.com
The author can be contacted by email at [email protected] or by mail at
the following address:
Paolo Brandoli
Preglov trg 6
1000 Ljubljana
Slovenia
*/
/*! \file dicomDict.h
\brief Declaration of the class dicomDict.
*/
#if !defined(imebraDicomDict_CC44A2C5_2B8C_42c1_9704_3F9C582643B9__INCLUDED_)
#define imebraDicomDict_CC44A2C5_2B8C_42c1_9704_3F9C582643B9__INCLUDED_
#include "../../base/include/baseObject.h"
#include <map>
///////////////////////////////////////////////////////////
//
// Everything is in the namespace puntoexe::imebra
//
///////////////////////////////////////////////////////////
namespace puntoexe
{
namespace imebra
{
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief The Dicom Dictionary.
///
/// This class can be used to retrieve the tags' default
/// data types and descriptions.
///
/// An instance of this class is automatically allocated
/// by the library: your application should use the
/// static function getDicomDictionary() in order to
/// get the only valid instance of this class.
///
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
class dicomDictionary
{
struct imageDataDictionaryElement
{
std::wstring m_tagName;
std::string m_tagType;
};
struct validDataTypesStruct
{
bool m_longLength; // true if the tag has a 4 bytes length descriptor
imbxUint32 m_wordLength; // Word's length, used for byte reversing in hi/lo endian conversion
imbxUint32 m_maxLength; // The maximum length for the tag. An exception will be trown while reading a tag which exceedes this size
};
public:
dicomDictionary();
void registerTag(imbxUint32 tagId, const wchar_t* tagName, const char* tagType);
void registerVR(std::string vr, bool bLongLength, imbxUint32 wordSize, imbxUint32 maxLength);
/// \brief Retrieve a tag's description.
///
/// @param groupId The group which the tag belongs to
/// @param tagId The tag's id
/// @return The tag's description
///
///////////////////////////////////////////////////////////
std::wstring getTagName(imbxUint16 groupId, imbxUint16 tagId) const;
/// \brief Retrieve a tag's default data type.
///
/// @param groupId The group which the tag belongs to
/// @param tagId The tag's id
/// @return The tag's data type
///
///////////////////////////////////////////////////////////
std::string getTagType(imbxUint16 groupId, imbxUint16 tagId) const;
/// \brief Retrieve the only valid instance of this class.
///
/// @return a pointer to the dicom dictionary
///
///////////////////////////////////////////////////////////
static dicomDictionary* getDicomDictionary();
/// \brief Return true if the specified string represents
/// a valid dicom data type.
///
/// @param dataType the string to be checked
/// @return true if the specified string is a valid
/// dicom data type
///
///////////////////////////////////////////////////////////
bool isDataTypeValid(std::string dataType) const;
/// \brief Return true if the tag's length in the dicom
/// stream must be written using a DWORD
///
/// @param dataType the data type for which the information
/// is required
/// @return true if the specified data type's
/// length must be written using a DWORD
///
///////////////////////////////////////////////////////////
bool getLongLength(std::string dataType) const ;
/// \brief Return the size of the data type's elements
///
/// @param dataType the data type for which the information
/// is required
/// @return the size of a single element
///
///////////////////////////////////////////////////////////
imbxUint32 getWordSize(std::string dataType) const;
/// \brief Return the maximum size of the tags with
/// the specified data type.
///
/// @param dataType the data type for which the information
/// is required
/// @return the maximum tag's size in bytes
///
///////////////////////////////////////////////////////////
imbxUint32 getMaxSize(std::string dataType) const;
protected:
typedef std::map<imbxUint32, imageDataDictionaryElement> tDicomDictionary;
tDicomDictionary m_dicomDict;
typedef std::map<std::string, validDataTypesStruct> tVRDictionary;
tVRDictionary m_vrDict;
};
} // namespace imebra
} // namespace puntoexe
#endif // !defined(imebraDicomDict_CC44A2C5_2B8C_42c1_9704_3F9C582643B9__INCLUDED_)
|
[
"[email protected]"
] |
[
[
[
1,
179
]
]
] |
f2a3a4ee2b37e902f33d7aeb239170fb9451d87b
|
02cd7f7be30f7660f6928a1b8262dc935673b2d7
|
/ invols --username [email protected]/tf2D_draw.cpp
|
48fdb3103934d19503373e4104615c627cc95f85
|
[] |
no_license
|
hksonngan/invols
|
f0886a304ffb81594016b3b82affc58bd61c4c0b
|
336b8c2d11d97892881c02afc2fa114dbf56b973
|
refs/heads/master
| 2021-01-10T10:04:55.844101 | 2011-11-09T07:44:24 | 2011-11-09T07:44:24 | 46,898,469 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,225 |
cpp
|
#include "CT/CT.h"
#include "Draw2D.h"
#include "wxIncludes.h"
#include "MainFrame.h"
#include "CPU_VD.h"
//#include <GL/gl.h>
//#include <GL/glu.h>
#include "AllDef.h"
#include "tf2D.h"
#include "drawtext.h"
#include "Img3DProc.h"
void TF2D_window::OnPaint( wxPaintEvent& WXUNUSED(event) )
{
wxPaintDC dc(this);
SetCurrent();
//if(MyApp::gl_window)MyApp::gl_window->GetContext();else
if (!GetContext()) return;
glViewport(0, 0, (GLint) width, (GLint) height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width, height,0);
glMatrixMode(GL_MODELVIEW);
InitGL();
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
int height1 = height-2*TF2D_MARGIN;
//this->tf = CT::color_table+TF_WIDTH*CT::GetCurDataID();
//tf = CT::iso->GetCurTF();
//isos = &CT::iso->GetCurRM()->isos[CT::GetCurDataID()];
// tf_quads2 = &CT::iso->GetCurRM()->tf_quads2[CT::GetCurDataID()];
/// Fill
//histogram
/// FRAME
glColor3f(0.5f,0.5f,0.5f);
DrawRectangle(vec2(0,TF2D_MARGIN),vec2(width,TF2D_MARGIN+height1));
glBegin(GL_LINES);
glColor3f(0.4f,0.4f,0.4f);
float hh=6;
float cx = (-center)*scale;
float step=scale/(256.0f*128.0f);
int grid_step = 1000;
if(scale>1000)grid_step = 100;
if(scale>10000)grid_step = 10;
if(scale>100000)grid_step = 1;
int aaa = data_stat.MinValue+10000;
int i1=data_stat.MinValue,i2=data_stat.MaxValue,i_max=data_stat.MaxValue-data_stat.MinValue;
for(int i=0;i<=i_max;i++)
{
if(cx>0)
{
if(i1==data_stat.MinValue)i1=i+data_stat.MinValue;
if(aaa%grid_step==0)
{
float hhh = 4+4*(aaa%(10*grid_step)==0);
if(aaa%(100*grid_step)==0)glColor3f(1,1,1);
if(aaa==10000){glColor3f(0,0,1);hhh=-height1/3;}
glVertex2f(cx,height1+TF2D_MARGIN);
glVertex2f(cx,height1+TF2D_MARGIN+hhh);
glVertex2f(cx,TF2D_MARGIN);
glVertex2f(cx,TF2D_MARGIN-hhh);
if(aaa%100==0)glColor3f(0.4f,0.4f,0.4f);
}
}
if(cx>=width){i2=i+data_stat.MinValue;break;}
cx += step;
aaa++;
}
glEnd();
start_view = i1;
end_view = i2;
//DrawText("DR SD",vec2(12,32),vec4(0.6f));
glFlush();
SwapBuffers();
}
|
[
"[email protected]"
] |
[
[
[
1,
105
]
]
] |
3b6ea916da03827e5721feed00d24192dbde9d95
|
71db16f07e91c3d49691f99c3edbfcba6a604189
|
/FahProxy/WorkUnit.h
|
40d6b42f3d1c2c9c72c216d8adff8eaddbf32d47
|
[] |
no_license
|
jaboles/fahproxy
|
503832879d9c1081e69b642d8cfe32fd0334a3b2
|
131b97ddf86220e4ba52878ba22d06f97003a023
|
refs/heads/master
| 2022-12-07T13:26:03.522052 | 2008-08-26T11:29:01 | 2008-08-26T11:29:01 | 290,090,861 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 937 |
h
|
#pragma once
namespace FahProxy
{
public ref class WorkUnit
{
public:
WorkUnit(System::String^ filename);
~WorkUnit();
System::DateTime GetTime();
int GetDataSize();
System::String^ GetHostReceivedFrom();
System::String^ GetUsername();
System::String^ GetUserId();
int GetMachineId();
System::String^ GetTeam();
System::String^ GetUploadHost();
int GetUploadPort();
System::IO::Stream^ GetDataStream();
System::IO::Stream^ GetTranslatedResponseStream();
void WriteReceipt(array<unsigned char,1>^ receiptBuffer);
void WriteSimulatedResponse();
void CleanUpFile();
static const int FAH_RESPONSE_BUFFER_SIZE = 512;
private:
System::String^ m_baseFilename;
System::String^ m_path;
System::String^ m_uploadHost;
System::String^ m_hostReceivedFrom;
int m_uploadPort;
int m_wuDataSize;
System::DateTime m_time;
array<unsigned char, 1>^ m_info;
};
}
|
[
"jb@dc620d95-ca3a-fc45-9de6-42b3e20515ab"
] |
[
[
[
1,
38
]
]
] |
b93652c1a8e336d11d4c4aaa7223e72ce28b4c36
|
30e4267e1a7fe172118bf26252aa2eb92b97a460
|
/code/pkg_UnitTest/Modules/TestCore/TestPluginManager.h
|
5160ec09b7d2f7a667635907d1e8a72d933c7b75
|
[
"Apache-2.0"
] |
permissive
|
thinkhy/x3c_extension
|
f299103002715365160c274314f02171ca9d9d97
|
8a31deb466df5d487561db0fbacb753a0873a19c
|
refs/heads/master
| 2020-04-22T22:02:44.934037 | 2011-01-07T06:20:28 | 2011-01-07T06:20:28 | 1,234,211 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,979 |
h
|
// Copyright 2008-2011 Zhang Yun Gui, [email protected]
// https://sourceforge.net/projects/x3c/
//
// 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.
#pragma once
#include "BaseTest.h"
#include "Ix_ObjectFactory.h"
#include "Ix_PluginLoader.h"
class TestPluginManager : public BaseTest
{
CPPUNIT_TEST_SUITE( TestPluginManager );
CPPUNIT_TEST( testLoadUnloadPlugin );
CPPUNIT_TEST( testLoadUnloadPlugins );
CPPUNIT_TEST( testLoadPluginFiles );
CPPUNIT_TEST( testInitializePlugins );
CPPUNIT_TEST( testRegisterPlugin );
CPPUNIT_TEST( testCreateObject );
CPPUNIT_TEST( testIsCreatorRegister );
CPPUNIT_TEST( testCreateSpecialInterfaceObjects );
CPPUNIT_TEST( testQuerySpecialInterfaceObject );
CPPUNIT_TEST( testHasCreatorReplaced );
CPPUNIT_TEST_SUITE_END();
public:
TestPluginManager(void);
~TestPluginManager(void);
virtual void setUp();
virtual void tearDown();
public:
void testLoadUnloadPlugin();
void testLoadUnloadPlugins();
void testLoadPluginFiles();
void testInitializePlugins();
void testRegisterPlugin();
void testCreateObject();
void testIsCreatorRegister();
void testCreateSpecialInterfaceObjects();
void testQuerySpecialInterfaceObject();
void testHasCreatorReplaced();
private:
Ix_PluginLoader* GetManagerLoader(void);
Ix_ObjectFactory* GetManagerObjectFactory(void);
long GetPluginsNum(LPCWSTR path, LPCWSTR ext = L".plugin.dll", bool recursive = true);
};
|
[
"rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3"
] |
[
[
[
1,
63
]
]
] |
e6c04e0fff0881f3825ff2f1a3eb89baf96ba703
|
5ac13fa1746046451f1989b5b8734f40d6445322
|
/minimangalore/Nebula2/code/contrib/nmax/src/export2/nmaxmaterial_shd.cc
|
b8fad5990eaed868ccdbe5138c2de6d287d6b95d
|
[] |
no_license
|
moltenguy1/minimangalore
|
9f2edf7901e7392490cc22486a7cf13c1790008d
|
4d849672a6f25d8e441245d374b6bde4b59cbd48
|
refs/heads/master
| 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 45,483 |
cc
|
//-----------------------------------------------------------------------------
// nmaxmaterial_shd.cc
//
// Generate 3dsmax scripted plug-in to handle Nebula2 custom material.
//
// (c)2005 Kim, Hyoun Woo
//-----------------------------------------------------------------------------
#include "export2/nmax.h"
#include "base/nmaxlistener.h"
#include "export2/nmaxscriptcall.h"
#include "export2/nmaxutil.h"
#include "util/nstring.h"
#include "export2/nmaxmaterial_ui.h"
#include "export2/nmaxoptions.h"
#include "kernel/nkernelserver.h"
#include "kernel/nfileserver2.h"
#include "kernel/nfile.h"
#include "misc/niniprefserver.h"
#include "util/nstring.h"
#include "tinyxml/tinyxml.h"
#include "gfx2/nshaderstate.h"
#if USE_ACTIVEX_ENVELOPECURVE_CTRL
// prefix of the envelopecurve activex control
extern const char* particlePrefix;
#endif
/// contains shader name which to be filtered out.
static nArray<nString> shaderFilterArray;
//-----------------------------------------------------------------------------
/**
Find the full path of shaders.xml file.
The reason we do not directly call nMaxOption::GetHomePath() is that
nMaxOption is mostly used for exporting.
It is singleton class so calling that here makes hard to handle and destroy
its instance.
@param file file to retrieve the path
*/
static
nString GetShaderXmlPath(nString file)
{
nString shdxml;
nString iniFilename;
iniFilename += GetCOREInterface()->GetDir(APP_PLUGCFG_DIR);
iniFilename += "\\";
iniFilename += N_MAXEXPORT_INIFILE;
nFileServer2* fileServer = nFileServer2::Instance();
// check the .ini file exist in 3dsmax plugin directory.
if (!fileServer->FileExists(iniFilename))
{
// .ini file does not exist in '/plugcfg' directory.
n_message("%s file does not exist in '$3dsmax/plugcfg' directory.\n",
N_MAXEXPORT_INIFILE);
// return a empty string.
return shdxml;
}
nString homeDir;
// read 'home' path from existing .ini flle in '$3dsmax/plugcfg' directory.
nIniPrefServer* iniFile = (nIniPrefServer*)nKernelServer::Instance()->New("niniprefserver", "/iniprefsrv");
iniFile->SetFileName(iniFilename);
iniFile->SetSection("GeneralSettings");
homeDir = iniFile->ReadString("HomeDir");
iniFile->Release();
if (homeDir.IsEmpty())
{
n_message("Home directory does not exist in %s file.\n", iniFilename.Get());
// return a empty string.
return shdxml;
}
shdxml += homeDir;
shdxml += "\\";
//shdxml += "data\\shaders\\shaders.xml";
shdxml += "data\\shaders\\";
shdxml += file;
if (!nFileServer2::Instance()->FileExists(shdxml))
{
n_message("File %s does not exist.\n", shdxml.Get());
// make the string to be empty then return.
shdxml += "";
return shdxml;
}
return shdxml;
}
//-----------------------------------------------------------------------------
/**
Retrieves parameter type based on the given shader type.
-02-Nov-06 kims Replaced point4 to floattab to retrieve valid values from 3dsmax control.
Thank ZHANG Zikai for the patch.
@param shdType shader type which described in xml file.
@return string which represent parameter type.
*/
static
nString GetParameterType(const nString &shdType)
{
if (shdType == "Int")
return "#integer";
else
if (shdType == "Bool")
return "#boolean";
else
if (shdType == "Float")
return "#float";
else
if (shdType == "String")
return "#string";
else
if (shdType == "Enum")
return "#integer";
else
if (shdType == "Color")
#if MAX_RELEASE >= 6000
return "#frgba"; // we use rgba, for 3dsmax6 or higher
#else
return "#color"; // 3dsmax5 or lower version does not support alpha in colorpicker.
#endif
else
if (shdType == "Vector")
//#if MAX_RELEASE >= 6000
// return "#point4";
//#else
return "#floatTab tabSize:4 tabSizeVariable:false";
//#endif
else
if (shdType == "Texture")
return "#texturemap";
else
if (shdType == "BumpTexture")
return "#texturemap";
else
if (shdType == "CubeTexture")
return "#texturemap";
else
if (shdType == "EnvelopeCurve")
//return "#maxObject";
#if USE_ACTIVEX_ENVELOPECURVE_CTRL
return "#floatTab tabSize:11 tabSizeVariable:false";
#else
return "#floatTab tabSize:9 tabSizeVariable:false";
#endif
else
if (shdType == "ColorEnvelopeCurve" )
#if USE_ACTIVEX_ENVELOPECURVE_CTRL
// add 2 params(min,max)
return "#floatTab tabSize:14 tabSizeVariable:false";
#else
return "#floatTab tabSize:12 tabSizeVariable:false";
#endif
else
{
return "<<unknown>>";
}
}
//-----------------------------------------------------------------------------
/**
Retrieves UI from the given type.
@note
EnvelopeCurve and ColorEnvelopeCurve are ignored.
The followings are parameters type and its corresponding UI control.
-# Int - spinner
-# Float - spinner
-# color - ColorPicker
-# Enum - dropdownlist
-# Texture - mapbutton
-# BumpTexture - mapbutton
-# CubeTexture - mapbutton
-# Vector - spinner
-# EnvelopeCurve - nmaxenvelopecurve custom control
-# ColorEnvelopeCurve - nmaxenvelopecurve custom control
-# Unknown - label
@param type 'type' value of xml element.
-17-Aug-06 kims Changed to add texutre directory setting button.
*/
static
nString GetUIFromType(TiXmlElement* elemParam, const nString &shdName, const nString &shaderHandler, const nString &type)
{
if (type == "Int")
return AddSpinner(shdName, shaderHandler, false, elemParam);
else
if (type == "Bool")
return AddCheckBox(shdName, shaderHandler, elemParam);
else
if (type == "Float")
return AddSpinner(shdName, shaderHandler, true, elemParam);
else
if (type == "Color")
return AddColorPicker(elemParam);
else
if (type == "Enum")
return AddDropdownList(shdName, shaderHandler, elemParam);
else
if (type == "Texture")
{
nString ret;
// Caution: The plugin max script code is always regenerated and
// executed at the start time of 3dsmax so it is useless to
// specifying any initial value to a control or parameter block.
ret += AddMapButton(elemParam);
ret += AddSetDirDlg(elemParam);
return ret;
}
else
if (type == "BumpTexture")
{
nString ret;
// Caution: The plugin max script code is always regenerated and
// executed at the start time of 3dsmax so it is useless to
// specifying any initial value to a control or parameter block.
ret += AddMapButton(elemParam);
ret += AddSetDirDlg(elemParam);
return ret;
}
else
if (type == "CubeTexture")
{
nString ret;
// Caution: The plugin max script code is always regenerated and
// executed at the start time of 3dsmax so it is useless to
// specifying any initial value to a control or parameter block.
ret += AddMapButton(elemParam);
ret += AddSetDirDlg(elemParam);
return ret;
}
else
if (type == "Vector")
return AddVector4Spinner(shdName, shaderHandler, elemParam);
else
if (type == "EnvelopeCurve" || type == "ColorEnvelopeCurve")
return AddEnvelopeCurve(shdName, shaderHandler, elemParam);
else
{
nString uiScript;
uiScript += "\t\t";
uiScript += "label Unknown \"Unknown\"\n";
return uiScript;
}
}
//-----------------------------------------------------------------------------
/**
The followinig maxscript is generated:
@verbatim
param = ""
param += (val.r/255.0) as string
param += " "
param += (val.g/255.0) as string
param += " "
param += (val.b/255.0) as string
param += " "
param += (val.a/255.0) as string
param += " "
nChangeShaderParameter "Standard" "common" "MatSpecular" param
@endverbatim
*/
static
nString GetStringForColorPicker(const nString &shdName, const nString &type, const nString ¶mName)
{
nString str;
nString indent = "\t\t\t\t";
str += indent + "param = \"\" \n";
str += indent + "param += (val.r/255.0) as string \n";
str += indent + "param += \" \"\n";
str += indent + "param += (val.g/255.0) as string\n";
str += indent + "param += \" \"\n";
str += indent + "param += (val.b/255.0) as string\n";
str += indent + "param += \" \"\n";
str += indent + "param += (val.a/255.0) as string\n";
str += indent + "param += \" \"\n";
str += indent + "nChangeShaderParameter ";
str += "\""; str += shdName; str += "\""; //e.g. "Standard"
str += " ";
str += "\""; str += type; str += "\"";
str += " ";
str += "\""; str += paramName; str += "\""; // e.g. "MatDiffuse"
str += " ";
str += "param\n";
return str;
}
//-----------------------------------------------------------------------------
/**
The followinig maxscript is generated:
@verbatim
nChangeShaderParameter "Standard" "common" "DiffMap0" val.filename
@endverbatim
*/
static
nString GetStringForMapButton(const nString &shdName, const nString &type, const nString ¶mName)
{
nString script;
nString tmp;
tmp.Format("\t\t\t\tnChangeShaderParameter \"%s\" \"%s\" \"%s\" val.filename\n",
shdName.Get(), type.Get(), paramName.Get());
script += tmp;
return script;
}
//-----------------------------------------------------------------------------
/**
The followinig maxscript is generated:
@verbatim
param = ""
param += val as string
nChangeShaderParameter "Standard" "common" "MatEmissiveIntensity" param
@endverbatim
*/
static
nString GetStringForDefault(const nString &shdName, const nString &type, const nString ¶mName)
{
nString script;
nString tmp;
tmp.Format("\t\t\t\tparam = \"\" \n");
script += tmp;
tmp.Format("\t\t\t\tparam += val as string \n");
script += tmp;
tmp.Format("\t\t\t\tnChangeShaderParameter \"%s\" \"%s\" \"%s\" param\n",
shdName.Get(), type.Get(), paramName.Get());
script += tmp;
return script;
}
//-----------------------------------------------------------------------------
/**
Generate max script code for a event which occurred a value of a control is
changed.
The following maxscript is one of an example which might be generated:
@verbatim
on RenderPri changed val do
(
nChangeShaderParameter "Standard", "common", "RenderPri", "1.0 1.0 1.0 1.0"
)
@endverbatim
-17-Aug-06 kims Added color picker to support MatAmbient.
*/
static
nString GetIpcEventHandler(const nString &shdName, const nString ¶mName)
{
nString handler;
nString tmp;
handler += "\t\t\tif nIsConnectedIpc() do\n";
handler += "\t\t\t(\n";
//color picker
if (paramName == "MatDiffuse" ||
paramName == "MatEmissive" ||
paramName == "MatSpecular" ||
paramName == "MatAmbient")
{
handler += GetStringForColorPicker(shdName, "common", paramName);
}
else
if (paramName == "MatEmissiveIntensity" ||
paramName == "MatSpecularPower" ||
paramName == "BumpScale")
{
handler += GetStringForDefault(shdName, "common", paramName);
}
else
if (paramName == "AlphaSrcBlend" ||
paramName == "AlphaDstBlend")
{
handler += GetStringForDefault(shdName, "common", paramName);
}
//texture map
else
if (strstr(paramName.Get(), "DiffMap") ||
strstr(paramName.Get(), "BumpMap") ||
strstr(paramName.Get(), "CubeMap") )
{
handler += GetStringForMapButton(shdName, "common", paramName);
}
else
{
tmp.Format("\t\t\t\tprint \"Unknown material type: shader name: %s parameter name: %s\"\n",
shdName.Get(), paramName.Get());
handler += tmp;
}
handler += "\t\t\t)\n";
return handler;
}
//-----------------------------------------------------------------------------
/**
Retrieves event handler for each parameters.
@note
Because we use custom attribute for plugin's parameters,
we cannot directly access its parameters of superclass with 'delegate'
local variable. Instead of doing that, we get current material in the
material editor then access its delegate like this:
@verbatim
on MapAmbient set val do
(
-- get the current material in the material editor.
-- this is the material which currently selected material in the slot.
curMaterial = medit.GetCurMtl()
-- now, we can access the ambient value of the superclass.
curMaterial.delegate.ambient = val
)
@endverbatim
@param paramName parameter name which in parameter block.
@return string which to be appended for parameter's event handler.
*/
static
nString GetEventHandler(const nString &shdName, const nString ¶mName)
{
bool validParam = true;
nString handler;
handler += "\t\ton ";
handler += paramName;
handler += " set val do \n";
handler += "\t\t(\n";
nShaderState::Param param = nShaderState::StringToParam(paramName.Get());
switch(param)
{
case nShaderState::MatAmbient:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
case nShaderState::MatDiffuse:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
case nShaderState::MatSpecular:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
case nShaderState::MatEmissive:
break;
case nShaderState::MatEmissiveIntensity:
break;
case nShaderState::MatSpecularPower:
break;
case nShaderState::AlphaSrcBlend:
case nShaderState::AlphaDstBlend:
break;
case nShaderState::DiffMap0:
case nShaderState::DiffMap1:
case nShaderState::DiffMap2:
case nShaderState::DiffMap3:
case nShaderState::DiffMap4:
case nShaderState::DiffMap5:
case nShaderState::DiffMap6:
case nShaderState::DiffMap7:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
case nShaderState::BumpMap0:
case nShaderState::BumpMap1:
case nShaderState::BumpMap2:
case nShaderState::BumpMap3:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
case nShaderState::CubeMap0:
case nShaderState::CubeMap1:
case nShaderState::CubeMap2:
case nShaderState::CubeMap3:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
case nShaderState::SpecMap0:
case nShaderState::SpecMap1:
case nShaderState::SpecMap2:
case nShaderState::SpecMap3:
handler += "\t\t\tOn" + paramName + "Changed val\n";
break;
default:
case nShaderState::InvalidParameter:
// put empty handler.
validParam = false;
break;
}
if (validParam)
{
handler += GetIpcEventHandler(shdName, paramName);
}
handler += "\t\t) \n";
return handler;
}
//-----------------------------------------------------------------------------
/**
Generate script plug-in script.(part of 'param' element in xml)
-02-Nov-06 kims Changd to 'Vector' type correctly. Thank ZHANG Zikai for the patch.
@param name 'name' attribute in param element
The followings are known names:
'name', 'label', 'type', 'gui', 'export', 'min', 'max', 'def', 'enum'
*/
static
void GenerateScript(TiXmlElement* elemParam, nString& shdName, nString& strParamBlock,
nString &strRollout, nString &openEvent, nString &closeEvent, nString &createEvent)
{
nString tmp;
// start to generate script for param block clause.
// parameter name in parameter block.
nString paramName = elemParam->Attribute("name");
// parameter type
nString paramType = elemParam->Attribute("type");
nString shaderHandler = "common";
int hasGui;
elemParam->Attribute("gui", &hasGui);
// not a common shader handler
if (nShaderState::StringToParam(paramName.Get()) == nShaderState::InvalidParameter)
{
if ("Particle2" == shdName )
{
shaderHandler = "particle2";
}
else if ("Leaf" == shdName || "Tree" == shdName)
{
shaderHandler = "swing";
}
else
{
shaderHandler = "";
}
}
#if 0
if (paramType == "ColorEnvelopeCurve")
{
n_assert(hasGui);
tmp.Format("\t\t%s_v0 type:%s ui:%s_v0\n", paramName.Get(), GetParameterType("Color").Get(), paramName.Get());
strParamBlock += tmp;
tmp.Format("\t\t%s_v1 type:%s ui:%s_v1\n", paramName.Get(), GetParameterType("Color").Get(), paramName.Get());
strParamBlock += tmp;
tmp.Format("\t\t%s_v2 type:%s ui:%s_v2\n", paramName.Get(), GetParameterType("Color").Get(), paramName.Get());
strParamBlock += tmp;
tmp.Format("\t\t%s_v3 type:%s ui:%s_v3\n", paramName.Get(), GetParameterType("Color").Get(), paramName.Get());
strParamBlock += tmp;
tmp.Format("\t\t%s_p1 type:%s ui:%s_p1\n", paramName.Get(), GetParameterType("Float").Get(), paramName.Get());
strParamBlock += tmp;
tmp.Format("\t\t%s_p2 type:%s ui:%s_p2\n", paramName.Get(), GetParameterType("Float").Get(), paramName.Get());
strParamBlock += tmp;
strRollout += GetUIFromType(elemParam, shdName, shaderHandler, paramType);
// append event handler.
strParamBlock += GetEventHandler(shdName, paramName, );
}
else
#endif
{
strParamBlock += "\t\t";
strParamBlock += paramName;
strParamBlock += " ";
strParamBlock += "type:";
strParamBlock += GetParameterType(paramType);
strParamBlock += " ";
// if the type is one of any texture types, specifies false to this parameter.
// default setting is 'true' on animatable parameter.
if (strstr(paramType.Get(), "Texture"))
{
//strParamBlock += "animatable:false";
strParamBlock += "animatable:true";
strParamBlock += " ";
}
// specify default value of the parameter.
if (paramType == "Vector" || paramType == "ColorEnvelopeCurve")
{
// we don't need default values for 'vector' and 'ColorEnvelopeCurve' type
// those are types uses floattab.
;
}
else
if (paramType == "EnvelopeCurve")
{
/*
nString defaultValue = GetDefault(elemParam);
if (!defaultValue.IsEmpty())
{
strParamBlock += "default:";
strParamBlock += defaultValue;
strParamBlock += " ";
}
*/
}
else
{
nString defaultValue = GetDefault(elemParam);
if (!defaultValue.IsEmpty())
{
strParamBlock += "default:";
strParamBlock += defaultValue;
strParamBlock += " ";
}
}
// if there's gui, we create ui in the given rollout.
if (hasGui)
{
if (paramType == "EnvelopeCurve")
{
// we do not combine ui if the parameter is envelopecurve or colorenvelopecurve due to
// it is hard to bind those control type with parameters block.
#if USE_ACTIVEX_ENVELOPECURVE_CTRL
// openEvent
tmp.Format("\t\t\t%s_modulation.selection = %s[9];\n", paramName.Get(), paramName.Get(), paramName.Get() ); openEvent += tmp;
tmp.Format("\t\t\tparams = \"\"\n"); openEvent += tmp;
int i;
for( i = 1; i<6; ++i )
{
tmp.Format("\t\t\tparams += (%s[%d] as string) + \", \"\n", paramName.Get(), i); openEvent += tmp;
}
tmp.Format("\t\t\tparams += (%s[%d] as string)\n", paramName.Get(), i); openEvent += tmp;
tmp.Format("\t\t\t%s%s.InitCurve params\n", particlePrefix, paramName.Get() ); openEvent += tmp;
// createEvent
nString defaultValue = GetDefault(elemParam);
tmp.Format("\t\t\t%s_def = %s", paramName.Get(), defaultValue.Get()); createEvent +=tmp;
tmp.Format("\t\t\tfor i = 1 to %s_def.count do\n", paramName.Get()); createEvent +=tmp;
tmp.Format("\t\t\t(\n"); createEvent +=tmp;
tmp.Format("\t\t\t\t%s[i] = %s_def[i]\n", paramName.Get(), paramName.Get()); createEvent +=tmp;
tmp.Format("\t\t\t)\n"); createEvent +=tmp;
// link ui
strParamBlock += "ui:";
nString name = paramName;
nString activeXName = particlePrefix + paramName + ", ";
strParamBlock += "(" + activeXName + activeXName + activeXName + activeXName + activeXName + activeXName;
strParamBlock += name + "_freq, ";
strParamBlock += name + "_ampl, ";
strParamBlock += name + "_modulation, ";
strParamBlock += name + "_min, ";
strParamBlock += name + "_max";
strParamBlock += ")";
#else
// 'ui' name should be same as parameter name.
strParamBlock += "ui:";
nString name = paramName;
strParamBlock += "(";
strParamBlock += name + "_v0, ";
strParamBlock += name + "_v1, ";
strParamBlock += name + "_v2, ";
strParamBlock += name + "_v3, ";
strParamBlock += name + "_p1, ";
strParamBlock += name + "_p2, ";
strParamBlock += name + "_freq, ";
strParamBlock += name + "_ampl, ";
strParamBlock += name + "_modulation";
strParamBlock += ")";
#endif
}
else
if (paramType == "ColorEnvelopeCurve")
{
#if USE_ACTIVEX_ENVELOPECURVE_CTRL
// open event
tmp.Format("\t\t\tparams = \"\"\n"); openEvent += tmp;
int i;
for( i = 1; i< 14; ++i )
{
tmp.Format("\t\t\tparams += (%s[%d] as string) + \", \"\n", paramName.Get(), i); openEvent += tmp;
}
tmp.Format("\t\t\tparams += (%s[%d] as string)\n", paramName.Get(), i); openEvent += tmp;
tmp.Format("\t\t\t%s%s.InitColorCurve params\n", particlePrefix, paramName.Get() ); openEvent += tmp;
// createEvent
tmp.Format("\t\t\tfor i = 1 to initColorCurve.count do\n"); createEvent +=tmp;
tmp.Format("\t\t\t(\n"); createEvent +=tmp;
tmp.Format("\t\t\t\t%s[i] = initColorCurve[i]\n", paramName.Get()); createEvent +=tmp;
tmp.Format("\t\t\t)\n"); createEvent +=tmp;
#else
// use color picker due to that we don't have envelope color curve control yet.
tmp.Format("\t\t\t%s_v0.color = (color (%s[1]*255) (%s[2]*255) (%s[3]*255))\n", paramName.Get(), paramName.Get(), paramName.Get(), paramName.Get()); openEvent += tmp;
tmp.Format("\t\t\t%s_v1.color = (color (%s[4]*255) (%s[5]*255) (%s[6]*255))\n", paramName.Get(), paramName.Get(), paramName.Get(), paramName.Get()); openEvent += tmp;
tmp.Format("\t\t\t%s_v2.color = (color (%s[7]*255) (%s[8]*255) (%s[9]*255))\n", paramName.Get(), paramName.Get(), paramName.Get(), paramName.Get()); openEvent += tmp;
tmp.Format("\t\t\t%s_v3.color = (color (%s[10]*255) (%s[11]*255) (%s[12]*255))\n", paramName.Get(), paramName.Get(), paramName.Get(), paramName.Get()); openEvent += tmp;
tmp.Format("\t\t\t%s_p1.value = %s[13]\n", paramName.Get(), paramName.Get()); openEvent += tmp;
tmp.Format("\t\t\t%s_p2.value = %s[14]\n", paramName.Get(), paramName.Get()); openEvent += tmp;
#endif
}
else
{
// 'ui' name should be same as parameter name.
strParamBlock += "ui:";
// combine the 4 spinner into a parameter
if (paramType == "Vector")
{
// names should be same as the spinners
// see AddVector4Spinner
nString name = paramName;
strParamBlock += "(";
name.AppendInt(0);
strParamBlock += name;
strParamBlock += ", ";
name.AppendInt(1);
strParamBlock += name;
strParamBlock += ", ";
name.AppendInt(2);
strParamBlock += name;
strParamBlock += ", ";
name.AppendInt(3);
strParamBlock += name;
strParamBlock += ")";
}
else
{
strParamBlock += paramName;
}
}
strParamBlock += " \n";
strRollout += GetUIFromType(elemParam, shdName, shaderHandler, paramType);
}
// append event handler.
strParamBlock += GetEventHandler(shdName, paramName);
// if it is texture type, add destination directory setting value.
if (strstr(paramType.Get(), "Texture") && hasGui)
{
//HACK: 'dirSetting' is used again in AddSetDirDlg() function and nMaxMaterial::GetNebulaMaterial().
// So, if you change the string, the string in AddSetDirDlg() also should be changed.
// The directory parameter has "" for default string. It is absolutely necessary in Max6.
// Without that, the plug-in with the panel have those contorls does not correctly work.
tmp.Format("\t\tdirSetting%s type:#string default:\"\" ui:edtFld%s\n",
paramName.Get(), paramName.Get());
strParamBlock += tmp;
}
}
}
//-----------------------------------------------------------------------------
/**
Parse each of the elements in xml and generate parameter block and rollout.
@param elemShader element of the given xml
@param strParamBlock parameter block script which to be generated.
@param strRollout rollout script which to be generated.
@param openEvent
@param closeEvent
*/
static
void ParseParams(TiXmlElement* elemShader, nString& shdName, nString& strParamBlock,
nString &strRollout, nString &openEvent, nString &closeEvent, nString &createEvent)
{
nString tmp;
nString shdType = elemShader->Attribute("shaderType");
nString meshType = elemShader->Attribute("meshType");
// Get .shader name.
nString effectFileName = elemShader->Attribute("file");
// 'Shader' parameter in parameter block.
tmp.Format("\t\tShader type:#string default:\"%s\" animatable:false\n", effectFileName.Get());
strParamBlock += tmp;
TiXmlElement* elemParam = elemShader->FirstChild("param")->ToElement();
for (elemParam; elemParam; elemParam = elemParam->NextSiblingElement())
{
GenerateScript(elemParam, shdName, strParamBlock, strRollout, openEvent, closeEvent, createEvent);
}
}
//-----------------------------------------------------------------------------
/**
Filter of the shader in filter array.
*/
static
bool DoFilter(const nString &str)
{
for (int i=0; i<shaderFilterArray.Size(); i++)
{
if (shaderFilterArray[i] == str)
return true;
}
return false;
}
//-----------------------------------------------------------------------------
/**
Add script plugin event handlers.
*/
static
nString AddPluginEventHandlers()
{
nString script;
nString tmp;
// 'create' plugin event handlers
tmp.Format("\ton create do\n\t(\n\t\tOnPluginCreate()\n\t)\n");
script += tmp;
// 'postCreate' plugin event handlers
tmp.Format("\ton postCreate do\n\t(\n\t\tOnPluginPostCreate()\n\t)\n");
script += tmp;
// 'load' plugin event handlers
tmp.Format("\ton load do\n\t(\n\t\tOnPluginLoad()\n\t)\n");
script += tmp;
// 'postLoad' plugin event handlers
tmp.Format("\ton postLoad do\n\t(\n\t\tOnPluginPostLoad()\n\t)\n");
script += tmp;
return script;
}
//-----------------------------------------------------------------------------
/**
Retrieve all shader names from xml file (e.g. shader.xml)
*/
TiXmlHandle GetShaderFromDataBase(TiXmlHandle& xmlHandle, const nString &shader)
{
// retrieves all shader names in xml file.
TiXmlElement* child = xmlHandle.FirstChild("NebulaShaderDatabase").FirstChild("shader").Element();
for (child; child; child=child->NextSiblingElement())
{
// get shader name.
nString name = child->Attribute("file");
if (name == shader)
{
return child;
}
}
return TiXmlHandle(0);
}
//-----------------------------------------------------------------------------
/**
Retrieve parameter from given shader.
*/
TiXmlHandle GetParamFromShader(TiXmlHandle& shader, const nString ¶m)
{
TiXmlElement* child = shader.FirstChild("param").Element();
for (child; child; child=child->NextSiblingElement())
{
nString name = child->Attribute("name");
if (name == param)
return TiXmlHandle(child);
}
return TiXmlHandle(0);
}
//-----------------------------------------------------------------------------
/**
Retrieve shader name which to be filtered out.
The shader names are listed in the filter.xml file which can be found
under the same directory with shader.xml file.
*/
bool GetShaderFilter()
{
// Get the full path of '$nebula/data/shaders/filter.xml' file.
nString filterXmlFilePath = GetShaderXmlPath("filter.xml");
if (filterXmlFilePath.IsEmpty())
{
n_listener("Cannot find filter.xml file.\n");
return false;
}
TiXmlDocument xmlDoc;
// Load the shaders.xml file
if (!xmlDoc.LoadFile(filterXmlFilePath.Get()))
{
n_listener("Filed to load %s.", filterXmlFilePath.Get());
return false;
}
TiXmlHandle xmlHandle(&xmlDoc);
TiXmlElement* child;
shaderFilterArray.Clear();
child = xmlHandle.FirstChild("NebulaShaderFilter").FirstChild("shader").Element();
for (child; child; child=child->NextSiblingElement())
{
// get shader name.
nString name = child->Attribute("name");
shaderFilterArray.Append(name);
}
return true;
}
//-----------------------------------------------------------------------------
/**
max script expose function which to generate material script plugin based on
'$nebula2/data/shaders/shaders.xml' file.
The following max script generate nebula2 custom material plugin.
@verbatim
nCreateCustomMaterialPlugin()
@endverbatim
@note
Do not call this script explicitly when 3DS Max running.
This function should be called at once when 3DS Max start up.
If not, all previously specified materials in the slot will be reset.
The generated file, "n2materialplugin.ms" can be found in the
'$3dsmax/scripts/' directory. Use it for the purpose of test or debugging.
It is only available on the debug version of plugin.
@return true if we success to generate scripted plug-in.
*/
bool EvalCustomMaterialPlugin()
{
// Get shader name which to be filted out.
if (!GetShaderFilter())
{
n_listener("Cannot find filter.xml file.\n");
shaderFilterArray.Clear();
}
// Get the full path of '$nebula/data/shaders/shaders.xml' file.
nString shdXmlFilePath = GetShaderXmlPath(nString("shaders.xml"));
if (shdXmlFilePath.IsEmpty())
{
n_listener("Cannot find shaders.xml file.\n");
return false;
}
TiXmlDocument xmlDoc;
// Load the shaders.xml file
if (!xmlDoc.LoadFile(shdXmlFilePath.Get()))
{
n_listener("Filed to load %s.", shdXmlFilePath.Get());
return false;
}
TiXmlHandle xmlHandle(&xmlDoc);
TiXmlElement* child;
// array for shader name of shader element.
nArray<nString> shaderArray;
shaderArray.Append("None");
nArray<nString> custAttribNameArray;
custAttribNameArray.Append("undefined");
nArray<nString> effectFileArray;
effectFileArray.Append("'None'");
// array for containing generated custom attribute script.
nArray<nString> custAttribArray;
nString tmp;
// retrieves all shader names in xml file.
child = xmlHandle.FirstChild("NebulaShaderDatabase").FirstChild("shader").Element();
for (child; child; child=child->NextSiblingElement())
{
// get shader name.
nString name = child->Attribute("name");
// if the given shader name is found in the shader filter,
// the plugin does not generate script code for the shader.
if (DoFilter(name))
continue;
nString caName = name;
// get shader name.
nString effectFile;
effectFile += "'";
effectFile += child->Attribute("file");
effectFile += "'";
effectFileArray.Append(effectFile);
shaderArray.Append(name);
nString custattrib, custattribName;
// we append 'ca' prefix to avoid name confliction.
// e.g. "Standard' and "Ocean' are already defined keyword in max script.
custattribName +="ca";
custattribName += nMaxUtil::CorrectName(name);
custAttribNameArray.Append(custattribName);
tmp.Format("%s = attributes \"%s\"\n(\n", custattribName.Get(), caName.Get());
custattrib += tmp;
// parameter block and rollout clause.
nString paramBlock, rollout, openEvent, closeEvent, createEvent;
nString shdName = nMaxUtil::CorrectName(name);
nString rolloutName = "r" + shdName; //e.g. "rStandard"
tmp.Format("\tparameters %s rollout:%s\n\t(\n", shdName.Get(), rolloutName.Get());
paramBlock += tmp;
// begin rollout
tmp.Format("\trollout %s \"%s Parameters\"\n", rolloutName.Get(), name.Get());
rollout += tmp;
rollout += "\t(\n";
// parse each param elements in shader element.
ParseParams(child, caName, paramBlock, rollout, openEvent, closeEvent, createEvent);
paramBlock += "\t)\n";
//if (!openEvent.IsEmpty())
{
tmp.Format("\t\ton %s open do\n\t\t(\n", rolloutName.Get());
rollout += tmp;
rollout += openEvent;
//HACK: ugly hardcoding, we assume if the rollout name contains "Particle",
// it uses activex control and enables accelerators.
if (strstr(rolloutName.Get(), "Particle"))
{
tmp.Format("\t\t\tenableAccelerators = false\n");
rollout += tmp;
}
rollout += "\t\t)\n";
}
//if (!closeEvent.IsEmpty())
{
tmp.Format("\t\ton %s close do\n\t\t(\n", rolloutName.Get());
rollout += tmp;
rollout += closeEvent;
if (strstr(rolloutName.Get(), "Particle"))
{
tmp.Format("\t\t\tenableAccelerators = true\n");
rollout += tmp;
}
rollout += "\t\t)\n";
}
rollout += "\t)\n";;
if( !createEvent.IsEmpty() )
{
tmp.Format("\t\ton create do\n\t\t(\n");
rollout += tmp;
rollout += "\t\t\tinitCurve = #(0.0, 0.3, 0.7, 1.0, 0.2, 0.8, 0.0, 0.0, 0.0, 0.0, 1.0)\n";
rollout += "\t\t\tinitColorCurve = #(1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.8)\n";
rollout += createEvent;
rollout += "\t\t)\n";
}
custattrib += paramBlock;
custattrib += rollout;
custattrib += "\n)\n";
custAttribArray.Append(custattrib);
}
int i;
nString script;
script += "--------------------------------------------------------------------------------\n";
script += "-- The Nebula2 3dsmax Toolkit MaxScript code \n";
script += "-- This file was automatically generated and executed when 3dsmax started. \n";
script += "--------------------------------------------------------------------------------\n";
// define 'materialhandlers.ms' including script.
script += "include \"nebula2\\materialhandlers.ms\"\n\n";
// add custom attributes.
for (i=0; i<custAttribArray.Size(); i++)
{
script += custAttribArray[i];
script += "\n";
}
// script plugin header
const int version = 100;
nString strVer;
strVer.AppendInt(version);
script += "plugin material Nebula2Material\n";
script += "\tname:\"Nebula2\"";
script += "\n";
script += "\tclassID:#(";
script += "0x6b5ae640";
script += ", ";
script += "0x319f53b8";
script += ")\n";
script += "\textends:Standard\n";
script += "\treplaceUI:true\n";
script += "\tversion:";
script += strVer; // version
script += "\n(\n";
// script plugin body.
// local variable : array of customAttributes
script += "\tlocal customAttributes = #(";
for (i=0; i<custAttribNameArray.Size(); i++)
{
script += custAttribNameArray[i];
if (i < custAttribNameArray.Size() - 1)
script += ",";
}
script += ")\n";
// local variable : array of shader types
script += "\tlocal effectFileNames = #(";
for (i=0; i<effectFileArray.Size(); i++)
{
script += "\"";
script += effectFileArray[i];
script += "\"";
if (i < effectFileArray.Size() - 1)
script += ",";
}
script += ")\n";
// parameter block
script += "\tparameters SelectShader rollout:main \n";
script += "\t(\n";
script += "\t\tparamCurShader type:#integer default:1 animatable:false \n";
script += "\t\tparamEffectFile type:#string default:\"'None'\" animatable:false ui:effectFileName \n";
script += "\t)\n";
nString mainRollout;
mainRollout += "\trollout main ";
mainRollout += "\"Nebula2 Shader Types\"\n";
mainRollout += "\t(\n";
// insert dropdownlist script for shader selection to rollout clause.
nString uiShdName = "Shader";
mainRollout += "\t\t";
mainRollout += "dropdownlist ";
mainRollout += uiShdName;
mainRollout += " ";
mainRollout += "\"Select Shader\"";
mainRollout += " ";
mainRollout += "width:160";
mainRollout += " ";
mainRollout += "items:#(";
for (i=0; i<shaderArray.Size(); i++)
{
mainRollout += "\"";
mainRollout += shaderArray[i];
mainRollout += "\"";
if (i < shaderArray.Size() - 1)
mainRollout += ",";
}
mainRollout += ") ";
mainRollout += "selection:1";
mainRollout += "\n";
// end of dropdownlist script for shader.
mainRollout += "\t\tlabel effectFileName \"Effect File: 'None'\" align:#left \n";
mainRollout += "\t\ton " + uiShdName + " " + "selected i do \n";
mainRollout += "\t\t(\n";
mainRollout += "\t\t\tcurMaterial = medit.GetCurMtl() \n";
mainRollout += "\t\t\tif customAttributes[paramCurShader] != undefine do \n";
mainRollout += "\t\t\t(\n";
mainRollout += "\t\t\t\tnumCustAttr = custAttributes.count curMaterial \n";
mainRollout += "\t\t\t\tfor i = 1 to numCustAttr do\n";
mainRollout += "\t\t\t\t(\n";
mainRollout += "\t\t\t\t\tattrDef = custAttributes.getdef curMaterial i \n";
mainRollout += "\t\t\t\t\tif attrDef != undefined and attrDef.name == customAttributes[paramCurShader].name do \n";
mainRollout += "\t\t\t\t\t(\n";
mainRollout += "\t\t\t\t\t\tcustAttributes.delete curMaterial i \n";
mainRollout += "\t\t\t\t\t)\n";
mainRollout += "\t\t\t\t)\n"; // end of for
mainRollout += "\t\t\t)\n";
mainRollout += "\t\t\tif customAttributes[i] != undefined then \n";
mainRollout += "\t\t\t(\n";
mainRollout += "\t\t\t\tcustAttributes.add curMaterial customAttributes[i] \n";
mainRollout += "\t\t\t)\n";
mainRollout += "\t\t\tShader.selection = i \n";
mainRollout += "\t\t\tparamCurShader = i \n";
mainRollout += "\t\t\teffectFileName.caption = \"Effect File: \" + effectFileNames[i] \n";
mainRollout += "\t\t\tparamEffectFile = effectFileNames[i]\n";
mainRollout += "\t\t)\n";
mainRollout += "\t\ton main open do \n";
mainRollout += "\t\t(\n";
mainRollout += "\t\t\tShader.selection = paramCurShader \n";
mainRollout += "\t\t\teffectFileName.caption = \"Effect File: \" + paramEffectFile\n";
mainRollout += "\t\t)\n";
mainRollout += "\t)\n";
script += mainRollout;
script += AddPluginEventHandlers();
script += "\n)";
nString scriptsPath;
scriptsPath += GetCOREInterface()->GetDir(APP_SCRIPTS_DIR);
#ifdef _DEBUG
nString sampleFile;
sampleFile += scriptsPath;
sampleFile += "\\";
sampleFile += "n2materialplugin.ms";
nFile* file = nFileServer2::Instance()->NewFileObject();
if (file->Open(sampleFile.Get(), "w"))
{
file->PutS(script);
file->Close();
file->Release();
}
#endif
// execute the generated script.
if (!nMaxScriptCall(script.Get()))
{
n_listener("Failed to evaluate the generated script.\n");
n_listener("See '$3dsmax/scripts/materialplugintemp.ms' for generated script.\n");
// if we failed to evaluate the given script, put it to 3dsmax script directory
nString debugFilePath;
debugFilePath += scriptsPath;
debugFilePath += "\\";
debugFilePath += "materialplugintemp.ms";
nFile* file = nFileServer2::Instance()->NewFileObject();
if (file->Open(debugFilePath.Get(), "w"))
{
file->PutS(script);
file->Close();
file->Release();
}
// open 3dsmax script editor with the script which failed to be evaluated
// for the purpose of debugging it.
n_openeditor(debugFilePath.Get());
return false;
}
return true;
}
//-----------------------------------------------------------------------------
/**
Retrieve default value which is defined in shader database file(shader.xml)
It is needed when the toolkit set default value if the parameter has not any value.
e.g) The toolkit specifies "nobump.dds" if there is no bump map is specified
in the material editor when it exports.
*/
bool GetDefaultValueFromDataBase(const nString &shader, const nString ¶m, nString &outvalue)
{
// Get the full path of '$nebula/data/shaders/shaders.xml' file.
nString shdXmlFilePath = GetShaderXmlPath("shaders.xml");
if (shdXmlFilePath.IsEmpty())
{
n_listener("Cannot find shaders.xml file.\n");
return false;
}
TiXmlDocument xmlDoc;
// Load the shaders.xml file
if (!xmlDoc.LoadFile(shdXmlFilePath.Get()))
{
n_listener("Filed to load %s.", shdXmlFilePath.Get());
return false;
}
TiXmlHandle xmlHandle(&xmlDoc);
TiXmlElement* pElem = GetParamFromShader(GetShaderFromDataBase(xmlHandle, shader), param).Element();
if (pElem == 0)
return false;
const char *attr = pElem->Attribute("def");
if (attr == 0)
return false;
outvalue = attr;
return true;
}
|
[
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c",
"ldw9981@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] |
[
[
[
1,
659
],
[
662,
711
],
[
714,
1351
]
],
[
[
660,
661
],
[
712,
713
]
]
] |
b7bc2700065cbde7d7deaed41e77809b386f14c8
|
216ae2fd7cba505c3690eaae33f62882102bd14a
|
/source/Terrain.cpp
|
57b288b1a46ebf79b4622d8eff63a33932772ad9
|
[] |
no_license
|
TimelineX/balyoz
|
c154d4de9129a8a366c1b8257169472dc02c5b19
|
5a0f2ee7402a827bbca210d7c7212a2eb698c109
|
refs/heads/master
| 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,519 |
cpp
|
#include "Terrain.h"
#define USE_REPORT
#include "macros.h"
using namespace Balyoz;
Terrain::Terrain(const std::string& name)
{
m_Name = name;
m_pEntity = 0;
m_pSceneNode = 0;
}
Terrain::~Terrain(void)
{
}
void Terrain::load( Ogre::SceneManager * pSceneManager, Ogre::RenderWindow * pRendenWindow, Ogre::SceneNode *pSceneNodeToAttach )
{
switch (m_TerrainType)
{
case TERRAIN_TYPE_FLAT:
break;
case TERRAIN_TYPE_HEIGT_MAP:
pSceneManager->setWorldGeometry(m_ResourceName);
break;
case TERRAIN_TYPE_OCEAN:
Ogre::Plane oceanSurface;
oceanSurface.normal = Ogre::Vector3::UNIT_Y;
oceanSurface.d = m_fHeight;
Ogre::MeshManager::getSingleton().createPlane("OceanSurface",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
oceanSurface,
m_fWidth, m_fLength, m_iWidthSegnemts, m_iLengthSegments,
true, 1, 1, 1, Ogre::Vector3::UNIT_Z);
m_pEntity = pSceneManager->createEntity( "OceanSurface", "OceanSurface" );
m_pEntity->setMaterialName(m_ResourceName);
if( !m_bStatic )
{
if ( pSceneNodeToAttach )
{
m_pSceneNode = pSceneNodeToAttach->createChildSceneNode();
m_pSceneNode->attachObject(m_pEntity);
}
else
{
REPORT_WARNING(m_Name + " terrain is not static however no scenenode is given; terrain will be loaded as static ");
m_pSceneNode = pSceneManager->getRootSceneNode()->createChildSceneNode();
m_pSceneNode->attachObject(m_pEntity);
}
}
break;
}
}
|
[
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
] |
[
[
[
1,
63
]
]
] |
691bdfc0326d2b2a2458fd8e0b349209e79e1f13
|
bb4789cc159c382a92dec127a7794013798cc453
|
/Win32/source/main.cpp
|
67b9dd9e769c78cf721170827562197b7d5d5670
|
[] |
no_license
|
oliveta/Image-Joiner
|
3c7fcefe0ec6264edbc3aba1562320bfc0fb146f
|
4115f7e06cb41f6791d045829d7d68f7e72bd9fd
|
refs/heads/master
| 2021-01-10T19:21:13.221455 | 2011-06-13T14:41:38 | 2011-06-13T14:41:38 | 1,889,064 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 223 |
cpp
|
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.setWindowIcon(QIcon("joiner.icns"));
w.show();
return a.exec();
}
|
[
"[email protected]"
] |
[
[
[
1,
13
]
]
] |
9426b11fb2a68e7e34768eac48cf15e6c6177c9d
|
0c738885f2dadce227f95c4d02ff9bb3a7ac77ed
|
/libsofadb/rapidjson/stringbuffer.h
|
506effd93b9f2c83ef1cf91f271191719ceb1b06
|
[] |
no_license
|
Cyberax/SofaDb
|
dc8283e7ecd7e0a8f2220deb763ca441184daaa6
|
c0b16333d7715ea2f3e04ab85cb2838256c5d722
|
refs/heads/master
| 2021-01-13T01:37:23.069348 | 2011-12-22T03:22:56 | 2011-12-22T03:22:56 | 2,700,170 | 7 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,396 |
h
|
#ifndef RAPIDJSON_STRINGBUFFER_H_
#define RAPIDJSON_STRINGBUFFER_H_
#include "rapidjson.h"
#include "internal/stack.h"
namespace rapidjson {
//! Represents an in-memory output stream.
/*!
\tparam Encoding Encoding of the stream.
\tparam Allocator type for allocating memory buffer.
\implements Stream
*/
template <typename Encoding, typename Allocator = CrtAllocator>
struct GenericStringBuffer {
typedef typename Encoding::Ch Ch;
GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
void Put(Ch c) { *stack_.template Push<Ch>() = c; }
void Flush() {}
void Clear() { stack_.Clear(); }
const char* GetString() const {
// Push and pop a null terminator. This is safe.
*stack_.template Push<Ch>() = '\0';
stack_.template Pop<Ch>(1);
return stack_.template Bottom<Ch>();
}
size_t GetSize() const { return stack_.GetSize(); }
static const size_t kDefaultCapacity = 256;
mutable internal::Stack<Allocator> stack_;
};
typedef GenericStringBuffer<UTF8<> > StringBuffer;
//! Implement specialized version of PutN() with memset() for better performance.
template<>
inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
memset(stream.stack_.Push<char>(n), c, n * sizeof(c));
}
} // namespace rapidjson
#endif // RAPIDJSON_STRINGBUFFER_H_
|
[
"[email protected]"
] |
[
[
[
1,
50
]
]
] |
d11f7e43d8de3bb44360aaff71c87cd147d790a6
|
a2904986c09bd07e8c89359632e849534970c1be
|
/topcoder/KDoubleSubstrings.cpp
|
82afe24f3dc8a04bbdc6c6e47a7efd766648ff1b
|
[] |
no_license
|
naturalself/topcoder_srms
|
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
|
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
|
refs/heads/master
| 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,721 |
cpp
|
// BEGIN CUT HERE
// END CUT HERE
#line 5 "KDoubleSubstrings.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define debug(p) cout << #p << "=" << p << endl;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
#define pb push_back
class KDoubleSubstrings {
public:
int howMuch(vector <string> str, int k) {
int ret=0;
return ret;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
int verify_case(int casenum, const int &expected, const int &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
case 0: {
string str[] = {"aa"};
int k = 0;
int expected__ = 1;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 1: {
string str[] = {"aaaa"};
int k = 0;
int expected__ = 4;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 2: {
string str[] = {"contest", "kontest"};
int k = 1;
int expected__ = 14;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 3: {
string str[] = {"abacaba", "d", "abacaba"};
int k = 1;
int expected__ = 34;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 4: {
string str[] = {"areyouready"};
int k = 2;
int expected__ = 18;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}
// custom cases
/* case 5: {
string str[] = ;
int k = ;
int expected__ = ;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 6: {
string str[] = ;
int k = ;
int expected__ = ;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 7: {
string str[] = ;
int k = ;
int expected__ = ;
clock_t start__ = clock();
int received__ = KDoubleSubstrings().howMuch(vector <string>(str, str + (sizeof str / sizeof str[0])), k);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
|
[
"shin@CF-7AUJ41TT52JO.(none)"
] |
[
[
[
1,
203
]
]
] |
eaabd0c777d02a1106a6e8596b9f01ec1c2ccce4
|
91ac219c4cde8c08a6b23ac3d207c1b21124b627
|
/common/mlc/BitInterleaver.cpp
|
b8ebaeb7961866e062b6058f04f4387f974263e5
|
[] |
no_license
|
DazDSP/hamdrm-dll
|
e41b78d5f5efb34f44eb3f0c366d7c1368acdbac
|
287da5949fd927e1d3993706204fe4392c35b351
|
refs/heads/master
| 2023-04-03T16:21:12.206998 | 2008-01-05T19:48:59 | 2008-01-05T19:48:59 | 354,168,520 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,794 |
cpp
|
/******************************************************************************\
* Technische Universitaet Darmstadt, Institut fuer Nachrichtentechnik
* Copyright (c) 2001
*
* Author(s):
* Volker Fischer
*
* Description:
*
* The two parts with different protection levels shall not overlap in the
* interleaving process. Therefore the interleaved lower protected part shall
* be appended to the interleaved higher protected part.
*
******************************************************************************
*
* 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 "BitInterleaver.h"
/* Implementation *************************************************************/
/******************************************************************************\
* Bit interleaver *
\******************************************************************************/
void CBitInterleaver::Interleave(CVector<_BINARY>& InputData)
{
int i;
/* Block 1 -------------------------------------------------------------- */
/* Interleave data according the interleaver table */
for (i = 0; i < ix_in1; i++)
vecbiInterlMemory1[i] = InputData[veciIntTable1[i]];
/* Copy result in input-vector */
for (i = 0; i < ix_in1; i++)
InputData[i] = vecbiInterlMemory1[i];
/* Block 2 -------------------------------------------------------------- */
/* Interleave data according the interleaver table */
for (i = 0; i < ix_in2; i++)
vecbiInterlMemory2[i] = InputData[veciIntTable2[i] + ix_in1];
/* Copy result in input-vector */
for (i = 0; i < ix_in2; i++)
InputData[i + ix_in1] = vecbiInterlMemory2[i];
}
void CBitInterleaver::Init(int iNewx_in1, int iNewx_in2, int it_0)
{
/* Set internal parameters */
ix_in1 = iNewx_in1;
ix_in2 = iNewx_in2;
/* ix_in1 can be 0 but ix_in2 is always greater than "0" */
if (ix_in1 > 0)
{
/* Allocate memory for table */
veciIntTable1.Init(ix_in1);
/* Make interleaver table */
MakeTable(veciIntTable1, ix_in1, it_0);
/* Allocate memory for interleaver */
vecbiInterlMemory1.Init(ix_in1);
}
/* Allocate memory for table */
veciIntTable2.Init(ix_in2);
/* Make interleaver table */
MakeTable(veciIntTable2, ix_in2, it_0);
/* Allocate memory for interleaver */
vecbiInterlMemory2.Init(ix_in2);
}
/******************************************************************************\
* Bit deinterleaver *
\******************************************************************************/
void CBitDeinterleaver::Deinterleave(CVector<CDistance>& vecInput)
{
int i;
/* Block 1 -------------------------------------------------------------- */
/* Deinterleave data according the deinterleaver table */
for (i = 0; i < ix_in1; i++)
vecDeinterlMemory1[veciIntTable1[i]] = vecInput[i];
/* Copy result in input-vector */
for (i = 0; i < ix_in1; i++)
vecInput[i] = vecDeinterlMemory1[i];
/* Block 2 -------------------------------------------------------------- */
/* Deinterleave data according the deinterleaver table */
for (i = 0; i < ix_in2; i++)
vecDeinterlMemory2[veciIntTable2[i]] = vecInput[i + ix_in1];
/* Copy result in input-vector */
for (i = 0; i < ix_in2; i++)
vecInput[i + ix_in1] = vecDeinterlMemory2[i];
}
void CBitDeinterleaver::Init(int iNewx_in1, int iNewx_in2, int it_0)
{
/* Set internal parameters */
ix_in1 = iNewx_in1;
ix_in2 = iNewx_in2;
/* ix_in1 can be 0 but ix_in2 is always greater than "0" */
if (ix_in1 > 0)
{
/* Allocate memory for table */
veciIntTable1.Init(ix_in1);
/* Make interleaver table */
MakeTable(veciIntTable1, ix_in1, it_0);
/* Allocate memory for interleaver */
vecDeinterlMemory1.Init(ix_in1);
}
/* Allocate memory for table */
veciIntTable2.Init(ix_in2);
/* Make interleaver table */
MakeTable(veciIntTable2, ix_in2, it_0);
/* Allocate memory for interleaver */
vecDeinterlMemory2.Init(ix_in2);
}
|
[
"[email protected]"
] |
[
[
[
1,
145
]
]
] |
6d8710ebf6b8302f33fec5d0fa18063c77e9f245
|
c8d8b08fb7e5dfe8f7d9d8b95bce08de843174d4
|
/SlingboxLib.cpp
|
b73ce81e79189c9cb05c1f3c92abbb262e4f59ff
|
[] |
no_license
|
lepmail/SlingboxLib
|
6ec9af1cb8c74c7bc060b93f13478252d593a773
|
04bca1ad9abfef16597de7e048e964482a6961e8
|
refs/heads/master
| 2023-03-19T12:04:05.155312 | 2011-06-20T16:02:04 | 2011-06-20T16:02:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 28,818 |
cpp
|
//
// Copyright (C) 2010-2011 Stonyx
// http://www.stonyx.com
//
// This library is free software. You can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 (or at your
// option any later version) as published by The Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// If you did not received a copy of the GNU General Public License along
// with this library see http://www.gnu.org/copyleft/gpl.html or write to
// The Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
//
#include "SlingboxLib.h"
#if defined _WIN32 || defined _WIN64
#include <ws2tcpip.h>
typedef int socklen_t;
#else
#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
// ********************
// Public Functions
// ********************
// Default constructor.
CSlingbox::CSlingbox()
{
// Set all variables to default/invalid values
m_socCommunication = INVALID_SOCKET;
m_socStream = INVALID_SOCKET;
memset(m_szAddress, 0, sizeof(m_szAddress));
m_uiPort = 0;
m_usCode = 0;
m_usSequence = 0;
m_iChannel = -1;
m_iInput = -1;
memset(&m_receivedMessages, 0, sizeof(m_receivedMessages));
}
// Alternative constructor used to set the address (IP or hostname) and port of the
// Slingbox we want to connect to. If no port is specified default port 5001 is used.
CSlingbox::CSlingbox(const char * szAddress, unsigned int uiPort /* = 5001 */)
{
// Call default constructor
CSlingbox();
// Set address and port variables to passed values
SetAddress(szAddress, uiPort);
}
// Destructor.
CSlingbox::~CSlingbox()
{
// Close all connections if they are still open
if (m_socStream != INVALID_SOCKET)
CloseSocket(m_socStream);
if (m_socCommunication != INVALID_SOCKET)
CloseSocket(m_socCommunication);
}
// Function used to find a Slingbox. Address and port of found Slingbox can be
// retrieved with the GetAddress function afterwards.
bool CSlingbox::FindSlingbox(unsigned int uiTimeout /* = 10 */)
{
// Open a UDP connection
SOCKET socSocket = OpenSocket(NULL, 0, true);
if (socSocket != INVALID_SOCKET)
{
// Prepare and send data
uint32_t uiData[8];
memset(uiData, 0, sizeof(uiData));
uiData[0] = 0x00000101;
uiData[1] = 0x00000002;
if (Broadcast(socSocket, 5004, uiData, sizeof(uiData), uiTimeout) <= 0)
return false;
// Reset address and port variables
memset(m_szAddress, 0, sizeof(m_szAddress));
m_uiPort = 0;
// Give the Slingbox time to respond
Wait(250);
// Look for correct return message and properly set variables
if (!ReceiveMessage(socSocket, true, uiTimeout) ||
!m_receivedMessages.bFindMessage ||
strlen(m_szAddress) == 0 || m_uiPort == 0)
{
CloseSocket(socSocket);
return false;
}
// Close socket
CloseSocket(socSocket);
}
else
{
return false;
}
return true;
}
// Function used to retrieve the address and port of a Slingbox found with the
// FindSlingbox function.
void CSlingbox::GetAddress(char * szAddress, unsigned int uiAddressLength,
unsigned int * uiPort)
{
// Copy requested data into passed pointers
memset(szAddress, 0, uiAddressLength);
strncpy(szAddress, m_szAddress, uiAddressLength - 1);
*uiPort = m_uiPort;
}
// Function used to set the address (IP or hostname) and port of the Slingbox we
// want to connect to. If no port is specified default port 5001 is used.
void CSlingbox::SetAddress(const char * szAddress, unsigned int uiPort /* = 5001 */)
{
// Set address and port variables to passed values
strncpy(m_szAddress, szAddress, sizeof(m_szAddress) - 1);
m_uiPort = uiPort;
}
// Function used to login into the Slingbox.
bool CSlingbox::Connect(bool bLoginAsAdmin, const char * szPassword)
{
// Check if a communication connection is already open
if (m_socCommunication != INVALID_SOCKET)
return false;
#if defined _WIN32 || defined _WIN64
// Enable use of the Winsock DLL
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
return false;
#endif
// Open the communication connection
m_socCommunication = OpenSocket(m_szAddress, m_uiPort);
if (m_socCommunication == INVALID_SOCKET)
{
#if defined _WIN32 || defined _WIN64
// Finish using the Winsock DLL
WSACleanup();
#endif
return false;
}
// Prepare and send string
char * szString = "GET /stream.asf HTTP/1.1\r\nAccept: */*\r\n"
"Pragma: Sling-Connection-Type=Control, Session-Id=0\r\n\r\n";
if (Send(m_socCommunication, (void *)szString, strlen(szString)) <= 0)
{
// Close the communication connection
CloseSocket(m_socCommunication);
m_socCommunication = INVALID_SOCKET;
#if defined _WIN32 || defined _WIN64
// Finish using the Winsock DLL
WSACleanup();
#endif
return false;
}
// Invalidate variables
m_usCode = 0;
m_usSequence = 0;
m_iChannel = -1;
m_iInput = -1;
// Prepare and send the connect message
ConnectMessage message(bLoginAsAdmin, szPassword);
if (!SendReceiveMessage(m_socCommunication, &message) ||
!m_receivedMessages.bConnectMessage)
{
// Close the communication connection
CloseSocket(m_socCommunication);
m_socCommunication = INVALID_SOCKET;
#if defined _WIN32 || defined _WIN64
// Finish using the Winsock DLL
WSACleanup();
#endif
return false;
}
// Check if we got a valid code
if (m_usCode == 0)
{
// Close the communication connection
CloseSocket(m_socCommunication);
m_socCommunication = INVALID_SOCKET;
#if defined _WIN32 || defined _WIN64
// Finish using the Winsock DLL
WSACleanup();
#endif
return false;
}
return true;
}
// Function used to send the initialization message and initialize the stream.
bool CSlingbox::InitializeStream()
{
// Prepare and send start message
InitializationMessage message;
return SendReceiveMessage(m_socCommunication, &message) &&
m_receivedMessages.bInitializationMessage;
}
// Function used to set the stream settings.
bool CSlingbox::StreamSettings(Resolution eResolution /* = RESOLUTION320X240 */,
uint32_t uiVideoBitrate /* = 704 */, uint32_t uiFrameRate /* = 30 */,
uint32_t uiVideoSmoothing /* = 50 */, uint32_t uiAudioBitrate /* = 64 */,
uint32_t uiIFrameInterval /* = 10 */)
{
// Check if a resolution was specified that requires encryption
if (eResolution == RESOLUTION320X480 ||
eResolution == RESOLUTION640X240 ||
eResolution == RESOLUTION640X480)
{
// Enable encryption to enable requested resolution
EncryptionMessage message;
if (!SendReceiveMessage(m_socCommunication, &message) ||
!m_receivedMessages.bEncryptionMessage)
return false;
}
// Create and send video message with all the stream details
SettingsMessage message(eResolution, uiVideoBitrate, uiFrameRate, uiVideoSmoothing,
uiAudioBitrate, uiIFrameInterval);
if (!SendReceiveMessage(m_socCommunication, &message) ||
!m_receivedMessages.bSettingsMessage)
return false;
// Give the Slingbox time to change settings
Wait(500);
return true;
}
// Function used to start the stream.
bool CSlingbox::StartStream()
{
// Check if a stream connection is already open
if (m_socStream != INVALID_SOCKET)
return false;
// Open a new connection
m_socStream = OpenSocket(m_szAddress, m_uiPort);
if (m_socStream != INVALID_SOCKET)
{
// Prepare and send string
char szString[128] = "GET /stream.asf HTTP/1.1\r\nAccept: */*\r\n"
"Pragma: Sling-Connection-Type=Stream, Session-Id=";
sprintf(&szString[strlen(szString)], "%u", m_usCode);
strcpy(&szString[strlen(szString)], "\r\n\r\n");
if (Send(m_socStream, (void *)szString, strlen(szString)) <= 0)
{
// Close the stream connection
CloseSocket(m_socStream);
m_socStream = INVALID_SOCKET;
return false;
}
// Invalidate channel and input variables
m_iChannel = -1;
m_iInput = -1;
// Give the Slingbox time to respond
Wait(250);
// Check for correct return message
if (!ReceiveMessage(m_socCommunication) ||
!(m_receivedMessages.bChannelStatusMessage ||
m_receivedMessages.bInputStatusMessage))
{
// Close the stream connection
CloseSocket(m_socStream);
m_socStream = INVALID_SOCKET;
return false;
}
}
else
{
return false;
}
return true;
}
// Function used to read the stream. Returns number of bytes actually received
// or -1 if an error occured.
int CSlingbox::ReadStream(void * pBuffer, unsigned int uiSize)
{
return Receive(m_socStream, pBuffer, uiSize);
}
// Function used to stop the stream.
bool CSlingbox::StopStream()
{
// Close the stream connection
bool bSuccess = CloseSocket(m_socStream);
m_socStream = INVALID_SOCKET;
// Invalidate channel and input variables
m_iChannel = -1;
m_iInput = -1;
return bSuccess;
}
// Function used to disconnect from the Slingbox
bool CSlingbox::Disconnect()
{
// Prepare variables
bool bSuccess = true;
// Prepare and send the disconnect message
DisconnectMessage message;
if (!SendReceiveMessage(m_socCommunication, &message) ||
!m_receivedMessages.bDisconnectMessage)
bSuccess = false;
// Close the stream connection if it's still active
if (m_socStream != INVALID_SOCKET && !StopStream())
bSuccess = false;
// Close the communication connection
if (!CloseSocket(m_socCommunication))
bSuccess = false;
m_socCommunication = INVALID_SOCKET;
#if defined _WIN32 || defined _WIN64
// Finish using the Winsock DLL
if (WSACleanup() != 0)
bSuccess = false;
#endif
// Invalidate variables
m_usCode = 0;
m_usSequence = 0;
m_iChannel = -1;
m_iInput = -1;
return bSuccess;
}
// Function used to check if a connection to the Slingbox is active
bool CSlingbox::IsConnected()
{
// Prepare and send status message
StatusMessage message;
return SendReceiveMessage(m_socCommunication, &message) &&
m_receivedMessages.bStatusMessage;
}
// Function used to change the channel up.
bool CSlingbox::ChannelUp()
{
// Prepare and send channel message
ChannelMessage message;
message.Up();
if (!SendMessage(m_socCommunication, &message))
return false;
// Invalidate channel variable
m_iChannel = -1;
// Give the Slingbox time to change things
Wait(1000);
// Check for return message
return ReceiveMessage(m_socCommunication) &&
m_receivedMessages.bChannelMessage;
}
// Function used to change the channel down.
bool CSlingbox::ChannelDown()
{
// Prepare and send channel message
ChannelMessage message;
message.Down();
if (!SendMessage(m_socCommunication, &message))
return false;
// Invalidate channel variable
m_iChannel = -1;
// Give the Slingbox time to change things
Wait(1000);
// Check for return message
return ReceiveMessage(m_socCommunication) &&
m_receivedMessages.bChannelMessage;
}
// Function used to set the channel.
bool CSlingbox::SetChannel(unsigned int uiChannel)
{
// Prepare and send channel message
ChannelMessage message(uiChannel);
if (!SendMessage(m_socCommunication, &message))
return false;
// Invalidate channel variable
m_iChannel = -1;
// Give the Slingbox time to change things
Wait(1000);
// Check for return message
return ReceiveMessage(m_socCommunication) &&
m_receivedMessages.bChannelMessage;
}
// Function used to set the input.
bool CSlingbox::SetInput(unsigned int uiInput)
{
// Prepare and send input message
InputMessage message(uiInput);
if (!SendMessage(m_socCommunication, &message))
return false;
// Invalidate input variable
m_iInput = -1;
// Give the Slingbox time to change things
Wait(1000);
// Check for return message
return ReceiveMessage(m_socCommunication) &&
m_receivedMessages.bInputMessage;
}
// Function used to get the current channel. Returns -1 if valid data is not
// available.
int CSlingbox::GetChannel()
{
return m_iChannel;
}
// Function used to get the current input. Returns -1 if valid data is not
// available.
int CSlingbox::GetInput()
{
return m_iInput;
}
// Function used to send IR commands.
bool CSlingbox::SendIRCommand(uint8_t ucCode)
{
// Prepare and send IR message
IRMessage message(ucCode);
if (!SendMessage(m_socCommunication, &message))
return false;
// Give the Slingbox time to send command
Wait(1000);
// Check for return message
return ReceiveMessage(m_socCommunication) &&
m_receivedMessages.bIRMessage;
}
// ********************
// Protected Functions
// ********************
// Function used to send a message and receive messages.
bool CSlingbox::SendReceiveMessage(SOCKET socSocket, MessageHeader * pHeader,
bool bEncrypt /* = true */, unsigned int uiTimeout /* = 10 */)
{
// Send message
if (!SendMessage(socSocket, pHeader, bEncrypt, uiTimeout))
return false;
// Give the Slingbox time to respond
Wait(250);
// Receive messages
if (!ReceiveMessage(socSocket, false, uiTimeout))
return false;
return true;
}
// Function used to send a messages to the Slingbox.
bool CSlingbox::SendMessage(SOCKET socSocket, MessageHeader * pHeader,
bool bEncode /* = true */, unsigned int uiTimeout /* = 10 */)
{
// Set message code and sequence numbers
pHeader->m_usCode = m_usCode;
pHeader->m_usSequence = m_usSequence;
m_usSequence++;
// Check if we need to encode the data from the message
if (bEncode)
{
void* pPointer = ((uint8_t *)pHeader) + sizeof(MessageHeader);
Encode(pPointer, pHeader->m_usSize);
pHeader->m_usEncoded = 0x2000;
}
// Send the message
if (Send(socSocket, pHeader, sizeof(MessageHeader) +
pHeader->m_usSize, uiTimeout) <= 0)
return false;
return true;
}
// Function used to receive messages from the Slingbox and process them.
bool CSlingbox::ReceiveMessage(SOCKET socSocket, bool bUDPMessage /* = false */,
unsigned int uiTimeout /* = 10 */)
{
// Prepare variables
bool bMessageReceived = false;
int iReceived;
int iProcessed = 0;
uint8_t ucBuffer[1024];
sockaddr sSocketAddress;
memset(&sSocketAddress, 0, sizeof(sSocketAddress));
// Reset received messages struct
memset(&m_receivedMessages, 0, sizeof(m_receivedMessages));
// Get the data
if (bUDPMessage)
{
iReceived = ReceiveFrom(socSocket, ucBuffer, sizeof(ucBuffer), uiTimeout,
&sSocketAddress);
}
else
{
iReceived = Receive(socSocket, ucBuffer, sizeof(ucBuffer), uiTimeout);
}
// Check for errors
if (iReceived == SOCKET_ERROR)
return false;
// Loop until we've processed all received data
while (iProcessed < iReceived)
{
// Prepare pointer
MessageHeader * pHeader = (MessageHeader *)(ucBuffer + iProcessed);
// Make sure it's a message and we got enough data to work with
if (pHeader->m_usHeader == 0x0101 && (iReceived - iProcessed) >=
(int)(sizeof(MessageHeader) + pHeader->m_usSize))
{
// Signal that we've recevied a message
bMessageReceived = true;
// Decode the message data
if (pHeader->m_usEncoded == 0x2000)
{
Decode((uint8_t *)pHeader + sizeof(MessageHeader), pHeader->m_usSize);
pHeader->m_usEncoded = 0x0000;
}
// Find message
if (pHeader->m_usMessageID == 0x0002 && pHeader->m_usSize == 0x005C)
{
m_receivedMessages.bFindMessage = true;
// Remove the port information from the structure received from ReceiveFrom
if (sSocketAddress.sa_family == AF_INET)
((sockaddr_in *)&sSocketAddress)->sin_port = 0;
else if (sSocketAddress.sa_family == AF_INET6)
((sockaddr_in6 *)&sSocketAddress)->sin6_port = 0;
// Convert the address received from ReceiveFrom to a string
#if defined _WIN32 || defined _WIN64
unsigned long ulSizeOfAddress = sizeof(m_szAddress);
WSAAddressToString(&sSocketAddress, sizeof(sSocketAddress), NULL,
m_szAddress, &ulSizeOfAddress);
#else
socklen_t iSizeOfAddress = sizeof(m_szAddress);
if (sSocketAddress.sa_family == AF_INET)
inet_ntop(sSocketAddress.sa_family,
&((sockaddr_in *)&sSocketAddress)->sin_addr, m_szAddress, iSizeOfAddress);
else if (sSocketAddress.sa_family == AF_INET6)
inet_ntop(sSocketAddress.sa_family,
&((sockaddr_in6 *)&sSocketAddress)->sin6_addr, m_szAddress, iSizeOfAddress);
#endif
// Get the port information from the received data
m_uiPort = ucBuffer[120] + (ucBuffer[121] << 8);
}
// Connect message
else if (pHeader->m_usMessageID == 0x0067 && pHeader->m_usSize == 0x0008)
{
m_receivedMessages.bConnectMessage = true;
m_usCode = pHeader->m_usCode;
}
// Initialization message
else if (pHeader->m_usMessageID == 0x007E)
{
m_receivedMessages.bInitializationMessage = true;
}
// Encryption message
else if (pHeader->m_usMessageID == 0x00A6)
{
m_receivedMessages.bEncryptionMessage = true;
}
// Settings message
else if (pHeader->m_usMessageID == 0x00B5)
{
m_receivedMessages.bSettingsMessage = true;
}
// Disconnect message
else if (pHeader->m_usMessageID == 0x0068)
{
m_receivedMessages.bDisconnectMessage = true;
}
// Status message
else if (pHeader->m_usMessageID == 0x0065 && pHeader->m_usSize == 0x0000)
{
m_receivedMessages.bStatusMessage = true;
}
// Channel message
else if (pHeader->m_usMessageID == 0x0089)
{
m_receivedMessages.bChannelMessage = true;
}
// Channel status massage
else if (pHeader->m_usMessageID == 0x0065 && pHeader->m_usSize == 0x0078)
{
m_receivedMessages.bChannelStatusMessage = true;
m_iChannel = *(uint16_t *)((uint8_t *)pHeader + sizeof(MessageHeader));
}
// Input message
else if (pHeader->m_usMessageID == 0x0085)
{
m_receivedMessages.bInputMessage = true;
}
// Input status message
else if (pHeader->m_usMessageID == 0x0065 && pHeader->m_usSize == 0x0008)
{
m_receivedMessages.bInputStatusMessage = true;
m_iInput = *((uint8_t *)pHeader + sizeof(MessageHeader));
}
// IR message
else if (pHeader->m_usMessageID == 0x0087)
{
m_receivedMessages.bIRMessage = true;
}
// Increase our counter
iProcessed += sizeof(MessageHeader) + pHeader->m_usSize;
}
else
{
return bMessageReceived;
}
}
return bMessageReceived;
}
// Function used to encode data being send to the Slingbox.
void CSlingbox::Encode(void * pData, unsigned int iSize)
{
for (unsigned int i = 0; i < iSize; i += 8)
{
// Prepare variables
const uint32_t ulKey[] = {0xBCDEAAAA, 0x87FBBBBA, 0x7CCCCFFA, 0xDDDDAABC};
uint32_t ulVar1 = ((uint32_t *)&((uint8_t *)pData)[i])[0];
uint32_t ulVar2 = ((uint32_t *)&((uint8_t *)pData)[i])[1];
uint32_t ulVar3 = 0;
// Encode
for (unsigned int j = 0; j < 32; j++)
{
ulVar3 -= 0x61C88647;
ulVar1 += ((ulVar2 >> 5) + ulKey[1]) ^ ((ulVar2 << 4) + ulKey[0]) ^ (ulVar3 +
ulVar2);
ulVar2 += ((ulVar1 >> 5) + ulKey[3]) ^ ((ulVar1 << 4) + ulKey[2]) ^ (ulVar3 +
ulVar1);
}
// Finish up
((uint32_t *)&((uint8_t *)pData)[i])[0] = ulVar1;
((uint32_t *)&((uint8_t *)pData)[i])[1] = ulVar2;
}
}
// Function used to decode data being received from the Slingbox.
void CSlingbox::Decode(void * pData, unsigned int iSize)
{
for (unsigned int i = 0 ; i < iSize; i += 8 )
{
// Prepare variables
const uint32_t ulKey[] = {0xBCDEAAAA, 0x87FBBBBA, 0x7CCCCFFA, 0xDDDDAABC};
uint32_t ulVar1 = ((uint32_t *)&((uint8_t *)pData)[i])[0];
uint32_t ulVar2 = ((uint32_t *)&((uint8_t *)pData)[i])[1];
uint32_t ulVar3 = 0xC6EF3720;
// Decode
for (unsigned int j = 0; j < 32; j++)
{
ulVar2 -= ((ulVar1 >> 5) + ulKey[3]) ^ ((ulVar1 << 4) + ulKey[2]) ^ (ulVar3 +
ulVar1);
ulVar1 -= ((ulVar2 >> 5) + ulKey[1]) ^ ((ulVar2 << 4) + ulKey[0]) ^ (ulVar3 +
ulVar2);
ulVar3 += 0x61C88647;
}
// Finish up
((uint32_t *)&((uint8_t *)pData)[i])[0] = ulVar1;
((uint32_t *)&((uint8_t *)pData)[i])[1] = ulVar2;
}
}
// Function used to open a new socket.
SOCKET CSlingbox::OpenSocket(const char * szAddress, unsigned int uiPort,
bool bUDP /* = false */)
{
// Prepare needed variables
SOCKET socSocket = INVALID_SOCKET;
struct addrinfo * pAddressInfo;
struct addrinfo addressInfoHints;
struct addrinfo * pPointer;
memset(&addressInfoHints, 0, sizeof(addressInfoHints));
addressInfoHints.ai_family = bUDP ? AF_INET : AF_UNSPEC;
addressInfoHints.ai_socktype = bUDP ? SOCK_DGRAM : SOCK_STREAM;
addressInfoHints.ai_protocol = bUDP ? IPPROTO_UDP : IPPROTO_TCP;
addressInfoHints.ai_flags = bUDP ? AI_PASSIVE : 0;
char szPort[32];
sprintf(szPort, "%u", uiPort);
// Get address info
if (getaddrinfo(szAddress, szPort, &addressInfoHints, &pAddressInfo) != 0)
return INVALID_SOCKET;
// Loop thru all the received address info
for (pPointer = pAddressInfo; pPointer != NULL; pPointer = pPointer->ai_next)
{
// Open a new socket
socSocket = socket(pPointer->ai_family, pPointer->ai_socktype,
pPointer->ai_protocol);
if (socSocket != INVALID_SOCKET)
{
// Bind if we're using UDP
if (bUDP)
{
if (bind(socSocket, pAddressInfo->ai_addr, pAddressInfo->ai_addrlen) == 0)
{
break;
}
else
{
CloseSocket(socSocket);
socSocket = INVALID_SOCKET;
}
}
// Open a new connection if we're using TCP
else
{
if (connect(socSocket, pAddressInfo->ai_addr, pAddressInfo->ai_addrlen) == 0)
{
break;
}
else
{
CloseSocket(socSocket);
socSocket = INVALID_SOCKET;
}
}
}
}
// Free variables
freeaddrinfo(pAddressInfo);
return socSocket;
}
// Function used to broadcast data to the local subnet. Returns the number of bytes
// actually sent or -1 if an error occured.
int CSlingbox::Broadcast(SOCKET socSocket, unsigned int uiPort, void * pBuffer,
unsigned int uiSize, unsigned int uiTimeout /* = 10 */)
{
// Enable broadcasting
#if defined _WIN32 || defined _WIN64
char vBroadcast = '1';
#else
int vBroadcast = 1;
#endif
if (setsockopt(socSocket, SOL_SOCKET, SO_BROADCAST, &vBroadcast,
sizeof(vBroadcast)) != 0)
return SOCKET_ERROR;
// Prepare variable
struct sockaddr sSocketAddress;
memset(&sSocketAddress, 0, sizeof(sSocketAddress));
((sockaddr_in *)&sSocketAddress)->sin_family = AF_INET;
#if defined _WIN32 || defined _WIN64
((sockaddr_in *)&sSocketAddress)->sin_addr.S_un.S_addr = htonl(0xFFFFFFFF);
#else
((sockaddr_in *)&sSocketAddress)->sin_addr.s_addr = htonl(0xFFFFFFFF);
#endif
((sockaddr_in *)&sSocketAddress)->sin_port = htons(uiPort);
// Send the data
return SendTo(socSocket, pBuffer, uiSize, uiTimeout, &sSocketAddress);
}
// Function used to send data. Returns the number of bytes actually sent
// or -1 if an error occured.
int CSlingbox::Send(SOCKET socSocket, void * pBuffer, unsigned int uiSize,
unsigned int uiTimeout /* = 10 */)
{
// Prepare variables
int iFDS = socSocket + 1;
fd_set sendFDS;
FD_ZERO(&sendFDS);
FD_SET(socSocket, &sendFDS);
timeval timeOut;
timeOut.tv_sec = uiTimeout;
timeOut.tv_usec = 0;
int iResult;
unsigned int uiBytesSent = 0;
unsigned int uiBytesLeft = uiSize;
// Loop until all data is sent
while (uiBytesSent < uiSize)
{
// Send the data once the socket is ready
if (select(iFDS, NULL, &sendFDS, NULL, &timeOut) > 0)
iResult = send(socSocket, (const char *)pBuffer + uiBytesSent, uiBytesLeft, 0);
else
return uiBytesSent;
// Check for any errors
if (iResult == SOCKET_ERROR)
return SOCKET_ERROR;
// Adjust variables
uiBytesSent += iResult;
uiBytesLeft -= iResult;
}
return uiBytesSent;
}
// Function used to send data to a specific address. Returns the number of bytes
// actually sent or -1 if an error occured.
int CSlingbox::SendTo(SOCKET socSocket, void * pBuffer, unsigned int uiSize,
unsigned int uiTimeout, struct sockaddr * pSocketAddress)
{
// Prepare variables
int iFDS = socSocket + 1;
fd_set sendFDS;
FD_ZERO(&sendFDS);
FD_SET(socSocket, &sendFDS);
timeval timeOut;
timeOut.tv_sec = uiTimeout;
timeOut.tv_usec = 0;
int iResult;
unsigned int uiBytesSent = 0;
unsigned int uiBytesLeft = uiSize;
// Loop until all data is sent
while (uiBytesSent < uiSize)
{
// Send the data once the socket is ready
if (select(iFDS, NULL, &sendFDS, NULL, &timeOut) > 0)
iResult = sendto(socSocket, (const char *)pBuffer + uiBytesSent, uiBytesLeft, 0,
pSocketAddress, sizeof(*pSocketAddress));
else
return uiBytesSent;
// Check for any errors
if (iResult == SOCKET_ERROR)
return SOCKET_ERROR;
// Adjust variables
uiBytesSent += iResult;
uiBytesLeft -= iResult;
}
return uiBytesSent;
}
// Function used to receive data. Returns the number of bytes actually received
// or -1 if an error occured.
int CSlingbox::Receive(SOCKET socSocket, void * pBuffer, unsigned int uiSize,
unsigned int uiTimeout /* = 10 */)
{
// Prepare needed variables
int iFDS = socSocket + 1;
fd_set readFDS;
FD_ZERO(&readFDS);
FD_SET(socSocket, &readFDS);
timeval timeValue;
timeValue.tv_sec = uiTimeout;
timeValue.tv_usec = 0;
// Do the actual receiving of data after waiting for socket to be readable
if (select(iFDS, &readFDS, NULL, NULL, &timeValue) > 0)
return recv(socSocket, (char *)pBuffer, uiSize, 0);
else
return 0;
}
// Function used to receive data and tell us from where. Returns the number of bytes
// actually received or -1 if an error occured. If successful, populates the
// pSocketAddress variable with details of where the data was received from.
int CSlingbox::ReceiveFrom(SOCKET socSocket, void * pBuffer, unsigned int uiSize,
unsigned int uiTimeout, struct sockaddr * pSocketAddress)
{
// Prepare needed variables
int iFDS = socSocket + 1;
fd_set readFDS;
FD_ZERO(&readFDS);
FD_SET(socSocket, &readFDS);
timeval timeValue;
timeValue.tv_sec = uiTimeout;
timeValue.tv_usec = 0;
socklen_t iSizeOfAddress = sizeof(*pSocketAddress);
// Do the actual receiving of data after waiting for socket to be readable
if (select(iFDS, &readFDS, NULL, NULL, &timeValue) > 0)
return recvfrom(socSocket, (char *)pBuffer, uiSize, 0, pSocketAddress,
&iSizeOfAddress);
else
return 0;
}
// Function used to close a socket connection.
bool CSlingbox::CloseSocket(SOCKET socSocket)
{
#if defined _WIN32 || defined _WIN64
if (closesocket(socSocket) != 0)
return false;
#else
if (close(socSocket) != 0)
return false;
#endif
return true;
}
// Function used to wait on the Slingbox for various reasons
void CSlingbox::Wait(unsigned int uiMilliseconds)
{
#if defined _WIN32 || defined _WIN64
Sleep(uiMilliseconds);
#else
struct timespec time;
time.tv_sec = uiMilliseconds / 1000;
time.tv_nsec = (uiMilliseconds % 1000) * 1000000;
while (nanosleep(&time, &time) == -1 && errno == EINTR &&
(time.tv_sec > 0 || time.tv_nsec > 0));
#endif
}
|
[
"[email protected]"
] |
[
[
[
1,
986
]
]
] |
b6a86ac75ef852a040bd7746fa66c76ad7dd2b5c
|
3d9323ae99d831e49a70653954c6f6633b947a98
|
/project 07 - VM - Stack Arithmetic/VMtranslator.cpp
|
ca1c68c7ef130fef84ada5b655fa123407f214e5
|
[] |
no_license
|
rkaganov/nand-to-tetris
|
ada51e3b43c3313eed233f2834c69c5b692fe1c3
|
7572408f9ee33a19a85b20cf29d844b4ca44e409
|
refs/heads/master
| 2020-05-20T05:52:34.484843 | 2009-12-09T20:26:33 | 2009-12-09T20:26:33 | 34,325,939 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,289 |
cpp
|
#include<fstream>
#include<iostream>
#include<string>
#define CALL_STACK_MAX 200
using namespace std;
enum cmdType {C_ARITHMETIC, C_PUSH, C_POP, C_LABEL, C_GOTO, C_IF, C_FUNCTION, C_RETURN, C_CALL};
class Parser{
fstream VM;
int lineNumber;
string currentCommand;
public:
Parser(char* filename){
VM.open(filename,ios::in);
if(VM.fail()){
cout << filename << " cannot be found\nPlease check whether you have entered the correct pathname\n";
getchar(); exit(0);
}
VM.unsetf(ios::skipws);
lineNumber=0;
}
~Parser(){VM.close();}
bool hasMoreCommands(){
if(VM.fail()) return false;
return true;
}
int advance();
cmdType commandType();
void argument(string&,int&);
};
class CodeWriter{
fstream Asm;
string fileName, funcName[CALL_STACK_MAX];
int trueCount,callCount,curFunction;
public:
CodeWriter(char* filename){
fileName=filename;
string file=fileName;
file.erase(file.size()-2,2);
file+="asm";
Asm.open(file.c_str(),ios::out);
fileName.erase(0,fileName.find_last_of('/')+1);
trueCount=0;
curFunction=0;
callCount=0;
}
~CodeWriter(){
Asm << "(INFINITE_LOOP)\n@INFINITE_LOOP\n0;JEQ\n";
Asm.close();
}
void writeInit();
void writeArithmetic(string);
void writePushPop(cmdType,string,int);
void writeLabel(string);
void writeGoto(string);
void writeIf(string);
void writeCall(string,int);
void writeReturn();
void writeFunction(string,int);
};
int Parser::advance(){
char ch;
string funcCommand;
currentCommand.erase(0,currentCommand.size());
while(hasMoreCommands()){
VM >> ch;
if(ch=='\n'){
if(currentCommand.size()!=0){lineNumber++; break;}
else continue;
}
if(ch!=' '&&ch!='\t'&&ch!='\n'&&ch!='\r'){currentCommand+=ch; funcCommand+=ch;}
if(ch==' '||ch=='\t'){funcCommand+=' ';}
if(currentCommand[currentCommand.size()-1]=='/'&¤tCommand[currentCommand.size()-2]=='/'){
currentCommand.erase(currentCommand.size()-2, 2);
funcCommand.erase(funcCommand.size()-2,2);
VM >> ch;
while(ch!='\n') VM >> ch;
if(currentCommand.size()!=0){
lineNumber++; break;}
}
}
if(!hasMoreCommands()) return -1;
if(commandType()==C_FUNCTION||commandType()==C_CALL) currentCommand=funcCommand;
return 0;
}
cmdType Parser::commandType(){
if(currentCommand=="add"||currentCommand=="sub"||currentCommand=="neg"||
currentCommand=="and"||currentCommand=="not"||currentCommand=="eq"||
currentCommand=="gt"||currentCommand=="lt"||currentCommand=="or")
return C_ARITHMETIC;
if(currentCommand.find("push")==0) return C_PUSH;
if(currentCommand.find("pop")==0) return C_POP;
if(currentCommand.find("label")==0) return C_LABEL;
if(currentCommand.find("goto")==0) return C_GOTO;
if(currentCommand.find("if-goto")==0) return C_IF;
if(currentCommand.find("function")==0) return C_FUNCTION;
if(currentCommand.find("call")==0) return C_CALL;
if(currentCommand=="return") return C_RETURN;
cout << lineNumber << ": Invalid command\n";
getchar();
exit(0);
}
void Parser::argument(string& arg1, int& arg2){
string arg=currentCommand;
if(commandType()==C_ARITHMETIC)arg1=arg;
else if(commandType()==C_PUSH||commandType()==C_POP){
if(commandType()==C_PUSH) arg.erase(0,4);
else arg.erase(0,3);
if(arg.find("argument")==0) arg1="argument";
else if(arg.find("local")==0) arg1="local";
else if(arg.find("static")==0) arg1="static";
else if(arg.find("this")==0) arg1="this";
else if(arg.find("that")==0) arg1="that";
else if(arg.find("pointer")==0) arg1="pointer";
else if(arg.find("temp")==0) arg1="temp";
else if(arg.find("constant")==0) arg1="constant";
else { cout << lineNumber << ": Segment name missing in a Push/Pop instruction\n";
getchar();
exit(0); }
arg.erase(0,arg1.size());
if(arg.size()==0) {
cout << lineNumber << ": Segment index missing in a Push/Pop instruction\n";
getchar();
exit(0);
}
arg2=0;
for(int i=0;i<arg.size();i++)
arg2=(arg2*10+arg[i]-'0');
}
else if(commandType()==C_LABEL){ arg.erase(0,5); arg1=arg; }
else if(commandType()==C_GOTO){ arg.erase(0,4); arg1=arg; }
else if(commandType()==C_IF){ arg.erase(0,7); arg1=arg; }
else if(commandType()==C_FUNCTION||commandType()==C_CALL){
if(commandType()==C_FUNCTION) arg.erase(0,9);
else arg.erase(0,5);
arg1=arg;
arg.erase(0,arg.find(" ")+1);
arg1.erase(arg1.find(" "),arg.size()+1);
if(arg.size()==0) {
cout << lineNumber << ": Number of arguments not specified in a Function/Call instruction\n";
getchar();
exit(0);
}
arg2=0;
for(int i=0;i<arg.size();i++)
arg2=(arg2*10+arg[i]-'0');
}
}
void CodeWriter::writeInit(){
Asm << "@256\nD=A\n@SP\nM=D\n)";
writeCall("Sys.init",0);
}
void CodeWriter::writeArithmetic(string command){
Asm << "@SP\nA=M-1\n";
if(command=="neg") Asm << "M=-M\n";
else if(command=="not") Asm << "M=!M\n";
else{
Asm << "D=M\n@SP\nAM=M-1\nM=0\nA=A-1\n";
if(command=="add") Asm << "M=M+D\n";
else if(command=="sub") Asm << "M=M-D\n";
else if(command=="and") Asm << "M=M&D\n";
else if(command=="or") Asm << "M=M|D\n";
else{
Asm << "D=M-D\n@TRUE" << trueCount << "\nD;J";
if(command=="eq") Asm << "EQ";
else if(command=="lt") Asm << "LT";
else if(command=="gt") Asm << "GT";
Asm << "\n@SP\nA=M-1\nM=0\n@FALSE" << trueCount << "\n0;JEQ\n(TRUE" << trueCount
<< ")\n@SP\nA=M-1\nM=-1\n" << "(FALSE" << trueCount << ")\n";
trueCount++;
}
}
}
void CodeWriter::writePushPop(cmdType command, string segment, int index){
if(segment=="static"&&index>240){
cout << "Index of a static variable > 240\n"; getchar(); exit(0); }
string strIndex;
strIndex+=(index+'0');
if(command==C_POP&&segment=="constant"){
cout << "Popping into a constant is invalid\n";
getchar();
exit(0);
}
if(segment=="local") Asm << "@LCL\nD=M";
else if(segment=="argument") Asm << "@ARG\nD=M";
else if(segment=="this") Asm << "@THIS\nD=M";
else if(segment=="that") Asm << "@THAT\nD=M";
else if(segment=="temp") Asm << "@5\nD=A";
else if(segment=="pointer") Asm << "@3\nD=A";
else if(segment=="static") Asm << "@" << fileName << "." << index << "\nD=A";
else if(segment=="constant"){
if(index==0||index==1) Asm << "\nD=" << index;
else Asm << "@" << index << "\nD=A";
}
if(segment!="static"&&segment!="constant"&&index!=0)
Asm << "\n@" << index << "\nD=D+A";
if(command==C_PUSH){
if(segment=="constant") Asm << "\n@SP\nAM=M+1\nA=A-1\nM=D\n";
else Asm << "\nA=D\nD=M\n@SP\nAM=M+1\nA=A-1\nM=D\n";
}
else Asm << "\n@R13\nM=D\n@SP\nAM=M-1\nD=M\nM=0\n@R13\nA=M\nM=D\n";
}
void CodeWriter::writeLabel(string label){
Asm << "(" << funcName[curFunction-1] << "." << label << ")\n";
}
void CodeWriter::writeGoto(string label){
Asm << "@" << funcName[curFunction-1] << "." << label << "\n0;JMP\n";
}
void CodeWriter::writeIf(string label){
Asm << "@SP\nA=M-1\nD=M\n@" << funcName[curFunction-1] << "." << label
<< "\nD=D+1;JEQ\n";
}
void CodeWriter::writeCall(string functionName,int numArgs){
callCount++;
string pushString="\nD=A\n@SP\nAM=M+1\nA=A-1\nM=D\n";
Asm << "@RETURN_ADDRESS." << callCount << pushString
<< "@LCL" << pushString
<< "@ARG" << pushString
<< "@THIS" << pushString
<< "@THAT" << pushString
<< "@SP\nD=A\n@" << numArgs << "\nD=D-A\n@5\nD=D-A\n@ARG\nM=D\n"
<< "@SP\nD=A\n@LCL\nM=D\n";
writeGoto(functionName);
Asm << "(" << "RETURN_ADDRESS." << callCount << ")\n";
funcName[curFunction++]=functionName;
}
void CodeWriter::writeReturn(){
Asm << "@LCL\nD=A\n@R13\nM=D\n"
<< "@5\nAD=D-A\nD=M\n@R14\nM=D\n"
<< "@SP\nM=M-1\nA=M\nD=M\nM=0\n@ARG\nM=D\n"
<< "@ARG\nD=A+1\n@SP\nM=D\n"
<< "@R13\nD=M-1\n@THAT\nM=D\n"
<< "@THIS\nDM=D-1\n"
<< "@ARG\nDM=D-1\n"
<< "@LCL\nDM=D-1\n"
<< "@R14\nA=M\n0;JMP\n";
curFunction--;
}
void CodeWriter::writeFunction(string functionName, int numLocals){
Asm << "@" << numLocals << "\nD=A\n"
<< "(" << funcName[curFunction-1] << "." << functionName << ")\n"
<< "@" << funcName[curFunction-1] << "." << functionName << "\n"
<< "@SP\nAM=M+1\nA=A-1\nM=0\n"
<< "D=D-1;JEQ";
}
void translate(char* filename){
Parser p(filename);
CodeWriter c(filename);
while(p.hasMoreCommands()){
string command;
int index=-1;
if(p.advance()==-1) return;
if(p.commandType()!=C_RETURN)
p.argument(command, index);
if(p.commandType()==C_ARITHMETIC){
if(index==-1) c.writeArithmetic(command);
else{
cout << "Invalid Arithmetic Command\n"; getchar(); exit(0);
}
}
else if(p.commandType()==C_PUSH||p.commandType()==C_POP)
c.writePushPop(p.commandType(),command,index);
}
}
int main(int argc, char** argv){
if(argc==2){
translate(argv[1]);
cout << argv[1] << " successfully translated\n";}
else
cout << "Correct Syntax is: ./VMtranslator.out <filename>\n";
getchar();
return 0;
}
|
[
"[email protected]@4a2a3032-e4fa-11de-a347-f34a4f72eb7d"
] |
[
[
[
1,
289
]
]
] |
2932e0ad3f68dfe62892c73ffd2725b719e08f75
|
a699a508742a0fd3c07901ab690cdeba2544a5d1
|
/RailwayDetection/RWDSClient/TCPTransmit.h
|
c862d5f212b8e1b905ad62eba5296ebf978ef0b5
|
[] |
no_license
|
xiaomailong/railway-detection
|
2bf92126bceaa9aebd193b570ca6cd5556faef5b
|
62e998f5de86ee2b6282ea71b592bc55ee25fe14
|
refs/heads/master
| 2021-01-17T06:04:48.782266 | 2011-09-27T15:13:55 | 2011-09-27T15:13:55 | 42,157,845 | 0 | 1 | null | 2015-09-09T05:24:10 | 2015-09-09T05:24:09 | null |
UTF-8
|
C++
| false | false | 1,569 |
h
|
#pragma once
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
/*
typedef struct _TCP_KEEPALIVE
{
u_long onoff;
u_long keepalivetime;
u_long keepaliveinterval;
}TCP_KeepAlive;*/
#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
class CSocketServer
{
public:
CSocketServer(void);
virtual ~CSocketServer(void);
public:
//virtual int Write(char *lpSendBuf, int iBufLen, char *lpDestIP=INADDR_ANY, int iDestPort=0) = 0;
//virtual int Read(char *lpReadBuf, int iBufLen, char *lpFromIP=INADDR_ANY, int iFromPort=0) = 0;
//virtual int Open(int iPort, int iListen=10, char *lpIP=INADDR_ANY) = 0;
public:
virtual void Close();
virtual int WaitForData(DWORD dwWaitTimeOut);
SOCKET GetSocket();
protected:
bool m_bOpen;
int m_iPort;
SOCKET m_sSocket;
};
class CTCPClient : public CSocketServer
{
public:
CTCPClient(void);
virtual ~CTCPClient(void);
public:
int Open(int iPort, char *lpIP);
int Read(char *lpReadBuf, int iBufLen);
int Write(char *lpSendBuf, int iBufLen);
};
class CTCPServer : public CTCPClient
{
public:
CTCPServer(void);
~CTCPServer(void);
public:
int SetSocketServer(SOCKET server);
int SetClientIPPort(char* IP, int Port);
void GetClientIPPort(char* IP, int *Port);
void Close();
private:
char m_lpClientIP[16];
int m_iClientPort;
};
class CTCPService : public CSocketServer
{
public:
CTCPService(void);
~CTCPService(void);
public:
int Open(int iPort, int iListen);
int AcceptSocket(CTCPServer *cAcceptTCP, DWORD dwTimeout);
private:
int m_iListen;
};
|
[
"[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3"
] |
[
[
[
1,
67
]
]
] |
eaa1e8cedd43de8132876330e14b857ba1c12c82
|
709cd826da3ae55945fd7036ecf872ee7cdbd82a
|
/Term/WildMagic2/Applications/Physics/BouncingBall/DeformableBall.cpp
|
849b0577aa235b5622d01e4fa643f7106e9e5a04
|
[] |
no_license
|
argapratama/kucgbowling
|
20dbaefe1596358156691e81ccceb9151b15efb0
|
65e40b6f33c5511bddf0fa350c1eefc647ace48a
|
refs/heads/master
| 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 10,048 |
cpp
|
// Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Game Physics source code is supplied under the terms of the license
// agreement http://www.magic-software.com/License/GamePhysics.pdf and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
#include "DeformableBall.h"
#include "WmlExtractSurfaceCubes.h"
#include "WmlTextureState.h"
using namespace Wml;
using namespace std;
//----------------------------------------------------------------------------
DeformableBall::DeformableBall (float fDuration, float fPeriod)
{
Set(fDuration,fPeriod);
m_bDeforming = false;
m_bDoAffine = true;
CreateBall();
}
//----------------------------------------------------------------------------
DeformableBall::~DeformableBall ()
{
m_spkMesh = NULL;
}
//----------------------------------------------------------------------------
void DeformableBall::Set (float fDuration, float fPeriod)
{
m_fDuration = fDuration;
m_fDeformMult = 4.0f/(m_fDuration*m_fDuration);
m_fPeriod = fPeriod;
m_fMinActive = 0.5f*(m_fPeriod - m_fDuration);
m_fMaxActive = 0.5f*(m_fPeriod + m_fDuration);
m_fInvActiveRange = 1.0f/(m_fMaxActive - m_fMinActive);
}
//----------------------------------------------------------------------------
void DeformableBall::CreateBall ()
{
// create initial image for surface extraction (16x16x16)
const int iBound = 16;
float fInvBm1 = 1.0f/(iBound-1.0f);
int* aiData = new int[iBound*iBound*iBound];
ExtractSurfaceCubes kExtract(iBound,iBound,iBound,aiData);
// scale function values to [-1024,1024]
const float fImageScale = 1024.0f;
// Initialize image and extract level surface F=0. Data stores samples
// for (x,y,z) in [-1,1]x[-1,1]x[0,2].
Vector3f kPos;
int i = 0;
for (int iZ = 0; iZ < iBound; iZ++)
{
kPos.Z() = -0.1f + 2.2f*fInvBm1*iZ;
for (int iY = 0; iY < iBound; iY++)
{
kPos.Y() = -1.1f + 2.2f*fInvBm1*iY;
for (int iX = 0; iX < iBound; iX++)
{
kPos.X() = -1.1f + 2.2f*fInvBm1*iX;
float fFunc;
Vector3f kGrad;
ComputeFunction(kPos,0.0f,fFunc,kGrad);
aiData[i++] = (int)(fImageScale*fFunc);
}
}
}
// extract the level surface
vector<Vector3f> kVA;
vector<TriangleKey> kTA;
kExtract.ExtractContour(0.0f,kVA,kTA);
kExtract.MakeUnique(kVA,kTA);
kExtract.OrientTriangles(kVA,kTA,true);
delete[] aiData;
// Convert to TriMesh object. Keep track of the level value of the
// vertices. Since a vertex might not be exactly on the level surface,
// we will use
// e = max{|F(x,y,z)| : (x,y,z) is a vertex}
// as the error tolerance for Newton's method in the level surface
// evolution.
int iVQuantity = (int)kVA.size();
Vector3f* akVertex = new Vector3f[iVQuantity];
Vector3f* akNormal = new Vector3f[iVQuantity];
Vector2f* akUV = new Vector2f[iVQuantity];
float fMaxLevel = 0.0f;
for (i = 0; i < iVQuantity; i++)
{
akVertex[i].X() = -1.1f + 2.2f*fInvBm1*kVA[i].X();
akVertex[i].Y() = -1.1f + 2.2f*fInvBm1*kVA[i].Y();
akVertex[i].Z() = -0.1f + 2.2f*fInvBm1*kVA[i].Z();
float fLevel = akVertex[i].SquaredLength() - 2.0f*akVertex[i].Z();
if ( Mathf::FAbs(fLevel) > fMaxLevel )
fMaxLevel = Mathf::FAbs(fLevel);
float fWidth = 0.5f*(1.0f+Mathf::ATan2(akVertex[i].Y(),
akVertex[i].Z())/Mathf::PI); // in [0,1)
if ( fWidth < 0.0f )
fWidth = 0.0f;
else if ( fWidth >= 1.0f )
fWidth = 0.999999f;
float fHeight = 0.5f*akVertex[i].Z(); // in [0,1)
if ( fHeight < 0.0f )
fHeight = 0.0f;
else if ( fHeight >= 1.0f )
fHeight = 0.999999f;
akUV[i].X() = fWidth;
akUV[i].Y() = fHeight;
}
int iTQuantity = (int)kTA.size();
int* aiConnect = new int[3*iTQuantity];
int* piConnect = aiConnect;
for (i = 0; i < iTQuantity; i++)
{
*piConnect++ = kTA[i].V[0];
*piConnect++ = kTA[i].V[1];
*piConnect++ = kTA[i].V[2];
}
m_spkMesh = new TriMesh(iVQuantity,akVertex,akNormal,NULL,akUV,iTQuantity,
aiConnect);
m_spkMesh->UpdateModelNormals();
Texture* pkTexture = new Texture;
pkTexture->SetImage(Image::Load("BallTexture.mif"));
pkTexture->Filter() = Texture::FM_LINEAR;
pkTexture->Mipmap() = Texture::MM_LINEAR;
TextureState* pkTS = new TextureState;
pkTS->Set(0,pkTexture);
m_spkMesh->SetRenderState(pkTS);
m_iMaxIterations = 8;
m_fErrorTolerance = fMaxLevel;
Create(iVQuantity,akVertex,iTQuantity,aiConnect);
Update(0.0f);
}
//----------------------------------------------------------------------------
bool DeformableBall::DoSimulationStep (float fRealTime)
{
float fTime = fmodf(fRealTime,m_fPeriod);
if ( m_fMinActive < fTime && fTime < m_fMaxActive )
{
// deform the mesh
m_bDeforming = true;
Update(fTime);
if ( m_bDoAffine )
{
// Nonuniform scaling as a hack to make it appear that the body is
// compressing in the z-direction. The transformations only
// affect the display. If the actual body coordinates were needed
// for other physics, you would have to modify the mesh vertices.
// The second hack is that Wild Magic does not support nonuniform
// scaling. However, by setting the rotation matrix to any
// general matrix, you get the desired scaling. This is safe as
// long as what you do with the TriMesh does not require inverting
// its local or world transformations. The x- and y-scales vary
// from 1 to 1.1 to 1 during the time interval [(p-d)/2,(p+d)/2].
// The z-scale is the inverse of this scale. (Expand radially,
// compress in z-direction.)
const float fMaxExpand = 0.1f;
float fAmp = 4.0f*fMaxExpand*m_fInvActiveRange;
float fXYScale = 1.0f+fAmp*(fTime-m_fMinActive)*
(m_fMaxActive-fTime);
float fZScale = 1.0f/fXYScale;
Matrix3f kMat(fXYScale,0.0f,0.0f,0.0f,fXYScale,0.0f,0.0f,0.0f,
fZScale);
m_spkMesh->Rotate() = kMat;
}
// deformation requires update of bounding sphere
m_spkMesh->UpdateModelBound();
// update occurred, application should update the scene graph
return true;
}
if ( m_bDeforming )
{
// Force restoration of body to its initial state on a transition
// from deforming to nondeforming.
m_bDeforming = false;
Update(0.0f);
if ( m_bDoAffine )
m_spkMesh->Rotate() = Matrix3f::IDENTITY;
m_spkMesh->UpdateModelBound();
return true;
}
m_bDeforming = false;
return false;
}
//----------------------------------------------------------------------------
bool DeformableBall::VertexInfluenced (int i, float fTime)
{
float fRSqr = m_akVertex[i].SquaredLength();
return fRSqr < 1.0f && m_fMinActive < fTime && fTime < m_fMaxActive;
}
//----------------------------------------------------------------------------
float DeformableBall::GetTangentWeight (int i, float)
{
return 0.5f;
}
//----------------------------------------------------------------------------
float DeformableBall::GetNormalWeight (int i, float fTime)
{
// find root of F along line origin+s*dir using Newton's method
float fS = 0.0f;
for (int iIter = 0; iIter < m_iMaxIterations; iIter++)
{
// point of evaluation
Vector3f kPos = m_akVertex[i] + fS*m_akNormal[i];
// get F(pos,time) and Grad(F)(pos,time)
float fFunc;
Vector3f kGrad;
ComputeFunction(kPos,fTime,fFunc,kGrad);
if ( Mathf::FAbs(fFunc) < m_fErrorTolerance )
return fS;
// get directional derivative Dot(dir,Grad(F)(pos,time))
float fDFunc = m_akNormal[i].Dot(kGrad);
if ( Mathf::FAbs(fDFunc) < m_fErrorTolerance )
{
// derivative too close to zero, no change
return 0.0f;
}
fS -= fFunc/fDFunc;
}
// method failed to converge within iteration budget, no change
return 0.0f;
}
//----------------------------------------------------------------------------
void DeformableBall::ComputeFunction (const Vector3f& rkPos, float fTime,
float& rfFunc, Vector3f& rkGrad)
{
// Level function is L(X,t) = F(X) + D(X,t) where F(X) = 0 defines the
// initial body.
// compute F(X) = x^2 + y^2 + z^2 - 2*z and Grad(F)(X)
float fRSqr = rkPos.SquaredLength();
float fF = fRSqr - 2.0f*rkPos.Z();
Vector3f kFGrad = 2.0f*Vector3f(rkPos.X(),rkPos.Y(),rkPos.Z()-1.0f);
// Compute D(X,t) = A(t)*G(X). The duration is d and the period is p.
// The amplitude is
// A(t) = 0, t in [0,p/2-d]
// [t-(p/2-d)][(p/2+d)-t]/d^2, t in [p/2-d,p/2+d]
// 0, t in [p/2+d,p]
// The spatial component is G(X) = 1 - (x^2 + y^2 + z^2)
float fD;
Vector3f kDGrad;
if ( fRSqr < 1.0f && m_fMinActive < fTime && fTime < m_fMaxActive )
{
float fAmp = GetAmplitude(fTime);
fD = fAmp*(1.0f - fRSqr);
kDGrad = -2.0f*fAmp*rkPos;
}
else
{
fD = 0.0f;
kDGrad = Vector3f::ZERO;
}
rfFunc = fF + fD;
rkGrad = kFGrad + kDGrad;
}
//----------------------------------------------------------------------------
|
[
"[email protected]"
] |
[
[
[
1,
280
]
]
] |
4baa1e7863fc0d61c08c5bee8f23d609fc4e0859
|
15f5ea95f75eebb643a9fa4d31592b2537a33030
|
/src/re167/RenderWidget.h
|
3cea9b7e66dda511713aadfffd9d411a06c3bbbd
|
[] |
no_license
|
festus-onboard/graphics
|
90aaf323e188b205661889db2c9ac59ed43bfaa7
|
fdd195cd758ef95147d2d02160062d2014e50e04
|
refs/heads/master
| 2021-05-26T14:38:54.088062 | 2009-05-10T16:59:28 | 2009-05-10T16:59:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 708 |
h
|
#ifndef __RenderWidget_h__
#define __RenderWidget_h__
#include <qwidget>
namespace RE167
{
/** This is an abstract class providing a widget for displaying
rendering output. Applications should not directly inherit
this class. Instead, applications should inherit, for example,
the OpenGL render widget GLRenderWidget.
*/
class RE167_EXPORT RenderWidget : public QWidget
{
protected:
/** To be re-implemented by RE167 subclass. */
virtual void updateScene() = 0;
/** To be re-implemented by client subclass. */
virtual void initSceneEvent() = 0;
virtual void renderSceneEvent() = 0;
virtual void resizeRenderWidgetEvent(const QSize &s) = 0;
};
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
26
]
]
] |
5c223762c5e2a6f39f15619467ae814ecde16ab6
|
2920ac8b9d3f25edf9f48cb8231d2422dffb485c
|
/source/code/Module.cpp
|
b5bac978ab361ed0601f11f87991c92294f86d60
|
[] |
no_license
|
TheBuzzSaw/legacy-dejarix
|
0b2e028fc6a2eeb50ed733750b0f69dab7b80d6d
|
0a119a465c9097f918c19153e1056ba9eabc18e7
|
refs/heads/master
| 2021-01-10T20:19:40.595842 | 2011-01-23T22:18:16 | 2011-01-23T22:18:16 | 41,321,281 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,155 |
cpp
|
/**
* This file is part of Dejarix.
*
* Dejarix is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dejarix 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 Dejarix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Module.h"
#include <iostream>
using namespace std;
Module::Module() : mRunning(true), mDead(true), mNextModule(NULL)
{
}
Module::~Module()
{
}
void Module::onLoad()
{
}
void Module::onUnload()
{
}
void Module::onOpen()
{
}
void Module::onClose()
{
}
void Module::onLoop()
{
}
void Module::onFrame()
{
}
/// event handlers
void Module::onEvent(SDL_Event* inEvent)
{
switch (inEvent->type)
{
case SDL_ACTIVEEVENT:
{
switch (inEvent->active.state)
{
case SDL_APPMOUSEFOCUS:
{
if (inEvent->active.gain) onMouseFocus();
else onMouseBlur();
break;
}
case SDL_APPINPUTFOCUS:
{
if (inEvent->active.gain) onInputFocus();
else onInputBlur();
break;
}
case SDL_APPACTIVE:
{
if (inEvent->active.gain) onRestore();
else onMinimize();
break;
}
}
break;
}
case SDL_KEYDOWN:
{
onKeyDown(inEvent->key.keysym.sym, inEvent->key.keysym.mod,
inEvent->key.keysym.unicode);
break;
}
case SDL_KEYUP:
{
onKeyUp(inEvent->key.keysym.sym, inEvent->key.keysym.mod,
inEvent->key.keysym.unicode);
break;
}
case SDL_MOUSEMOTION:
{
onMouseMove(inEvent->motion.x, inEvent->motion.y,
inEvent->motion.xrel, inEvent->motion.yrel,
(inEvent->motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0,
(inEvent->motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0,
(inEvent->motion.state & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0);
break;
}
case SDL_MOUSEBUTTONDOWN:
{
switch (inEvent->button.button)
{
case SDL_BUTTON_LEFT:
{
onLButtonDown(inEvent->button.x, inEvent->button.y);
break;
}
case SDL_BUTTON_RIGHT:
{
onRButtonDown(inEvent->button.x, inEvent->button.y);
break;
}
case SDL_BUTTON_MIDDLE:
{
onMButtonDown(inEvent->button.x, inEvent->button.y);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP:
{
switch (inEvent->button.button)
{
case SDL_BUTTON_LEFT:
{
onLButtonUp(inEvent->button.x, inEvent->button.y);
break;
}
case SDL_BUTTON_RIGHT:
{
onRButtonUp(inEvent->button.x, inEvent->button.y);
break;
}
case SDL_BUTTON_MIDDLE:
{
onMButtonUp(inEvent->button.x, inEvent->button.y);
break;
}
case SDL_BUTTON_WHEELUP:
{
onMouseWheel(true, false);
break;
}
case SDL_BUTTON_WHEELDOWN:
{
onMouseWheel(false, true);
break;
}
}
break;
}
case SDL_JOYAXISMOTION:
{
onJoyAxis(inEvent->jaxis.which, inEvent->jaxis.axis,
inEvent->jaxis.value);
break;
}
case SDL_JOYBALLMOTION:
{
onJoyBall(inEvent->jball.which, inEvent->jball.ball,
inEvent->jball.xrel, inEvent->jball.yrel);
break;
}
case SDL_JOYHATMOTION:
{
onJoyHat(inEvent->jhat.which, inEvent->jhat.hat,
inEvent->jhat.value);
break;
}
case SDL_JOYBUTTONDOWN:
{
onJoyButtonDown(inEvent->jbutton.which, inEvent->jbutton.button);
break;
}
case SDL_JOYBUTTONUP:
{
onJoyButtonUp(inEvent->jbutton.which, inEvent->jbutton.button);
break;
}
case SDL_QUIT:
{
onExit();
break;
}
case SDL_SYSWMEVENT:
{
//Ignore
break;
}
case SDL_VIDEORESIZE:
{
onResize(inEvent->resize.w, inEvent->resize.h);
break;
}
case SDL_VIDEOEXPOSE:
{
onExpose();
break;
}
default:
{
onUser(inEvent->user.type, inEvent->user.code, inEvent->user.data1,
inEvent->user.data2);
break;
}
}
}
void Module::onInputFocus()
{
}
void Module::onInputBlur()
{
}
void Module::onKeyDown(SDLKey inSym, SDLMod inMod, Uint16 inUnicode)
{
if (inSym == SDLK_ESCAPE) mRunning = false;
}
void Module::onKeyUp(SDLKey inSym, SDLMod inMod, Uint16 inUnicode)
{
}
void Module::onMouseFocus()
{
}
void Module::onMouseBlur()
{
}
void Module::onMouseMove(int inX, int inY, int inRelX, int inRelY,
bool inLeft, bool inRight, bool inMiddle)
{
}
void Module::onMouseWheel(bool inUp, bool inDown)
{
}
void Module::onLButtonDown(int inX, int inY)
{
}
void Module::onLButtonUp(int inX, int inY)
{
}
void Module::onRButtonDown(int inX, int inY)
{
}
void Module::onRButtonUp(int inX, int inY)
{
}
void Module::onMButtonDown(int inX, int inY)
{
}
void Module::onMButtonUp(int inX, int inY)
{
}
void Module::onJoyAxis(Uint8 inWhich, Uint8 inAxis, Sint16 inValue)
{
}
void Module::onJoyButtonDown(Uint8 inWhich, Uint8 inButton)
{
}
void Module::onJoyButtonUp(Uint8 inWhich, Uint8 inButton)
{
}
void Module::onJoyHat(Uint8 inWhich, Uint8 inHat, Uint8 inValue)
{
}
void Module::onJoyBall(Uint8 inWhich, Uint8 inBall, Sint16 inXRel,
Sint16 inYRel)
{
}
void Module::onMinimize()
{
}
void Module::onRestore()
{
}
void Module::onResize(int inWidth, int inHeight)
{
}
void Module::onExpose()
{
}
void Module::onExit()
{
mRunning = false;
}
void Module::onUser(Uint8 inType, int inCode, void* inData1, void* inData2)
{
}
|
[
"TheBuzzSaw@35cf13a5-3602-408e-9700-a7e2e4f0c3b8"
] |
[
[
[
1,
337
]
]
] |
3ddf79ecc12c21563c56e5cb91e72e11f654fed3
|
78d417d85d69bb498d4dc0ee6e6f24eba83166fb
|
/tts_proto_fep/fep_proxy.cpp
|
dd1975ff5957eae62ac90451c5113043ebde8122
|
[] |
no_license
|
xubing/tts
|
8ae98ead65d232f85bafd47451da3f160f64517c
|
b5babcb376e54fdb9c999775a329eb297f5d3f8b
|
refs/heads/master
| 2020-12-29T03:30:55.026619 | 2009-09-10T09:53:09 | 2009-09-10T09:53:09 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,635 |
cpp
|
#include "fep_proxy.h"
#include <eikenv.h>
#include <fepplugin.h>
// FEP loading works so that the previous FEP is kept loaded until the new
// one completes loading.
// Loading the AKNFEP while the previous instance is loaded causes problems
// (guess it keeps state in TLS). Hence we load it afterwards, asynchronously.
//
// This does cause editors that are active to behave badly. I think the most
// reasonable solution is to kill all running applications when the FEP
// is installed by the production helper.
class AknFepLoader : public CActive {
public:
AknFepLoader() : CActive(CActive::EPriorityStandard) {
CActiveScheduler::Add(this);
}
~AknFepLoader() {
Cancel();
delete akn_fep_;
delete akn_plugin_;
}
void Trigger() {
TRequestStatus* s = &iStatus;
User::RequestComplete(s, KErrNone);
SetActive();
}
void DoCancel() {}
void RunL() {
const TUid aknfepuid = { 0x101fd65a };
akn_plugin_ = CCoeFepPlugIn::NewL(aknfepuid);
CCoeEnv* env = CEikonEnv::Static();
// the parameters are ignored.
CCoeFepParameters* params = NULL;
akn_fep_ = akn_plugin_->NewFepL(*env, *params);
}
CCoeFep* fep() { return akn_fep_; }
const CCoeFep* fep() const { return akn_fep_; }
CCoeFepPlugIn* akn_plugin_;
CCoeFep* akn_fep_;
};
FepProxy::FepProxy(CCoeEnv& aConeEnvironment) :
CCoeFep(aConeEnvironment) {
}
MFepAttributeStorer* FepProxy::storer() {
MFepAttributeStorer* storer = akn_loader_->fep();
return storer;
}
const MFepAttributeStorer* FepProxy::storer() const {
const MFepAttributeStorer* storer = akn_loader_->fep();
return storer;
}
void FepProxy::ConstructL(const CCoeFepParameters& aFepParameters) {
BaseConstructL(aFepParameters);
akn_loader_ = new (ELeave) AknFepLoader;
akn_loader_->Trigger();
}
FepProxy::~FepProxy() {
delete akn_loader_;
}
TInt FepProxy::NumberOfAttributes() const {
if (!storer()) return 0;
return storer()->NumberOfAttributes();
}
TUid FepProxy::AttributeAtIndex(TInt index) const {
if (!storer()) return KNullUid;
return storer()->AttributeAtIndex(index);
}
void FepProxy::WriteAttributeDataToStreamL(TUid uid,
RWriteStream& stream) const {
if (!storer()) return;
storer()->WriteAttributeDataToStreamL(uid, stream);
}
void FepProxy::ReadAttributeDataFromStreamL(TUid uid,
RReadStream& stream) {
if (!storer()) return;
storer()->ReadAttributeDataFromStreamL(uid, stream);
}
void FepProxy::HandleChangeInFocus() {
if (!akn_loader_->fep()) return;
akn_loader_->fep()->HandleChangeInFocus();
}
void FepProxy::HandleDestructionOfFocusedItem() {
if (!akn_loader_->fep()) return;
akn_loader_->fep()->HandleDestructionOfFocusedItem();
}
void FepProxy::HandleGainingForeground() {
if (!akn_loader_->fep()) return;
akn_loader_->fep()->HandleGainingForeground();
}
void FepProxy::HandleLosingForeground() {
if (!akn_loader_->fep()) return;
akn_loader_->fep()->HandleLosingForeground();
}
void FepProxy::CancelTransaction() {
if (!akn_loader_->fep()) return;
akn_loader_->fep()->CancelTransaction();
}
void FepProxy::IsOnHasChangedState() {
if (!akn_loader_->fep()) return;
FepProxy* cast_for_access = (FepProxy*)akn_loader_->fep();
cast_for_access->IsOnHasChangedState();
}
void FepProxy::SynchronouslyExecuteSettingsDialogL(CCoeEnv& env) {
if (!akn_loader_->akn_plugin_) return;
akn_loader_->akn_plugin_->SynchronouslyExecuteSettingsDialogL(env);
}
|
[
"[email protected]"
] |
[
[
[
1,
124
]
]
] |
63c2d118fd573b519a2aa8b32631c915d1066ef7
|
ce10be13a62b6ed6e3ccdd0780fe98e08573166e
|
/source/module.cpp
|
9c52aaed0b460dd091adb383e777fd3ffce5e4bc
|
[] |
no_license
|
pfeyssaguet/afrods
|
b2d63fd501a60a5c40d2d128bc03820f389c4d59
|
df2e85990bac4a2107bba5ad7ba9232753cf7725
|
refs/heads/master
| 2016-09-06T02:13:26.546098 | 2010-02-07T13:07:01 | 2010-02-07T13:07:01 | 32,130,697 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 291 |
cpp
|
#include "module.h"
using namespace AfroDS;
Module::Module(Context * context) : m_context(context) {
}
Context * Module::getContext() const {
return m_context;
}
void Module::moduleEvents() {
}
void Module::modulePause() {
}
void Module::moduleResume() {
}
|
[
"deuspi@fce96c3e-db3a-11de-b64b-7d26b27941e2"
] |
[
[
[
1,
23
]
]
] |
c198048bd47e24e60ca9dd4bdba220101aa9689c
|
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
|
/mytesgnikrow --username hotga2801/SELAB/Dongle/Source/HID_Client/HID.cpp
|
1892843e1d340a484f82d215996fc017d1271699
|
[] |
no_license
|
taicent/mytesgnikrow
|
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
|
9264faa662454484ade7137ee8a0794e00bf762f
|
refs/heads/master
| 2020-04-06T04:25:30.075548 | 2011-02-17T13:37:16 | 2011-02-17T13:37:16 | 34,991,750 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,117 |
cpp
|
#include "stdafx.h"
extern "C"
{
#include "setupapi.h"
#include "hidsdi.h"
}
#include "HID.h"
#define DEV_NUM 10
int DevCount;
PSP_DEVICE_INTERFACE_DETAIL_DATA DevDetailData[DEV_NUM];
HANDLE DevHandle;
/*
* HID Initialization
* Parameters: None
* Return Value: None
*/
void HID_Init() {
int i;
DevCount = 0;
for (i = 0; i < DEV_NUM; i++) {
DevDetailData[i] = NULL;
}
}
/*
* HID Uninitialization
* Parameters: None
* Return Value: None
*/
void HID_UnInit() {
int i;
for (i = 0; i < DEV_NUM; i++) {
if (DevDetailData[i]) free(DevDetailData[i]);
}
}
/*
* HID Find Devices
* Parameters: None
* Return Value: Number of Devices found
*/
int HID_FindDevices() {
GUID HidGuid;
HDEVINFO DevInfo;
SP_DEVICE_INTERFACE_DATA DevData;
PSP_DEVICE_INTERFACE_DETAIL_DATA DevDetail;
PHIDP_PREPARSED_DATA PreparsedData;
HIDP_CAPS Capabilities;
ULONG Length;
int Index;
BOOL ok;
/* Get GUID for all System HIDs */
HidD_GetHidGuid(&HidGuid);
/* Get Device Information for all present devices */
DevInfo = SetupDiGetClassDevs(&HidGuid,
NULL,
NULL,
(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)
);
DevData.cbSize = sizeof(DevData);
DevDetail = NULL;
Index = -1;
/* Scan all Devices */
do {
Index++;
/* Device Interface Element of a Device Information set */
ok = SetupDiEnumDeviceInterfaces(DevInfo,
0,
&HidGuid,
Index,
&DevData
);
if (!ok) break;
/* Get Device Interface Details - Get Length */
ok = SetupDiGetDeviceInterfaceDetail(DevInfo,
&DevData,
NULL,
0,
&Length,
NULL
);
/* Allocate memory for Device Detailed Data */
if (DevDetail) free(DevDetail);
DevDetail = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(Length);
/* Set cbSize in the DevDetail structure */
DevDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
/* Get Device Interface Details */
ok = SetupDiGetDeviceInterfaceDetail(DevInfo,
&DevData,
DevDetail,
Length,
NULL,
NULL
);
if (!ok) continue;
/* Create File for Device Read/Write */
DevHandle = CreateFile(DevDetail->DevicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
0,
NULL
);
if (DevHandle == INVALID_HANDLE_VALUE) continue;
/* Get Preparsed Data */
ok = HidD_GetPreparsedData(DevHandle, &PreparsedData);
if (!ok) continue;
/* Get Device's Capabilities */
HidP_GetCaps(PreparsedData, &Capabilities);
/* Free the PreparsedData */
HidD_FreePreparsedData(PreparsedData);
/* Remember Device Interface Detail Data for acceptable Devices */
if ((Capabilities.UsagePage == 0xFF00) && (Capabilities.Usage == 0x0001)) {
DevDetailData[DevCount++] = DevDetail;
DevDetail = NULL;
}
CloseHandle (DevHandle);
} while (DevCount < DEV_NUM);
if (DevDetail) free(DevDetail);
SetupDiDestroyDeviceInfoList (DevInfo);
return (DevCount);
}
/*
* HID Get Name (Product String)
* Parameters: num: Device number
* buf: Pointer to buffer that receives data
* sz: Number of bytes to read
* Return Value: TRUE - Success, FALSE - Error
*/
BOOL HID_GetName(int num, char *buf, int sz) {
HANDLE DevHandle;
WCHAR wbuf[128];
int i;
BOOL ok;
if (DevDetailData[num] == NULL) return (FALSE);
/* Create File for Device Read/Write */
DevHandle = CreateFile(DevDetailData[num]->DevicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
0,
NULL
);
if (DevHandle == INVALID_HANDLE_VALUE) return (FALSE);
ok = HidD_GetProductString(DevHandle, wbuf, sizeof(wbuf));
if (ok) {
for (i = 0; i < sz; i++) {
*buf++ = (char)wbuf[i];
}
}
CloseHandle (DevHandle);
return (ok);
}
/*
* HID Open
* Parameters: num: Device number
* Return Value: TRUE - Success, FALSE - Error
*/
BOOL HID_Open(int num) {
DevHandle = INVALID_HANDLE_VALUE;
if (DevDetailData[num] == NULL) return (FALSE);
/* Create File for Device Read/Write */
DevHandle = CreateFile(DevDetailData[num]->DevicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
0,
NULL
);
if (DevHandle == INVALID_HANDLE_VALUE) return (FALSE);
return (TRUE);
}
/*
* HID Open
* Parameters: None
* Return Value: None
*/
void HID_Close() {
if (DevHandle != INVALID_HANDLE_VALUE) {
CloseHandle(DevHandle);
DevHandle = INVALID_HANDLE_VALUE;
}
}
/*
* HID Read
* Parameters: buf: Pointer to buffer that receives data
* sz: Number of bytes to read
* cnt: Pointer to number of bytes read
* Return Value: TRUE - Success, FALSE - Error
*/
BOOL HID_Read(BYTE *buf, DWORD sz, DWORD *cnt) {
BOOL ok;
/* Read from Device */
ok = ReadFile(DevHandle, buf, sz, cnt, NULL);
return (ok);
}
/*
* HID Write
* Parameters: buf: Pointer to buffer with data to write
* sz: Number of bytes to write
* cnt: Pointer to number of bytes written
* Return Value: TRUE - Success, FALSE - Error
*/
BOOL HID_Write(BYTE *buf, DWORD sz, DWORD *cnt) {
BOOL ok;
struct { /* new Output Report */
BYTE OutReport[2]; /* LED control */
BYTE LcdLine1 [16]; /* LCD line #1 */
BYTE LcdLine2 [16]; /* LCD line #2 */
} OutRep;
time_t curTime;
tm locTime;
/* prepare date and time */
time(&curTime); /* get time */
locTime = *(localtime(&curTime)); /* convert time */
/* prepare Output Report */
memcpy (OutRep.OutReport, buf, sz); /* copy original Output Report */
sprintf((char *)OutRep.LcdLine1,"date %02d.%02d.%04d", locTime.tm_mday, locTime.tm_mon+1, locTime.tm_year+1900);
sprintf((char *)OutRep.LcdLine2,"time %02d:%02d:%02d", locTime.tm_hour, locTime.tm_min, locTime.tm_sec);
/* Write to Device */
ok = WriteFile(DevHandle, &OutRep, /*sizeof(OutRep)*/ 34, cnt, NULL);
return (ok);
}
|
[
"hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076"
] |
[
[
[
1,
301
]
]
] |
6ccda54a10e324cafb43437fdb410f2d74c95210
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/zombie/nscene/src/nscene/nintanimator_cmds.cc
|
3172e9ac9ab5ce0ec4c2d22018805f42ad61b6b5
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,913 |
cc
|
#include "precompiled/pchnscene.h"
//------------------------------------------------------------------------------
// nintanimator_cmds.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "nscene/nintanimator.h"
#include "kernel/npersistserver.h"
static void n_addkey(void* slf, nCmd* cmd);
static void n_getnumkeys(void* slf, nCmd* cmd);
static void n_getkeyat(void* slf, nCmd* cmd);
//------------------------------------------------------------------------------
/**
@scriptclass
nintanimator
@cppclass
nIntAnimator
@superclass
nshaderanimator
@classinfo
Animate a int vector attribute of a nabstractshadernode.
*/
void
n_initcmds_nIntAnimator(nClass* cl)
{
cl->BeginCmds();
cl->AddCmd("v_addkey_fi", 'ADDK', n_addkey);
cl->AddCmd("i_getnumkeys_v", 'GNKS', n_getnumkeys);
cl->AddCmd("fi_getkeyat_i", 'GKAT', n_getkeyat);
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
addkey
@input
f(Time), i(Value)
@output
v
@info
Add a int vector key to the animation key array.
*/
void
n_addkey(void* slf, nCmd* cmd)
{
nIntAnimator* self = (nIntAnimator*) slf;
float f0;
int i0;
f0 = cmd->In()->GetF();
i0 = cmd->In()->GetI();
self->AddKey(f0, i0);
}
//------------------------------------------------------------------------------
/**
@cmd
getnumkeys
@input
v
@output
i(NumKeys)
@info
Returns number of key in animation array.
*/
void
n_getnumkeys(void* slf, nCmd* cmd)
{
nIntAnimator* self = (nIntAnimator*) slf;
cmd->Out()->SetI(self->GetNumKeys());
}
//------------------------------------------------------------------------------
/**
@cmd
getkeyat
@input
i(KeyIndex)
@output
f(Time), i(Value)
@info
Returns key at given index.
*/
void
n_getkeyat(void* slf, nCmd* cmd)
{
nIntAnimator* self = (nIntAnimator*) slf;
float f0;
int i0;
self->GetKeyAt(cmd->In()->GetI(), f0, i0);
cmd->Out()->SetF(f0);
cmd->Out()->SetI(i0);
}
//------------------------------------------------------------------------------
/**
*/
bool
nIntAnimator::SaveCmds(nPersistServer* ps)
{
if (nShaderAnimator::SaveCmds(ps))
{
nCmd* cmd;
//--- addkey ---
int i;
int numKeys = this->GetNumKeys();
for (i = 0; i < numKeys; i++)
{
float time;
int val;
cmd = ps->GetCmd(this, 'ADDK');
this->GetKeyAt(i, time, val);
cmd->In()->SetF(time);
cmd->In()->SetI(val);
ps->PutCmd(cmd);
}
return true;
}
return false;
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
126
]
]
] |
5e5f935f038464cd4ab371887b74d83ab75f9a1b
|
9ad9345e116ead00be7b3bd147a0f43144a2e402
|
/Integration_WAH_&_Extraction/SMDataExtraction/FlexVCBridgeStaticLib/ASProxy.h
|
49c79f13d9d742cc8895b9c47c647b858f525c59
|
[] |
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 | 1,277 |
h
|
/*
* 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):
*
*/
#pragma once
#include <string>
#include <map>
enum ASProxyType { ASPROXY_GETTER, ASPROXY_SETTER, ASPROXY_METHOD, ASPROXY_FUNCTION, ASPROXY_NONE };
/* List of as functions and their type (getter, setter, mothod) */
class CASProxy
{
public:
CASProxy(void);
~CASProxy(void);
std::map<std::string, ASProxyType> m_Properties;
void Add(std::string& sVal, ASProxyType iPType);
ASProxyType GetType(std::string& sVal) const;
};
|
[
"jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
] |
[
[
[
1,
42
]
]
] |
037123462dedd0c04516c75efa4fd1d5277dc263
|
611fc0940b78862ca89de79a8bbeab991f5f471a
|
/src/Jiki/Jiki.h
|
26f98b3a0416915c8cb35aed31ac4510d7d06a66
|
[] |
no_license
|
LakeIshikawa/splstage2
|
df1d8f59319a4e8d9375b9d3379c3548bc520f44
|
b4bf7caadf940773a977edd0de8edc610cd2f736
|
refs/heads/master
| 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,132 |
h
|
#pragma once
#include "..\\\Mob\\LightResponseAble.h"
#include "..\\Mob\\Collidable.h"
#include "InterfaceView.h"
#include "..\\Collision\\Rect.h"
#include "..\\Mob\\IRideCapable.h"
#include "..\\Effect\\ChargeEffect.h"
#include "..\\Management\\GameControl.h"
class Ashiba;
////パラメータ
#define ANIFR 100//アニメーションフレームMAX
#define GRAME 200//グラフィック名の文字数MAX
#define TENSU 20 //当たり判定の点の最大個数
#define MAX_CHAIN 5
/*
自機
*/
class Jiki :
public virtual LightResponseAble, public virtual Collidable, public IRideCapable
{
public:
Jiki(int rXPx, int rYPx);
~Jiki(void);
void Move();
void ResponseAka();
void ResponseAo();
void ResponseMidori();
void ResponseMushoku();
void NoLight();
int GetAtHtPointX();
int GetAtHtPointY();
bool GetMuki();
void CollisionResponse(ICollidable* rCollObject, int rThisGroupId, int rOpGroupId);
int GetSizeX();
void RunTask();
void HrWalk();
// 外部インターフェース
void InflictDamage();
void IncreaseTensEmpa();
void HantenOrRebound();
void DisableCollision();
void EnableCollision();
void ToggleNoDamageMode();
void RestoreEmpacy(int n, bool SEdelayed);
void RestoreTension(int n, bool SEdelayed);
void RestoreLife(int n, bool SEdelayed);
int GetLife() { return mLife; }
float GetEmpa() { return mEmp; }
float GetTens() { return mTen; }
InterfaceView* GetInterface() { return mInterface; }
void SetPos(int rX, int rY) { mX = rX; mY = rY; }
void SetMuki( int rMuki ) { mMuki = rMuki; }
void ResetLife();
void ResetTension();
void ResetEmpacy();
void ResetTempParams();
void Die();
bool IsDying();
bool IsControl();
bool IsBusy();
bool IsStageclearable();
// チェイン
void IncrementChain();
void ResetChain();
int GetChainLv();
// 打撃エフェクト
void MakeHitEffect();
//強風
void SetWindForce(float rAccX) { if( !mHouseProtected) mKazeAccX = rAccX; }
void SetHouseProtected() { mHouseProtected = true; }
void SetSuperWait(float rTime);
void SetSuperControl();
void SetSuperPause();
// IRideCapableの実装
Rect* GetRideRect() { collisionFrames(); return (Rect*)(pCollision->GetFrame(FR_ARUKI)->GetIndexedShape(0)); }
float GetSpX() {return mSpX;}
float GetSpY() {return mSpY;}
void SetX(int rX) { mX = rX; }
void SetY(int rY) { mY = rY; }
void SetSpX(float rNewSpX) { mSpX = rNewSpX; }
void SetSpY(float rNewSpY) { mSpY = rNewSpY; }
void AddSpX(float rAddX){ mAshiSpX = rAddX; }
void RideResponse(Ashiba* rAshiba) { mCurAshiba = rAshiba; }
void GetOffResponse(Ashiba* rAshiba) { mCurAshiba = NULL; }
enum SUPER_STATUS{
WAIT,
CONTROL,
PAUSE
};
enum STATUS
{
WALK = 0,
TEISHI,
HANTEN,
KOGEKI_START,
KOGEKI,
KOGEKI_END,
KOGEKI_STAN,
JUMP_START,
JUMP_UP,
JUMP_DOWN,
JUMP_END,
DRILL_START,
DRILL,
DRILL_END,
FUYU,
DAMAGE,
DAMAGE_END,
HISATU,
DEAD,
MAKUDOWN,
FADEOUT,
FADEIN
};
enum FRAMES
{
FR_ARUKI,
FR_TACHI,
FR_JUMP,
FR_KOGEKI,
FR_DRILL,
FR_HISATU,
FR_DISABLE
};
private:
float mSpX;//スピード
float mSpY;
float mAccX;//加速度
float mAccY;
float mKazeAccX;
bool mHouseProtected;
//当たり判定
int mHitFl[4];//0:↓ 1:↑ 2:前 3:後
int mKabeIchi[4];
static int sAniData[][ANIFR];
static double sAniTime[][ANIFR];
static char sGraphic[][GRAME];
static int sHitX[][4][TENSU];
static int sHitY[][4][TENSU];
SUPER_STATUS mSuperStatus;
STATUS mStatus;
//アニメーション
float mAniTimer;
int mAniNoX;
int mAniNoY;
bool mAniTeishi;
//ダメージ用
int mDgMutekiFl;
bool mDgMapFl;
float mDamageTimer;
//float mTenmetuTimer;
float mAlphaTimer;
float mAlphaVal;
//当たり判定オン・オフ
bool collisionEnabled;
//赤用
float mAkaTimer;
float mAkaTimer2;
float mStanTimer;
int mStanAni;
//青用
float mAoTimer;
//緑用
float mMidTimer;
bool mMidFl;
//ドリルキック
float mHozonY;
int mDrillFl;
//必殺技
float mHisatuTime;
float mHsX;
float mHsY;
float mHshozon;
float mHisatuMuki;
//フェード
int mFadeFl;
bool mFadeFl2;
//ゲームオーバー
int mGmOvFl;
//チャージエフェクト
ChargeEffect* mChargeFx;
//SE
bool mDmSE;
float mDmSETimer;
bool mTenSE;
bool mHisatuSE;
//ゲージ類
int mLife;
float mEmp;
float mEmpTeki;
float mTen;
float mTenTime;
bool mTenFl;
// 完全無敵
bool mNoDamage;
// インターフェースビュー
InterfaceView *mInterface;
// スーパーステータス
float mSuperWaitTimer;
// 足場よう
bool mAshibaFl;
Ashiba* mCurAshiba;
float mAshiSpX;
// チェイン
int mChainIdx;
static float sChainMultSp[MAX_CHAIN+1];
static float sChainMultShoSp[MAX_CHAIN+1];
//関数群
void UnTeishi();
void AkaCheck();
void AoCheck();
void MidCheck();
void Hisatu();
void MapAtHt();
int GetMukiMult();
//アクション
void Hanten();
//当たり判定
void collisionFrames();
//テンション
void Tension();
//フェード
void Fade();
//ゲームオーバー
void Gameover();
//半透明にする
void SetTransparent(bool mOnOff);
//設定定数
int LIFE_MAX;
int LIFE_SHOKI;
float EMP_SHOKI;
int HERSIZE;
float DAMAGE_SP;
float EMP_DOWN;
float EMP_MAX;
float TEN_DOWN2;
float TEN_UP2;
float TEN_MAX;
float EMP_UP;
float SPANI;
float SPWALK;
float ACCKOGEKI;
float STAN_TIME;
float STAN_ANI;
float JUMP_SHOSP;
float DRILL_SP;
float FUYU_SP;
float HISATU_TIME;
float MUTEKI_TIME;
float TENMETU_TIME;
float END_TIME;
float DRILL_HEIGTH;
float HANTEN_TIME;
float HISATU_LTSP;
float HISATU_HRSP;
float HISATU_FADE;
float TEN_UTIME;
float TEN_UP1;
float TEN_DTIME;
float TEN_DOWN1;
float HER_DIE_TIME;
};
|
[
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b",
"cat2.silly.affection@c9935178-01ba-11df-8f7b-bfe16de6f99b"
] |
[
[
[
1,
7
],
[
10,
227
],
[
229,
256
],
[
258,
320
]
],
[
[
8,
9
],
[
228,
228
],
[
257,
257
]
]
] |
217d5f61fa831fa32a9c9efc4a8dc207f39084be
|
942b88e59417352fbbb1a37d266fdb3f0f839d27
|
/src/argss/tilemap.hxx
|
53ed3f8fd27e607f9913678773307ae6a7235f10
|
[
"BSD-2-Clause"
] |
permissive
|
take-cheeze/ARGSS...
|
2c1595d924c24730cc714d017edb375cfdbae9ef
|
2f2830e8cc7e9c4a5f21f7649287cb6a4924573f
|
refs/heads/master
| 2016-09-05T15:27:26.319404 | 2010-12-13T09:07:24 | 2010-12-13T09:07:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,987 |
hxx
|
//////////////////////////////////////////////////////////////////////////////////
/// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf)
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE 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 AUTHOR 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 _ARGSS_TILEMAP_HXX_
#define _ARGSS_TILEMAP_HXX_
////////////////////////////////////////////////////////////
/// Headers
////////////////////////////////////////////////////////////
#include <options.hxx>
#if RPGMAKER == RPGXP
#include <argss/XP/tilemap.hxx>
#elif RPGMAKER == RPGVX
#include <argss/VX/tilemap.hxx>
#else
#error unknown RGSS version
#endif
#endif // _ARGSS_TILEMAP_HXX_
|
[
"takeshi@takeshi-laptop.(none)",
"[email protected]"
] |
[
[
[
1,
24
],
[
27,
30
],
[
32,
32
],
[
40,
40
]
],
[
[
25,
26
],
[
31,
31
],
[
33,
39
],
[
41,
41
]
]
] |
73d3f16a17e1ea06521683fa562aae5477c888b7
|
e5ded38277ec6db30ef7721a9f6f5757924e130e
|
/Cpp/SoSe10/Blatt01.Aufgabe07/Blatt01.Aufgabe07.cpp
|
5db80739e70b1079fb48c7a4ff7cd1e690b106a7
|
[] |
no_license
|
TetsuoCologne/sose10
|
67986c8a014c4bdef19dc52e0e71e91602600aa0
|
67505537b0eec497d474bd2d28621e36e8858307
|
refs/heads/master
| 2020-05-27T04:36:02.620546 | 2010-06-22T20:47:08 | 2010-06-22T20:47:08 | 32,480,813 | 0 | 0 | null | null | null | null |
ISO-8859-1
|
C++
| false | false | 599 |
cpp
|
// Blatt01.Aufgabe07.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define PI 3.14156
#define max(n,m) ((n > m) ? n : m)
#define AmulB(a,b) (a * b)
void _tmain(int argc, _TCHAR* argv[])
{
#if defined(PI)
cout << "Pi = " << PI << endl;
#else
cout << "Pi unbekannt" << endl;
#endif
int n = 3, m = 4;
cout << "max(n,m) = " << max(++n,++m) << endl;
cout << "n = " << n << ", m = " << m << endl;
int a = 2, b = 3, c = 4;
cout << "AmulB(a,b+c) = " << AmulB(a, b + c) << endl;
}
|
[
"[email protected]@f2f8bf26-27bb-74d3-be08-1e18597623ec"
] |
[
[
[
1,
29
]
]
] |
2cde9591f8a0e484d72a714a5646ab17468c24c0
|
8fcfa439a6c1ea4753ace06b87d7d49f55bdd1e6
|
/tgeScriptIntf.cpp
|
b82f3f08f605437aad7961b29d34a4191e6d0b00
|
[] |
no_license
|
blacksqr/tge-cpp
|
bb3e0216830ace08d9381d14bd1916994009ba19
|
e51f36dcc46790ccadab2f2dcaa0849970b57eb3
|
refs/heads/master
| 2021-01-10T14:14:34.381325 | 2010-03-22T12:37:36 | 2010-03-22T12:37:36 | 48,471,490 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,270 |
cpp
|
#include "tgeScriptIntf.h"
#include "tgeObj.h"
#include "tgeInterpreter.h"
namespace tge
{
ScriptIntf::ScriptIntf(void)
{
}
ScriptIntf::~ScriptIntf(void)
{
}
void ScriptIntf::init(const String& scriptingName, const String& className)
{
mScriptingInstanceName = scriptingName;
mScriptingClassName = className;
}
/** ID for this object which could be accessed in script. */
const String& ScriptIntf::getScriptingInstanceName(void) const
{
return mScriptingInstanceName;
}
const String& ScriptIntf::getScriptingClassName(void) const
{
return mScriptingClassName;
}
const Obj& ScriptIntf::get(const String& propName)
{
static Obj obj; // Empty
PropBag::const_iterator it = mProps.find(propName);
if (it==mProps.end())
{
// Issues a warning
std::cerr<<String("Specified property \"")+ propName + String(" not found. - ["+mScriptingClassName+"]") << std::endl;
return obj;
}
else
{ obj = mProps[propName];
return obj;
}
}
void ScriptIntf::set(const String& propName, const Obj& value)
{
mProps[propName] = value;
}
CmdStatus ScriptIntf::run(const String& cmdName, const Obj& arg1, const Obj& arg2, const Obj& argRest, size_t argRestc)
{
if (!arg1.isNull())
{
String action = static_cast<String>(arg1);
if ( action.compare("set") == 0)
{
if (arg2.isNull())
{
mInterp->_panic("Null args for 'setter'. Please specify prop name. ", cmdName);
}
else
{
if (argRestc<1)
{
mInterp->_panic("Null args for 'set " + (String)arg2 + "'. Please specify prop value.", cmdName);
}
else
{
Obj obj = argRest.lindex(0);
if (!obj.isNull())
{
set(static_cast<String>(arg2), obj);
}
}
}
return TGE_OK;
}
else if ( action.compare("get") == 0)
{
if (arg2.isNull())
{
mInterp->_panic("Null args for 'getter'. Please specify prop name.", cmdName);
}
_setObjResult( get(static_cast<String>(arg2)) );
return TGE_OK;
}
else
{
return scriptAccess(action, arg2, argRest, argRestc);
}
}
else
{
mInterp->_panic("No actions given.", cmdName);
}
return TGE_OK;
}
}
|
[
"jeffreybian@99f00b9d-c5df-25c8-5ecf-577a790fa8fa"
] |
[
[
[
1,
100
]
]
] |
79da21259f8a517f87def39b5e41a607348016e0
|
86e2a83280120c2c7018393f43ad5d4a5c217345
|
/src/nsCrasher.h
|
6bd56f0fe02c27391bb3cef25661c43db8a5252e
|
[] |
no_license
|
m8ttyB/crashmenow
|
cdade189f20ee0dffccf57dbe6658feefa12a6b3
|
6cfa7ec5a9f2829713c00dbe5cc05bfe607d0c14
|
refs/heads/master
| 2020-12-24T13:43:52.422889 | 2010-11-09T23:36:16 | 2010-11-09T23:36:16 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 176 |
h
|
#include "nsICrasher.h"
class nsCrasher : public nsICrasher
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICRASHER
nsCrasher() {};
private:
~nsCrasher() {};
};
|
[
"[email protected]"
] |
[
[
[
1,
13
]
]
] |
ecde708e32d9ad221ebfa230656cbe69ef138b3f
|
0da7fec56f63012180d848b1e72bada9f6984ef3
|
/PocketDjVu_root/PocketDjvu/ScrollByTap.h
|
55650afa99594dc64f53ad6062a0d17584e89ac3
|
[] |
no_license
|
UIKit0/pocketdjvu
|
a34fb2b8ac724d25fab7a0298942db1755098b25
|
4c0c761e6a3d3628440fb4fb0a9c54e5594807d9
|
refs/heads/master
| 2021-01-20T12:01:16.947853 | 2010-05-03T12:29:44 | 2010-05-03T12:29:44 | 32,293,688 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 693 |
h
|
#pragma once
#include "./ICtrlNotify.h"
class CScrollByTap : public CControllerBase
{
public:
CScrollByTap( ICtrlNotify * pSubscriber ) : CControllerBase(pSubscriber)
, m_vkey()
{
}
virtual ~CScrollByTap()
{
}
public:
BEGIN_MSG_MAP(CRectZoomCtrl)
CHAIN_MSG_MAP(CControllerBase)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
END_MSG_MAP()
public:
LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
// DATA:
private:
WPARAM m_vkey;
};
|
[
"Igor.Solovyov@84cd470b-3125-0410-acc3-039690e87181"
] |
[
[
[
1,
30
]
]
] |
c63279ea67190db7324f9af9063e0c1a518f7dea
|
992d3f90ab0f41ca157000c4b18d071087d14d85
|
/MINES.CPP
|
132cab5682676d0da1d33b802bf5dec7d16fb0b9
|
[] |
no_license
|
axemclion/visionizzer
|
cabc53c9be41c07c04436a4733697e4ca35104e3
|
5b0158f8a3614e519183055e50c27349328677e7
|
refs/heads/master
| 2020-12-25T19:04:17.853016 | 2009-05-22T14:44:53 | 2009-05-22T14:44:53 | 29,331,323 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 8,743 |
cpp
|
#include <time.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <dos.h>
#include "d:\prog\c\mouse.h"
#include "d:\prog\c\button.cls"
# define ROWS 8
# define COLS 8
# define MINES 10
# define X 0
# define Y 0
# define length 20
# define bredth 20
int check();
void msgbox(char *);
void edit();
void solve();
static signed char play[ROWS][COLS];
static signed char open[ROWS][COLS];
void intro()
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "");
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
//filling columns and rows with mines
setfillstyle(SOLID_FILL,8);
bar(X,Y,X+ROWS*length,Y+COLS*bredth);
randomize();
{
for (int x =0;x < ROWS;x++)
for (int y =0;y < COLS;y++)
play[x][y] =0;
}
for (int i=0;i < MINES;i++)
{
int x = random(ROWS);
int y = random(COLS);
if (play[x][y] == -1)
i--;
else
play[x][y] =-1;
}
//filling with digits
for (int x =0;x < ROWS;x++)
for (int y =0;y < COLS;y++)
{
if (play[x][y] != -1)
{
int initx,inity,endx,endy;
initx = x > 0 ? x-1:x;
inity = y > 0 ? y-1:y;
endx = x != ROWS-1?x + 1:ROWS-1;
endy = y != COLS-1?y + 1:COLS-1;
int counter = 0;
int x1=0,y1=0;
for (y1=inity;y1 <= endy;y1++)
for (x1=initx;x1 <= endx;x1++)
if (play[x1][y1] == -1)
counter++;
play[x][y] = counter;
}//digit fill*/
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,"");
t.draw();
}//end of filling with numbers
}//end of introduction
int main(void)
{
intro();
int quit =0 ;
mouse_status mouse;
mouse_present();
show_mouse();
bind_mouse(X,Y,X+ROWS*length-1,Y+COLS*bredth-1);
char word[6][64] = {
{255,254,127,254,31,254,7,254,1,254,1,254,0,254,255,254,255,254,255,254,255,254,255,254,255,254,127,252,63,248,63,248,0,1,128,1,96,1,24,1,6,1,2,1,255,1,0,1,0,1,0,1,0,1,0,1,0,1,128,3,64,4,192,7},
{255,254,63,254,15,254,3,254,0,254,1,254,15,254,255,254,255,254,255,254,255,254,255,254,255,254,127,252,63,248,63,248,0,1,192,1,48,1,12,1,3,1,30,1,240,1,0,1,0,1,0,1,0,1,0,1,0,1,128,3,64,4,192,7},
{255,254,63,254,3,254,0,254,1,254,7,254,15,254,255,254,255,254,255,254,255,254,255,254,255,254,127,252,63,248,63,248,0,1,192,1,60,1,3,1,6,1,24,1,240,1,0,1,0,1,0,1,0,1,0,1,0,1,128,3,64,4,192,7},
{255,254,63,254,7,254,3,254,3,254,7,254,15,254,255,254,255,254,255,254,255,254,255,254,255,254,127,252,63,248,63,248,0,1,192,1,56,1,4,1,4,1,24,1,240,1,0,1,0,1,0,1,0,1,0,1,0,1,128,3,64,4,192,7},
{255,254,63,254,7,254,7,254,7,254,7,254,31,254,255,254,255,254,255,254,255,254,255,254,255,254,127,252,63,248,63,248,0,1,192,1,56,1,8,1,8,1,24,1,224,1,0,1,0,1,0,1,0,1,0,1,0,1,128,3,64,4,192,7},
{255,254,63,254,15,254,3,254,1,254,3,254,15,254,255,254,255,254,255,254,255,254,255,254,255,254,127,252,63,248,63,248,0,1,192,1,48,1,12,1,2,1,12,1,240,1,0,1,0,1,0,1,0,1,0,1,0,1,128,3,64,4,192,7}};
int key = 0;
while (!quit)
{
anim(word,6,10,8,15);
key = 0;
if (kbhit())
{
key = getch();
if (key == 0)
key = 1000+getch();
}//end of getting key
switch(key)
{
case 5 : //ctrl e
hide_mouse();
msgbox("Editing..");
bar(X,Y,ROWS*length+X,COLS*bredth+Y);
settextjustify(LEFT_TEXT,TOP_TEXT);
show_mouse();
edit();
break;
case 17: //ctrl q
msgbox("Quitting..");
quit = 1;
break;
case 1059: //F1
solve();
case 18: //ctrl R
msgbox("Resetting..");
hide_mouse();
intro();
bind_mouse(X,Y,X+ROWS*length-1,Y+COLS*bredth-1);
show_mouse();
break;
}//end of switch case
mouse = click();
unsigned int x,y;
x = mouse.x/length;
y = mouse.y/bredth;
if (mouse.button == BOTH_CLICK)
quit = 1;
else if (mouse.button == RIGHT_CLICK && open[x][y] != 1)
{
hide_mouse();
bar(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1);
if (open[x][y] == -1)
{
open[x][y] = -2;
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,"þ");
t.draw();
}//end of mark
else if (open[x][y] == -2)
{
open[x][y] = 0;
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1," ");
t.draw();
}//end of question
else if (open[x][y] == 0)
{
open[x][y] = -1;
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,"?");
t.draw();
}//end of clear
show_mouse();
}//end of roight click
else if (mouse.button == LEFT_CLICK && open[x][y] == 0)
{
hide_mouse();
if (open [x][y] == 0)
open[x][y] = 1;
char s[2];
play[x][y] != 0 ? sprintf(s,"%1d",play[x][y]) : sprintf(s," ");
s[1] = NULL;
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,s);
t.draw();
t.depress();
//flood clearing
if (play[x][y] == 0)
{
setactivepage(1);
setfillstyle(SOLID_FILL,0);
bar(0,0,ROWS,COLS);
for (int x1 =0;x1 < ROWS;x1++)
for (int y1 =0;y1 < COLS;y1++)
if (play[x1][y1] != 0)
putpixel(x1+1,y1+1,15);
setfillstyle(SOLID_FILL,7);
rectangle(0,0,ROWS+1,COLS+1);
floodfill(x+1,y+1,15);
for (x1 =0;x1 < ROWS;x1++)
for (y1 =0;y1 < COLS;y1++)
if (getpixel(x1+1,y1+1) == 7 && open[x1][y1] == 0)
{
open[x1][y1] = 1;
setactivepage(0);
button t(X+x1*length+1,Y+y1*bredth+1,X+x1*length+length-1,Y+y1*bredth+bredth-1,"");
t.draw();
t.depress();
setactivepage(1);
}//end of clearing
}//end of clearing
setactivepage(0);
show_mouse();
switch (check())
{
case 1:
quit = 1;
msgbox("You Win");
break;
case -1:
quit = 1;
msgbox("Mine Hit");
break;
}//end of check victory
}//end of left click
}//end of quitting
closegraph();
return 0;
}
void solve()
{
}
void edit()
{
int quit = 0;
for (int x=0;x < ROWS;x++)
for (int y=0;y < COLS;y++)
{
char s[2];
play[x][y] != 0 ? sprintf(s,"%1d",play[x][y]) : sprintf(s," ");
s[1] = NULL;
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,s);
t.draw();
t.depress();
}
mouse_status mouse;
while (!quit)
{
mouse = click();
x = mouse.x/length;
y = mouse.y/bredth;
if (mouse.button == BOTH_CLICK)
quit = 1;
else if (mouse.button == RIGHT_CLICK)
{
hide_mouse();
play[x][y]--;
if (play[x][y] == -2)
play[x][y] = 8;
char s[2];
play[x][y] != 0 ? sprintf(s,"%1d",play[x][y]) : sprintf(s," ");
s[1] = NULL;
bar(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1);
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,s);
t.draw();
show_mouse();
}//end of this
else if (mouse.button == LEFT_CLICK)
{
hide_mouse();
play[x][y]++;
if (play[x][y] == 9)
play[x][y] = -1;
char s[2];
play[x][y] != 0 ? sprintf(s,"%1d",play[x][y]) : sprintf(s," ");
s[1] = NULL;
bar(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1);
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,s);
t.draw();
show_mouse();
}//end of left_click
}//end of quitting
hide_mouse();
for (x=0;x < ROWS;x++)
for (y=0;y < COLS;y++)
{
bar(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1);
button t(X+x*length+1,Y+y*bredth+1,X+x*length+length-1,Y+y*bredth+bredth-1,"");
t.draw();
}
show_mouse();
}
int check()
{
for (int x = 0;x < ROWS;x++)
for (int y=0;y < COLS;y++)
if (open[x][y] == 1 && play[x][y] == -1)
return -1;
for (x = 0;x < ROWS;x++)
for (y=0;y < COLS;y++)
if (open[x][y] == 0 && play[x][y] != -1)
return 0;
return 1;
}
void msgbox(char *str)
{
hide_mouse();
setfillstyle(SOLID_FILL,8);
bar(X+length*ROWS/8,Y+bredth*COLS/4,X+length*ROWS*7/8,Y+bredth*COLS*3/4);
rectangle(X+length*ROWS/8,Y+bredth*COLS/4,X+length*ROWS*7/8,Y+bredth*COLS*3/4);
settextjustify(1,1);
setcolor(7);
outtextxy(X-1+ROWS/2*length,Y-1+COLS/2*bredth,str);
outtextxy(1+X+ROWS/2*length,Y-1+COLS/2*bredth,str);
outtextxy(X-1+ROWS/2*length,1+Y+COLS/2*bredth,str);
outtextxy(1+X+ROWS/2*length,1+Y+COLS/2*bredth,str);
setcolor(15);
outtextxy(X+ROWS/2*length,Y+COLS/2*bredth,str);
show_mouse();
getch();
}
|
[
"[email protected]"
] |
[
[
[
1,
327
]
]
] |
7d3870d46e9a11cadbf0534145d1ac1f4d76c467
|
fbe2cbeb947664ba278ba30ce713810676a2c412
|
/iptv_root/iptv_media3/CClockSync.cpp
|
0ff3ef981538a029654eb8f7bb9a237d84673cfa
|
[] |
no_license
|
abhipr1/multitv
|
0b3b863bfb61b83c30053b15688b070d4149ca0b
|
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
|
refs/heads/master
| 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 842 |
cpp
|
#include "compat.h"
#include "CClockSync.h"
#include "global_error.h"
#include "Global_functions.h"
CClockSync::CClockSync() :
m_ClockSemaph()
{
m_Ref = 0;
m_ulTime = 0;
m_bClockStarted = FALSE;
}
CClockSync::~CClockSync()
{
}
ULONG CClockSync::SetClockRef()
{
m_ClockSemaph.Wait();
if (!m_bClockStarted)
{
GetTime(&m_Ref);
m_bClockStarted = TRUE;
}
m_ClockSemaph.Signal();
return RET_OK;
}
ULONG CClockSync::UpdateTime(ULONG *_pulCurTime)
{
if (!m_bClockStarted)
return RET_INIT_ERROR;
if (!_pulCurTime)
return RET_INVALID_ARG;
m_ClockSemaph.Wait();
ULONG ulAuxTime;
GetTime(&ulAuxTime);
m_ulTime = ulAuxTime - m_Ref;
*_pulCurTime = m_ulTime;
m_ClockSemaph.Signal();
return RET_OK;
}
|
[
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
] |
[
[
[
1,
55
]
]
] |
710f2b4261f34a394b96220c586f7cad295aac5f
|
8b4f7e8e746b8592a2289337a2013d7cf7d04c44
|
/SharedObject.cpp
|
616b40dda55813fe3124f7e616ba69d7f1c2361f
|
[] |
no_license
|
seansu4you87/osclaser
|
8f0aac69dc9d803f097df34a9938fbabe25fde14
|
dcd3bcb898db4957209c9c04115b2375aea7ab35
|
refs/heads/master
| 2021-01-01T16:55:14.318564 | 2010-02-18T03:52:17 | 2010-02-18T03:52:17 | 32,344,063 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 825 |
cpp
|
#include "stdafx.h"
#include "SharedObject.h"
#include "OscReceivedElements.h"
#include "OscPacketListener.h"
#include "UdpSocket.h"
SharedObject::SharedObject()
{
numPoints = 0;
points = NULL;
objectID = 0;
objectName = "";
}
SharedObject::~SharedObject()
{
if(points != NULL)
{
free(points);
}
}
int SharedObject::getNumPoints()
{
return numPoints;
}
void SharedObject::setColor(float r, float g, float b)
{
if(points != NULL)
{
for(int i = 0; i < numPoints; i++)
{
LaserPoint * curPoint = points + 1;
curPoint->r = r;
curPoint->g = g;
curPoint->b = b;
}
}
}
LaserPoint * SharedObject::pointAt(int index)
{
return points + index;
}
void SharedObject::step()
{
}
void SharedObject::setFromMessage(const osc::ReceivedMessage& m)
{
}
|
[
"codeb87@ba1854fa-1114-11df-8588-0bb593d8ec56"
] |
[
[
[
1,
54
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.