first step in refactoring/cleaning up demos

This commit is contained in:
ejcoumans
2006-09-11 05:31:22 +00:00
parent a27c35ecaa
commit 43370aaa4f
33 changed files with 2449 additions and 7548 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef CCD_PHYSICS_DEMO_H
#define CCD_PHYSICS_DEMO_H
#include "DemoApplication.h"
///CcdPhysicsDemo shows basic stacking using Bullet physics, and allows toggle of Ccd (using key '1')
class CcdPhysicsDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene();
};
#endif //CCD_PHYSICS_DEMO_H

View File

@@ -1,282 +0,0 @@
/*
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.
*/
#include "BspConverter.h"
#include "BspLoader.h"
#include "CcdPhysicsEnvironment.h"
#include "SimdVector3.h"
void BspConverter::convertBsp(BspLoader& bspLoader,float scaling)
{
{
SimdVector3 playerStart (0.f, 0.f, 100.f);
if (bspLoader.findVectorByName(&playerStart[0],"info_player_start"))
{
printf("found playerstart\n");
}
else
{
if (bspLoader.findVectorByName(&playerStart[0],"info_player_deathmatch"))
{
printf("found deatchmatch start\n");
}
}
playerStart[2] += 20.f; //start a bit higher
playerStart *= scaling;
//progressBegin("Loading bsp");
for (int i=0;i<bspLoader.m_numleafs;i++)
{
printf("Reading bspLeaf %i from total %i (%f procent)\n",i, bspLoader.m_numleafs,(100.f*(float)i/float(bspLoader.m_numleafs)) );
bool isValid = false;
bool isValidBrush = false;
BSPLeaf& leaf = bspLoader.m_dleafs[i];
for (int b=0;b<leaf.numLeafBrushes;b++)
{
std::vector<SimdVector3> planeEquations;
int brushid = bspLoader.m_dleafbrushes[leaf.firstLeafBrush+b];
BSPBrush& brush = bspLoader.m_dbrushes[brushid];
if (brush.shaderNum!=-1)
{
if (bspLoader.m_dshaders[ brush.shaderNum ].contentFlags & BSPCONTENTS_SOLID)
{
brush.shaderNum = -1;
for (int p=0;p<brush.numSides;p++)
{
int sideid = brush.firstSide+p;
BSPBrushSide& brushside = bspLoader.m_dbrushsides[sideid];
int planeid = brushside.planeNum;
BSPPlane& plane = bspLoader.m_dplanes[planeid];
SimdVector3 planeEq;
planeEq.setValue(
plane.normal[0],
plane.normal[1],
plane.normal[2],
scaling*-plane.dist);
planeEquations.push_back(planeEq);
isValidBrush=true;
}
if (isValidBrush)
{
std::vector<SimdVector3> vertices;
getVerticesFromPlaneEquations(planeEquations,vertices);
printf("getVerticesFromPlaneEquations returned %i\n",vertices.size());
bool isEntity = false;
SimdVector3 entityTarget(0.f,0.f,0.f);
AddConvexVerticesCollider(vertices,isEntity,entityTarget);
}
}
}
else
{
int i=0;
}
}
}
#define USE_ENTITIES
#ifdef USE_ENTITIES
{
int i;
for (i=0;i<bspLoader.m_num_entities;i++)
{
const BSPEntity& entity = bspLoader.m_entities[i];
const char* cl = bspLoader.ValueForKey(&entity,"classname");
if ( !strcmp( cl, "trigger_push" ) ) {
SimdVector3 targetLocation(0.f,0.f,0.f);
cl = bspLoader.ValueForKey(&entity,"target");
if ( strcmp( cl, "" ) ) {
//its not empty so ...
//lookup the target position for the jumppad:
const BSPEntity* targetentity = bspLoader.getEntityByValue( "targetname" , cl );
if (targetentity)
{
if (bspLoader.GetVectorForKey( targetentity , "origin",&targetLocation[0]))
{
}
}
cl = bspLoader.ValueForKey(&entity,"model");
if ( strcmp( cl, "" ) ) {
// add the model as a brush
if (cl[0] == '*')
{
int modelnr = atoi(&cl[1]);
if ((modelnr >=0) && (modelnr < bspLoader.m_nummodels))
{
const BSPModel& model = bspLoader.m_dmodels[modelnr];
for (int n=0;n<model.numBrushes;n++)
{
std::vector<SimdVector3> planeEquations;
bool isValidBrush = false;
//convert brush
const BSPBrush& brush = bspLoader.m_dbrushes[model.firstBrush+n];
{
for (int p=0;p<brush.numSides;p++)
{
int sideid = brush.firstSide+p;
BSPBrushSide& brushside = bspLoader.m_dbrushsides[sideid];
int planeid = brushside.planeNum;
BSPPlane& plane = bspLoader.m_dplanes[planeid];
SimdVector3 planeEq;
planeEq.setValue(
plane.normal[0],
plane.normal[1],
plane.normal[2],
scaling*-plane.dist);
planeEquations.push_back(planeEq);
isValidBrush=true;
}
if (isValidBrush)
{
std::vector<SimdVector3> vertices;
getVerticesFromPlaneEquations(planeEquations,vertices);
bool isEntity=true;
AddConvexVerticesCollider(vertices,isEntity,targetLocation);
}
}
}
}
}
else
{
printf("unsupported trigger_push model, md3 ?\n");
}
}
}
}
}
}
#endif //USE_ENTITIES
//progressEnd();
}
}
void BspConverter::getVerticesFromPlaneEquations(const std::vector<SimdVector3>& planeEquations , std::vector<SimdVector3>& verticesOut )
{
float minimumDotProduct = 1e30f;
const int numbrushes = planeEquations.size();
// brute force:
for (int i=0;i<numbrushes;i++)
{
const SimdVector3& N1 = planeEquations[i];
for (int j=i+1;j<numbrushes;j++)
{
const SimdVector3& N2 = planeEquations[j];
for (int k=j+1;k<numbrushes;k++)
{
const SimdVector3& N3 = planeEquations[k];
SimdVector3 n2n3; n2n3 = N2.cross(N3);
SimdVector3 n3n1; n3n1 = N3.cross(N1);
SimdVector3 n1n2; n1n2 = N1.cross(N2);
if ( ( n2n3.length2() > 0.0001f ) &&
( n3n1.length2() > 0.0001f ) &&
( n1n2.length2() > 0.0001f ) )
{
//point P out of 3 plane equations:
// d1 ( N2 * N3 ) + d2 ( N3 * N1 ) + d3 ( N1 * N2 )
//P = -------------------------------------------------------------------------
// N1 . ( N2 * N3 )
float quotient = (N1.dot(n2n3));
if (SimdFabs(quotient) > 0.000001f)
{
quotient = -1.f / quotient;
n2n3 *= N1[3];
n3n1 *= N2[3];
n1n2 *= N3[3];
SimdVector3 potentialVertex = n2n3;
potentialVertex += n3n1;
potentialVertex += n1n2;
potentialVertex *= quotient;
//check if inside, and replace supportingVertexOut if needed
if (isInside(planeEquations,potentialVertex,0.1f))
{
verticesOut.push_back(potentialVertex);
}
}
}
}
}
}
}
bool BspConverter::isInside(const std::vector<SimdVector3>& planeEquations, const SimdVector3& point, float margin)
{
int numbrushes = planeEquations.size();
for (int i=0;i<numbrushes;i++)
{
const SimdVector3& N1 = planeEquations[i];
float dist = float(N1.dot(point))+float(N1[3])-margin;
if (dist>0.f)
{
return false;
}
}
return true;
}

View File

@@ -1,713 +0,0 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "BspLoader.h"
typedef struct
{
char filename[1024];
char *buffer,*script_p,*end_p;
int line;
} BSPScript;
#define MAX_INCLUDES 8
BSPScript scriptstack[MAX_INCLUDES];
BSPScript *script;
int scriptline;
char token[BSPMAXTOKEN];
bool endofscript;
bool tokenready; // only true if UnGetToken was just called
//
//LoadBSPFile
//
int extrasize = 100;
bool BspLoader::LoadBSPFile( void* memoryBuffer) {
BSPHeader *header = (BSPHeader*) memoryBuffer;
// load the file header
if (header)
{
// swap the header
SwapBlock( (int *)header, sizeof(*header) );
int length = (header->lumps[BSPLUMP_SHADERS].filelen) / sizeof(BSPShader);
m_dshaders.resize(length+extrasize);
m_numShaders = CopyLump( header, BSPLUMP_SHADERS, &m_dshaders[0], sizeof(BSPShader) );
length = (header->lumps[LUMP_MODELS].filelen) / sizeof(BSPModel);
m_dmodels.resize(length+extrasize);
m_nummodels = CopyLump( header, LUMP_MODELS, &m_dmodels[0], sizeof(BSPModel) );
length = (header->lumps[BSPLUMP_PLANES].filelen) / sizeof(BSPPlane);
m_dplanes.resize(length+extrasize);
m_numplanes = CopyLump( header, BSPLUMP_PLANES, &m_dplanes[0], sizeof(BSPPlane) );
length = (header->lumps[BSPLUMP_LEAFS].filelen) / sizeof(BSPLeaf);
m_dleafs.resize(length+extrasize);
m_numleafs = CopyLump( header, BSPLUMP_LEAFS, &m_dleafs[0], sizeof(BSPLeaf) );
length = (header->lumps[BSPLUMP_NODES].filelen) / sizeof(BSPNode);
m_dnodes.resize(length+extrasize);
m_numnodes = CopyLump( header, BSPLUMP_NODES, &m_dnodes[0], sizeof(BSPNode) );
length = (header->lumps[BSPLUMP_LEAFSURFACES].filelen) / sizeof(m_dleafsurfaces[0]);
m_dleafsurfaces.resize(length+extrasize);
m_numleafsurfaces = CopyLump( header, BSPLUMP_LEAFSURFACES, &m_dleafsurfaces[0], sizeof(m_dleafsurfaces[0]) );
length = (header->lumps[BSPLUMP_LEAFBRUSHES].filelen) / sizeof(m_dleafbrushes[0]) ;
m_dleafbrushes.resize(length+extrasize);
m_numleafbrushes = CopyLump( header, BSPLUMP_LEAFBRUSHES, &m_dleafbrushes[0], sizeof(m_dleafbrushes[0]) );
length = (header->lumps[LUMP_BRUSHES].filelen) / sizeof(BSPBrush);
m_dbrushes.resize(length+extrasize);
m_numbrushes = CopyLump( header, LUMP_BRUSHES, &m_dbrushes[0], sizeof(BSPBrush) );
length = (header->lumps[LUMP_BRUSHSIDES].filelen) / sizeof(BSPBrushSide);
m_dbrushsides.resize(length+extrasize);
m_numbrushsides = CopyLump( header, LUMP_BRUSHSIDES, &m_dbrushsides[0], sizeof(BSPBrushSide) );
length = (header->lumps[LUMP_SURFACES].filelen) / sizeof(BSPSurface);
m_drawSurfaces.resize(length+extrasize);
m_numDrawSurfaces = CopyLump( header, LUMP_SURFACES, &m_drawSurfaces[0], sizeof(BSPSurface) );
length = (header->lumps[LUMP_DRAWINDEXES].filelen) / sizeof(m_drawIndexes[0]);
m_drawIndexes.resize(length+extrasize);
m_numDrawIndexes = CopyLump( header, LUMP_DRAWINDEXES, &m_drawIndexes[0], sizeof(m_drawIndexes[0]) );
length = (header->lumps[LUMP_VISIBILITY].filelen) / 1;
m_visBytes.resize(length+extrasize);
m_numVisBytes = CopyLump( header, LUMP_VISIBILITY, &m_visBytes[0], 1 );
length = (header->lumps[LUMP_LIGHTMAPS].filelen) / 1;
m_lightBytes.resize(length+extrasize);
m_numLightBytes = CopyLump( header, LUMP_LIGHTMAPS, &m_lightBytes[0], 1 );
length = (header->lumps[BSPLUMP_ENTITIES].filelen) / 1;
m_dentdata.resize(length+extrasize);
m_entdatasize = CopyLump( header, BSPLUMP_ENTITIES, &m_dentdata[0], 1);
length = (header->lumps[LUMP_LIGHTGRID].filelen) / 1;
m_gridData.resize(length+extrasize);
m_numGridPoints = CopyLump( header, LUMP_LIGHTGRID, &m_gridData[0], 8 );
// swap everything
SwapBSPFile();
return true;
}
return false;
}
const char* BspLoader::ValueForKey( const BSPEntity* ent, const char* key ) const {
const BSPKeyValuePair* ep;
for (ep=ent->epairs ; ep ; ep=ep->next) {
if (!strcmp(ep->key, key) ) {
return ep->value;
}
}
return "";
}
float BspLoader::FloatForKey( const BSPEntity *ent, const char *key ) {
const char *k;
k = ValueForKey( ent, key );
return float(atof(k));
}
bool BspLoader::GetVectorForKey( const BSPEntity *ent, const char *key, BSPVector3 vec ) {
const char *k;
k = ValueForKey (ent, key);
if (strcmp(k, ""))
{
sscanf (k, "%f %f %f", &vec[0], &vec[1], &vec[2]);
return true;
}
return false;
}
/*
==============
ParseFromMemory
==============
*/
void BspLoader::ParseFromMemory (char *buffer, int size)
{
script = scriptstack;
script++;
if (script == &scriptstack[MAX_INCLUDES])
{
//printf("script file exceeded MAX_INCLUDES");
}
strcpy (script->filename, "memory buffer" );
script->buffer = buffer;
script->line = 1;
script->script_p = script->buffer;
script->end_p = script->buffer + size;
endofscript = false;
tokenready = false;
}
bool BspLoader::EndOfScript (bool crossline)
{
if (!crossline)
//printf("Line %i is incomplete\n",scriptline);
if (!strcmp (script->filename, "memory buffer"))
{
endofscript = true;
return false;
}
//free (script->buffer);
if (script == scriptstack+1)
{
endofscript = true;
return false;
}
script--;
scriptline = script->line;
//printf ("returning to %s\n", script->filename);
return GetToken (crossline);
}
/*
==============
GetToken
==============
*/
bool BspLoader::GetToken (bool crossline)
{
char *token_p;
if (tokenready) // is a token allready waiting?
{
tokenready = false;
return true;
}
if (script->script_p >= script->end_p)
return EndOfScript (crossline);
//
// skip space
//
skipspace:
while (*script->script_p <= 32)
{
if (script->script_p >= script->end_p)
return EndOfScript (crossline);
if (*script->script_p++ == '\n')
{
if (!crossline)
{
//printf("Line %i is incomplete\n",scriptline);
}
scriptline = script->line++;
}
}
if (script->script_p >= script->end_p)
return EndOfScript (crossline);
// ; # // comments
if (*script->script_p == ';' || *script->script_p == '#'
|| ( script->script_p[0] == '/' && script->script_p[1] == '/') )
{
if (!crossline)
{
//printf("Line %i is incomplete\n",scriptline);
}
while (*script->script_p++ != '\n')
if (script->script_p >= script->end_p)
return EndOfScript (crossline);
scriptline = script->line++;
goto skipspace;
}
// /* */ comments
if (script->script_p[0] == '/' && script->script_p[1] == '*')
{
if (!crossline)
{
//printf("Line %i is incomplete\n",scriptline);
}
script->script_p+=2;
while (script->script_p[0] != '*' && script->script_p[1] != '/')
{
if ( *script->script_p == '\n' ) {
scriptline = script->line++;
}
script->script_p++;
if (script->script_p >= script->end_p)
return EndOfScript (crossline);
}
script->script_p += 2;
goto skipspace;
}
//
// copy token
//
token_p = token;
if (*script->script_p == '"')
{
// quoted token
script->script_p++;
while (*script->script_p != '"')
{
*token_p++ = *script->script_p++;
if (script->script_p == script->end_p)
break;
if (token_p == &token[BSPMAXTOKEN])
{
//printf ("Token too large on line %i\n",scriptline);
}
}
script->script_p++;
}
else // regular token
while ( *script->script_p > 32 && *script->script_p != ';')
{
*token_p++ = *script->script_p++;
if (script->script_p == script->end_p)
break;
if (token_p == &token[BSPMAXTOKEN])
{
//printf ("Token too large on line %i\n",scriptline);
}
}
*token_p = 0;
if (!strcmp (token, "$include"))
{
//GetToken (false);
//AddScriptToStack (token);
return false;//GetToken (crossline);
}
return true;
}
char *BspLoader::copystring(const char *s)
{
char *b;
b = (char*) malloc( strlen(s)+1);
strcpy (b, s);
return b;
}
void BspLoader::StripTrailing( char *e ) {
char *s;
s = e + strlen(e)-1;
while (s >= e && *s <= 32)
{
*s = 0;
s--;
}
}
/*
=================
ParseEpair
=================
*/
BSPKeyValuePair *BspLoader::ParseEpair( void ) {
BSPKeyValuePair *e;
e = (struct BSPPair*) malloc( sizeof(BSPKeyValuePair));
memset( e, 0, sizeof(BSPKeyValuePair) );
if ( strlen(token) >= BSPMAX_KEY-1 ) {
//printf ("ParseEpar: token too long");
}
e->key = copystring( token );
GetToken( false );
if ( strlen(token) >= BSPMAX_VALUE-1 ) {
//printf ("ParseEpar: token too long");
}
e->value = copystring( token );
// strip trailing spaces that sometimes get accidentally
// added in the editor
StripTrailing( e->key );
StripTrailing( e->value );
return e;
}
/*
================
ParseEntity
================
*/
bool BspLoader::ParseEntity( void ) {
BSPKeyValuePair *e;
BSPEntity *mapent;
if ( !GetToken (true) ) {
return false;
}
if ( strcmp (token, "{") ) {
//printf ("ParseEntity: { not found");
}
BSPEntity bla;
bla.brushes = 0;
bla.epairs = 0;
bla.firstDrawSurf = 0;
bla.origin[0] = 0.f;
bla.origin[1] = 0.f;
bla.origin[2] = 0.f;
bla.patches = 0;
m_entities.push_back(bla);
mapent = &m_entities[m_entities.size()-1];
m_num_entities++;
do {
if ( !GetToken (true) ) {
//printf("ParseEntity: EOF without closing brace");
}
if ( !strcmp (token, "}") ) {
break;
}
e = (struct BSPPair*)ParseEpair ();
e->next = mapent->epairs;
mapent->epairs = e;
} while (1);
return true;
}
/*
================
ParseEntities
Parses the dentdata string into entities
================
*/
void BspLoader::ParseEntities( void ) {
m_num_entities = 0;
m_entities.clear();
ParseFromMemory( &m_dentdata[0], m_entdatasize );
while ( ParseEntity () ) {
}
}
int BspLoader::getMachineEndianness()
{
long int i = 1;
const char *p = (const char *) &i;
if (p[0] == 1) // Lowest address contains the least significant byte
return BSP_LITTLE_ENDIAN;
else
return BSP_BIG_ENDIAN;
}
short BspLoader::LittleShort (short l)
{
if (machineEndianness() == BSP_BIG_ENDIAN)
{
unsigned char b1,b2;
b1 = l&255;
b2 = (l>>8)&255;
return (b1<<8) + b2;
}
//little endian
return l;
}
short BspLoader::BigShort (short l)
{
if (machineEndianness() == BSP_BIG_ENDIAN)
{
return l;
}
unsigned char b1,b2;
b1 = l&255;
b2 = (l>>8)&255;
return (b1<<8) + b2;
}
int BspLoader::LittleLong (int l)
{
if (machineEndianness() == BSP_BIG_ENDIAN)
{
unsigned char b1,b2,b3,b4;
b1 = l&255;
b2 = (l>>8)&255;
b3 = (l>>16)&255;
b4 = (l>>24)&255;
return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
}
//little endian
return l;
}
int BspLoader::BigLong (int l)
{
if (machineEndianness() == BSP_BIG_ENDIAN)
{
return l;
}
unsigned char b1,b2,b3,b4;
b1 = l&255;
b2 = (l>>8)&255;
b3 = (l>>16)&255;
b4 = (l>>24)&255;
return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
}
float BspLoader::LittleFloat (float l)
{
if (machineEndianness() == BSP_BIG_ENDIAN)
{
union {unsigned char b[4]; float f;} in, out;
in.f = l;
out.b[0] = in.b[3];
out.b[1] = in.b[2];
out.b[2] = in.b[1];
out.b[3] = in.b[0];
return out.f;
}
//little endian
return l;
}
float BspLoader::BigFloat (float l)
{
if (machineEndianness() == BSP_BIG_ENDIAN)
{
return l;
}
//little endian
union {unsigned char b[4]; float f;} in, out;
in.f = l;
out.b[0] = in.b[3];
out.b[1] = in.b[2];
out.b[2] = in.b[1];
out.b[3] = in.b[0];
return out.f;
}
//
// SwapBlock
// If all values are 32 bits, this can be used to swap everything
//
void BspLoader::SwapBlock( int *block, int sizeOfBlock ) {
int i;
sizeOfBlock >>= 2;
for ( i = 0 ; i < sizeOfBlock ; i++ ) {
block[i] = LittleLong( block[i] );
}
}
//
// CopyLump
//
int BspLoader::CopyLump( BSPHeader *header, int lump, void *dest, int size ) {
int length, ofs;
length = header->lumps[lump].filelen;
ofs = header->lumps[lump].fileofs;
//if ( length % size ) {
// printf ("LoadBSPFile: odd lump size");
//}
memcpy( dest, (unsigned char *)header + ofs, length );
return length / size;
}
//
// SwapBSPFile
//
void BspLoader::SwapBSPFile( void ) {
int i;
// models
SwapBlock( (int *) &m_dmodels[0], m_nummodels * sizeof( m_dmodels[0] ) );
// shaders (don't swap the name)
for ( i = 0 ; i < m_numShaders ; i++ ) {
m_dshaders[i].contentFlags = LittleLong( m_dshaders[i].contentFlags );
m_dshaders[i].surfaceFlags = LittleLong( m_dshaders[i].surfaceFlags );
}
// planes
SwapBlock( (int *)&m_dplanes[0], m_numplanes * sizeof( m_dplanes[0] ) );
// nodes
SwapBlock( (int *)&m_dnodes[0], m_numnodes * sizeof( m_dnodes[0] ) );
// leafs
SwapBlock( (int *)&m_dleafs[0], m_numleafs * sizeof( m_dleafs[0] ) );
// leaffaces
SwapBlock( (int *)&m_dleafsurfaces[0], m_numleafsurfaces * sizeof( m_dleafsurfaces[0] ) );
// leafbrushes
SwapBlock( (int *)&m_dleafbrushes[0], m_numleafbrushes * sizeof( m_dleafbrushes[0] ) );
// brushes
SwapBlock( (int *)&m_dbrushes[0], m_numbrushes * sizeof( m_dbrushes[0] ) );
// brushsides
SwapBlock( (int *)&m_dbrushsides[0], m_numbrushsides * sizeof( m_dbrushsides[0] ) );
// vis
((int *)&m_visBytes)[0] = LittleLong( ((int *)&m_visBytes)[0] );
((int *)&m_visBytes)[1] = LittleLong( ((int *)&m_visBytes)[1] );
// drawindexes
SwapBlock( (int *)&m_drawIndexes[0], m_numDrawIndexes * sizeof( m_drawIndexes[0] ) );
// drawsurfs
SwapBlock( (int *)&m_drawSurfaces[0], m_numDrawSurfaces * sizeof( m_drawSurfaces[0] ) );
}
bool BspLoader::findVectorByName(float* outvec,const char* name)
{
const char *cl;
BSPVector3 origin;
bool found = false;
ParseEntities();
for ( int i = 1; i < m_num_entities; i++ ) {
cl = ValueForKey (&m_entities[i], "classname");
if ( !strcmp( cl, "info_player_start" ) ) {
GetVectorForKey( &m_entities[i], "origin", origin );
found = true;
break;
}
if ( !strcmp( cl, "info_player_deathmatch" ) ) {
GetVectorForKey( &m_entities[i], "origin", origin );
found = true;
break;
}
}
if (found)
{
outvec[0] = origin[0];
outvec[1] = origin[1];
outvec[2] = origin[2];
}
return found;
}
const BSPEntity * BspLoader::getEntityByValue( const char* name, const char* value)
{
const BSPEntity* entity = NULL;
for ( int i = 1; i < m_num_entities; i++ ) {
const BSPEntity& ent = m_entities[i];
const char* cl = ValueForKey (&m_entities[i], name);
if ( !strcmp( cl, value ) ) {
entity = &ent;
break;
}
}
return entity;
}

View File

@@ -1,304 +0,0 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef BSP_LOADER_H
#define BSP_LOADER_H
#define BSPMAXTOKEN 1024
#define BSPMAX_KEY 32
#define BSPMAX_VALUE 1024
#define BSPCONTENTS_SOLID 1
#define BSPCONTENTS_AREAPORTAL 0x8000
#define BSPLUMP_ENTITIES 0
#define BSPLUMP_SHADERS 1
#define BSPLUMP_PLANES 2
#define BSPLUMP_NODES 3
#define BSPLUMP_LEAFS 4
#define BSPLUMP_LEAFSURFACES 5
#define BSPLUMP_LEAFBRUSHES 6
#define LUMP_MODELS 7
#define LUMP_BRUSHES 8
#define LUMP_BRUSHSIDES 9
#define LUMP_DRAWVERTS 10
#define LUMP_DRAWINDEXES 11
#define LUMP_SURFACES 13
#define LUMP_LIGHTMAPS 14
#define LUMP_LIGHTGRID 15
#define LUMP_VISIBILITY 16
#define HEADER_LUMPS 17
#define MAX_QPATH 64
#include <vector>
typedef struct {
int fileofs, filelen;
} BSPLump;
typedef float BSPVector3[3];
typedef struct {
int ident;
int version;
BSPLump lumps[HEADER_LUMPS];
} BSPHeader;
typedef struct {
float mins[3], maxs[3];
int firstSurface, numSurfaces;
int firstBrush, numBrushes;
} BSPModel;
typedef struct {
char shader[MAX_QPATH];
int surfaceFlags;
int contentFlags;
} BSPShader;
typedef struct {
float normal[3];
float dist;
} BSPPlane;
typedef struct {
int planeNum;
int children[2];
int mins[3];
int maxs[3];
} BSPNode;
typedef struct {
int cluster;
int area;
int mins[3];
int maxs[3];
int firstLeafSurface;
int numLeafSurfaces;
int firstLeafBrush;
int numLeafBrushes;
} BSPLeaf;
typedef struct {
int planeNum;
int shaderNum;
} BSPBrushSide;
typedef struct {
int firstSide;
int numSides;
int shaderNum;
} BSPBrush;
typedef struct BSPPair {
struct BSPPair *next;
char *key;
char *value;
} BSPKeyValuePair;
typedef struct {
BSPVector3 origin;
struct bspbrush_s *brushes;
struct parseMesh_s *patches;
int firstDrawSurf;
BSPKeyValuePair *epairs;
} BSPEntity;
typedef enum {
MST_BAD,
MST_PLANAR,
MST_PATCH,
MST_TRIANGLE_SOUP,
MST_FLARE
} BSPMapSurface;
typedef struct {
int shaderNum;
int fogNum;
int surfaceType;
int firstVert;
int numVerts;
int firstIndex;
int numIndexes;
int lightmapNum;
int lightmapX, lightmapY;
int lightmapWidth, lightmapHeight;
BSPVector3 lightmapOrigin;
BSPVector3 lightmapVecs[3];
int patchWidth;
int patchHeight;
} BSPSurface;
///GPL code from IdSofware to parse a Quake 3 BSP file
///check that your platform define __BIG_ENDIAN__ correctly (in BspLoader.cpp)
class BspLoader
{
int m_Endianness;
public:
BspLoader()
:m_num_entities(0)
{
m_Endianness = getMachineEndianness();
if (m_Endianness == BSP_BIG_ENDIAN)
{
printf("Machine is BIG_ENDIAN\n");
} else
{
printf("Machine is Little Endian\n");
}
}
bool LoadBSPFile( void* memoryBuffer);
const char* ValueForKey( const BSPEntity *ent, const char *key ) const;
bool GetVectorForKey( const BSPEntity *ent, const char *key, BSPVector3 vec );
float FloatForKey( const BSPEntity *ent, const char *key );
void ParseEntities( void );
bool findVectorByName(float* outvec,const char* name);
const BSPEntity * getEntityByValue( const char* name, const char* value);
protected:
void ParseFromMemory (char *buffer, int size);
bool EndOfScript (bool crossline);
bool GetToken (bool crossline);
char *copystring(const char *s);
void StripTrailing( char *e );
BSPKeyValuePair * ParseEpair( void );
bool ParseEntity( void );
short LittleShort (short l);
int LittleLong (int l);
float LittleFloat (float l);
int BigLong (int l);
short BigShort (short l);
float BigFloat (float l);
void SwapBlock( int *block, int sizeOfBlock );
int CopyLump( BSPHeader *header, int lump, void *dest, int size );
void SwapBSPFile( void );
public: //easier for conversion
int m_num_entities;
std::vector<BSPEntity> m_entities;
int m_nummodels;
std::vector<BSPModel> m_dmodels;
int m_numShaders;
std::vector<BSPShader> m_dshaders;
int m_entdatasize;
std::vector<char> m_dentdata;
int m_numleafs;
std::vector<BSPLeaf> m_dleafs;
int m_numplanes;
std::vector<BSPPlane> m_dplanes;
int m_numnodes;
std::vector<BSPNode> m_dnodes;
int m_numleafsurfaces;
std::vector<int> m_dleafsurfaces;
int m_numleafbrushes;
std::vector<int> m_dleafbrushes;
int m_numbrushes;
std::vector<BSPBrush> m_dbrushes;
int m_numbrushsides;
std::vector<BSPBrushSide> m_dbrushsides;
int m_numLightBytes;
std::vector<unsigned char> m_lightBytes;
int m_numGridPoints;
std::vector<unsigned char> m_gridData;
int m_numVisBytes;
std::vector<unsigned char> m_visBytes;
int m_numDrawIndexes;
std::vector<int> m_drawIndexes;
int m_numDrawSurfaces;
std::vector<BSPSurface> m_drawSurfaces;
enum
{
BSP_LITTLE_ENDIAN = 0,
BSP_BIG_ENDIAN = 1,
};
//returns machines big endian / little endian
//
int getMachineEndianness();
inline int machineEndianness()
{
return m_Endianness;
}
};
#endif //BSP_LOADER_H

File diff suppressed because it is too large Load Diff

View File

@@ -12,29 +12,29 @@ subject to the following restrictions:
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef COLLADA_PHYSICS_DEMO_H
#define COLLADA_PHYSICS_DEMO_H
#ifndef BSP_CONVERTER_H
#define BSP_CONVERTER_H
#include "DemoApplication.h"
class BspLoader;
#include <vector>
#include "SimdVector3.h"
///BspConverter turns a loaded bsp level into convex parts (vertices)
class BspConverter
///ColladaDemo shows the loading and exporting of COLLADA physics xml files.
///It uses COLLADA DOM
class ColladaDemo : public DemoApplication
{
public:
void convertBsp(BspLoader& bspLoader,float scaling);
void initPhysics(const char* filename);
///Utility function to create vertices from a Quake Brush. Brute force but it works.
///Bit overkill to use QHull package
void getVerticesFromPlaneEquations(const std::vector<SimdVector3>& planeEquations , std::vector<SimdVector3>& verticesOut );
bool isInside(const std::vector<SimdVector3>& planeEquations, const SimdVector3& point, float margin);
virtual void clientMoveAndDisplay();
///this callback is called for each brush that succesfully converted into vertices
virtual void AddConvexVerticesCollider(std::vector<SimdVector3>& vertices, bool isEntity, const SimdVector3& entityTargetLocation) = 0;
virtual void displayCallback();
virtual void clientResetScene()
{
}
virtual void keyboardCallback(unsigned char key, int x, int y);
};
#endif //BSP_CONVERTER_H
#endif //COLLADA_PHYSICS_DEMO_H

View File

@@ -30,19 +30,10 @@ subject to the following restrictions:
#include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
#include "NarrowPhaseCollision/ConvexPenetrationDepthSolver.h"
#include "CollisionDemo.h"
#include "GL_ShapeDrawer.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "GlutStuff.h"
#include "IDebugDraw.h"
float yaw=0.f,pitch=0.f,roll=0.f;
@@ -64,7 +55,22 @@ void DrawRasterizerLine(float const* , float const*, int)
int main(int argc,char** argv)
{
setCameraDistance(20.f);
CollisionDemo* colDemo = new CollisionDemo();
colDemo->setCameraDistance(18.f);
colDemo->initPhysics();
return glutmain(argc, argv,screenWidth,screenHeight,"Collision Demo",colDemo);
}
void CollisionDemo::initPhysics()
{
m_debugMode |= IDebugDraw::DBG_DrawWireframe;
m_azi = 250.f;
m_ele = 25.f;
tr[0].setOrigin(SimdVector3(0.0013328250f,8.1363249f,7.0390840f));
tr[1].setOrigin(SimdVector3(0.00000000f,9.1262732f,2.0343180f));
@@ -90,25 +96,17 @@ int main(int argc,char** argv)
SimdVector3 boxHalfExtentsA(1.0000004768371582f,1.0000004768371582f,1.0000001192092896f);
SimdVector3 boxHalfExtentsB(3.2836332321166992f,3.2836332321166992f,3.2836320400238037f);
BoxShape boxA(boxHalfExtentsA);
BoxShape boxB(boxHalfExtentsB);
shapePtr[0] = &boxA;
shapePtr[1] = &boxB;
BoxShape* boxA = new BoxShape(boxHalfExtentsA);
BoxShape* boxB = new BoxShape(boxHalfExtentsB);
shapePtr[0] = boxA;
shapePtr[1] = boxB;
SimdTransform tr;
tr.setIdentity();
return glutmain(argc, argv,screenWidth,screenHeight,"Collision Demo");
}
//to be implemented by the demo
void clientMoveAndDisplay()
void CollisionDemo::clientMoveAndDisplay()
{
clientDisplay();
displayCallback();
}
@@ -117,7 +115,7 @@ SimplexSolverInterface& gGjkSimplexSolver = sGjkSimplexSolver;
void clientDisplay(void) {
void CollisionDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
@@ -182,37 +180,10 @@ void clientDisplay(void) {
orn.setEuler(yaw,pitch,roll);
tr[0].setRotation(orn);
// pitch += 0.005f;
// yaw += 0.01f;
pitch += 0.005f;
yaw += 0.01f;
glFlush();
glutSwapBuffers();
}
void clientResetScene()
{
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef COLLISION_DEMO_H
#define COLLISION_DEMO_H
#include "DemoApplication.h"
///CollisionDemo shows the low-level direct access to GJK
class CollisionDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
}
};
#endif //COLLISION_DEMO_H

View File

@@ -24,29 +24,14 @@ subject to the following restrictions:
#include "CollisionShapes/ConvexHullShape.h"
#include "CollisionShapes/BoxShape.h"
#include "CollisionDispatch/CollisionWorld.h"
#include "CollisionDispatch/CollisionObject.h"
#include "CollisionDispatch/CollisionDispatcher.h"
#include "BroadphaseCollision/SimpleBroadphase.h"
#include "BroadphaseCollision/AxisSweep3.h"
#include "IDebugDraw.h"
#include "GL_ShapeDrawer.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "CollisionInterfaceDemo.h"
#include "GlutStuff.h"
@@ -66,8 +51,20 @@ int screenHeight = 480.f;
int main(int argc,char** argv)
{
clientResetScene();
CollisionInterfaceDemo* collisionInterfaceDemo = new CollisionInterfaceDemo();
collisionInterfaceDemo->initPhysics();
collisionInterfaceDemo->clientResetScene();
return glutmain(argc, argv,screenWidth,screenHeight,"Collision Interface Demo",collisionInterfaceDemo);
}
void CollisionInterfaceDemo::initPhysics()
{
m_debugMode |= IDebugDraw::DBG_DrawWireframe;
SimdMatrix3x3 basisA;
basisA.setIdentity();
@@ -80,38 +77,39 @@ int main(int argc,char** argv)
SimdPoint3 points0[3]={SimdPoint3(1,0,0),SimdPoint3(0,1,0),SimdPoint3(0,0,1)};
SimdPoint3 points1[5]={SimdPoint3(1,0,0),SimdPoint3(0,1,0),SimdPoint3(0,0,1),SimdPoint3(0,0,-1),SimdPoint3(-1,-1,0)};
BoxShape boxA(SimdVector3(1,1,1));
BoxShape boxB(SimdVector3(0.5,0.5,0.5));
BoxShape* boxA = new BoxShape(SimdVector3(1,1,1));
BoxShape* boxB = new BoxShape(SimdVector3(0.5,0.5,0.5));
//ConvexHullShape hullA(points0,3);
//hullA.setLocalScaling(SimdVector3(3,3,3));
//ConvexHullShape hullB(points1,4);
//hullB.setLocalScaling(SimdVector3(4,4,4));
objects[0].m_collisionShape = boxA;//&hullA;
objects[1].m_collisionShape = boxB;//&hullB;
objects[0].m_collisionShape = &boxA;//&hullA;
objects[1].m_collisionShape = &boxB;//&hullB;
CollisionDispatcher dispatcher;
//SimpleBroadphase broadphase;
CollisionDispatcher* dispatcher = new CollisionDispatcher;
SimdVector3 worldAabbMin(-1000,-1000,-1000);
SimdVector3 worldAabbMax(1000,1000,1000);
AxisSweep3 broadphase(worldAabbMin,worldAabbMax);
AxisSweep3* broadphase = new AxisSweep3(worldAabbMin,worldAabbMax);
//SimpleBroadphase is a brute force alternative, performing N^2 aabb overlap tests
//SimpleBroadphase* broadphase = new SimpleBroadphase;
collisionWorld = new CollisionWorld(&dispatcher,&broadphase);
collisionWorld = new CollisionWorld(dispatcher,broadphase);
collisionWorld->AddCollisionObject(&objects[0]);
collisionWorld->AddCollisionObject(&objects[1]);
return glutmain(argc, argv,screenWidth,screenHeight,"Collision Interface Demo");
}
//to be implemented by the demo
void clientMoveAndDisplay()
void CollisionInterfaceDemo::clientMoveAndDisplay()
{
clientDisplay();
displayCallback();
}
@@ -120,7 +118,7 @@ SimplexSolverInterface& gGjkSimplexSolver = sGjkSimplexSolver;
void clientDisplay(void) {
void CollisionInterfaceDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
@@ -129,7 +127,7 @@ void clientDisplay(void) {
collisionWorld->PerformDiscreteCollisionDetection();
int i;
/*
///one way to draw all the contact points is iterating over contact manifolds / points:
int numManifolds = collisionWorld->GetDispatcher()->GetNumManifolds();
@@ -155,9 +153,10 @@ void clientDisplay(void) {
glVertex3d(ptB.x(),ptB.y(),ptB.z());
glEnd();
}
}
*/
//you can un-comment out this line, and then all points are removed
//contactManifold->ClearManifold();
}
//GL_ShapeDrawer::DrawCoordSystem();
@@ -178,7 +177,7 @@ void clientDisplay(void) {
orn.setEuler(yaw,pitch,roll);
objects[1].m_worldTransform.setOrigin(objects[1].m_worldTransform.getOrigin()+SimdVector3(0,-0.01,0));
//objects[0].m_worldTransform.setRotation(orn);
objects[0].m_worldTransform.setRotation(orn);
pitch += 0.005f;
yaw += 0.01f;
@@ -187,28 +186,10 @@ void clientDisplay(void) {
glutSwapBuffers();
}
void clientResetScene()
void CollisionInterfaceDemo::clientResetScene()
{
objects[0].m_worldTransform.setOrigin(SimdVector3(0.0f,3.f,0.f));
objects[1].m_worldTransform.setOrigin(SimdVector3(0.0f,9.f,0.f));
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

View File

@@ -0,0 +1,35 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef COLLISION_INTERFACE_DEMO_H
#define COLLISION_INTERFACE_DEMO_H
#include "DemoApplication.h"
///CollisionInterfaceDemo shows how to use the collision detection without dynamics (CollisionWorld/CollisionObject)
class CollisionInterfaceDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene();
};
#endif //COLLISION_INTERFACE_DEMO_H

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef CONCAVE_DEMO_H
#define CONCAVE_DEMO_H
#include "DemoApplication.h"
///ConcaveDemo shows usage of static concave triangle meshes
///It also shows per-triangle material (friction/restitution) through CustomMaterialCombinerCallback
class ConcaveDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene();
};
#endif //CONCAVE_DEMO_H

View File

@@ -16,76 +16,28 @@ subject to the following restrictions:
#include "CcdPhysicsEnvironment.h"
#include "CcdPhysicsController.h"
#include "MyMotionState.h"
//#include "GL_LineSegmentShape.h"
#include "CollisionShapes/BoxShape.h"
#include "CollisionShapes/Simplex1to4Shape.h"
#include "Dynamics/RigidBody.h"
#include "BroadphaseCollision/AxisSweep3.h"
#include "ConstraintSolver/SequentialImpulseConstraintSolver.h"
//#include "ConstraintSolver/OdeConstraintSolver.h"
#include "CollisionDispatch/CollisionDispatcher.h"
#include "BroadphaseCollision/SimpleBroadphase.h"
#include "CollisionShapes/TriangleMeshShape.h"
#include "CollisionShapes/TriangleIndexVertexArray.h"
#include "CollisionShapes/BvhTriangleMeshShape.h"
#include "CollisionShapes/TriangleMesh.h"
#include "IDebugDraw.h"
#include "GLDebugDrawer.h"
#include "PHY_Pro.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "ConcaveDemo.h"
#include "GL_ShapeDrawer.h"
#include "GlutStuff.h"
const int numObjects = 80;
const int maxNumObjects = 100;
MyMotionState ms[maxNumObjects];
CcdPhysicsController* physObjects[maxNumObjects] = {0,0,0,0};
int shapeIndex[maxNumObjects];
CcdPhysicsEnvironment* physicsEnvironmentPtr = 0;
TriangleMesh meshData;
StridingMeshInterface* ptr;
GLDebugDrawer debugDrawer;
//GL_LineSegmentShape shapeE(SimdPoint3(-50,0,0),
// SimdPoint3(50,0,0));
CollisionShape* shapePtr[5] =
{
new BoxShape (SimdVector3(100,10,100)),
new BoxShape (SimdVector3(2,2,2)),
new BU_Simplex1to4(SimdPoint3(-2,-2,-2),SimdPoint3(2,-2,-2),SimdPoint3(-2,2,-2),SimdPoint3(0,0,2)),
new BoxShape (SimdVector3(1,3,1)),
#ifdef DEBUG_MESH
new TriangleMeshShape(&meshData),
#else
NULL,
#endif
//(&meshData)
};
static const int NUM_VERTICES = 5;
static const int NUM_TRIANGLES=4;
@@ -155,82 +107,16 @@ int main(int argc,char** argv)
{
gContactAddedCallback = CustomMaterialCombinerCallback;
printf("BroadphaseProxy: %i\n",sizeof(BroadphaseProxy));
printf("AxisSweep3::Handle : %i\n",sizeof(AxisSweep3::Handle));
ConcaveDemo* concaveDemo = new ConcaveDemo();
concaveDemo->initPhysics();
concaveDemo->setCameraDistance(30.f);
printf("SimpleBroadphaseProxy : %i\n",sizeof(SimpleBroadphaseProxy));
return glutmain(argc, argv,640,480,"Static Concave Mesh Demo",concaveDemo);
}
printf("RigidBody : %i\n",sizeof(RigidBody));
printf("CcdPhysicsController: %i\n",sizeof(CcdPhysicsController));
printf("ManifoldPoint: %i\n",sizeof(ManifoldPoint));
setCameraDistance(30.f);
#define TRISIZE 10.f
#ifdef DEBUG_MESH
SimdVector3 vert0(-TRISIZE ,0,TRISIZE );
SimdVector3 vert1(TRISIZE ,10,TRISIZE );
SimdVector3 vert2(TRISIZE ,0,-TRISIZE );
meshData.AddTriangle(vert0,vert1,vert2);
SimdVector3 vert3(-TRISIZE ,0,TRISIZE );
SimdVector3 vert4(TRISIZE ,0,-TRISIZE );
SimdVector3 vert5(-TRISIZE ,0,-TRISIZE );
meshData.AddTriangle(vert3,vert4,vert5);
#else
#ifdef ODE_MESH
SimdVector3 Size = SimdVector3(15.f,15.f,12.5f);
gVertices[0][0] = -Size[0];
gVertices[0][1] = Size[2];
gVertices[0][2] = -Size[1];
gVertices[1][0] = Size[0];
gVertices[1][1] = Size[2];
gVertices[1][2] = -Size[1];
gVertices[2][0] = Size[0];
gVertices[2][1] = Size[2];
gVertices[2][2] = Size[1];
gVertices[3][0] = -Size[0];
gVertices[3][1] = Size[2];
gVertices[3][2] = Size[1];
gVertices[4][0] = 0;
gVertices[4][1] = 0;
gVertices[4][2] = 0;
gIndices[0] = 0;
gIndices[1] = 1;
gIndices[2] = 4;
gIndices[3] = 1;
gIndices[4] = 2;
gIndices[5] = 4;
gIndices[6] = 2;
gIndices[7] = 3;
gIndices[8] = 4;
gIndices[9] = 3;
gIndices[10] = 0;
gIndices[11] = 4;
int vertStride = sizeof(SimdVector3);
int indexStride = 3*sizeof(int);
TriangleIndexVertexArray* indexVertexArrays = new TriangleIndexVertexArray(NUM_TRIANGLES,
gIndices,
indexStride,
NUM_VERTICES,(float*) &gVertices[0].x(),vertStride);
//shapePtr[4] = new TriangleMeshShape(indexVertexArrays);
shapePtr[4] = new BvhTriangleMeshShape(indexVertexArrays);
#else
void ConcaveDemo::initPhysics()
{
#define TRISIZE 10.f
int vertStride = sizeof(SimdVector3);
int indexStride = 3*sizeof(int);
@@ -274,190 +160,49 @@ int main(int argc,char** argv)
indexStride,
totalVerts,(float*) &gVertices[0].x(),vertStride);
//shapePtr[4] = new TriangleMeshShape(indexVertexArrays);
shapePtr[4] = new BvhTriangleMeshShape(indexVertexArrays);
#endif
CollisionShape* trimeshShape = new BvhTriangleMeshShape(indexVertexArrays);
#endif//DEBUG_MESH
ConstraintSolver* solver = new SequentialImpulseConstraintSolver;
//ConstraintSolver* solver = new OdeConstraintSolver;
CollisionDispatcher* dispatcher = new CollisionDispatcher();
OverlappingPairCache* broadphase = new SimpleBroadphase();
physicsEnvironmentPtr = new CcdPhysicsEnvironment(dispatcher,broadphase);
m_physicsEnvironmentPtr = new CcdPhysicsEnvironment(dispatcher,broadphase);
bool isDynamic = false;
float mass = 0.f;
SimdTransform startTransform;
startTransform.setIdentity();
startTransform.setOrigin(SimdVector3(0,-2,0));
physicsEnvironmentPtr->setGravity(-1,-10,1);
PHY_ShapeProps shapeProps;
shapeProps.m_do_anisotropic = false;
shapeProps.m_do_fh = false;
shapeProps.m_do_rot_fh = false;
shapeProps.m_friction_scaling[0] = 1.;
shapeProps.m_friction_scaling[1] = 1.;
shapeProps.m_friction_scaling[2] = 1.;
CcdPhysicsController* staticTrimesh = LocalCreatePhysicsObject(isDynamic, mass, startTransform,trimeshShape);
//enable custom material callback
staticTrimesh->GetRigidBody()->m_collisionFlags |= CollisionObject::customMaterialCallback;
shapeProps.m_inertia = 1.f;
shapeProps.m_lin_drag = 0.95999998f;
shapeProps.m_ang_drag = 0.89999998f;
shapeProps.m_mass = 1.0f;
PHY_MaterialProps materialProps;
materialProps.m_friction = 0.f;// 50.5f;
materialProps.m_restitution = 0.1f;
CcdConstructionInfo ccdObjectCi;
ccdObjectCi.m_friction = 0.f;//50.5f;
ccdObjectCi.m_linearDamping = shapeProps.m_lin_drag;
ccdObjectCi.m_angularDamping = shapeProps.m_ang_drag;
SimdTransform tr;
tr.setIdentity();
for (i=0;i<numObjects;i++)
{
if (i>0)
shapeIndex[i] = 1;//2 = tetrahedron
else
shapeIndex[i] = 4;
for (int i=0;i<10;i++)
{
CollisionShape* boxShape = new BoxShape(SimdVector3(1,1,1));
startTransform.setOrigin(SimdVector3(2*i,1,1));
CcdPhysicsController* boxRigidBody = LocalCreatePhysicsObject(true, 1, startTransform,boxShape);
}
}
for (i=0;i<numObjects;i++)
{
shapeProps.m_shape = shapePtr[shapeIndex[i]];
bool isDyna = i>0;
if (!i)
{
ccdObjectCi.m_friction = 0.0f;
//SimdQuaternion orn(0,0,0.1*SIMD_HALF_PI);
//ms[i].setWorldOrientation(orn.x(),orn.y(),orn.z(),orn[3]);
//ms[i].setWorldPosition(0,-10,0);
} else
{
ccdObjectCi.m_friction = 0.5f;
ms[i].setWorldPosition(10,i*15-10,0);
}
//either create a few stacks, to show several islands, or create 1 large stack, showing stability
//ms[i].setWorldPosition((i*5) % 30,i*15-10,0);
ccdObjectCi.m_MotionState = &ms[i];
ccdObjectCi.m_gravity = SimdVector3(0,0,0);
ccdObjectCi.m_localInertiaTensor =SimdVector3(0,0,0);
if (!isDyna)
{
shapeProps.m_mass = 0.f;
ccdObjectCi.m_mass = shapeProps.m_mass;
ccdObjectCi.m_collisionFlags = CollisionObject::customMaterialCallback;
}
else
{
shapeProps.m_mass = 1.f;
ccdObjectCi.m_mass = shapeProps.m_mass;
ccdObjectCi.m_collisionFlags =0;
}
SimdVector3 localInertia;
if (shapeProps.m_mass>0.f)
{
shapePtr[shapeIndex[i]]->CalculateLocalInertia(shapeProps.m_mass,localInertia);
} else
{
localInertia.setValue(0.f,0.f,0.f);
m_physicsEnvironmentPtr->setGravity(-1,-10,1);
}
ccdObjectCi.m_localInertiaTensor = localInertia;
ccdObjectCi.m_collisionShape = shapePtr[shapeIndex[i]];
physObjects[i]= new CcdPhysicsController( ccdObjectCi);
physicsEnvironmentPtr->addCcdPhysicsController( physObjects[i]);
/* if (i==0)
{
physObjects[i]->SetAngularVelocity(0,0,-2,true);
physObjects[i]->GetRigidBody()->setDamping(0,0);
}
*/
//for the line that represents the AABB extents
physicsEnvironmentPtr->setDebugDrawer(&debugDrawer);
}
return glutmain(argc, argv,640,480,"Static Concave Mesh Demo");
m_physicsEnvironmentPtr->setDebugDrawer(&debugDrawer);
}
void renderme()
{
float m[16];
int i;
debugDrawer.SetDebugMode(getDebugMode());
for (i=0;i<numObjects;i++)
{
SimdTransform transA;
transA.setIdentity();
float pos[3];
float rot[4];
ms[i].getWorldPosition(pos[0],pos[1],pos[2]);
ms[i].getWorldOrientation(rot[0],rot[1],rot[2],rot[3]);
SimdQuaternion q(rot[0],rot[1],rot[2],rot[3]);
transA.setRotation(q);
SimdPoint3 dpos;
dpos.setValue(pos[0],pos[1],pos[2]);
transA.setOrigin( dpos );
transA.getOpenGLMatrix( m );
SimdVector3 wireColor(0.f,0.f,1.f); //wants deactivation
///color differently for active, sleeping, wantsdeactivation states
if (physObjects[i]->GetRigidBody()->GetActivationState() == 1) //active
{
wireColor = SimdVector3 (1.f,0.f,0.f);
}
if (physObjects[i]->GetRigidBody()->GetActivationState() == 2) //ISLAND_SLEEPING
{
wireColor = SimdVector3 (0.f,1.f,0.f);
}
char extraDebug[125];
//sprintf(extraDebug,"islId, Body=%i , %i",physObjects[i]->GetRigidBody()->m_islandTag1,physObjects[i]->GetRigidBody()->m_debugBodyId);
shapePtr[shapeIndex[i]]->SetExtraDebugInfo(extraDebug);
GL_ShapeDrawer::DrawOpenGL(m,shapePtr[shapeIndex[i]],wireColor,getDebugMode());
}
}
void clientMoveAndDisplay()
void ConcaveDemo::clientMoveAndDisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float deltaTime = 1.f/60.f;
physicsEnvironmentPtr->proceedDeltaTime(0.f,deltaTime);
m_physicsEnvironmentPtr->proceedDeltaTime(0.f,deltaTime);
renderme();
@@ -466,10 +211,25 @@ void clientMoveAndDisplay()
}
void ConcaveDemo::clientResetScene()
{
int numObj = m_physicsEnvironmentPtr->GetNumControllers();
//skip ground
for (int i=1;i<numObj;i++)
{
CcdPhysicsController* ctrl = m_physicsEnvironmentPtr->GetPhysicsController(i);
ctrl->setPosition(2*i,1,1);
ctrl->setOrientation(0,0,0,1);
ctrl->SetLinearVelocity(0,0,0,0);
ctrl->SetAngularVelocity(0,0,0,0);
}
}
void clientDisplay(void) {
void ConcaveDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -480,26 +240,3 @@ void clientDisplay(void) {
}
void clientResetScene()
{
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

View File

@@ -16,14 +16,12 @@ subject to the following restrictions:
#include "CcdPhysicsEnvironment.h"
#include "CcdPhysicsController.h"
#include "MyMotionState.h"
//#include "GL_LineSegmentShape.h"
#include "CollisionShapes/BoxShape.h"
#include "CollisionShapes/Simplex1to4Shape.h"
#include "CollisionShapes/EmptyShape.h"
#include "Dynamics/RigidBody.h"
#include "ConstraintSolver/SequentialImpulseConstraintSolver.h"
//#include "ConstraintSolver/OdeConstraintSolver.h"
#include "CollisionDispatch/CollisionDispatcher.h"
#include "BroadphaseCollision/SimpleBroadphase.h"
#include "IDebugDraw.h"
@@ -34,50 +32,35 @@ subject to the following restrictions:
#include "BMF_Api.h"
#include <stdio.h> //printf debugging
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "ConstraintDemo.h"
#include "GL_ShapeDrawer.h"
#include "GlutStuff.h"
const int numObjects = 3;
const int maxNumObjects = 400;
MyMotionState ms[maxNumObjects];
CcdPhysicsController* physObjects[maxNumObjects] = {0,0,0,0};
int shapeIndex[maxNumObjects];
CcdPhysicsEnvironment* physicsEnvironmentPtr = 0;
#define CUBE_HALF_EXTENTS 1.f
#define CUBE_HALF_EXTENTS 1
//GL_LineSegmentShape shapeE(SimdPoint3(-50,0,0),
// SimdPoint3(50,0,0));
CollisionShape* shapePtr[4] =
{
new BoxShape (SimdVector3(10,10,10)),
new BoxShape (SimdVector3(CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS)),
//new EmptyShape(),
new BU_Simplex1to4(SimdPoint3(-1,-1,-1),SimdPoint3(1,-1,-1),SimdPoint3(-1,1,-1),SimdPoint3(0,0,1)),
//new BoxShape (SimdVector3(0.4,1,0.8))
};
GLDebugDrawer debugDrawer;
GLDebugDrawer debugDrawer;
int main(int argc,char** argv)
{
ConstraintDemo* constraintDemo = new ConstraintDemo();
constraintDemo->initPhysics();
constraintDemo->setCameraDistance(46.f);
return glutmain(argc, argv,640,480,"Constraint Demo. http://www.continuousphysics.com/Bullet/phpBB2/",constraintDemo);
}
void ConstraintDemo::initPhysics()
{
ConstraintSolver* solver = new SequentialImpulseConstraintSolver;
//ConstraintSolver* solver = new OdeConstraintSolver;
@@ -87,111 +70,28 @@ int main(int argc,char** argv)
OverlappingPairCache* broadphase = new SimpleBroadphase();
physicsEnvironmentPtr = new CcdPhysicsEnvironment(dispatcher,broadphase);
physicsEnvironmentPtr->setDeactivationTime(0.f);
m_physicsEnvironmentPtr = new CcdPhysicsEnvironment(dispatcher,broadphase);
m_physicsEnvironmentPtr->setDeactivationTime(0.f);
m_physicsEnvironmentPtr->setGravity(0,-10,0);
physicsEnvironmentPtr->setGravity(0,-10,0);
PHY_ShapeProps shapeProps;
CollisionShape* shape = new BoxShape(SimdVector3(CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS));
SimdTransform trans;
trans.setIdentity();
trans.setOrigin(SimdVector3(0,20,0));
bool isDynamic = false;
float mass = 1.f;
CcdPhysicsController* ctrl0 = LocalCreatePhysicsObject( isDynamic,mass,trans,shape);
trans.setOrigin(SimdVector3(2*CUBE_HALF_EXTENTS,20,0));
isDynamic = true;
CcdPhysicsController* ctrl1 = LocalCreatePhysicsObject( isDynamic,mass,trans,shape);
shapeProps.m_do_anisotropic = false;
shapeProps.m_do_fh = false;
shapeProps.m_do_rot_fh = false;
shapeProps.m_friction_scaling[0] = 1.;
shapeProps.m_friction_scaling[1] = 1.;
shapeProps.m_friction_scaling[2] = 1.;
shapeProps.m_inertia = 1.f;
shapeProps.m_lin_drag = 0.2f;
shapeProps.m_ang_drag = 0.1f;
shapeProps.m_mass = 10.0f;
PHY_MaterialProps materialProps;
materialProps.m_friction = 10.5f;
materialProps.m_restitution = 0.0f;
CcdConstructionInfo ccdObjectCi;
ccdObjectCi.m_friction = 0.5f;
ccdObjectCi.m_linearDamping = shapeProps.m_lin_drag;
ccdObjectCi.m_angularDamping = shapeProps.m_ang_drag;
SimdTransform tr;
tr.setIdentity();
int i;
for (i=0;i<numObjects;i++)
{
if (i>0)
shapeIndex[i] = 1;//2 to test start with EmptyShape
else
shapeIndex[i] = 0;
}
for (i=0;i<numObjects;i++)
{
shapeProps.m_shape = shapePtr[shapeIndex[i]];
shapeProps.m_shape->SetMargin(0.05f);
bool isDyna = i>1;
if (0)//i==1)
{
SimdQuaternion orn(0,0,0.1*SIMD_HALF_PI);
ms[i].setWorldOrientation(orn.x(),orn.y(),orn.z(),orn[3]);
}
if (i>0)
{
ms[i].setWorldPosition(0,i*CUBE_HALF_EXTENTS*2 - CUBE_HALF_EXTENTS,0);
} else
{
ms[i].setWorldPosition(0,-10,0);
}
ccdObjectCi.m_MotionState = &ms[i];
ccdObjectCi.m_gravity = SimdVector3(0,0,0);
ccdObjectCi.m_localInertiaTensor =SimdVector3(0,0,0);
if (!isDyna)
{
shapeProps.m_mass = 0.f;
ccdObjectCi.m_mass = shapeProps.m_mass;
}
else
{
shapeProps.m_mass = 1.f;
ccdObjectCi.m_mass = shapeProps.m_mass;
}
SimdVector3 localInertia;
if (shapePtr[shapeIndex[i]]->GetShapeType() == EMPTY_SHAPE_PROXYTYPE)
{
//take inertia from first shape
shapePtr[1]->CalculateLocalInertia(shapeProps.m_mass,localInertia);
} else
{
shapePtr[shapeIndex[i]]->CalculateLocalInertia(shapeProps.m_mass,localInertia);
}
ccdObjectCi.m_localInertiaTensor = localInertia;
ccdObjectCi.m_collisionShape = shapePtr[shapeIndex[i]];
physObjects[i]= new CcdPhysicsController( ccdObjectCi);
physicsEnvironmentPtr->addCcdPhysicsController( physObjects[i]);
physicsEnvironmentPtr->setDebugDrawer(&debugDrawer);
}
clientResetScene();
{
//physObjects[i]->SetAngularVelocity(0,0,-2,true);
int constraintId;
float pivotX=CUBE_HALF_EXTENTS,
@@ -200,131 +100,28 @@ int main(int argc,char** argv)
float axisX=0,axisY=0,axisZ=1;
constraintId =physicsEnvironmentPtr->createConstraint(
physObjects[1],
//0,
physObjects[2],
//PHY_POINT2POINT_CONSTRAINT,
PHY_GENERIC_6DOF_CONSTRAINT,//can leave any of the 6 degree of freedom 'free' or 'locked'
constraintId =m_physicsEnvironmentPtr->createConstraint(
ctrl0,
ctrl1,
PHY_POINT2POINT_CONSTRAINT,
//PHY_GENERIC_6DOF_CONSTRAINT,//can leave any of the 6 degree of freedom 'free' or 'locked'
//PHY_LINEHINGE_CONSTRAINT,
pivotX,pivotY,pivotZ,
axisX,axisY,axisZ
);
}
setCameraDistance(46.f);
return glutmain(argc, argv,640,480,"Constraint Demo. http://www.continuousphysics.com/Bullet/phpBB2/");
}
//to be implemented by the demo
void renderme()
{
debugDrawer.SetDebugMode(getDebugMode());
float m[16];
int i;
for (i=0;i<numObjects;i++)
{
SimdTransform transA;
transA.setIdentity();
float pos[3];
float rot[4];
ms[i].getWorldPosition(pos[0],pos[1],pos[2]);
ms[i].getWorldOrientation(rot[0],rot[1],rot[2],rot[3]);
SimdQuaternion q(rot[0],rot[1],rot[2],rot[3]);
transA.setRotation(q);
SimdPoint3 dpos;
dpos.setValue(pos[0],pos[1],pos[2]);
transA.setOrigin( dpos );
transA.getOpenGLMatrix( m );
SimdVector3 wireColor(0.f,0.f,1.f); //wants deactivation
///color differently for active, sleeping, wantsdeactivation states
if (physObjects[i]->GetRigidBody()->GetActivationState() == 1) //active
{
wireColor = SimdVector3 (1.f,0.f,0.f);
}
if (physObjects[i]->GetRigidBody()->GetActivationState() == 2) //ISLAND_SLEEPING
{
wireColor = SimdVector3 (0.f,1.f,0.f);
}
char extraDebug[125];
sprintf(extraDebug,"islId, Body=%i , %i",physObjects[i]->GetRigidBody()->m_islandTag1,physObjects[i]->GetRigidBody()->m_debugBodyId);
physObjects[i]->GetRigidBody()->GetCollisionShape()->SetExtraDebugInfo(extraDebug);
GL_ShapeDrawer::DrawOpenGL(m,physObjects[i]->GetRigidBody()->GetCollisionShape(),wireColor,getDebugMode());
if (getDebugMode()!=0 && (i>0))
{
if (physObjects[i]->GetRigidBody()->GetCollisionShape()->GetShapeType() == EMPTY_SHAPE_PROXYTYPE)
{
physObjects[i]->GetRigidBody()->SetCollisionShape(shapePtr[1]);
//remove the persistent collision pairs that were created based on the previous shape
BroadphaseProxy* bpproxy = physObjects[i]->GetRigidBody()->m_broadphaseHandle;
physicsEnvironmentPtr->GetBroadphase()->CleanProxyFromPairs(bpproxy);
SimdVector3 newinertia;
SimdScalar newmass = 10.f;
physObjects[i]->GetRigidBody()->GetCollisionShape()->CalculateLocalInertia(newmass,newinertia);
physObjects[i]->GetRigidBody()->setMassProps(newmass,newinertia);
physObjects[i]->GetRigidBody()->updateInertiaTensor();
}
}
}
glRasterPos3f(20,20,0);
char buf[124];
sprintf(buf,"space to reset");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
glRasterPos3f(20,15,0);
sprintf(buf,"c to show contact points");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
glRasterPos3f(20,10,0);
sprintf(buf,"cursor keys and z,x to navigate");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
glRasterPos3f(20,5,0);
sprintf(buf,"i to toggle simulation, s single step");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
glRasterPos3f(20,0,0);
sprintf(buf,"q to quit");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
glRasterPos3f(20,-5,0);
sprintf(buf,"d to toggle deactivation");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
}
void clientMoveAndDisplay()
void ConstraintDemo::clientMoveAndDisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float deltaTime = 1.f/60.f;
physicsEnvironmentPtr->proceedDeltaTime(0.f,deltaTime);
m_physicsEnvironmentPtr->proceedDeltaTime(0.f,deltaTime);
renderme();
@@ -336,67 +133,14 @@ void clientMoveAndDisplay()
void clientDisplay(void) {
void ConstraintDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderme();
glFlush();
glutSwapBuffers();
}
///make this positive to show stack falling from a distance
///this shows the penalty tresholds in action, springy/spungy look
#define EXTRA_HEIGHT 20.f
void clientResetScene()
{
int i;
for (i=0;i<numObjects;i++)
{
if (i>0)
{
//stack them
int colsize = 10;
int row = (i*CUBE_HALF_EXTENTS*2)/(colsize*2*CUBE_HALF_EXTENTS);
int col = (i)%(colsize)-colsize/2;
physObjects[i]->setPosition(col*2*CUBE_HALF_EXTENTS + (row%2)*CUBE_HALF_EXTENTS,
row*2*CUBE_HALF_EXTENTS+CUBE_HALF_EXTENTS+EXTRA_HEIGHT,
0);
physObjects[i]->setOrientation(0,0,0,1);
physObjects[i]->SetLinearVelocity(0,0,0,false);
physObjects[i]->SetAngularVelocity(0,0,0,false);
} else
{
ms[i].setWorldPosition(0,-10,0);
}
}
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef CONSTRAINT_DEMO_H
#define CONSTRAINT_DEMO_H
#include "DemoApplication.h"
///ConstraintDemo shows how to create a constraint, like Hinge or GenericD6constraint
class ConstraintDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
}
};
#endif //CONSTRAINT_DEMO_H

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef CONTINUOUS_CONVEX_COLLISION_DEMO_H
#define CONTINUOUS_CONVEX_COLLISION_DEMO_H
#include "DemoApplication.h"
///ContinuousConvexCollisionDemo shows the working of the continuous collision detection, including linear and angular motion
class ContinuousConvexCollisionDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
}
};
#endif //CONTINUOUS_CONVEX_COLLISION_DEMO_H

View File

@@ -36,19 +36,11 @@
#include "CollisionShapes/Simplex1to4Shape.h"
#include "GL_ShapeDrawer.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
#include "NarrowPhaseCollision/ConvexPenetrationDepthSolver.h"
#include "GL_ShapeDrawer.h"
#include "ContinuousConvexCollision.h"
#include "GlutStuff.h"
@@ -65,21 +57,24 @@ PolyhedralConvexShape* shapePtr[maxNumObjects];
SimdTransform fromTrans[maxNumObjects];
SimdTransform toTrans[maxNumObjects];
//SimdTransform tr[numObjects];
void DrawRasterizerLine(float const* , float const*, int)
{
}
int screenWidth = 640.f;
int screenHeight = 480.f;
int main(int argc,char** argv)
{
ContinuousConvexCollisionDemo* ccdDemo = new ContinuousConvexCollisionDemo();
setCameraDistance(40.f);
ccdDemo->setCameraDistance(40.f);
ccdDemo->initPhysics();
return glutmain(argc, argv,screenWidth,screenHeight,"Continuous Convex Collision Demo",ccdDemo);
}
void ContinuousConvexCollisionDemo::initPhysics()
{
fromTrans[0].setOrigin(SimdVector3(0,10,20));
toTrans[0].setOrigin(SimdVector3(0,10,-20));
fromTrans[1].setOrigin(SimdVector3(-2,7,0));
@@ -101,17 +96,17 @@ int main(int argc,char** argv)
toTrans[1].setBasis(identBasis);
SimdVector3 boxHalfExtentsA(10,1,1);
SimdVector3 boxHalfExtentsB(1.1f,1.1f,1.1f);
BoxShape boxA(boxHalfExtentsA);
// BU_Simplex1to4 boxA(SimdPoint3(-2,0,-2),SimdPoint3(2,0,-2),SimdPoint3(0,0,2),SimdPoint3(0,2,0));
// BU_Simplex1to4 boxA(SimdPoint3(-12,0,0),SimdPoint3(12,0,0));
BoxShape* boxA = new BoxShape(boxHalfExtentsA);
// BU_Simplex1to4* boxA = new BU_Simplex1to4(SimdPoint3(-2,0,-2),SimdPoint3(2,0,-2),SimdPoint3(0,0,2),SimdPoint3(0,2,0));
// BU_Simplex1to4* boxA = new BU_Simplex1to4(SimdPoint3(-12,0,0),SimdPoint3(12,0,0));
BoxShape boxB(boxHalfExtentsB);
BoxShape* boxB = new BoxShape(boxHalfExtentsB);
// BU_Simplex1to4 boxB(SimdPoint3(0,10,0),SimdPoint3(0,-10,0));
shapePtr[0] = &boxA;
shapePtr[1] = &boxB;
shapePtr[0] = boxA;
shapePtr[1] = boxB;
shapePtr[0]->SetMargin(0.01f);
shapePtr[1]->SetMargin(0.01f);
@@ -121,18 +116,15 @@ int main(int argc,char** argv)
SimdTransformUtil::CalculateVelocity(fromTrans[i],toTrans[i],1.f,linVels[i],angVels[i]);
}
return glutmain(argc, argv,screenWidth,screenHeight,"Continuous Convex Collision Demo");
}
//to be implemented by the demo
void clientMoveAndDisplay()
void ContinuousConvexCollisionDemo::clientMoveAndDisplay()
{
clientDisplay();
displayCallback();
}
#include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
#include "NarrowPhaseCollision/ConvexPenetrationDepthSolver.h"
static VoronoiSimplexSolver sVoronoiSimplexSolver;
@@ -145,7 +137,7 @@ int minlines = 0;
int maxlines = 512;
void clientDisplay(void) {
void ContinuousConvexCollisionDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
@@ -206,12 +198,10 @@ void clientDisplay(void) {
fromTrans[1].setRotation(orn);
toTrans[1].setRotation(orn);
extern bool stepping;
extern bool singleStep;
if (stepping || singleStep)
if (m_stepping || m_singleStep)
{
singleStep = false;
m_singleStep = false;
pitch += 0.005f;
// yaw += 0.01f;
}
@@ -299,26 +289,4 @@ void clientDisplay(void) {
glutSwapBuffers();
}
void clientResetScene()
{
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef CONVEX_DECOMPOSITION_DEMO_H
#define CONVEX_DECOMPOSITION_DEMO_H
#include "DemoApplication.h"
///ConvexDecompositionDemo shows automatic convex decomposition of a concave mesh
class ConvexDecompositionDemo : public DemoApplication
{
public:
void initPhysics(const char* filename);
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
//not yet
}
};
#endif //CONVEX_DECOMPOSITION_DEMO_H

View File

@@ -35,21 +35,10 @@
#endif //USE_ALGEBRAIC_CCD
#include "CollisionShapes/SphereShape.h"
#include "CollisionShapes/Simplex1to4Shape.h"
#include "GL_ShapeDrawer.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "LinearConvexCastDemo.h"
#include "GlutStuff.h"
@@ -71,6 +60,16 @@ void DrawRasterizerLine(float const* , float const*, int)
int main(int argc,char** argv)
{
LinearConvexCastDemo* linearCastDemo = new LinearConvexCastDemo();
linearCastDemo->initPhysics();
return glutmain(argc, argv,screenWidth,screenHeight,"Linear Convex Cast Demo",linearCastDemo);
}
void LinearConvexCastDemo::initPhysics()
{
setCameraDistance(30.f);
tr[0].setOrigin(SimdVector3(0,0,0));
tr[1].setOrigin(SimdVector3(0,10,0));
@@ -93,7 +92,7 @@ int main(int argc,char** argv)
SimdVector3 boxHalfExtentsA(0.2,4,4);
SimdVector3 boxHalfExtentsB(6,6,6);
BoxShape boxA(boxHalfExtentsA);
BoxShape* boxA = new BoxShape(boxHalfExtentsA);
/* BU_Simplex1to4 boxB;
boxB.AddVertex(SimdPoint3(-5,0,-5));
boxB.AddVertex(SimdPoint3(5,0,-5));
@@ -101,30 +100,23 @@ int main(int argc,char** argv)
boxB.AddVertex(SimdPoint3(0,5,0));
*/
BoxShape boxB(boxHalfExtentsB);
shapePtr[0] = &boxA;
shapePtr[1] = &boxB;
BoxShape* boxB = new BoxShape(boxHalfExtentsB);
shapePtr[0] = boxA;
shapePtr[1] = boxB;
shapePtr[0]->SetMargin(0.01f);
shapePtr[1]->SetMargin(0.01f);
// boxA.SetMargin(1.f);
// boxB.SetMargin(1.f);
SimdTransform tr;
tr.setIdentity();
return glutmain(argc, argv,screenWidth,screenHeight,"Linear Convex Cast Demo");
}
//to be implemented by the demo
void clientMoveAndDisplay()
void LinearConvexCastDemo::clientMoveAndDisplay()
{
clientDisplay();
displayCallback();
}
#include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
@@ -136,7 +128,9 @@ SimplexSolverInterface& gGjkSimplexSolver = sVoronoiSimplexSolver;
bool drawLine= false;
void clientDisplay(void) {
void LinearConvexCastDemo::displayCallback(void)
{
updateCamera();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
@@ -159,12 +153,10 @@ void clientDisplay(void) {
orn.setEuler(yaw,pitch,roll);
tr[shapeIndex].setRotation(orn);
extern bool stepping;
extern bool singleStep;
if (stepping || singleStep)
if (m_stepping || m_singleStep)
{
singleStep = false;
m_singleStep = false;
pitch += 0.005f;
yaw += 0.01f;
}
@@ -239,25 +231,3 @@ void clientDisplay(void) {
glFlush();
glutSwapBuffers();
}
void clientResetScene()
{
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef LINEAR_CONVEX_CAST_DEMO_H
#define LINEAR_CONVEX_CAST_DEMO_H
#include "DemoApplication.h"
///LinearConvexCastDemo shows the working of the object sweep / pure-linear continuous collision detection query
class LinearConvexCastDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
}
};
#endif //LINEAR_CONVEX_CAST_DEMO_H

View File

@@ -0,0 +1,894 @@
/*
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.
*/
#include "DemoApplication.h"
#include "IDebugDraw.h"
#include "CcdPhysicsEnvironment.h"
#include "CcdPhysicsController.h"
#include "ConstraintSolver/Point2PointConstraint.h"//picking
#include "PHY_Pro.h"
#include "CollisionShapes/CollisionShape.h"
#include "CollisionShapes/BoxShape.h"
#include "GL_ShapeDrawer.h"
#include "BMF_Api.h"
int numObjects = 0;
const int maxNumObjects = 450;
DefaultMotionState ms[maxNumObjects];
CcdPhysicsController* physObjects[maxNumObjects];
SimdTransform startTransforms[maxNumObjects];
CollisionShape* gShapePtr[maxNumObjects];//1 rigidbody has 1 shape (no re-use of shapes)
DemoApplication::DemoApplication()
//see IDebugDraw.h for modes
:
m_physicsEnvironmentPtr(0),
m_debugMode(0),
m_cameraDistance(15.0),
m_ele(0.f),
m_azi(0.f),
m_cameraPosition(0.f,0.f,0.f),
m_cameraTargetPosition(0.f,0.f,0.f),
m_scaleBottom(0.5f),
m_scaleFactor(2.f),
m_cameraUp(0,1,0),
m_forwardAxis(2),
m_glutScreenWidth(0),
m_glutScreenHeight(0),
m_ShootBoxInitialSpeed(40.f),
m_stepping(true),
m_singleStep(false),
m_idle(false)
{
}
DemoApplication::~DemoApplication()
{
}
void DemoApplication::myinit(void)
{
GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
/* light_position is NOT default value */
GLfloat light_position0[] = { 1.0, 1.0, 1.0, 0.0 };
GLfloat light_position1[] = { -1.0, -1.0, -1.0, 0.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClearColor(0.8,0.8,0.8,0);
// glEnable(GL_CULL_FACE);
// glCullFace(GL_BACK);
}
void DemoApplication::setCameraDistance(float dist)
{
m_cameraDistance = dist;
}
float DemoApplication::getCameraDistance()
{
return m_cameraDistance;
}
void DemoApplication::toggleIdle() {
if (m_idle) {
m_idle = false;
}
else {
m_idle = true;
}
}
void DemoApplication::updateCamera() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float rele = m_ele * 0.01745329251994329547;// rads per deg
float razi = m_azi * 0.01745329251994329547;// rads per deg
SimdQuaternion rot(m_cameraUp,razi);
SimdVector3 eyePos(0,0,0);
eyePos[m_forwardAxis] = -m_cameraDistance;
SimdVector3 forward(eyePos[0],eyePos[1],eyePos[2]);
if (forward.length2() < SIMD_EPSILON)
{
forward.setValue(1.f,0.f,0.f);
}
SimdVector3 right = m_cameraUp.cross(forward);
SimdQuaternion roll(right,-rele);
eyePos = SimdMatrix3x3(rot) * SimdMatrix3x3(roll) * eyePos;
m_cameraPosition[0] = eyePos.getX();
m_cameraPosition[1] = eyePos.getY();
m_cameraPosition[2] = eyePos.getZ();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10000.0);
gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2],
m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2],
m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
glMatrixMode(GL_MODELVIEW);
}
const float STEPSIZE = 5;
void DemoApplication::stepLeft()
{
m_azi -= STEPSIZE; if (m_azi < 0) m_azi += 360; updateCamera();
}
void DemoApplication::stepRight()
{
m_azi += STEPSIZE; if (m_azi >= 360) m_azi -= 360; updateCamera();
}
void DemoApplication::stepFront()
{
m_ele += STEPSIZE; if (m_azi >= 360) m_azi -= 360; updateCamera();
}
void DemoApplication::stepBack()
{
m_ele -= STEPSIZE; if (m_azi < 0) m_azi += 360; updateCamera();
}
void DemoApplication::zoomIn()
{
m_cameraDistance -= 1; updateCamera();
}
void DemoApplication::zoomOut()
{
m_cameraDistance += 1; updateCamera();
}
void DemoApplication::reshape(int w, int h)
{
m_glutScreenWidth = w;
m_glutScreenHeight = h;
glViewport(0, 0, w, h);
updateCamera();
}
void DemoApplication::keyboardCallback(unsigned char key, int x, int y)
{
m_lastKey = 0;
switch (key)
{
case 'q' : exit(0); break;
case 'l' : stepLeft(); break;
case 'r' : stepRight(); break;
case 'f' : stepFront(); break;
case 'b' : stepBack(); break;
case 'z' : zoomIn(); break;
case 'x' : zoomOut(); break;
case 'i' : toggleIdle(); break;
case 'h':
if (m_debugMode & IDebugDraw::DBG_NoHelpText)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_NoHelpText);
else
m_debugMode |= IDebugDraw::DBG_NoHelpText;
break;
case 'w':
if (m_debugMode & IDebugDraw::DBG_DrawWireframe)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_DrawWireframe);
else
m_debugMode |= IDebugDraw::DBG_DrawWireframe;
break;
case 'p':
if (m_debugMode & IDebugDraw::DBG_ProfileTimings)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_ProfileTimings);
else
m_debugMode |= IDebugDraw::DBG_ProfileTimings;
break;
case 'm':
if (m_debugMode & IDebugDraw::DBG_EnableSatComparison)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_EnableSatComparison);
else
m_debugMode |= IDebugDraw::DBG_EnableSatComparison;
break;
case 'n':
if (m_debugMode & IDebugDraw::DBG_DisableBulletLCP)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_DisableBulletLCP);
else
m_debugMode |= IDebugDraw::DBG_DisableBulletLCP;
break;
case 't' :
if (m_debugMode & IDebugDraw::DBG_DrawText)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_DrawText);
else
m_debugMode |= IDebugDraw::DBG_DrawText;
break;
case 'y':
if (m_debugMode & IDebugDraw::DBG_DrawFeaturesText)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_DrawFeaturesText);
else
m_debugMode |= IDebugDraw::DBG_DrawFeaturesText;
break;
case 'a':
if (m_debugMode & IDebugDraw::DBG_DrawAabb)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_DrawAabb);
else
m_debugMode |= IDebugDraw::DBG_DrawAabb;
break;
case 'c' :
if (m_debugMode & IDebugDraw::DBG_DrawContactPoints)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_DrawContactPoints);
else
m_debugMode |= IDebugDraw::DBG_DrawContactPoints;
break;
case 'd' :
if (m_debugMode & IDebugDraw::DBG_NoDeactivation)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_NoDeactivation);
else
m_debugMode |= IDebugDraw::DBG_NoDeactivation;
break;
case 'o' :
{
m_stepping = !m_stepping;
break;
}
case 's' : clientMoveAndDisplay(); break;
// case ' ' : newRandom(); break;
case ' ':
clientResetScene();
break;
case '1':
{
if (m_debugMode & IDebugDraw::DBG_EnableCCD)
m_debugMode = m_debugMode & (~IDebugDraw::DBG_EnableCCD);
else
m_debugMode |= IDebugDraw::DBG_EnableCCD;
break;
}
case '.':
{
shootBox(getCameraTargetPosition());
break;
}
case '+':
{
m_ShootBoxInitialSpeed += 10.f;
break;
}
case '-':
{
m_ShootBoxInitialSpeed -= 10.f;
break;
}
default:
// std::cout << "unused key : " << key << std::endl;
break;
}
glutPostRedisplay();
}
void DemoApplication::specialKeyboard(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT : stepLeft(); break;
case GLUT_KEY_RIGHT : stepRight(); break;
case GLUT_KEY_UP : stepFront(); break;
case GLUT_KEY_DOWN : stepBack(); break;
case GLUT_KEY_PAGE_UP : zoomIn(); break;
case GLUT_KEY_PAGE_DOWN : zoomOut(); break;
case GLUT_KEY_HOME : toggleIdle(); break;
default:
// std::cout << "unused (special) key : " << key << std::endl;
break;
}
glutPostRedisplay();
}
void DemoApplication::moveAndDisplay()
{
if (!m_idle)
clientMoveAndDisplay();
}
void DemoApplication::displayCallback()
{
}
void DemoApplication::shootBox(const SimdVector3& destination)
{
if (m_physicsEnvironmentPtr)
{
bool isDynamic = true;
float mass = 1.f;
SimdTransform startTransform;
startTransform.setIdentity();
SimdVector3 camPos = getCameraPosition();
startTransform.setOrigin(camPos);
CollisionShape* boxShape = new BoxShape(SimdVector3(1.f,1.f,1.f));
CcdPhysicsController* newBox = LocalCreatePhysicsObject(isDynamic, mass, startTransform,boxShape);
SimdVector3 linVel(destination[0]-camPos[0],destination[1]-camPos[1],destination[2]-camPos[2]);
linVel.normalize();
linVel*=m_ShootBoxInitialSpeed;
newBox->setPosition(camPos[0],camPos[1],camPos[2]);
newBox->setOrientation(0,0,0,1);
newBox->SetLinearVelocity(linVel[0],linVel[1],linVel[2],false);
newBox->SetAngularVelocity(0,0,0,false);
}
}
int gPickingConstraintId = 0;
SimdVector3 gOldPickingPos;
float gOldPickingDist = 0.f;
RigidBody* pickedBody = 0;//for deactivation state
SimdVector3 DemoApplication::GetRayTo(int x,int y)
{
float top = 1.f;
float bottom = -1.f;
float nearPlane = 1.f;
float tanFov = (top-bottom)*0.5f / nearPlane;
float fov = 2.0 * atanf (tanFov);
SimdVector3 rayFrom = getCameraPosition();
SimdVector3 rayForward = (getCameraTargetPosition()-getCameraPosition());
rayForward.normalize();
float farPlane = 600.f;
rayForward*= farPlane;
SimdVector3 rightOffset;
SimdVector3 vertical = m_cameraUp;
SimdVector3 hor;
hor = rayForward.cross(vertical);
hor.normalize();
vertical = hor.cross(rayForward);
vertical.normalize();
float tanfov = tanf(0.5f*fov);
hor *= 2.f * farPlane * tanfov;
vertical *= 2.f * farPlane * tanfov;
SimdVector3 rayToCenter = rayFrom + rayForward;
SimdVector3 dHor = hor * 1.f/float(m_glutScreenWidth);
SimdVector3 dVert = vertical * 1.f/float(m_glutScreenHeight);
SimdVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical;
rayTo += x * dHor;
rayTo -= y * dVert;
return rayTo;
}
void DemoApplication::mouseFunc(int button, int state, int x, int y)
{
//printf("button %i, state %i, x=%i,y=%i\n",button,state,x,y);
//button 0, state 0 means left mouse down
SimdVector3 rayTo = GetRayTo(x,y);
switch (button)
{
case 2:
{
if (state==0)
{
shootBox(rayTo);
}
break;
};
case 1:
{
if (state==0)
{
//apply an impulse
if (m_physicsEnvironmentPtr)
{
float hit[3];
float normal[3];
PHY_IPhysicsController* hitObj = m_physicsEnvironmentPtr->rayTest(0,m_cameraPosition[0],m_cameraPosition[1],m_cameraPosition[2],rayTo.getX(),rayTo.getY(),rayTo.getZ(),hit[0],hit[1],hit[2],normal[0],normal[1],normal[2]);
if (hitObj)
{
CcdPhysicsController* physCtrl = static_cast<CcdPhysicsController*>(hitObj);
RigidBody* body = physCtrl->GetRigidBody();
if (body)
{
body->SetActivationState(ACTIVE_TAG);
SimdVector3 impulse = rayTo;
impulse.normalize();
float impulseStrength = 10.f;
impulse *= impulseStrength;
SimdVector3 relPos(
hit[0] - body->getCenterOfMassPosition().getX(),
hit[1] - body->getCenterOfMassPosition().getY(),
hit[2] - body->getCenterOfMassPosition().getZ());
body->applyImpulse(impulse,relPos);
}
}
}
} else
{
}
break;
}
case 0:
{
if (state==0)
{
//add a point to point constraint for picking
if (m_physicsEnvironmentPtr)
{
float hit[3];
float normal[3];
PHY_IPhysicsController* hitObj = m_physicsEnvironmentPtr->rayTest(0,m_cameraPosition[0],m_cameraPosition[1],m_cameraPosition[2],rayTo.getX(),rayTo.getY(),rayTo.getZ(),hit[0],hit[1],hit[2],normal[0],normal[1],normal[2]);
if (hitObj)
{
CcdPhysicsController* physCtrl = static_cast<CcdPhysicsController*>(hitObj);
RigidBody* body = physCtrl->GetRigidBody();
if (body && !body->IsStatic())
{
pickedBody = body;
pickedBody->SetActivationState(DISABLE_DEACTIVATION);
SimdVector3 pickPos(hit[0],hit[1],hit[2]);
SimdVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;
gPickingConstraintId = m_physicsEnvironmentPtr->createConstraint(physCtrl,0,PHY_POINT2POINT_CONSTRAINT,
localPivot.getX(),
localPivot.getY(),
localPivot.getZ(),
0,0,0);
//printf("created constraint %i",gPickingConstraintId);
//save mouse position for dragging
gOldPickingPos = rayTo;
SimdVector3 eyePos(m_cameraPosition[0],m_cameraPosition[1],m_cameraPosition[2]);
gOldPickingDist = (pickPos-eyePos).length();
Point2PointConstraint* p2p = static_cast<Point2PointConstraint*>(m_physicsEnvironmentPtr->getConstraintById(gPickingConstraintId));
if (p2p)
{
//very weak constraint for picking
p2p->m_setting.m_tau = 0.1f;
}
}
}
}
} else
{
if (gPickingConstraintId && m_physicsEnvironmentPtr)
{
m_physicsEnvironmentPtr->removeConstraint(gPickingConstraintId);
//printf("removed constraint %i",gPickingConstraintId);
gPickingConstraintId = 0;
pickedBody->ForceActivationState(ACTIVE_TAG);
pickedBody->m_deactivationTime = 0.f;
pickedBody = 0;
}
}
break;
}
default:
{
}
}
}
void DemoApplication::mouseMotionFunc(int x,int y)
{
if (gPickingConstraintId && m_physicsEnvironmentPtr)
{
//move the constraint pivot
Point2PointConstraint* p2p = static_cast<Point2PointConstraint*>(m_physicsEnvironmentPtr->getConstraintById(gPickingConstraintId));
if (p2p)
{
//keep it at the same picking distance
SimdVector3 newRayTo = GetRayTo(x,y);
SimdVector3 eyePos(m_cameraPosition[0],m_cameraPosition[1],m_cameraPosition[2]);
SimdVector3 dir = newRayTo-eyePos;
dir.normalize();
dir *= gOldPickingDist;
SimdVector3 newPos = eyePos + dir;
p2p->SetPivotB(newPos);
}
}
}
///Very basic import
CcdPhysicsController* DemoApplication::LocalCreatePhysicsObject(bool isDynamic, float mass, const SimdTransform& startTransform,CollisionShape* shape)
{
startTransforms[numObjects] = startTransform;
PHY_ShapeProps shapeProps;
shapeProps.m_do_anisotropic = false;
shapeProps.m_do_fh = false;
shapeProps.m_do_rot_fh = false;
shapeProps.m_friction_scaling[0] = 1.;
shapeProps.m_friction_scaling[1] = 1.;
shapeProps.m_friction_scaling[2] = 1.;
shapeProps.m_inertia = 1.f;
shapeProps.m_lin_drag = 0.2f;
shapeProps.m_ang_drag = 0.1f;
shapeProps.m_mass = 10.0f;
PHY_MaterialProps materialProps;
materialProps.m_friction = 10.5f;
materialProps.m_restitution = 0.0f;
CcdConstructionInfo ccdObjectCi;
ccdObjectCi.m_friction = 0.5f;
ccdObjectCi.m_linearDamping = shapeProps.m_lin_drag;
ccdObjectCi.m_angularDamping = shapeProps.m_ang_drag;
SimdTransform tr;
tr.setIdentity();
int i = numObjects;
{
gShapePtr[i] = shape;
shapeProps.m_shape = gShapePtr[i];
shapeProps.m_shape->SetMargin(0.05f);
SimdQuaternion orn = startTransform.getRotation();
ms[i].setWorldOrientation(orn[0],orn[1],orn[2],orn[3]);
ms[i].setWorldPosition(startTransform.getOrigin().getX(),startTransform.getOrigin().getY(),startTransform.getOrigin().getZ());
ccdObjectCi.m_MotionState = &ms[i];
ccdObjectCi.m_gravity = SimdVector3(0,-9.8,0);
ccdObjectCi.m_localInertiaTensor =SimdVector3(0,0,0);
if (!isDynamic)
{
shapeProps.m_mass = 0.f;
ccdObjectCi.m_mass = shapeProps.m_mass;
ccdObjectCi.m_collisionFlags = CollisionObject::isStatic;
ccdObjectCi.m_collisionFilterGroup = CcdConstructionInfo::StaticFilter;
ccdObjectCi.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::StaticFilter;
}
else
{
shapeProps.m_mass = mass;
ccdObjectCi.m_mass = shapeProps.m_mass;
ccdObjectCi.m_collisionFlags = 0;
}
SimdVector3 localInertia(0.f,0.f,0.f);
if (isDynamic)
{
gShapePtr[i]->CalculateLocalInertia(shapeProps.m_mass,localInertia);
}
ccdObjectCi.m_localInertiaTensor = localInertia;
ccdObjectCi.m_collisionShape = gShapePtr[i];
physObjects[i]= new CcdPhysicsController( ccdObjectCi);
// Only do CCD if motion in one timestep (1.f/60.f) exceeds CUBE_HALF_EXTENTS
physObjects[i]->GetRigidBody()->m_ccdSquareMotionTreshold = 0.f;
//Experimental: better estimation of CCD Time of Impact:
//physObjects[i]->GetRigidBody()->m_ccdSweptShereRadius = 0.5*CUBE_HALF_EXTENTS;
m_physicsEnvironmentPtr->addCcdPhysicsController( physObjects[i]);
}
//return newly created PhysicsController
return physObjects[numObjects++];
}
void DemoApplication::renderme()
{
updateCamera();
float m[16];
if (m_physicsEnvironmentPtr)
{
if (getDebugMode() & IDebugDraw::DBG_DisableBulletLCP)
{
//don't use Bullet, use quickstep
m_physicsEnvironmentPtr->setSolverType(0);
} else
{
//Bullet LCP solver
m_physicsEnvironmentPtr->setSolverType(1);
}
if (getDebugMode() & IDebugDraw::DBG_EnableCCD)
{
m_physicsEnvironmentPtr->setCcdMode(3);
} else
{
m_physicsEnvironmentPtr->setCcdMode(0);
}
bool isSatEnabled = (getDebugMode() & IDebugDraw::DBG_EnableSatComparison);
m_physicsEnvironmentPtr->EnableSatCollisionDetection(isSatEnabled);
int numPhysicsObjects = m_physicsEnvironmentPtr->GetNumControllers();
int i;
for (i=0;i<numPhysicsObjects;i++)
{
CcdPhysicsController* ctrl = m_physicsEnvironmentPtr->GetPhysicsController(i);
RigidBody* body = ctrl->GetRigidBody();
body->m_worldTransform.getOpenGLMatrix( m );
SimdVector3 wireColor(1.f,1.0f,0.5f); //wants deactivation
if (i & 1)
{
wireColor = SimdVector3(0.f,0.0f,1.f);
}
///color differently for active, sleeping, wantsdeactivation states
if (ctrl->GetRigidBody()->GetActivationState() == 1) //active
{
if (i & 1)
{
wireColor += SimdVector3 (1.f,0.f,0.f);
} else
{
wireColor += SimdVector3 (.5f,0.f,0.f);
}
}
if (ctrl->GetRigidBody()->GetActivationState() == 2) //ISLAND_SLEEPING
{
if (i & 1)
{
wireColor += SimdVector3 (0.f,1.f, 0.f);
} else
{
wireColor += SimdVector3 (0.f,0.5f,0.f);
}
}
char extraDebug[125];
sprintf(extraDebug,"islId, Body=%i , %i",ctrl->GetRigidBody()->m_islandTag1,ctrl->GetRigidBody()->m_debugBodyId);
ctrl->GetRigidBody()->GetCollisionShape()->SetExtraDebugInfo(extraDebug);
float vec[16];
SimdTransform ident;
ident.setIdentity();
ident.getOpenGLMatrix(vec);
GL_ShapeDrawer::DrawOpenGL(m,ctrl->GetRigidBody()->GetCollisionShape(),wireColor,getDebugMode());
}
if (!(getDebugMode() & IDebugDraw::DBG_NoHelpText))
{
float xOffset = 10.f;
float yStart = 20.f;
float yIncr = -2.f;
char buf[124];
glColor3f(0, 0, 0);
#ifdef USE_QUICKPROF
if ( getDebugMode() & IDebugDraw::DBG_ProfileTimings)
{
static int counter = 0;
counter++;
std::map<std::string, hidden::ProfileBlock*>::iterator iter;
for (iter = Profiler::mProfileBlocks.begin(); iter != Profiler::mProfileBlocks.end(); ++iter)
{
char blockTime[128];
sprintf(blockTime, "%s: %lf",&((*iter).first[0]),Profiler::getBlockTime((*iter).first, Profiler::BLOCK_CYCLE_SECONDS));//BLOCK_TOTAL_PERCENT));
glRasterPos3f(xOffset,yStart,0);
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),blockTime);
yStart += yIncr;
}
}
#endif //USE_QUICKPROF
//profiling << Profiler::createStatsString(Profiler::BLOCK_TOTAL_PERCENT);
//<< std::endl;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"mouse to interact");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"space to reset");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"cursor keys and z,x to navigate");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"i to toggle simulation, s single step");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"q to quit");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"d to toggle deactivation");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"a to draw temporal AABBs");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"h to toggle help text");
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
bool useBulletLCP = !(getDebugMode() & IDebugDraw::DBG_DisableBulletLCP);
bool useCCD = (getDebugMode() & IDebugDraw::DBG_EnableCCD);
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"m Bullet GJK = %i",!isSatEnabled);
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"n Bullet LCP = %i",useBulletLCP);
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"1 CCD mode (adhoc) = %i",useCCD);
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"+- shooting speed = %10.2f",m_ShootBoxInitialSpeed);
BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),buf);
yStart += yIncr;
}
}
}

View File

@@ -0,0 +1,170 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef DEMO_APPLICATION_H
#define DEMO_APPLICATION_H
#ifdef WIN32//for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "SimdVector3.h"
#include "SimdMatrix3x3.h"
#include "SimdTransform.h"
class CcdPhysicsEnvironment;
class CcdPhysicsController;
class CollisionShape;
class DemoApplication
{
protected:
///this is the most important class
CcdPhysicsEnvironment* m_physicsEnvironmentPtr;
float m_cameraDistance;
int m_debugMode;
float m_ele;
float m_azi;
SimdVector3 m_cameraPosition;
SimdVector3 m_cameraTargetPosition;//look at
float m_scaleBottom;
float m_scaleFactor;
SimdVector3 m_cameraUp;
int m_forwardAxis;
int m_glutScreenWidth;
int m_glutScreenHeight;
float m_ShootBoxInitialSpeed;
bool m_stepping;
bool m_singleStep;
bool m_idle;
int m_lastKey;
public:
DemoApplication();
virtual ~DemoApplication();
int getDebugMode()
{
return m_debugMode ;
}
void setDebugMode(int mode)
{
m_debugMode = mode;
}
CcdPhysicsEnvironment* GetPhysicsEnvironment()
{
return m_physicsEnvironmentPtr;
}
void setCameraUp(const SimdVector3& camUp)
{
m_cameraUp = camUp;
}
void setCameraForwardAxis(int axis)
{
m_forwardAxis = axis;
}
void myinit();
void toggleIdle();
virtual void updateCamera();
SimdVector3 getCameraPosition()
{
return m_cameraPosition;
}
SimdVector3 getCameraTargetPosition()
{
return m_cameraTargetPosition;
}
///glut callbacks
float getCameraDistance();
void setCameraDistance(float dist);
void moveAndDisplay();
virtual void clientMoveAndDisplay() = 0;
virtual void clientResetScene() =0 ;
///Demo functions
void shootBox(const SimdVector3& destination);
SimdVector3 GetRayTo(int x,int y);
CcdPhysicsController* LocalCreatePhysicsObject(bool isDynamic, float mass, const SimdTransform& startTransform,CollisionShape* shape);
///callback methods by glut
virtual void keyboardCallback(unsigned char key, int x, int y);
virtual void specialKeyboard(int key, int x, int y);
virtual void reshape(int w, int h);
virtual void mouseFunc(int button, int state, int x, int y);
virtual void mouseMotionFunc(int x,int y);
virtual void displayCallback();
virtual void renderme();
void stepLeft();
void stepRight();
void stepFront();
void stepBack();
void zoomIn();
void zoomOut();
};
#endif //DEMO_APPLICATION_H

View File

@@ -153,7 +153,7 @@ void GL_ShapeDrawer::DrawOpenGL(float* m, const CollisionShape* shape, const Sim
{
const BU_Simplex1to4* tetra = static_cast<const BU_Simplex1to4*>(shape);
//todo:
useWireframeFallback = false;
// useWireframeFallback = false;
break;
}
case CONVEX_HULL_SHAPE_PROXYTYPE:
@@ -307,10 +307,10 @@ void GL_ShapeDrawer::DrawOpenGL(float* m, const CollisionShape* shape, const Sim
TriangleMeshShape* concaveMesh = (TriangleMeshShape*) shape;
//SimdVector3 aabbMax(1e30f,1e30f,1e30f);
//SimdVector3 aabbMax(100,100,100);//1e30f,1e30f,1e30f);
extern float eye[3];
SimdVector3 aabbMax(eye[0]+100,eye[1]+100,eye[2]+100);//1e30f,1e30f,1e30f);
SimdVector3 aabbMin(eye[0]-100,eye[1]-100,eye[2]-100);//1e30f,1e30f,1e30f);
//todo pass camera, for some culling
SimdVector3 aabbMax(1e30f,1e30f,1e30f);
SimdVector3 aabbMin(-1e30f,-1e30f,-1e30f);
GlDrawcallback drawCallback;
@@ -323,9 +323,9 @@ void GL_ShapeDrawer::DrawOpenGL(float* m, const CollisionShape* shape, const Sim
{
ConvexTriangleMeshShape* convexMesh = (ConvexTriangleMeshShape*) shape;
extern float eye[3];
SimdVector3 aabbMax(eye[0]+100,eye[1]+100,eye[2]+100);
SimdVector3 aabbMin(eye[0]-100,eye[1]-100,eye[2]-100);
//todo: pass camera for some culling
SimdVector3 aabbMax(1e30f,1e30f,1e30f);
SimdVector3 aabbMin(-1e30f,-1e30f,-1e30f);
TriangleGlDrawcallback drawCallback;
convexMesh->GetStridingMesh()->InternalProcessAllTriangles(&drawCallback,aabbMin,aabbMax);

View File

@@ -13,361 +13,57 @@ subject to the following restrictions:
3. This notice may not be removed or altered from any source distribution.
*/
#ifdef WIN32//for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "IDebugDraw.h"
//see IDebugDraw.h for modes
static int sDebugMode = 0;
int getDebugMode()
{
return sDebugMode ;
}
void setDebugMode(int mode)
{
sDebugMode = mode;
}
#include "DemoApplication.h"
//glut is C code, this global gDemoApplication links glut to the C++ demo
static DemoApplication* gDemoApplication = 0;
#include "GlutStuff.h"
void myinit(void) {
GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
/* light_position is NOT default value */
GLfloat light_position0[] = { 1.0, 1.0, 1.0, 0.0 };
GLfloat light_position1[] = { -1.0, -1.0, -1.0, 0.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClearColor(0.8,0.8,0.8,0);
// glEnable(GL_CULL_FACE);
// glCullFace(GL_BACK);
}
static float DISTANCE = 15;
void setCameraDistance(float dist)
static void glutKeyboardCallback(unsigned char key, int x, int y)
{
DISTANCE = dist;
gDemoApplication->keyboardCallback(key,x,y);
}
static float ele = 0, azi = 0;
float eye[3] = {0, 0, DISTANCE};
static float center[3] = {0, 0, 0};
static const double SCALE_BOTTOM = 0.5;
static const double SCALE_FACTOR = 2;
bool stepping= true;
bool singleStep = false;
static bool idle = false;
void toggleIdle() {
if (idle) {
glutIdleFunc(clientMoveAndDisplay);
idle = false;
}
else {
glutIdleFunc(0);
idle = true;
}
static void glutSpecialKeyboardCallback(int key, int x, int y)
{
gDemoApplication->specialKeyboard(key,x,y);
}
#include "SimdMatrix3x3.h"
static void glutReshapeCallback(int w, int h)
{
gDemoApplication->reshape(w,h);
}
SimdVector3 gCameraUp(0,1,0);
int gForwardAxis = 2;
static void glutMoveAndDisplayCallback()
{
gDemoApplication->moveAndDisplay();
}
void setCamera() {
static void glutMouseFuncCallback(int button, int state, int x, int y)
{
gDemoApplication->mouseFunc(button,state,x,y);
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float rele = ele * 0.01745329251994329547;// rads per deg
float razi = azi * 0.01745329251994329547;// rads per deg
SimdQuaternion rot(gCameraUp,razi);
SimdVector3 eyePos(0,0,0);
eyePos[gForwardAxis] = -DISTANCE;
SimdVector3 forward(eyePos[0],eyePos[1],eyePos[2]);
if (forward.length2() < SIMD_EPSILON)
{
forward.setValue(1.f,0.f,0.f);
}
SimdVector3 right = gCameraUp.cross(forward);
SimdQuaternion roll(right,-rele);
eyePos = SimdMatrix3x3(rot) * SimdMatrix3x3(roll) * eyePos;
eye[0] = eyePos.getX();
eye[1] = eyePos.getY();
eye[2] = eyePos.getZ();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10000.0);
gluLookAt(eye[0], eye[1], eye[2],
center[0], center[1], center[2],
gCameraUp.getX(),gCameraUp.getY(),gCameraUp.getZ());
glMatrixMode(GL_MODELVIEW);
}
const float STEPSIZE = 5;
void stepLeft() { azi -= STEPSIZE; if (azi < 0) azi += 360; setCamera(); }
void stepRight() { azi += STEPSIZE; if (azi >= 360) azi -= 360; setCamera(); }
void stepFront() { ele += STEPSIZE; if (azi >= 360) azi -= 360; setCamera(); }
void stepBack() { ele -= STEPSIZE; if (azi < 0) azi += 360; setCamera(); }
void zoomIn() { DISTANCE -= 1; setCamera(); }
void zoomOut() { DISTANCE += 1; setCamera(); }
int glutScreenWidth = 0;
int glutScreenHeight = 0;
void myReshape(int w, int h) {
glutScreenWidth = w;
glutScreenHeight = h;
glViewport(0, 0, w, h);
setCamera();
}
int lastKey = 0;
void defaultKeyboard(unsigned char key, int x, int y)
{
lastKey = 0;
switch (key)
{
case 'q' : exit(0); break;
case 'l' : stepLeft(); break;
case 'r' : stepRight(); break;
case 'f' : stepFront(); break;
case 'b' : stepBack(); break;
case 'z' : zoomIn(); break;
case 'x' : zoomOut(); break;
case 'i' : toggleIdle(); break;
case 'h':
if (sDebugMode & IDebugDraw::DBG_NoHelpText)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_NoHelpText);
else
sDebugMode |= IDebugDraw::DBG_NoHelpText;
break;
case 'w':
if (sDebugMode & IDebugDraw::DBG_DrawWireframe)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_DrawWireframe);
else
sDebugMode |= IDebugDraw::DBG_DrawWireframe;
break;
case 'p':
if (sDebugMode & IDebugDraw::DBG_ProfileTimings)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_ProfileTimings);
else
sDebugMode |= IDebugDraw::DBG_ProfileTimings;
break;
case 'm':
if (sDebugMode & IDebugDraw::DBG_EnableSatComparison)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_EnableSatComparison);
else
sDebugMode |= IDebugDraw::DBG_EnableSatComparison;
break;
case 'n':
if (sDebugMode & IDebugDraw::DBG_DisableBulletLCP)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_DisableBulletLCP);
else
sDebugMode |= IDebugDraw::DBG_DisableBulletLCP;
break;
case 't' :
if (sDebugMode & IDebugDraw::DBG_DrawText)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_DrawText);
else
sDebugMode |= IDebugDraw::DBG_DrawText;
break;
case 'y':
if (sDebugMode & IDebugDraw::DBG_DrawFeaturesText)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_DrawFeaturesText);
else
sDebugMode |= IDebugDraw::DBG_DrawFeaturesText;
break;
case 'a':
if (sDebugMode & IDebugDraw::DBG_DrawAabb)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_DrawAabb);
else
sDebugMode |= IDebugDraw::DBG_DrawAabb;
break;
case 'c' :
if (sDebugMode & IDebugDraw::DBG_DrawContactPoints)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_DrawContactPoints);
else
sDebugMode |= IDebugDraw::DBG_DrawContactPoints;
break;
case 'd' :
if (sDebugMode & IDebugDraw::DBG_NoDeactivation)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_NoDeactivation);
else
sDebugMode |= IDebugDraw::DBG_NoDeactivation;
break;
case 'o' :
{
stepping = !stepping;
break;
}
case 's' : clientMoveAndDisplay(); break;
// case ' ' : newRandom(); break;
case ' ':
clientResetScene();
break;
case '1':
{
if (sDebugMode & IDebugDraw::DBG_EnableCCD)
sDebugMode = sDebugMode & (~IDebugDraw::DBG_EnableCCD);
else
sDebugMode |= IDebugDraw::DBG_EnableCCD;
break;
}
default:
// std::cout << "unused key : " << key << std::endl;
break;
}
glutPostRedisplay();
}
void defaultSpecialKeyboard(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT : stepLeft(); break;
case GLUT_KEY_RIGHT : stepRight(); break;
case GLUT_KEY_UP : stepFront(); break;
case GLUT_KEY_DOWN : stepBack(); break;
case GLUT_KEY_PAGE_UP : zoomIn(); break;
case GLUT_KEY_PAGE_DOWN : zoomOut(); break;
case GLUT_KEY_HOME : toggleIdle(); break;
default:
// std::cout << "unused (special) key : " << key << std::endl;
break;
}
glutPostRedisplay();
}
void goodbye( void)
{
printf("goodbye \n");
exit(0);
}
void menu(int choice)
{
static int fullScreen = 0;
static int px, py, sx, sy;
switch(choice) {
case 1:
if (fullScreen == 1) {
glutPositionWindow(px,py);
glutReshapeWindow(sx,sy);
glutChangeToMenuEntry(1,"Full Screen",1);
fullScreen = 0;
} else {
px=glutGet((GLenum)GLUT_WINDOW_X);
py=glutGet((GLenum)GLUT_WINDOW_Y);
sx=glutGet((GLenum)GLUT_WINDOW_WIDTH);
sy=glutGet((GLenum)GLUT_WINDOW_HEIGHT);
glutFullScreen();
glutChangeToMenuEntry(1,"Close Full Screen",1);
fullScreen = 1;
}
break;
case 2:
toggleIdle();
break;
case 3:
goodbye();
break;
default:
break;
}
}
void createMenu()
{
glutCreateMenu(menu);
glutAddMenuEntry("Full Screen", 1);
glutAddMenuEntry("Toggle Idle (Start/Stop)", 2);
glutAddMenuEntry("Quit", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int glutmain(int argc, char **argv,int width,int height,const char* title) {
static void glutMotionFuncCallback(int x,int y)
{
gDemoApplication->mouseMotionFunc(x,y);
}
static void glutDisplayCallback(void)
{
gDemoApplication->displayCallback();
}
int glutmain(int argc, char **argv,int width,int height,const char* title,DemoApplication* demoApp) {
gDemoApplication = demoApp;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
@@ -375,17 +71,18 @@ int glutmain(int argc, char **argv,int width,int height,const char* title) {
glutInitWindowSize(width, height);
glutCreateWindow(title);
myinit();
glutKeyboardFunc(clientKeyboard);
glutSpecialFunc(clientSpecialKeyboard);
glutReshapeFunc(myReshape);
//createMenu();
glutIdleFunc(clientMoveAndDisplay);
glutMouseFunc(clientMouseFunc);
glutMotionFunc(clientMotionFunc);
glutDisplayFunc( clientDisplay );
gDemoApplication->myinit();
clientMoveAndDisplay();
glutKeyboardFunc(glutKeyboardCallback);
glutSpecialFunc(glutSpecialKeyboardCallback);
glutReshapeFunc(glutReshapeCallback);
//createMenu();
glutIdleFunc(glutMoveAndDisplayCallback);
glutMouseFunc(glutMouseFuncCallback);
glutMotionFunc(glutMotionFuncCallback);
glutDisplayFunc( glutDisplayCallback );
glutMoveAndDisplayCallback();
glutMainLoop();
return 0;

View File

@@ -15,24 +15,8 @@ subject to the following restrictions:
#ifndef GLUT_STUFF_H
#define GLUT_STUFF_H
//to be implemented by the demo
void clientDisplay();
void clientMoveAndDisplay();
void clientResetScene();
class DemoApplication;
int glutmain(int argc, char **argv,int width,int height,const char* title,DemoApplication* demoApp);
int glutmain(int argc, char **argv,int width,int height,const char* title);
void setCameraDistance(float dist);
int getDebugMode();
void setDebugMode(int mode);
void defaultKeyboard(unsigned char key, int x, int y);
void clientKeyboard(unsigned char key, int x, int y);
void defaultSpecialKeyboard(int key, int x, int y);
void clientSpecialKeyboard(int key, int x, int y);
void clientMouseFunc(int button, int state, int x, int y);
void clientMotionFunc(int x,int y);
#endif //GLUT_STUFF_H

View File

@@ -20,17 +20,8 @@ Very basic raytracer, rendering into a texture.
#include "SimdQuaternion.h"
#include "SimdTransform.h"
#include "GL_ShapeDrawer.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif>
#include "Raytracer.h"
#include "GlutStuff.h"
#include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
@@ -85,6 +76,17 @@ MinkowskiSumShape myMink(&myCylinder,&myBox);
///
///
int main(int argc,char** argv)
{
Raytracer* raytraceDemo = new Raytracer();
raytraceDemo->initPhysics();
raytraceDemo->setCameraDistance(6.f);
return glutmain(argc, argv,screenWidth,screenHeight,"Minkowski-Sum Raytracer Demo",raytraceDemo);
}
void Raytracer::initPhysics()
{
raytracePicture = new RenderTexture(screenWidth,screenHeight);
@@ -110,38 +112,36 @@ int main(int argc,char** argv)
};
SimdScalar radi[NUM_SPHERES] = { 0.35f,0.35f,0.45f,0.40f,0.40f };
MultiSphereShape multiSphereShape(inertiaHalfExtents,positions,radi,NUM_SPHERES);
ConvexHullShape convexHullShape(positions,3);
MultiSphereShape* multiSphereShape = new MultiSphereShape(inertiaHalfExtents,positions,radi,NUM_SPHERES);
ConvexHullShape* convexHullShape = new ConvexHullShape(positions,3);
//choose shape
shapePtr[0] = &myCone;
shapePtr[1] =&simplex;
shapePtr[2] =&convexHullShape;
shapePtr[3] =&myMink;//myBox;
shapePtr[2] =convexHullShape;
shapePtr[3] =&myMink;//myBox;//multiSphereShape
simplex.SetMargin(0.3f);
setCameraDistance(6.f);
return glutmain(argc, argv,screenWidth,screenHeight,"Minkowski-Sum Raytracer Demo");
}
//to be implemented by the demo
void clientMoveAndDisplay()
void Raytracer::clientMoveAndDisplay()
{
clientDisplay();
displayCallback();
}
int once = 1;
extern float eye[3];
void clientDisplay(void)
void Raytracer::displayCallback()
{
updateCamera();
for (int i=0;i<numObjects;i++)
{
transforms[i].setIdentity();
@@ -194,8 +194,8 @@ void clientDisplay(void)
float fov = 2.0 * atanf (tanFov);
SimdVector3 rayFrom(eye[0],eye[1],eye[2]);
SimdVector3 rayForward = -rayFrom;
SimdVector3 rayFrom = getCameraPosition();
SimdVector3 rayForward = getCameraTargetPosition()-getCameraPosition();
rayForward.normalize();
float farPlane = 600.f;
rayForward*= farPlane;
@@ -401,25 +401,3 @@ void clientDisplay(void)
glutSwapBuffers();
}
void clientResetScene()
{
}
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef RAYTRACER_H
#define RAYTRACER_H
#include "DemoApplication.h"
///Raytracer shows the inner working of the ray casting, using ray tracing rendering into a texture.
class Raytracer : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
}
};
#endif //RAYTRACER_H

View File

@@ -22,22 +22,10 @@ subject to the following restrictions:
#include "SimdQuaternion.h"
#include "SimdTransform.h"
#include "GL_ShapeDrawer.h"
#ifdef WIN32 //needed for glut.h
#include <windows.h>
#endif
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "GlutStuff.h"
#include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
#include "SimplexDemo.h"
#include "GlutStuff.h"
VoronoiSimplexSolver simplexSolver;
@@ -61,34 +49,26 @@ PolyhedralConvexShape* shapePtr[maxNumObjects];
int main(int argc,char** argv)
{
simplex.SetSimplexSolver(&simplexSolver);
SimplexDemo* demo = new SimplexDemo();
simplex.AddVertex(SimdPoint3(-2,0,-2));
simplex.AddVertex(SimdPoint3(2,0,-2));
simplex.AddVertex(SimdPoint3(0,0,2));
simplex.AddVertex(SimdPoint3(0,2,0));
shapePtr[0] = &simplex;
SimdTransform tr;
tr.setIdentity();
return glutmain(argc, argv,screenWidth,screenHeight,"SimplexDemo");
demo->initPhysics();
return glutmain(argc, argv,screenWidth,screenHeight,"SimplexDemo",demo);
}
//to be implemented by the demo
void clientMoveAndDisplay()
void SimplexDemo::clientMoveAndDisplay()
{
clientDisplay();
displayCallback();
}
void clientDisplay(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
void SimplexDemo::displayCallback()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
GL_ShapeDrawer::DrawCoordSystem();
@@ -121,26 +101,18 @@ void clientDisplay(void) {
glutSwapBuffers();
}
void clientResetScene()
void SimplexDemo::initPhysics()
{
}
simplex.SetSimplexSolver(&simplexSolver);
void clientSpecialKeyboard(int key, int x, int y)
{
defaultSpecialKeyboard(key,x,y);
}
simplex.AddVertex(SimdPoint3(-2,0,-2));
simplex.AddVertex(SimdPoint3(2,0,-2));
simplex.AddVertex(SimdPoint3(0,0,2));
simplex.AddVertex(SimdPoint3(0,2,0));
void clientKeyboard(unsigned char key, int x, int y)
{
defaultKeyboard(key, x, y);
}
shapePtr[0] = &simplex;
void clientMouseFunc(int button, int state, int x, int y)
{
}
void clientMotionFunc(int x,int y)
{
}
SimdTransform tr;
tr.setIdentity();
}

View File

@@ -0,0 +1,36 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SIMPLEX_DEMO_H
#define SIMPLEX_DEMO_H
#include "DemoApplication.h"
///SimplexDemo shows the working of the sub-distance algorithm, used inside GJK
class SimplexDemo : public DemoApplication
{
public:
void initPhysics();
virtual void clientMoveAndDisplay();
virtual void displayCallback();
virtual void clientResetScene()
{
}
};
#endif //SIMPLEX_DEMO_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef VEHICLE_DEMO_H
#define VEHICLE_DEMO_H
#include "DemoApplication.h"
///VehicleDemo shows how to setup and use the built-in raycast vehicle
class VehicleDemo : public DemoApplication
{
public:
CcdPhysicsController* m_carChassis;
float m_cameraHeight;
float m_minCameraDistance;
float m_maxCameraDistance;
VehicleDemo();
virtual void clientMoveAndDisplay();
virtual void clientResetScene();
virtual void displayCallback();
///a very basic camera following the vehicle
virtual void updateCamera();
virtual void specialKeyboard(int key, int x, int y);
void renderme();
void setupPhysics();
};
#endif //VEHICLE_DEMO_H