fix: some file didn't have the svn:eol-style native yet

This commit is contained in:
erwin.coumans
2010-03-06 15:23:36 +00:00
parent 4fd48ac691
commit 81f04a4d48
641 changed files with 301123 additions and 301123 deletions

View File

@@ -1,101 +1,101 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
LINK_DIRECTORIES( LINK_DIRECTORIES(
"C:/MinGW/lib" "C:/MinGW/lib"
) )
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/Extras ${BULLET_PHYSICS_SOURCE_DIR}/Extras
${BULLET_PHYSICS_SOURCE_DIR}/Extras/GIMPACTUtils ${BULLET_PHYSICS_SOURCE_DIR}/Extras/GIMPACTUtils
${BULLET_PHYSICS_SOURCE_DIR}/Extras/ConvexDecomposition ${BULLET_PHYSICS_SOURCE_DIR}/Extras/ConvexDecomposition
${BULLET_PHYSICS_SOURCE_DIR}/Extras/LibXML ${BULLET_PHYSICS_SOURCE_DIR}/Extras/LibXML
${BULLET_PHYSICS_SOURCE_DIR}/Extras/LibXML/include ${BULLET_PHYSICS_SOURCE_DIR}/Extras/LibXML/include
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/src
${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletFileLoader ${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletFileLoader
${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletWorldImporter ${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletWorldImporter
) )
LINK_LIBRARIES( LINK_LIBRARIES(
GLUI GIMPACTUtils ConvexDecomposition OpenGLSupport BulletWorldImporter BulletSoftBody BulletDynamics BulletCollision BulletFileLoader LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} GLUI GIMPACTUtils ConvexDecomposition OpenGLSupport BulletWorldImporter BulletSoftBody BulletDynamics BulletCollision BulletFileLoader LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
SET(AllBulletDemos_SRCS SET(AllBulletDemos_SRCS
Main.cpp Main.cpp
DemoEntries.cpp DemoEntries.cpp
../CcdPhysicsDemo/CcdPhysicsDemo.cpp ../CcdPhysicsDemo/CcdPhysicsDemo.cpp
../BasicDemo/BasicDemo.cpp ../BasicDemo/BasicDemo.cpp
../BspDemo/BspDemo.cpp ../BspDemo/BspDemo.cpp
../BspDemo/BspConverter.cpp ../BspDemo/BspConverter.cpp
../BspDemo/BspLoader.cpp ../BspDemo/BspLoader.cpp
../DynamicControlDemo/MotorDemo.cpp ../DynamicControlDemo/MotorDemo.cpp
../ConcaveDemo/ConcavePhysicsDemo.cpp ../ConcaveDemo/ConcavePhysicsDemo.cpp
../ConcaveRaycastDemo/ConcaveRaycastDemo.cpp ../ConcaveRaycastDemo/ConcaveRaycastDemo.cpp
../ConcaveConvexcastDemo/ConcaveConvexcastDemo.cpp ../ConcaveConvexcastDemo/ConcaveConvexcastDemo.cpp
../ConvexDecompositionDemo/ConvexDecompositionDemo.cpp ../ConvexDecompositionDemo/ConvexDecompositionDemo.cpp
../SliderConstraintDemo/SliderConstraintDemo.cpp ../SliderConstraintDemo/SliderConstraintDemo.cpp
../RagdollDemo/RagdollDemo.cpp ../RagdollDemo/RagdollDemo.cpp
../GimpactTestDemo/GimpactTestDemo.cpp ../GimpactTestDemo/GimpactTestDemo.cpp
../Raytracer/Raytracer.cpp ../Raytracer/Raytracer.cpp
../GjkConvexCastDemo/LinearConvexCastDemo.cpp ../GjkConvexCastDemo/LinearConvexCastDemo.cpp
../ForkLiftDemo/ForkLiftDemo.cpp ../ForkLiftDemo/ForkLiftDemo.cpp
../SoftDemo/SoftDemo.cpp ../SoftDemo/SoftDemo.cpp
../ConstraintDemo/ConstraintDemo.cpp ../ConstraintDemo/ConstraintDemo.cpp
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppAllBulletDemos ADD_EXECUTABLE(AppAllBulletDemos
${AllBulletDemos_SRCS} ${AllBulletDemos_SRCS}
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppAllBulletDemos ADD_EXECUTABLE(AppAllBulletDemos
${AllBulletDemos_SRCS} ${AllBulletDemos_SRCS}
) )
ENDIF() ENDIF()
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES) IF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppAllBulletDemos TARGET AppAllBulletDemos
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppAllBulletDemos TARGET AppAllBulletDemos
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppAllBulletDemos TARGET AppAllBulletDemos
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/Demos/SerializeDemo/testFile.bullet ${CMAKE_CURRENT_BINARY_DIR}/testFile.bullet COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/Demos/SerializeDemo/testFile.bullet ${CMAKE_CURRENT_BINARY_DIR}/testFile.bullet
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/file.obj ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/file.obj ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppAllBulletDemos PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppAllBulletDemos PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppAllBulletDemos PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppAllBulletDemos PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppAllBulletDemos PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppAllBulletDemos PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,174 +1,174 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "DemoEntries.h" #include "DemoEntries.h"
#include "../CcdPhysicsDemo/CcdPhysicsDemo.h" #include "../CcdPhysicsDemo/CcdPhysicsDemo.h"
#include "../BspDemo/BspDemo.h" #include "../BspDemo/BspDemo.h"
#include "../BasicDemo/BasicDemo.h" #include "../BasicDemo/BasicDemo.h"
#include "../ConcaveDemo/ConcaveDemo.h" #include "../ConcaveDemo/ConcaveDemo.h"
#include "../ConcaveRaycastDemo/ConcaveRaycastDemo.h" #include "../ConcaveRaycastDemo/ConcaveRaycastDemo.h"
#include "../ConcaveConvexcastDemo/ConcaveConvexcastDemo.h" #include "../ConcaveConvexcastDemo/ConcaveConvexcastDemo.h"
#include "../ConvexDecompositionDemo/ConvexDecompositionDemo.h" #include "../ConvexDecompositionDemo/ConvexDecompositionDemo.h"
#include "../DynamicControlDemo/MotorDemo.h" #include "../DynamicControlDemo/MotorDemo.h"
#include "../SliderConstraintDemo/SliderConstraintDemo.h" #include "../SliderConstraintDemo/SliderConstraintDemo.h"
#include "../RagdollDemo/RagdollDemo.h" #include "../RagdollDemo/RagdollDemo.h"
#include "../GimpactTestDemo/GimpactTestDemo.h" #include "../GimpactTestDemo/GimpactTestDemo.h"
#include "../Raytracer/Raytracer.h" #include "../Raytracer/Raytracer.h"
#include "../GjkConvexCastDemo/LinearConvexCastDemo.h" #include "../GjkConvexCastDemo/LinearConvexCastDemo.h"
#include "../ForkLiftDemo/ForkLiftDemo.h" #include "../ForkLiftDemo/ForkLiftDemo.h"
#include "../ConstraintDemo/ConstraintDemo.h" #include "../ConstraintDemo/ConstraintDemo.h"
//#include "../Benchmarks/BenchmarkDemo.h" //#include "../Benchmarks/BenchmarkDemo.h"
#include "../SoftDemo/SoftDemo.h" #include "../SoftDemo/SoftDemo.h"
#include "GLDebugFont.h" #include "GLDebugFont.h"
#include "GlutStuff.h"//OpenGL stuff #include "GlutStuff.h"//OpenGL stuff
extern int gNumAlignedAllocs; extern int gNumAlignedAllocs;
extern int gNumAlignedFree; extern int gNumAlignedFree;
extern int gTotalBytesAlignedAllocs; extern int gTotalBytesAlignedAllocs;
class btEmptyDebugDemo : public GlutDemoApplication class btEmptyDebugDemo : public GlutDemoApplication
{ {
public: public:
btEmptyDebugDemo() btEmptyDebugDemo()
{ {
} }
virtual void clientMoveAndDisplay() virtual void clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float xOffset = 10.f; float xOffset = 10.f;
float yStart = 20.f; float yStart = 20.f;
float yIncr = 20.f; float yIncr = 20.f;
char buf[124]; char buf[124];
glColor3f(0, 0, 0); glColor3f(0, 0, 0);
setOrthographicProjection(); setOrthographicProjection();
glRasterPos3f(xOffset,yStart,0); glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"gNumAlignedAllocs= %d",gNumAlignedAllocs); sprintf(buf,"gNumAlignedAllocs= %d",gNumAlignedAllocs);
GLDebugDrawString(xOffset,yStart,buf); GLDebugDrawString(xOffset,yStart,buf);
yStart += yIncr; yStart += yIncr;
glRasterPos3f(xOffset,yStart,0); glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"gNumAlignedFree= %d",gNumAlignedFree); sprintf(buf,"gNumAlignedFree= %d",gNumAlignedFree);
GLDebugDrawString(xOffset,yStart,buf); GLDebugDrawString(xOffset,yStart,buf);
yStart += yIncr; yStart += yIncr;
glRasterPos3f(xOffset,yStart,0); glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"# alloc-free = %d",gNumAlignedAllocs-gNumAlignedFree); sprintf(buf,"# alloc-free = %d",gNumAlignedAllocs-gNumAlignedFree);
GLDebugDrawString(xOffset,yStart,buf); GLDebugDrawString(xOffset,yStart,buf);
yStart += yIncr; yStart += yIncr;
#ifdef BT_DEBUG_MEMORY_ALLOCATIONS #ifdef BT_DEBUG_MEMORY_ALLOCATIONS
glRasterPos3f(xOffset,yStart,0); glRasterPos3f(xOffset,yStart,0);
sprintf(buf,"gTotalBytesAlignedAllocs = %d",gTotalBytesAlignedAllocs); sprintf(buf,"gTotalBytesAlignedAllocs = %d",gTotalBytesAlignedAllocs);
GLDebugDrawString(xOffset,yStart,buf); GLDebugDrawString(xOffset,yStart,buf);
yStart += yIncr; yStart += yIncr;
#endif //BT_DEBUG_MEMORY_ALLOCATIONS #endif //BT_DEBUG_MEMORY_ALLOCATIONS
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
virtual void initPhysics() {} virtual void initPhysics() {}
static DemoApplication* Create() static DemoApplication* Create()
{ {
btEmptyDebugDemo* demo = new btEmptyDebugDemo(); btEmptyDebugDemo* demo = new btEmptyDebugDemo();
demo->myinit(); demo->myinit();
return demo; return demo;
} }
}; };
btDemoEntry g_demoEntries[] = btDemoEntry g_demoEntries[] =
{ {
{"ConstraintDemo",ConstraintDemo::Create}, {"ConstraintDemo",ConstraintDemo::Create},
{"ForkLift Demo",ForkLiftDemo::Create}, {"ForkLift Demo",ForkLiftDemo::Create},
{"Ragdoll Demo",RagdollDemo::Create}, {"Ragdoll Demo",RagdollDemo::Create},
{"Basic Demo", BasicDemo::Create}, {"Basic Demo", BasicDemo::Create},
{"CcdPhysicsDemo", CcdPhysicsDemo::Create}, {"CcdPhysicsDemo", CcdPhysicsDemo::Create},
{"Convex Decomposition",ConvexDecompositionDemo::Create}, {"Convex Decomposition",ConvexDecompositionDemo::Create},
{"Concave Moving", GimpactConcaveDemo::Create}, {"Concave Moving", GimpactConcaveDemo::Create},
{"Dynamic Control Demo",MotorDemo::Create}, {"Dynamic Control Demo",MotorDemo::Create},
{"ConcaveDemo",ConcaveDemo::Create}, {"ConcaveDemo",ConcaveDemo::Create},
{"Concave Convexcast Demo",ConcaveConvexcastDemo::Create}, {"Concave Convexcast Demo",ConcaveConvexcastDemo::Create},
{"SoftBody Cluster Collide1",SoftDemo19::Create}, {"SoftBody Cluster Collide1",SoftDemo19::Create},
{"SoftBody Ropes Attach",SoftDemo4::Create}, {"SoftBody Ropes Attach",SoftDemo4::Create},
{"SoftBody Cloth Attach",SoftDemo5::Create}, {"SoftBody Cloth Attach",SoftDemo5::Create},
{"SoftBody Cloth",SoftDemo0::Create}, {"SoftBody Cloth",SoftDemo0::Create},
// {"SoftBody Volume",SoftDemo2::Create}, // {"SoftBody Volume",SoftDemo2::Create},
{"SoftBody Pressure",SoftDemo1::Create}, {"SoftBody Pressure",SoftDemo1::Create},
{"SoftBody Cluster Car",SoftDemo24::Create}, {"SoftBody Cluster Car",SoftDemo24::Create},
{"SoftBody Cluster Robot",SoftDemo25::Create}, {"SoftBody Cluster Robot",SoftDemo25::Create},
// {"SoftBody Ropes",SoftDemo3::Create}, // {"SoftBody Ropes",SoftDemo3::Create},
{"SoftBody Sticks",SoftDemo6::Create}, {"SoftBody Sticks",SoftDemo6::Create},
{"SoftBody Collide",SoftDemo7::Create}, {"SoftBody Collide",SoftDemo7::Create},
{"SoftBody Collide2",SoftDemo8::Create}, {"SoftBody Collide2",SoftDemo8::Create},
// {"SoftBody Collide3",SoftDemo9::Create}, // {"SoftBody Collide3",SoftDemo9::Create},
// {"SoftBody Impact",SoftDemo10::Create}, // {"SoftBody Impact",SoftDemo10::Create},
{"SoftBody Aero",SoftDemo11::Create}, {"SoftBody Aero",SoftDemo11::Create},
{"SoftBody Friction",SoftDemo12::Create}, {"SoftBody Friction",SoftDemo12::Create},
// {"SoftBody Torus",SoftDemo13::Create}, // {"SoftBody Torus",SoftDemo13::Create},
// {"SoftBody Torus Match",SoftDemo14::Create}, // {"SoftBody Torus Match",SoftDemo14::Create},
// {"SoftBody Bunny",SoftDemo15::Create}, // {"SoftBody Bunny",SoftDemo15::Create},
// {"SoftBody Bunny Match",SoftDemo16::Create}, // {"SoftBody Bunny Match",SoftDemo16::Create},
{"SoftBody Init Cutting",SoftDemo17::Create}, {"SoftBody Init Cutting",SoftDemo17::Create},
// {"SoftBody Cluster Deform",SoftDemo18::Create}, // {"SoftBody Cluster Deform",SoftDemo18::Create},
// {"SoftBody Cluster Collide2",SoftDemo20::Create}, // {"SoftBody Cluster Collide2",SoftDemo20::Create},
// {"SoftBody Cluster Socket",SoftDemo21::Create}, // {"SoftBody Cluster Socket",SoftDemo21::Create},
{"SoftBody Cluster Hinge",SoftDemo22::Create}, {"SoftBody Cluster Hinge",SoftDemo22::Create},
{"SoftBody Cluster Combine",SoftDemo23::Create}, {"SoftBody Cluster Combine",SoftDemo23::Create},
// {"SoftBody Cluster Stack Soft",SoftDemo26::Create}, // {"SoftBody Cluster Stack Soft",SoftDemo26::Create},
{"SoftBody Cluster Stack Mixed",SoftDemo27::Create}, {"SoftBody Cluster Stack Mixed",SoftDemo27::Create},
{"SoftBody TetGen Tetrahedral Cube",SoftDemo28::Create}, {"SoftBody TetGen Tetrahedral Cube",SoftDemo28::Create},
{"SoftBody TetGen Tetrahedral Bunny",SoftDemo29::Create}, {"SoftBody TetGen Tetrahedral Bunny",SoftDemo29::Create},
// {"SliderConstraint",SliderConstraintDemo::Create}, // {"SliderConstraint",SliderConstraintDemo::Create},
// {"ConcaveRaycastDemo",ConcaveRaycastDemo::Create}, // {"ConcaveRaycastDemo",ConcaveRaycastDemo::Create},
//{"BspDemo", BspDemo::Create}, //{"BspDemo", BspDemo::Create},
// {"Raytracer Test",Raytracer::Create}, // {"Raytracer Test",Raytracer::Create},
// {"GjkConvexCast",LinearConvexCastDemo::Create}, // {"GjkConvexCast",LinearConvexCastDemo::Create},
// {"Benchmark 3000 FALL",BenchmarkDemo1::Create}, // {"Benchmark 3000 FALL",BenchmarkDemo1::Create},
// {"Benchmark 1000 STACK",BenchmarkDemo2::Create}, // {"Benchmark 1000 STACK",BenchmarkDemo2::Create},
// {"Benchmark 136 RAGDOLLS",BenchmarkDemo3::Create}, // {"Benchmark 136 RAGDOLLS",BenchmarkDemo3::Create},
// {"Benchmark 1000 CONVEX",BenchmarkDemo4::Create}, // {"Benchmark 1000 CONVEX",BenchmarkDemo4::Create},
// {"Benchmark Mesh-Prim",BenchmarkDemo5::Create}, // {"Benchmark Mesh-Prim",BenchmarkDemo5::Create},
// {"Benchmark Mesh-Convex",BenchmarkDemo6::Create}, // {"Benchmark Mesh-Convex",BenchmarkDemo6::Create},
// {"Benchmark Raycast",BenchmarkDemo7::Create}, // {"Benchmark Raycast",BenchmarkDemo7::Create},
{"MemoryLeak Checker",btEmptyDebugDemo::Create}, {"MemoryLeak Checker",btEmptyDebugDemo::Create},
{0, 0} {0, 0}
}; };

View File

@@ -1,34 +1,34 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BT_DEMO_ENTRIES_H #ifndef BT_DEMO_ENTRIES_H
#define BT_DEMO_ENTRIES_H #define BT_DEMO_ENTRIES_H
class DemoApplication; class DemoApplication;
typedef DemoApplication* DemoCreateFcn(); typedef DemoApplication* DemoCreateFcn();
struct btDemoEntry struct btDemoEntry
{ {
const char *name; const char *name;
DemoCreateFcn *createFcn; DemoCreateFcn *createFcn;
}; };
extern btDemoEntry g_demoEntries[]; extern btDemoEntry g_demoEntries[];
#endif //BT_DEMO_ENTRIES_H #endif //BT_DEMO_ENTRIES_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,266 +1,266 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
//#define TEST_SERIALIZATION 1 //#define TEST_SERIALIZATION 1
///create 125 (5x5x5) dynamic object ///create 125 (5x5x5) dynamic object
#define ARRAY_SIZE_X 5 #define ARRAY_SIZE_X 5
#define ARRAY_SIZE_Y 5 #define ARRAY_SIZE_Y 5
#define ARRAY_SIZE_Z 5 #define ARRAY_SIZE_Z 5
//maximum number of objects (and allow user to shoot additional boxes) //maximum number of objects (and allow user to shoot additional boxes)
#define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024) #define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024)
///scaling of the objects (0.1 = 20 centimeter boxes ) ///scaling of the objects (0.1 = 20 centimeter boxes )
#define SCALING 1. #define SCALING 1.
#define START_POS_X -5 #define START_POS_X -5
#define START_POS_Y -5 #define START_POS_Y -5
#define START_POS_Z -3 #define START_POS_Z -3
#include "BasicDemo.h" #include "BasicDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files. ///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#ifdef TEST_SERIALIZATION #ifdef TEST_SERIALIZATION
#include "LinearMath/btSerializer.h" #include "LinearMath/btSerializer.h"
#endif //TEST_SERIALIZATION #endif //TEST_SERIALIZATION
#include <stdio.h> //printf debugging #include <stdio.h> //printf debugging
void BasicDemo::clientMoveAndDisplay() void BasicDemo::clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//simple dynamics world doesn't handle fixed-time-stepping //simple dynamics world doesn't handle fixed-time-stepping
float ms = getDeltaTimeMicroseconds(); float ms = getDeltaTimeMicroseconds();
///step the simulation ///step the simulation
if (m_dynamicsWorld) if (m_dynamicsWorld)
{ {
m_dynamicsWorld->stepSimulation(ms / 1000000.f); m_dynamicsWorld->stepSimulation(ms / 1000000.f);
//optional but useful: debug drawing //optional but useful: debug drawing
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
} }
renderme(); renderme();
glFlush(); glFlush();
swapBuffers(); swapBuffers();
} }
void BasicDemo::displayCallback(void) { void BasicDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderme(); renderme();
//optional but useful: debug drawing to detect problems //optional but useful: debug drawing to detect problems
if (m_dynamicsWorld) if (m_dynamicsWorld)
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
glFlush(); glFlush();
swapBuffers(); swapBuffers();
} }
void BasicDemo::initPhysics() void BasicDemo::initPhysics()
{ {
setTexturing(true); setTexturing(true);
setShadows(true); setShadows(true);
setCameraDistance(btScalar(SCALING*50.)); setCameraDistance(btScalar(SCALING*50.));
///collision configuration contains default setup for memory, collision setup ///collision configuration contains default setup for memory, collision setup
m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_collisionConfiguration = new btDefaultCollisionConfiguration();
//m_collisionConfiguration->setConvexConvexMultipointIterations(); //m_collisionConfiguration->setConvexConvexMultipointIterations();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
m_broadphase = new btDbvtBroadphase(); m_broadphase = new btDbvtBroadphase();
///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver; btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
m_solver = sol; m_solver = sol;
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
m_dynamicsWorld->setGravity(btVector3(0,-10,0)); m_dynamicsWorld->setGravity(btVector3(0,-10,0));
///create a few basic rigid bodies ///create a few basic rigid bodies
btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.))); btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
// btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50); // btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
m_collisionShapes.push_back(groundShape); m_collisionShapes.push_back(groundShape);
btTransform groundTransform; btTransform groundTransform;
groundTransform.setIdentity(); groundTransform.setIdentity();
groundTransform.setOrigin(btVector3(0,-50,0)); groundTransform.setOrigin(btVector3(0,-50,0));
//We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here: //We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
{ {
btScalar mass(0.); btScalar mass(0.);
//rigidbody is dynamic if and only if mass is non zero, otherwise static //rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f); bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0); btVector3 localInertia(0,0,0);
if (isDynamic) if (isDynamic)
groundShape->calculateLocalInertia(mass,localInertia); groundShape->calculateLocalInertia(mass,localInertia);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
btRigidBody* body = new btRigidBody(rbInfo); btRigidBody* body = new btRigidBody(rbInfo);
//add the body to the dynamics world //add the body to the dynamics world
m_dynamicsWorld->addRigidBody(body); m_dynamicsWorld->addRigidBody(body);
} }
{ {
//create a few dynamic rigidbodies //create a few dynamic rigidbodies
// Re-using the same collision is better for memory usage and performance // Re-using the same collision is better for memory usage and performance
btCollisionShape* colShape = new btBoxShape(btVector3(SCALING*1,SCALING*1,SCALING*1)); btCollisionShape* colShape = new btBoxShape(btVector3(SCALING*1,SCALING*1,SCALING*1));
//btCollisionShape* colShape = new btSphereShape(btScalar(1.)); //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
m_collisionShapes.push_back(colShape); m_collisionShapes.push_back(colShape);
/// Create Dynamic Objects /// Create Dynamic Objects
btTransform startTransform; btTransform startTransform;
startTransform.setIdentity(); startTransform.setIdentity();
btScalar mass(1.f); btScalar mass(1.f);
//rigidbody is dynamic if and only if mass is non zero, otherwise static //rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f); bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0); btVector3 localInertia(0,0,0);
if (isDynamic) if (isDynamic)
colShape->calculateLocalInertia(mass,localInertia); colShape->calculateLocalInertia(mass,localInertia);
float start_x = START_POS_X - ARRAY_SIZE_X/2; float start_x = START_POS_X - ARRAY_SIZE_X/2;
float start_y = START_POS_Y; float start_y = START_POS_Y;
float start_z = START_POS_Z - ARRAY_SIZE_Z/2; float start_z = START_POS_Z - ARRAY_SIZE_Z/2;
for (int k=0;k<ARRAY_SIZE_Y;k++) for (int k=0;k<ARRAY_SIZE_Y;k++)
{ {
for (int i=0;i<ARRAY_SIZE_X;i++) for (int i=0;i<ARRAY_SIZE_X;i++)
{ {
for(int j = 0;j<ARRAY_SIZE_Z;j++) for(int j = 0;j<ARRAY_SIZE_Z;j++)
{ {
startTransform.setOrigin(SCALING*btVector3( startTransform.setOrigin(SCALING*btVector3(
btScalar(2.0*i + start_x), btScalar(2.0*i + start_x),
btScalar(20+2.0*k + start_y), btScalar(20+2.0*k + start_y),
btScalar(2.0*j + start_z))); btScalar(2.0*j + start_z)));
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);
btRigidBody* body = new btRigidBody(rbInfo); btRigidBody* body = new btRigidBody(rbInfo);
body->setActivationState(ISLAND_SLEEPING); body->setActivationState(ISLAND_SLEEPING);
m_dynamicsWorld->addRigidBody(body); m_dynamicsWorld->addRigidBody(body);
body->setActivationState(ISLAND_SLEEPING); body->setActivationState(ISLAND_SLEEPING);
} }
} }
} }
} }
clientResetScene(); clientResetScene();
#ifdef TEST_SERIALIZATION #ifdef TEST_SERIALIZATION
//test serializing this //test serializing this
int maxSerializeBufferSize = 1024*1024*5; int maxSerializeBufferSize = 1024*1024*5;
btDefaultSerializer* serializer = new btDefaultSerializer(maxSerializeBufferSize); btDefaultSerializer* serializer = new btDefaultSerializer(maxSerializeBufferSize);
m_dynamicsWorld->serialize(serializer); m_dynamicsWorld->serialize(serializer);
FILE* f2 = fopen("testFile.bullet","wb"); FILE* f2 = fopen("testFile.bullet","wb");
fwrite(serializer->m_buffer,serializer->m_currentSize,1,f2); fwrite(serializer->m_buffer,serializer->m_currentSize,1,f2);
fclose(f2); fclose(f2);
#endif #endif
#if 0 #if 0
bParse::btBulletFile* bulletFile2 = new bParse::btBulletFile("testFile.bullet"); bParse::btBulletFile* bulletFile2 = new bParse::btBulletFile("testFile.bullet");
bool ok = (bulletFile2->getFlags()& bParse::FD_OK)!=0; bool ok = (bulletFile2->getFlags()& bParse::FD_OK)!=0;
bool verboseDumpAllTypes = true; bool verboseDumpAllTypes = true;
if (ok) if (ok)
bulletFile2->parse(verboseDumpAllTypes); bulletFile2->parse(verboseDumpAllTypes);
if (verboseDumpAllTypes) if (verboseDumpAllTypes)
{ {
bulletFile2->dumpChunks(bulletFile2->getFileDNA()); bulletFile2->dumpChunks(bulletFile2->getFileDNA());
} }
#endif //TEST_SERIALIZATION #endif //TEST_SERIALIZATION
} }
void BasicDemo::exitPhysics() void BasicDemo::exitPhysics()
{ {
//cleanup in the reverse order of creation/initialization //cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them //remove the rigidbodies from the dynamics world and delete them
int i; int i;
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{ {
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj); btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState()) if (body && body->getMotionState())
{ {
delete body->getMotionState(); delete body->getMotionState();
} }
m_dynamicsWorld->removeCollisionObject( obj ); m_dynamicsWorld->removeCollisionObject( obj );
delete obj; delete obj;
} }
//delete collision shapes //delete collision shapes
for (int j=0;j<m_collisionShapes.size();j++) for (int j=0;j<m_collisionShapes.size();j++)
{ {
btCollisionShape* shape = m_collisionShapes[j]; btCollisionShape* shape = m_collisionShapes[j];
delete shape; delete shape;
} }
delete m_dynamicsWorld; delete m_dynamicsWorld;
delete m_solver; delete m_solver;
delete m_broadphase; delete m_broadphase;
delete m_dispatcher; delete m_dispatcher;
delete m_collisionConfiguration; delete m_collisionConfiguration;
} }

View File

@@ -1,81 +1,81 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BASIC_DEMO_H #ifndef BASIC_DEMO_H
#define BASIC_DEMO_H #define BASIC_DEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
///BasicDemo is good starting point for learning the code base and porting. ///BasicDemo is good starting point for learning the code base and porting.
class BasicDemo : public PlatformDemoApplication class BasicDemo : public PlatformDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
public: public:
BasicDemo() BasicDemo()
{ {
} }
virtual ~BasicDemo() virtual ~BasicDemo()
{ {
exitPhysics(); exitPhysics();
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
static DemoApplication* Create() static DemoApplication* Create()
{ {
BasicDemo* demo = new BasicDemo; BasicDemo* demo = new BasicDemo;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
#endif //BASIC_DEMO_H #endif //BASIC_DEMO_H

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BasicDemo.h" #include "BasicDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new BasicDemo(); return new BasicDemo();
} }
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,265 +1,265 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BENCHMARK_DEMO_H #ifndef BENCHMARK_DEMO_H
#define BENCHMARK_DEMO_H #define BENCHMARK_DEMO_H
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btTransform.h" #include "LinearMath/btTransform.h"
class btDynamicsWorld; class btDynamicsWorld;
#define NUMRAYS 500 #define NUMRAYS 500
class btRigidBody; class btRigidBody;
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
#ifndef USE_GRAPHICAL_BENCHMARK #ifndef USE_GRAPHICAL_BENCHMARK
///empty placeholder ///empty placeholder
class DemoApplication class DemoApplication
{ {
protected: protected:
btDynamicsWorld* m_dynamicsWorld; btDynamicsWorld* m_dynamicsWorld;
btScalar m_defaultContactProcessingThreshold; btScalar m_defaultContactProcessingThreshold;
public: public:
DemoApplication() DemoApplication()
:m_defaultContactProcessingThreshold(BT_LARGE_FLOAT) :m_defaultContactProcessingThreshold(BT_LARGE_FLOAT)
{ {
} }
virtual void myinit() {} virtual void myinit() {}
virtual btDynamicsWorld* getDynamicsWorld() virtual btDynamicsWorld* getDynamicsWorld()
{ {
return m_dynamicsWorld; return m_dynamicsWorld;
} }
btScalar getDeltaTimeMicroseconds() btScalar getDeltaTimeMicroseconds()
{ {
return 1.f; return 1.f;
} }
void renderme() {} void renderme() {}
void setCameraDistance(btScalar dist){} void setCameraDistance(btScalar dist){}
void clientResetScene(){} void clientResetScene(){}
btRigidBody* localCreateRigidBody(float mass, const btTransform& startTransform,btCollisionShape* shape); btRigidBody* localCreateRigidBody(float mass, const btTransform& startTransform,btCollisionShape* shape);
}; };
///BenchmarkDemo is provides several performance tests ///BenchmarkDemo is provides several performance tests
#define PlatformDemoApplication DemoApplication #define PlatformDemoApplication DemoApplication
#else //USE_GRAPHICAL_BENCHMARK #else //USE_GRAPHICAL_BENCHMARK
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
#endif //USE_GRAPHICAL_BENCHMARK #endif //USE_GRAPHICAL_BENCHMARK
class BenchmarkDemo : public PlatformDemoApplication class BenchmarkDemo : public PlatformDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btAlignedObjectArray<class RagDoll*> m_ragdolls; btAlignedObjectArray<class RagDoll*> m_ragdolls;
btBroadphaseInterface* m_overlappingPairCache; btBroadphaseInterface* m_overlappingPairCache;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
int m_benchmark; int m_benchmark;
void createTest1(); void createTest1();
void createTest2(); void createTest2();
void createTest3(); void createTest3();
void createTest4(); void createTest4();
void createTest5(); void createTest5();
void createTest6(); void createTest6();
void createTest7(); void createTest7();
void createWall(const btVector3& offsetPosition,int stackSize,const btVector3& boxSize); void createWall(const btVector3& offsetPosition,int stackSize,const btVector3& boxSize);
void createPyramid(const btVector3& offsetPosition,int stackSize,const btVector3& boxSize); void createPyramid(const btVector3& offsetPosition,int stackSize,const btVector3& boxSize);
void createTowerCircle(const btVector3& offsetPosition,int stackSize,int rotSize,const btVector3& boxSize); void createTowerCircle(const btVector3& offsetPosition,int stackSize,int rotSize,const btVector3& boxSize);
void createLargeMeshBody(); void createLargeMeshBody();
class SpuBatchRaycaster* m_batchRaycaster; class SpuBatchRaycaster* m_batchRaycaster;
class btThreadSupportInterface* m_batchRaycasterThreadSupport; class btThreadSupportInterface* m_batchRaycasterThreadSupport;
void castRays(); void castRays();
void initRays(); void initRays();
public: public:
BenchmarkDemo(int benchmark) BenchmarkDemo(int benchmark)
:m_benchmark(benchmark) :m_benchmark(benchmark)
{ {
} }
virtual ~BenchmarkDemo() virtual ~BenchmarkDemo()
{ {
exitPhysics(); exitPhysics();
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
}; };
class BenchmarkDemo1 : public BenchmarkDemo class BenchmarkDemo1 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo1() BenchmarkDemo1()
:BenchmarkDemo(1) :BenchmarkDemo(1)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo1* demo = new BenchmarkDemo1; BenchmarkDemo1* demo = new BenchmarkDemo1;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
class BenchmarkDemo2 : public BenchmarkDemo class BenchmarkDemo2 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo2() BenchmarkDemo2()
:BenchmarkDemo(2) :BenchmarkDemo(2)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo2* demo = new BenchmarkDemo2; BenchmarkDemo2* demo = new BenchmarkDemo2;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
class BenchmarkDemo3 : public BenchmarkDemo class BenchmarkDemo3 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo3() BenchmarkDemo3()
:BenchmarkDemo(3) :BenchmarkDemo(3)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo3* demo = new BenchmarkDemo3; BenchmarkDemo3* demo = new BenchmarkDemo3;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
class BenchmarkDemo4 : public BenchmarkDemo class BenchmarkDemo4 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo4() BenchmarkDemo4()
:BenchmarkDemo(4) :BenchmarkDemo(4)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo4* demo = new BenchmarkDemo4; BenchmarkDemo4* demo = new BenchmarkDemo4;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
class BenchmarkDemo5 : public BenchmarkDemo class BenchmarkDemo5 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo5() BenchmarkDemo5()
:BenchmarkDemo(5) :BenchmarkDemo(5)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo5* demo = new BenchmarkDemo5; BenchmarkDemo5* demo = new BenchmarkDemo5;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
class BenchmarkDemo6 : public BenchmarkDemo class BenchmarkDemo6 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo6() BenchmarkDemo6()
:BenchmarkDemo(6) :BenchmarkDemo(6)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo6* demo = new BenchmarkDemo6; BenchmarkDemo6* demo = new BenchmarkDemo6;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
class BenchmarkDemo7 : public BenchmarkDemo class BenchmarkDemo7 : public BenchmarkDemo
{ {
public: public:
BenchmarkDemo7() BenchmarkDemo7()
:BenchmarkDemo(7) :BenchmarkDemo(7)
{ {
} }
static DemoApplication* Create() static DemoApplication* Create()
{ {
BenchmarkDemo7* demo = new BenchmarkDemo7; BenchmarkDemo7* demo = new BenchmarkDemo7;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
#endif //BENCHMARK_DEMO_H #endif //BENCHMARK_DEMO_H

View File

@@ -1,105 +1,105 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
IF (USE_GRAPHICAL_BENCHMARK) IF (USE_GRAPHICAL_BENCHMARK)
IF (USE_GLUT) IF (USE_GLUT)
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/src
${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
IF (USE_MULTITHREADED_BENCHMARK) IF (USE_MULTITHREADED_BENCHMARK)
LINK_LIBRARIES( OpenGLSupport BulletMultiThreaded BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}) LINK_LIBRARIES( OpenGLSupport BulletMultiThreaded BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY})
ELSE() ELSE()
LINK_LIBRARIES( OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}) LINK_LIBRARIES( OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY})
ENDIF(USE_MULTITHREADED_BENCHMARK) ENDIF(USE_MULTITHREADED_BENCHMARK)
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppBenchmarks ADD_EXECUTABLE(AppBenchmarks
main.cpp main.cpp
BenchmarkDemo.cpp BenchmarkDemo.cpp
BenchmarkDemo.h BenchmarkDemo.h
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppBenchmarks ADD_EXECUTABLE(AppBenchmarks
main.cpp main.cpp
BenchmarkDemo.cpp BenchmarkDemo.cpp
BenchmarkDemo.h BenchmarkDemo.h
) )
ENDIF () ENDIF ()
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES) IF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppBenchmarks TARGET AppBenchmarks
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppBenchmarks TARGET AppBenchmarks
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_MSVC_RELATIVE_PATH_PROJECTFILES)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppBenchmarks PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppBenchmarks PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppBenchmarks PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppBenchmarks PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppBenchmarks PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppBenchmarks PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
ENDIF(WIN32) ENDIF(WIN32)
ELSE (USE_GLUT) ELSE (USE_GLUT)
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/src
${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
IF (USE_MULTITHREADED_BENCHMARK) IF (USE_MULTITHREADED_BENCHMARK)
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletMultiThreaded BulletDynamics BulletCollision LinearMath ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletMultiThreaded BulletDynamics BulletCollision LinearMath ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ELSE() ELSE()
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ENDIF() ENDIF()
ADD_EXECUTABLE(AppBenchmarks ADD_EXECUTABLE(AppBenchmarks
WIN32 WIN32
../OpenGL/Win32AppMain.cpp ../OpenGL/Win32AppMain.cpp
BenchmarkDemo.cpp BenchmarkDemo.cpp
BenchmarkDemo.h BenchmarkDemo.h
Win32BenchmarkDemo.cpp Win32BenchmarkDemo.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ENDIF (USE_GLUT) ENDIF (USE_GLUT)
ELSE (USE_GRAPHICAL_BENCHMARK) ELSE (USE_GRAPHICAL_BENCHMARK)
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/src
${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
IF (USE_MULTITHREADED_BENCHMARK) IF (USE_MULTITHREADED_BENCHMARK)
LINK_LIBRARIES( BulletMultiThreaded BulletDynamics BulletCollision LinearMath ) LINK_LIBRARIES( BulletMultiThreaded BulletDynamics BulletCollision LinearMath )
ELSE() ELSE()
LINK_LIBRARIES( BulletDynamics BulletCollision LinearMath ) LINK_LIBRARIES( BulletDynamics BulletCollision LinearMath )
ENDIF() ENDIF()
ADD_EXECUTABLE(AppBenchmarks ADD_EXECUTABLE(AppBenchmarks
main.cpp main.cpp
BenchmarkDemo.cpp BenchmarkDemo.cpp
) )
ENDIF (USE_GRAPHICAL_BENCHMARK) ENDIF (USE_GRAPHICAL_BENCHMARK)

View File

@@ -1,49 +1,49 @@
#define TaruVtxCount 43 #define TaruVtxCount 43
#define TaruIdxCount 132 #define TaruIdxCount 132
static float TaruVtx[] = { static float TaruVtx[] = {
1.08664f,-1.99237f,0.0f, 1.08664f,-1.99237f,0.0f,
0.768369f,-1.99237f,-0.768369f, 0.768369f,-1.99237f,-0.768369f,
1.28852f,1.34412e-007f,-1.28852f, 1.28852f,1.34412e-007f,-1.28852f,
1.82224f,1.90735e-007f,0.0f, 1.82224f,1.90735e-007f,0.0f,
0.0f,-1.99237f,-1.08664f, 0.0f,-1.99237f,-1.08664f,
0.0f,0.0f,-1.82224f, 0.0f,0.0f,-1.82224f,
0.0f,-1.99237f,-1.08664f, 0.0f,-1.99237f,-1.08664f,
-0.768369f,-1.99237f,-0.768369f, -0.768369f,-1.99237f,-0.768369f,
-1.28852f,1.34412e-007f,-1.28852f, -1.28852f,1.34412e-007f,-1.28852f,
0.0f,0.0f,-1.82224f, 0.0f,0.0f,-1.82224f,
-1.08664f,-1.99237f,1.82086e-007f, -1.08664f,-1.99237f,1.82086e-007f,
-1.82224f,1.90735e-007f,1.59305e-007f, -1.82224f,1.90735e-007f,1.59305e-007f,
-0.768369f,-1.99237f,0.76837f, -0.768369f,-1.99237f,0.76837f,
-1.28852f,2.47058e-007f,1.28852f, -1.28852f,2.47058e-007f,1.28852f,
1.42495e-007f,-1.99237f,1.08664f, 1.42495e-007f,-1.99237f,1.08664f,
2.38958e-007f,2.70388e-007f,1.82224f, 2.38958e-007f,2.70388e-007f,1.82224f,
0.768369f,-1.99237f,0.768369f, 0.768369f,-1.99237f,0.768369f,
1.28852f,2.47058e-007f,1.28852f, 1.28852f,2.47058e-007f,1.28852f,
0.768369f,1.99237f,-0.768369f, 0.768369f,1.99237f,-0.768369f,
1.08664f,1.99237f,0.0f, 1.08664f,1.99237f,0.0f,
0.0f,1.99237f,-1.08664f, 0.0f,1.99237f,-1.08664f,
-0.768369f,1.99237f,-0.768369f, -0.768369f,1.99237f,-0.768369f,
0.0f,1.99237f,-1.08664f, 0.0f,1.99237f,-1.08664f,
-1.08664f,1.99237f,0.0f, -1.08664f,1.99237f,0.0f,
-0.768369f,1.99237f,0.768369f, -0.768369f,1.99237f,0.768369f,
1.42495e-007f,1.99237f,1.08664f, 1.42495e-007f,1.99237f,1.08664f,
0.768369f,1.99237f,0.768369f, 0.768369f,1.99237f,0.768369f,
1.42495e-007f,-1.99237f,1.08664f, 1.42495e-007f,-1.99237f,1.08664f,
-0.768369f,-1.99237f,0.76837f, -0.768369f,-1.99237f,0.76837f,
-1.08664f,-1.99237f,1.82086e-007f, -1.08664f,-1.99237f,1.82086e-007f,
-0.768369f,-1.99237f,-0.768369f, -0.768369f,-1.99237f,-0.768369f,
0.0f,-1.99237f,-1.08664f, 0.0f,-1.99237f,-1.08664f,
0.768369f,-1.99237f,-0.768369f, 0.768369f,-1.99237f,-0.768369f,
1.08664f,-1.99237f,0.0f, 1.08664f,-1.99237f,0.0f,
0.768369f,-1.99237f,0.768369f, 0.768369f,-1.99237f,0.768369f,
0.768369f,1.99237f,-0.768369f, 0.768369f,1.99237f,-0.768369f,
0.0f,1.99237f,-1.08664f, 0.0f,1.99237f,-1.08664f,
-0.768369f,1.99237f,-0.768369f, -0.768369f,1.99237f,-0.768369f,
-1.08664f,1.99237f,0.0f, -1.08664f,1.99237f,0.0f,
-0.768369f,1.99237f,0.768369f, -0.768369f,1.99237f,0.768369f,
1.42495e-007f,1.99237f,1.08664f, 1.42495e-007f,1.99237f,1.08664f,
0.768369f,1.99237f,0.768369f, 0.768369f,1.99237f,0.768369f,
1.08664f,1.99237f,0.0f, 1.08664f,1.99237f,0.0f,
}; };

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BenchmarkDemo.h" #include "BenchmarkDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new BenchmarkDemo(1); return new BenchmarkDemo(1);
} }
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,88 +1,88 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BenchmarkDemo.h" #include "BenchmarkDemo.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "LinearMath/btHashMap.h" #include "LinearMath/btHashMap.h"
#include <stdio.h> #include <stdio.h>
#ifdef USE_GRAPHICAL_BENCHMARK #ifdef USE_GRAPHICAL_BENCHMARK
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
GLDebugDrawer gDebugDrawer; GLDebugDrawer gDebugDrawer;
#define benchmarkDemo benchmarkDemo2 #define benchmarkDemo benchmarkDemo2
#endif //USE_GRAPHICAL_BENCHMARK #endif //USE_GRAPHICAL_BENCHMARK
#define NUM_DEMOS 7 #define NUM_DEMOS 7
#define NUM_TESTS 650 #define NUM_TESTS 650
extern bool gDisableDeactivation; extern bool gDisableDeactivation;
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
gDisableDeactivation = true; gDisableDeactivation = true;
BenchmarkDemo1 benchmarkDemo1; BenchmarkDemo1 benchmarkDemo1;
BenchmarkDemo2 benchmarkDemo2; BenchmarkDemo2 benchmarkDemo2;
BenchmarkDemo3 benchmarkDemo3; BenchmarkDemo3 benchmarkDemo3;
BenchmarkDemo4 benchmarkDemo4; BenchmarkDemo4 benchmarkDemo4;
BenchmarkDemo5 benchmarkDemo5; BenchmarkDemo5 benchmarkDemo5;
BenchmarkDemo6 benchmarkDemo6; BenchmarkDemo6 benchmarkDemo6;
BenchmarkDemo7 benchmarkDemo7; BenchmarkDemo7 benchmarkDemo7;
BenchmarkDemo* demoArray[NUM_DEMOS] = {&benchmarkDemo1,&benchmarkDemo2,&benchmarkDemo3,&benchmarkDemo4,&benchmarkDemo5,&benchmarkDemo6,&benchmarkDemo7}; BenchmarkDemo* demoArray[NUM_DEMOS] = {&benchmarkDemo1,&benchmarkDemo2,&benchmarkDemo3,&benchmarkDemo4,&benchmarkDemo5,&benchmarkDemo6,&benchmarkDemo7};
const char* demoNames[NUM_DEMOS] = {"3000 fall", "1000 stack", "136 ragdolls","1000 convex", "prim-trimesh", "convex-trimesh","raytests"}; const char* demoNames[NUM_DEMOS] = {"3000 fall", "1000 stack", "136 ragdolls","1000 convex", "prim-trimesh", "convex-trimesh","raytests"};
float totalTime[NUM_DEMOS] = {0.f,0.f,0.f,0.f,0.f,0.f,0.f}; float totalTime[NUM_DEMOS] = {0.f,0.f,0.f,0.f,0.f,0.f,0.f};
#ifdef USE_GRAPHICAL_BENCHMARK #ifdef USE_GRAPHICAL_BENCHMARK
benchmarkDemo.initPhysics(); benchmarkDemo.initPhysics();
benchmarkDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); benchmarkDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);
benchmarkDemo.setDebugMode(benchmarkDemo.getDebugMode() | btIDebugDraw::DBG_NoDeactivation); benchmarkDemo.setDebugMode(benchmarkDemo.getDebugMode() | btIDebugDraw::DBG_NoDeactivation);
return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&benchmarkDemo); return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&benchmarkDemo);
#else //USE_GRAPHICAL_BENCHMARK #else //USE_GRAPHICAL_BENCHMARK
int d; int d;
for (d=0;d<NUM_DEMOS;d++) for (d=0;d<NUM_DEMOS;d++)
{ {
demoArray[d]->initPhysics(); demoArray[d]->initPhysics();
for (int i=0;i<NUM_TESTS;i++) for (int i=0;i<NUM_TESTS;i++)
{ {
demoArray[d]->clientMoveAndDisplay(); demoArray[d]->clientMoveAndDisplay();
float frameTime = CProfileManager::Get_Time_Since_Reset(); float frameTime = CProfileManager::Get_Time_Since_Reset();
if ((i % 25)==0) if ((i % 25)==0)
{ {
printf("BenchmarkDemo: %s, Frame %d, Duration (ms): %f\n",demoNames[d],i,frameTime); printf("BenchmarkDemo: %s, Frame %d, Duration (ms): %f\n",demoNames[d],i,frameTime);
} }
totalTime[d] += frameTime; totalTime[d] += frameTime;
if (i==NUM_TESTS-1) if (i==NUM_TESTS-1)
CProfileManager::dumpAll(); CProfileManager::dumpAll();
} }
} }
for (d=0;d<NUM_DEMOS;d++) for (d=0;d<NUM_DEMOS;d++)
{ {
printf("\nResults for %s: %f",demoNames[d],totalTime[d]*(1.f/NUM_TESTS)); printf("\nResults for %s: %f",demoNames[d],totalTime[d]*(1.f/NUM_TESTS));
} }
#endif //USE_GRAPHICAL_BENCHMARK #endif //USE_GRAPHICAL_BENCHMARK
return 0; return 0;
} }

View File

@@ -1,358 +1,358 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BulletCollision/CollisionShapes/btBox2dShape.h" #include "BulletCollision/CollisionShapes/btBox2dShape.h"
#include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h" #include "BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h"
#include "GL_DialogDynamicsWorld.h" #include "GL_DialogDynamicsWorld.h"
#include "GL_DialogWindow.h" #include "GL_DialogWindow.h"
#include "BulletCollision/CollisionShapes/btBox2dShape.h" #include "BulletCollision/CollisionShapes/btBox2dShape.h"
#include "BulletCollision/CollisionShapes/btConvex2dShape.h" #include "BulletCollision/CollisionShapes/btConvex2dShape.h"
#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
///create 125 (5x5x5) dynamic object ///create 125 (5x5x5) dynamic object
#define ARRAY_SIZE_X 5 #define ARRAY_SIZE_X 5
#define ARRAY_SIZE_Y 5 #define ARRAY_SIZE_Y 5
#define ARRAY_SIZE_Z 1 #define ARRAY_SIZE_Z 1
//maximum number of objects (and allow user to shoot additional boxes) //maximum number of objects (and allow user to shoot additional boxes)
#define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024) #define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024)
///scaling of the objects (0.1 = 20 centimeter boxes ) ///scaling of the objects (0.1 = 20 centimeter boxes )
#define SCALING 1 #define SCALING 1
#define START_POS_X -5 #define START_POS_X -5
#define START_POS_Y -5 #define START_POS_Y -5
#define START_POS_Z -3 #define START_POS_Z -3
#include "Box2dDemo.h" #include "Box2dDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files. ///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include <stdio.h> //printf debugging #include <stdio.h> //printf debugging
void Box2dDemo::clientMoveAndDisplay() void Box2dDemo::clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//simple dynamics world doesn't handle fixed-time-stepping //simple dynamics world doesn't handle fixed-time-stepping
float ms = getDeltaTimeMicroseconds(); float ms = getDeltaTimeMicroseconds();
///step the simulation ///step the simulation
if (m_dynamicsWorld) if (m_dynamicsWorld)
{ {
m_dynamicsWorld->stepSimulation(ms / 1000000.f); m_dynamicsWorld->stepSimulation(ms / 1000000.f);
//optional but useful: debug drawing //optional but useful: debug drawing
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
} }
renderme(); renderme();
if (m_dialogDynamicsWorld) if (m_dialogDynamicsWorld)
m_dialogDynamicsWorld->draw(ms / 1000000.f); m_dialogDynamicsWorld->draw(ms / 1000000.f);
glFlush(); glFlush();
swapBuffers(); swapBuffers();
} }
void Box2dDemo::displayCallback(void) { void Box2dDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderme(); renderme();
//optional but useful: debug drawing to detect problems //optional but useful: debug drawing to detect problems
if (m_dynamicsWorld) if (m_dynamicsWorld)
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
if (m_dialogDynamicsWorld) if (m_dialogDynamicsWorld)
m_dialogDynamicsWorld->draw(0.f); m_dialogDynamicsWorld->draw(0.f);
glFlush(); glFlush();
swapBuffers(); swapBuffers();
} }
void Box2dDemo::reshape(int w, int h) void Box2dDemo::reshape(int w, int h)
{ {
if (m_dialogDynamicsWorld) if (m_dialogDynamicsWorld)
m_dialogDynamicsWorld->setScreenSize(w,h); m_dialogDynamicsWorld->setScreenSize(w,h);
PlatformDemoApplication::reshape(w,h); PlatformDemoApplication::reshape(w,h);
} }
void Box2dDemo::initPhysics() void Box2dDemo::initPhysics()
{ {
m_dialogDynamicsWorld = new GL_DialogDynamicsWorld(); m_dialogDynamicsWorld = new GL_DialogDynamicsWorld();
//m_dialogDynamicsWorld->createDialog(100,110,200,50); //m_dialogDynamicsWorld->createDialog(100,110,200,50);
//m_dialogDynamicsWorld->createDialog(100,00,100,100); //m_dialogDynamicsWorld->createDialog(100,00,100,100);
//m_dialogDynamicsWorld->createDialog(0,0,100,100); //m_dialogDynamicsWorld->createDialog(0,0,100,100);
GL_DialogWindow* settings = m_dialogDynamicsWorld->createDialog(50,0,200,120,"Settings"); GL_DialogWindow* settings = m_dialogDynamicsWorld->createDialog(50,0,200,120,"Settings");
GL_ToggleControl* toggle = m_dialogDynamicsWorld->createToggle(settings,"Toggle 1"); GL_ToggleControl* toggle = m_dialogDynamicsWorld->createToggle(settings,"Toggle 1");
toggle = m_dialogDynamicsWorld->createToggle(settings,"Toggle 2"); toggle = m_dialogDynamicsWorld->createToggle(settings,"Toggle 2");
toggle ->m_active = true; toggle ->m_active = true;
toggle = m_dialogDynamicsWorld->createToggle(settings,"Toggle 3"); toggle = m_dialogDynamicsWorld->createToggle(settings,"Toggle 3");
GL_SliderControl* slider = m_dialogDynamicsWorld->createSlider(settings,"Slider"); GL_SliderControl* slider = m_dialogDynamicsWorld->createSlider(settings,"Slider");
GL_DialogWindow* dialog = m_dialogDynamicsWorld->createDialog(0,200,420,300,"Help"); GL_DialogWindow* dialog = m_dialogDynamicsWorld->createDialog(0,200,420,300,"Help");
GL_TextControl* txt = new GL_TextControl; GL_TextControl* txt = new GL_TextControl;
dialog->addControl(txt); dialog->addControl(txt);
txt->m_textLines.push_back("Mouse to move"); txt->m_textLines.push_back("Mouse to move");
txt->m_textLines.push_back("Test 2"); txt->m_textLines.push_back("Test 2");
txt->m_textLines.push_back("mouse to interact"); txt->m_textLines.push_back("mouse to interact");
txt->m_textLines.push_back("ALT + mouse to move camera"); txt->m_textLines.push_back("ALT + mouse to move camera");
txt->m_textLines.push_back("space to reset"); txt->m_textLines.push_back("space to reset");
txt->m_textLines.push_back("cursor keys and z,x to navigate"); txt->m_textLines.push_back("cursor keys and z,x to navigate");
txt->m_textLines.push_back("i to toggle simulation, s single step"); txt->m_textLines.push_back("i to toggle simulation, s single step");
txt->m_textLines.push_back("q to quit"); txt->m_textLines.push_back("q to quit");
txt->m_textLines.push_back(". to shoot box"); txt->m_textLines.push_back(". to shoot box");
txt->m_textLines.push_back("d to toggle deactivation"); txt->m_textLines.push_back("d to toggle deactivation");
txt->m_textLines.push_back("g to toggle mesh animation (ConcaveDemo)"); txt->m_textLines.push_back("g to toggle mesh animation (ConcaveDemo)");
txt->m_textLines.push_back("h to toggle help text"); txt->m_textLines.push_back("h to toggle help text");
txt->m_textLines.push_back("o to toggle orthogonal/perspective view"); txt->m_textLines.push_back("o to toggle orthogonal/perspective view");
//txt->m_textLines.push_back("+- shooting speed = %10.2f",m_ShootBoxInitialSpeed); //txt->m_textLines.push_back("+- shooting speed = %10.2f",m_ShootBoxInitialSpeed);
setTexturing(true); setTexturing(true);
setShadows(true); setShadows(true);
setCameraDistance(btScalar(SCALING*50.)); setCameraDistance(btScalar(SCALING*50.));
m_cameraTargetPosition.setValue(0,0,0);//0, ARRAY_SIZE_Y, 0); m_cameraTargetPosition.setValue(0,0,0);//0, ARRAY_SIZE_Y, 0);
///collision configuration contains default setup for memory, collision setup ///collision configuration contains default setup for memory, collision setup
m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_collisionConfiguration = new btDefaultCollisionConfiguration();
//m_collisionConfiguration->setConvexConvexMultipointIterations(); //m_collisionConfiguration->setConvexConvexMultipointIterations();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
btVoronoiSimplexSolver* simplex = new btVoronoiSimplexSolver(); btVoronoiSimplexSolver* simplex = new btVoronoiSimplexSolver();
btMinkowskiPenetrationDepthSolver* pdSolver = new btMinkowskiPenetrationDepthSolver(); btMinkowskiPenetrationDepthSolver* pdSolver = new btMinkowskiPenetrationDepthSolver();
btConvex2dConvex2dAlgorithm::CreateFunc* convexAlgo2d = new btConvex2dConvex2dAlgorithm::CreateFunc(simplex,pdSolver); btConvex2dConvex2dAlgorithm::CreateFunc* convexAlgo2d = new btConvex2dConvex2dAlgorithm::CreateFunc(simplex,pdSolver);
m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE,convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE,convexAlgo2d);
m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE,convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE,convexAlgo2d);
m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE,convexAlgo2d); m_dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE,convexAlgo2d);
m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE,new btBox2dBox2dCollisionAlgorithm::CreateFunc()); m_dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE,new btBox2dBox2dCollisionAlgorithm::CreateFunc());
m_broadphase = new btDbvtBroadphase(); m_broadphase = new btDbvtBroadphase();
//m_broadphase = new btSimpleBroadphase(); //m_broadphase = new btSimpleBroadphase();
///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver; btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
m_solver = sol; m_solver = sol;
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
//m_dynamicsWorld->getSolverInfo().m_erp = 1.f; //m_dynamicsWorld->getSolverInfo().m_erp = 1.f;
//m_dynamicsWorld->getSolverInfo().m_numIterations = 4; //m_dynamicsWorld->getSolverInfo().m_numIterations = 4;
m_dynamicsWorld->setGravity(btVector3(0,-10,0)); m_dynamicsWorld->setGravity(btVector3(0,-10,0));
///create a few basic rigid bodies ///create a few basic rigid bodies
btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(150.),btScalar(50.),btScalar(150.))); btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(150.),btScalar(50.),btScalar(150.)));
// btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50); // btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
m_collisionShapes.push_back(groundShape); m_collisionShapes.push_back(groundShape);
btTransform groundTransform; btTransform groundTransform;
groundTransform.setIdentity(); groundTransform.setIdentity();
groundTransform.setOrigin(btVector3(0,-43,0)); groundTransform.setOrigin(btVector3(0,-43,0));
//We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here: //We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
{ {
btScalar mass(0.); btScalar mass(0.);
//rigidbody is dynamic if and only if mass is non zero, otherwise static //rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f); bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0); btVector3 localInertia(0,0,0);
if (isDynamic) if (isDynamic)
groundShape->calculateLocalInertia(mass,localInertia); groundShape->calculateLocalInertia(mass,localInertia);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
btRigidBody* body = new btRigidBody(rbInfo); btRigidBody* body = new btRigidBody(rbInfo);
//add the body to the dynamics world //add the body to the dynamics world
m_dynamicsWorld->addRigidBody(body); m_dynamicsWorld->addRigidBody(body);
} }
{ {
//create a few dynamic rigidbodies //create a few dynamic rigidbodies
// Re-using the same collision is better for memory usage and performance // Re-using the same collision is better for memory usage and performance
btScalar u= btScalar(1*SCALING-0.04); btScalar u= btScalar(1*SCALING-0.04);
btVector3 points[3] = {btVector3(0,u,0),btVector3(-u,-u,0),btVector3(u,-u,0)}; btVector3 points[3] = {btVector3(0,u,0),btVector3(-u,-u,0),btVector3(u,-u,0)};
btConvexShape* colShape= new btConvex2dShape(new btBoxShape(btVector3(btScalar(SCALING*1),btScalar(SCALING*1),btScalar(0.04)))); btConvexShape* colShape= new btConvex2dShape(new btBoxShape(btVector3(btScalar(SCALING*1),btScalar(SCALING*1),btScalar(0.04))));
//btCollisionShape* colShape = new btBox2dShape(btVector3(SCALING*1,SCALING*1,0.04)); //btCollisionShape* colShape = new btBox2dShape(btVector3(SCALING*1,SCALING*1,0.04));
btConvexShape* colShape2= new btConvex2dShape(new btConvexHullShape(&points[0].getX(),3)); btConvexShape* colShape2= new btConvex2dShape(new btConvexHullShape(&points[0].getX(),3));
btConvexShape* colShape3= new btConvex2dShape(new btCylinderShapeZ(btVector3(btScalar(SCALING*1),btScalar(SCALING*1),btScalar(0.04)))); btConvexShape* colShape3= new btConvex2dShape(new btCylinderShapeZ(btVector3(btScalar(SCALING*1),btScalar(SCALING*1),btScalar(0.04))));
//btUniformScalingShape* colShape = new btUniformScalingShape(convexColShape,1.f); //btUniformScalingShape* colShape = new btUniformScalingShape(convexColShape,1.f);
colShape->setMargin(btScalar(0.03)); colShape->setMargin(btScalar(0.03));
//btCollisionShape* colShape = new btSphereShape(btScalar(1.)); //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
m_collisionShapes.push_back(colShape); m_collisionShapes.push_back(colShape);
m_collisionShapes.push_back(colShape2); m_collisionShapes.push_back(colShape2);
/// Create Dynamic Objects /// Create Dynamic Objects
btTransform startTransform; btTransform startTransform;
startTransform.setIdentity(); startTransform.setIdentity();
btScalar mass(1.f); btScalar mass(1.f);
//rigidbody is dynamic if and only if mass is non zero, otherwise static //rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f); bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0); btVector3 localInertia(0,0,0);
if (isDynamic) if (isDynamic)
colShape->calculateLocalInertia(mass,localInertia); colShape->calculateLocalInertia(mass,localInertia);
// float start_x = START_POS_X - ARRAY_SIZE_X/2; // float start_x = START_POS_X - ARRAY_SIZE_X/2;
// float start_y = START_POS_Y; // float start_y = START_POS_Y;
// float start_z = START_POS_Z - ARRAY_SIZE_Z/2; // float start_z = START_POS_Z - ARRAY_SIZE_Z/2;
btVector3 x(-ARRAY_SIZE_X, 8.0f,-20.f); btVector3 x(-ARRAY_SIZE_X, 8.0f,-20.f);
btVector3 y; btVector3 y;
btVector3 deltaX(SCALING*1, SCALING*2,0.f); btVector3 deltaX(SCALING*1, SCALING*2,0.f);
btVector3 deltaY(SCALING*2, 0.0f,0.f); btVector3 deltaY(SCALING*2, 0.0f,0.f);
for (int i = 0; i < ARRAY_SIZE_X; ++i) for (int i = 0; i < ARRAY_SIZE_X; ++i)
{ {
y = x; y = x;
for (int j = i; j < ARRAY_SIZE_Y; ++j) for (int j = i; j < ARRAY_SIZE_Y; ++j)
{ {
startTransform.setOrigin(y-btVector3(-10,0,0)); startTransform.setOrigin(y-btVector3(-10,0,0));
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(0,0,0); btRigidBody::btRigidBodyConstructionInfo rbInfo(0,0,0);
switch (j%3) switch (j%3)
{ {
#if 1 #if 1
case 0: case 0:
rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass,myMotionState,colShape,localInertia); rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass,myMotionState,colShape,localInertia);
break; break;
case 1: case 1:
rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass,myMotionState,colShape3,localInertia); rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass,myMotionState,colShape3,localInertia);
break; break;
#endif #endif
default: default:
rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass,myMotionState,colShape2,localInertia); rbInfo = btRigidBody::btRigidBodyConstructionInfo(mass,myMotionState,colShape2,localInertia);
} }
btRigidBody* body = new btRigidBody(rbInfo); btRigidBody* body = new btRigidBody(rbInfo);
//body->setContactProcessingThreshold(colShape->getContactBreakingThreshold()); //body->setContactProcessingThreshold(colShape->getContactBreakingThreshold());
body->setActivationState(ISLAND_SLEEPING); body->setActivationState(ISLAND_SLEEPING);
body->setLinearFactor(btVector3(1,1,0)); body->setLinearFactor(btVector3(1,1,0));
body->setAngularFactor(btVector3(0,0,1)); body->setAngularFactor(btVector3(0,0,1));
m_dynamicsWorld->addRigidBody(body); m_dynamicsWorld->addRigidBody(body);
body->setActivationState(ISLAND_SLEEPING); body->setActivationState(ISLAND_SLEEPING);
// y += -0.8*deltaY; // y += -0.8*deltaY;
y += deltaY; y += deltaY;
} }
x += deltaX; x += deltaX;
} }
} }
clientResetScene(); clientResetScene();
} }
void Box2dDemo::exitPhysics() void Box2dDemo::exitPhysics()
{ {
delete m_dialogDynamicsWorld; delete m_dialogDynamicsWorld;
m_dialogDynamicsWorld = 0; m_dialogDynamicsWorld = 0;
//cleanup in the reverse order of creation/initialization //cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them //remove the rigidbodies from the dynamics world and delete them
int i; int i;
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{ {
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj); btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState()) if (body && body->getMotionState())
{ {
delete body->getMotionState(); delete body->getMotionState();
} }
m_dynamicsWorld->removeCollisionObject( obj ); m_dynamicsWorld->removeCollisionObject( obj );
delete obj; delete obj;
} }
//delete collision shapes //delete collision shapes
for (int j=0;j<m_collisionShapes.size();j++) for (int j=0;j<m_collisionShapes.size();j++)
{ {
btCollisionShape* shape = m_collisionShapes[j]; btCollisionShape* shape = m_collisionShapes[j];
delete shape; delete shape;
} }
delete m_dynamicsWorld; delete m_dynamicsWorld;
delete m_solver; delete m_solver;
delete m_broadphase; delete m_broadphase;
delete m_dispatcher; delete m_dispatcher;
delete m_collisionConfiguration; delete m_collisionConfiguration;
} }
void Box2dDemo::mouseFunc(int button, int state, int x, int y) void Box2dDemo::mouseFunc(int button, int state, int x, int y)
{ {
if (!m_dialogDynamicsWorld->mouseFunc(button,state,x,y)) if (!m_dialogDynamicsWorld->mouseFunc(button,state,x,y))
{ {
DemoApplication::mouseFunc(button,state,x,y); DemoApplication::mouseFunc(button,state,x,y);
} }
} }
void Box2dDemo::mouseMotionFunc(int x,int y) void Box2dDemo::mouseMotionFunc(int x,int y)
{ {
m_dialogDynamicsWorld->mouseMotionFunc(x,y); m_dialogDynamicsWorld->mouseMotionFunc(x,y);
DemoApplication::mouseMotionFunc(x,y); DemoApplication::mouseMotionFunc(x,y);
} }

View File

@@ -1,89 +1,89 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BOX2D_DEMO_H #ifndef BOX2D_DEMO_H
#define BOX2D_DEMO_H #define BOX2D_DEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
class GL_DialogDynamicsWorld; class GL_DialogDynamicsWorld;
///Box2dDemo is good starting point for learning the code base and porting. ///Box2dDemo is good starting point for learning the code base and porting.
class Box2dDemo : public PlatformDemoApplication class Box2dDemo : public PlatformDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
GL_DialogDynamicsWorld* m_dialogDynamicsWorld; GL_DialogDynamicsWorld* m_dialogDynamicsWorld;
public: public:
Box2dDemo() : m_dialogDynamicsWorld(0) Box2dDemo() : m_dialogDynamicsWorld(0)
{ {
} }
virtual ~Box2dDemo() virtual ~Box2dDemo()
{ {
exitPhysics(); exitPhysics();
} }
virtual void reshape(int w, int h); virtual void reshape(int w, int h);
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
static DemoApplication* Create() static DemoApplication* Create()
{ {
Box2dDemo* demo = new Box2dDemo; Box2dDemo* demo = new Box2dDemo;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
virtual void mouseFunc(int button, int state, int x, int y); virtual void mouseFunc(int button, int state, int x, int y);
virtual void mouseMotionFunc(int x,int y); virtual void mouseMotionFunc(int x,int y);
}; };
#endif //BOX2D_DEMO_H #endif //BOX2D_DEMO_H

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "Box2dDemo.h" #include "Box2dDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new Box2dDemo(); return new Box2dDemo();
} }
#endif #endif

View File

@@ -1,61 +1,61 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "Box2dDemo.h" #include "Box2dDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "LinearMath/btHashMap.h" #include "LinearMath/btHashMap.h"
class OurValue class OurValue
{ {
int m_uid; int m_uid;
public: public:
OurValue(const btVector3& initialPos) OurValue(const btVector3& initialPos)
:m_position(initialPos) :m_position(initialPos)
{ {
static int gUid=0; static int gUid=0;
m_uid=gUid; m_uid=gUid;
gUid++; gUid++;
} }
btVector3 m_position; btVector3 m_position;
int getUid() const int getUid() const
{ {
return m_uid; return m_uid;
} }
}; };
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
GLDebugDrawer gDebugDrawer; GLDebugDrawer gDebugDrawer;
Box2dDemo ccdDemo; Box2dDemo ccdDemo;
ccdDemo.initPhysics(); ccdDemo.initPhysics();
ccdDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); ccdDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);
#ifdef CHECK_MEMORY_LEAKS #ifdef CHECK_MEMORY_LEAKS
ccdDemo.exitPhysics(); ccdDemo.exitPhysics();
#else #else
return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&ccdDemo); return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&ccdDemo);
#endif #endif
//default glut doesn't return from mainloop //default glut doesn't return from mainloop
return 0; return 0;
} }

View File

@@ -1,207 +1,207 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BspConverter.h" #include "BspConverter.h"
#include "BspLoader.h" #include "BspLoader.h"
#include "LinearMath/btVector3.h" #include "LinearMath/btVector3.h"
#include "LinearMath/btGeometryUtil.h" #include "LinearMath/btGeometryUtil.h"
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
void BspConverter::convertBsp(BspLoader& bspLoader,float scaling) void BspConverter::convertBsp(BspLoader& bspLoader,float scaling)
{ {
{ {
float playstartf[3] = {0,0,100}; float playstartf[3] = {0,0,100};
if (bspLoader.findVectorByName(&playstartf[0],"info_player_start")) if (bspLoader.findVectorByName(&playstartf[0],"info_player_start"))
{ {
printf("found playerstart\n"); printf("found playerstart\n");
} }
else else
{ {
if (bspLoader.findVectorByName(&playstartf[0],"info_player_deathmatch")) if (bspLoader.findVectorByName(&playstartf[0],"info_player_deathmatch"))
{ {
printf("found deatchmatch start\n"); printf("found deatchmatch start\n");
} }
} }
btVector3 playerStart (playstartf[0],playstartf[1],playstartf[2]); btVector3 playerStart (playstartf[0],playstartf[1],playstartf[2]);
playerStart[2] += 20.f; //start a bit higher playerStart[2] += 20.f; //start a bit higher
playerStart *= scaling; playerStart *= scaling;
//progressBegin("Loading bsp"); //progressBegin("Loading bsp");
for (int i=0;i<bspLoader.m_numleafs;i++) 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)) ); printf("Reading bspLeaf %i from total %i (%f procent)\n",i, bspLoader.m_numleafs,(100.f*(float)i/float(bspLoader.m_numleafs)) );
bool isValidBrush = false; bool isValidBrush = false;
BSPLeaf& leaf = bspLoader.m_dleafs[i]; BSPLeaf& leaf = bspLoader.m_dleafs[i];
for (int b=0;b<leaf.numLeafBrushes;b++) for (int b=0;b<leaf.numLeafBrushes;b++)
{ {
btAlignedObjectArray<btVector3> planeEquations; btAlignedObjectArray<btVector3> planeEquations;
int brushid = bspLoader.m_dleafbrushes[leaf.firstLeafBrush+b]; int brushid = bspLoader.m_dleafbrushes[leaf.firstLeafBrush+b];
BSPBrush& brush = bspLoader.m_dbrushes[brushid]; BSPBrush& brush = bspLoader.m_dbrushes[brushid];
if (brush.shaderNum!=-1) if (brush.shaderNum!=-1)
{ {
if (bspLoader.m_dshaders[ brush.shaderNum ].contentFlags & BSPCONTENTS_SOLID) if (bspLoader.m_dshaders[ brush.shaderNum ].contentFlags & BSPCONTENTS_SOLID)
{ {
brush.shaderNum = -1; brush.shaderNum = -1;
for (int p=0;p<brush.numSides;p++) for (int p=0;p<brush.numSides;p++)
{ {
int sideid = brush.firstSide+p; int sideid = brush.firstSide+p;
BSPBrushSide& brushside = bspLoader.m_dbrushsides[sideid]; BSPBrushSide& brushside = bspLoader.m_dbrushsides[sideid];
int planeid = brushside.planeNum; int planeid = brushside.planeNum;
BSPPlane& plane = bspLoader.m_dplanes[planeid]; BSPPlane& plane = bspLoader.m_dplanes[planeid];
btVector3 planeEq; btVector3 planeEq;
planeEq.setValue( planeEq.setValue(
plane.normal[0], plane.normal[0],
plane.normal[1], plane.normal[1],
plane.normal[2]); plane.normal[2]);
planeEq[3] = scaling*-plane.dist; planeEq[3] = scaling*-plane.dist;
planeEquations.push_back(planeEq); planeEquations.push_back(planeEq);
isValidBrush=true; isValidBrush=true;
} }
if (isValidBrush) if (isValidBrush)
{ {
btAlignedObjectArray<btVector3> vertices; btAlignedObjectArray<btVector3> vertices;
btGeometryUtil::getVerticesFromPlaneEquations(planeEquations,vertices); btGeometryUtil::getVerticesFromPlaneEquations(planeEquations,vertices);
bool isEntity = false; bool isEntity = false;
btVector3 entityTarget(0.f,0.f,0.f); btVector3 entityTarget(0.f,0.f,0.f);
addConvexVerticesCollider(vertices,isEntity,entityTarget); addConvexVerticesCollider(vertices,isEntity,entityTarget);
} }
} }
} }
} }
} }
#define USE_ENTITIES #define USE_ENTITIES
#ifdef USE_ENTITIES #ifdef USE_ENTITIES
{ {
int i; int i;
for (i=0;i<bspLoader.m_num_entities;i++) for (i=0;i<bspLoader.m_num_entities;i++)
{ {
const BSPEntity& entity = bspLoader.m_entities[i]; const BSPEntity& entity = bspLoader.m_entities[i];
const char* cl = bspLoader.getValueForKey(&entity,"classname"); const char* cl = bspLoader.getValueForKey(&entity,"classname");
if ( !strcmp( cl, "trigger_push" ) ) { if ( !strcmp( cl, "trigger_push" ) ) {
btVector3 targetLocation(0.f,0.f,0.f); btVector3 targetLocation(0.f,0.f,0.f);
cl = bspLoader.getValueForKey(&entity,"target"); cl = bspLoader.getValueForKey(&entity,"target");
if ( strcmp( cl, "" ) ) { if ( strcmp( cl, "" ) ) {
//its not empty so ... //its not empty so ...
/* /*
//lookup the target position for the jumppad: //lookup the target position for the jumppad:
const BSPEntity* targetentity = bspLoader.getEntityByValue( "targetname" , cl ); const BSPEntity* targetentity = bspLoader.getEntityByValue( "targetname" , cl );
if (targetentity) if (targetentity)
{ {
if (bspLoader.getVectorForKey( targetentity , "origin",&targetLocation[0])) if (bspLoader.getVectorForKey( targetentity , "origin",&targetLocation[0]))
{ {
} }
} }
*/ */
cl = bspLoader.getValueForKey(&entity,"model"); cl = bspLoader.getValueForKey(&entity,"model");
if ( strcmp( cl, "" ) ) { if ( strcmp( cl, "" ) ) {
// add the model as a brush // add the model as a brush
if (cl[0] == '*') if (cl[0] == '*')
{ {
int modelnr = atoi(&cl[1]); int modelnr = atoi(&cl[1]);
if ((modelnr >=0) && (modelnr < bspLoader.m_nummodels)) if ((modelnr >=0) && (modelnr < bspLoader.m_nummodels))
{ {
const BSPModel& model = bspLoader.m_dmodels[modelnr]; const BSPModel& model = bspLoader.m_dmodels[modelnr];
for (int n=0;n<model.numBrushes;n++) for (int n=0;n<model.numBrushes;n++)
{ {
btAlignedObjectArray<btVector3> planeEquations; btAlignedObjectArray<btVector3> planeEquations;
bool isValidBrush = false; bool isValidBrush = false;
//convert brush //convert brush
const BSPBrush& brush = bspLoader.m_dbrushes[model.firstBrush+n]; const BSPBrush& brush = bspLoader.m_dbrushes[model.firstBrush+n];
{ {
for (int p=0;p<brush.numSides;p++) for (int p=0;p<brush.numSides;p++)
{ {
int sideid = brush.firstSide+p; int sideid = brush.firstSide+p;
BSPBrushSide& brushside = bspLoader.m_dbrushsides[sideid]; BSPBrushSide& brushside = bspLoader.m_dbrushsides[sideid];
int planeid = brushside.planeNum; int planeid = brushside.planeNum;
BSPPlane& plane = bspLoader.m_dplanes[planeid]; BSPPlane& plane = bspLoader.m_dplanes[planeid];
btVector3 planeEq; btVector3 planeEq;
planeEq.setValue( planeEq.setValue(
plane.normal[0], plane.normal[0],
plane.normal[1], plane.normal[1],
plane.normal[2]); plane.normal[2]);
planeEq[3] = scaling*-plane.dist; planeEq[3] = scaling*-plane.dist;
planeEquations.push_back(planeEq); planeEquations.push_back(planeEq);
isValidBrush=true; isValidBrush=true;
} }
if (isValidBrush) if (isValidBrush)
{ {
btAlignedObjectArray<btVector3> vertices; btAlignedObjectArray<btVector3> vertices;
btGeometryUtil::getVerticesFromPlaneEquations(planeEquations,vertices); btGeometryUtil::getVerticesFromPlaneEquations(planeEquations,vertices);
bool isEntity=true; bool isEntity=true;
addConvexVerticesCollider(vertices,isEntity,targetLocation); addConvexVerticesCollider(vertices,isEntity,targetLocation);
} }
} }
} }
} }
} }
else else
{ {
printf("unsupported trigger_push model, md3 ?\n"); printf("unsupported trigger_push model, md3 ?\n");
} }
} }
} }
} }
} }
} }
#endif //USE_ENTITIES #endif //USE_ENTITIES
//progressEnd(); //progressEnd();
} }
} }

View File

@@ -1,39 +1,39 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BSP_CONVERTER_H #ifndef BSP_CONVERTER_H
#define BSP_CONVERTER_H #define BSP_CONVERTER_H
class BspLoader; class BspLoader;
#include "LinearMath/btVector3.h" #include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
///BspConverter turns a loaded bsp level into convex parts (vertices) ///BspConverter turns a loaded bsp level into convex parts (vertices)
class BspConverter class BspConverter
{ {
public: public:
void convertBsp(BspLoader& bspLoader,float scaling); void convertBsp(BspLoader& bspLoader,float scaling);
virtual ~BspConverter() virtual ~BspConverter()
{ {
} }
///this callback is called for each brush that succesfully converted into vertices ///this callback is called for each brush that succesfully converted into vertices
virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation) = 0; virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation) = 0;
}; };
#endif //BSP_CONVERTER_H #endif //BSP_CONVERTER_H

View File

@@ -1,321 +1,321 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "LinearMath/btQuickprof.h" #include "LinearMath/btQuickprof.h"
#include "LinearMath/btIDebugDraw.h" #include "LinearMath/btIDebugDraw.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#define QUAKE_BSP_IMPORTING 1 #define QUAKE_BSP_IMPORTING 1
#ifdef QUAKE_BSP_IMPORTING #ifdef QUAKE_BSP_IMPORTING
#include "BspLoader.h" #include "BspLoader.h"
#include "BspConverter.h" #include "BspConverter.h"
#endif //QUAKE_BSP_IMPORTING #endif //QUAKE_BSP_IMPORTING
#include <stdio.h> //printf debugging #include <stdio.h> //printf debugging
#include "BspDemo.h" #include "BspDemo.h"
#include "GL_ShapeDrawer.h" #include "GL_ShapeDrawer.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#define CUBE_HALF_EXTENTS 1 #define CUBE_HALF_EXTENTS 1
#define EXTRA_HEIGHT -20.f #define EXTRA_HEIGHT -20.f
///BspToBulletConverter extends the BspConverter to convert to Bullet datastructures ///BspToBulletConverter extends the BspConverter to convert to Bullet datastructures
class BspToBulletConverter : public BspConverter class BspToBulletConverter : public BspConverter
{ {
BspDemo* m_demoApp; BspDemo* m_demoApp;
public: public:
BspToBulletConverter(BspDemo* demoApp) BspToBulletConverter(BspDemo* demoApp)
:m_demoApp(demoApp) :m_demoApp(demoApp)
{ {
} }
virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation) virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation)
{ {
///perhaps we can do something special with entities (isEntity) ///perhaps we can do something special with entities (isEntity)
///like adding a collision Triggering (as example) ///like adding a collision Triggering (as example)
if (vertices.size() > 0) if (vertices.size() > 0)
{ {
float mass = 0.f; float mass = 0.f;
btTransform startTransform; btTransform startTransform;
//can use a shift //can use a shift
startTransform.setIdentity(); startTransform.setIdentity();
startTransform.setOrigin(btVector3(0,0,-10.f)); startTransform.setOrigin(btVector3(0,0,-10.f));
//this create an internal copy of the vertices //this create an internal copy of the vertices
btCollisionShape* shape = new btConvexHullShape(&(vertices[0].getX()),vertices.size()); btCollisionShape* shape = new btConvexHullShape(&(vertices[0].getX()),vertices.size());
m_demoApp->m_collisionShapes.push_back(shape); m_demoApp->m_collisionShapes.push_back(shape);
//btRigidBody* body = m_demoApp->localCreateRigidBody(mass, startTransform,shape); //btRigidBody* body = m_demoApp->localCreateRigidBody(mass, startTransform,shape);
m_demoApp->localCreateRigidBody(mass, startTransform,shape); m_demoApp->localCreateRigidBody(mass, startTransform,shape);
} }
} }
}; };
//////////////////////////////////// ////////////////////////////////////
BspDemo::~BspDemo() BspDemo::~BspDemo()
{ {
//cleanup in the reverse order of creation/initialization //cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them //remove the rigidbodies from the dynamics world and delete them
int i; int i;
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{ {
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj); btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState()) if (body && body->getMotionState())
{ {
delete body->getMotionState(); delete body->getMotionState();
} }
m_dynamicsWorld->removeCollisionObject( obj ); m_dynamicsWorld->removeCollisionObject( obj );
delete obj; delete obj;
} }
//delete collision shapes //delete collision shapes
for (int j=0;j<m_collisionShapes.size();j++) for (int j=0;j<m_collisionShapes.size();j++)
{ {
btCollisionShape* shape = m_collisionShapes[j]; btCollisionShape* shape = m_collisionShapes[j];
delete shape; delete shape;
} }
//delete dynamics world //delete dynamics world
delete m_dynamicsWorld; delete m_dynamicsWorld;
//delete solver //delete solver
delete m_solver; delete m_solver;
//delete broadphase //delete broadphase
delete m_broadphase; delete m_broadphase;
//delete dispatcher //delete dispatcher
delete m_dispatcher; delete m_dispatcher;
delete m_collisionConfiguration; delete m_collisionConfiguration;
} }
void BspDemo::initPhysics() void BspDemo::initPhysics()
{ {
const char* bspfilename = "BspDemo.bsp"; const char* bspfilename = "BspDemo.bsp";
initPhysics(bspfilename); initPhysics(bspfilename);
} }
void BspDemo::initPhysics(const char* bspfilename) void BspDemo::initPhysics(const char* bspfilename)
{ {
setTexturing(true); setTexturing(true);
setShadows(false); setShadows(false);
m_cameraUp = btVector3(0,0,1); m_cameraUp = btVector3(0,0,1);
m_forwardAxis = 1; m_forwardAxis = 1;
setCameraDistance(22.f); setCameraDistance(22.f);
///Setup a Physics Simulation Environment ///Setup a Physics Simulation Environment
m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_collisionConfiguration = new btDefaultCollisionConfiguration();
// btCollisionShape* groundShape = new btBoxShape(btVector3(50,3,50)); // btCollisionShape* groundShape = new btBoxShape(btVector3(50,3,50));
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
btVector3 worldMin(-1000,-1000,-1000); btVector3 worldMin(-1000,-1000,-1000);
btVector3 worldMax(1000,1000,1000); btVector3 worldMax(1000,1000,1000);
m_broadphase = new btDbvtBroadphase(); m_broadphase = new btDbvtBroadphase();
//m_broadphase = new btAxisSweep3(worldMin,worldMax); //m_broadphase = new btAxisSweep3(worldMin,worldMax);
//btOverlappingPairCache* broadphase = new btSimpleBroadphase(); //btOverlappingPairCache* broadphase = new btSimpleBroadphase();
m_solver = new btSequentialImpulseConstraintSolver(); m_solver = new btSequentialImpulseConstraintSolver();
//ConstraintSolver* solver = new OdeConstraintSolver; //ConstraintSolver* solver = new OdeConstraintSolver;
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
m_dynamicsWorld->setGravity(-m_cameraUp * 10); m_dynamicsWorld->setGravity(-m_cameraUp * 10);
#ifdef QUAKE_BSP_IMPORTING #ifdef QUAKE_BSP_IMPORTING
void* memoryBuffer = 0; void* memoryBuffer = 0;
FILE* file = fopen(bspfilename,"r"); FILE* file = fopen(bspfilename,"r");
if (!file) if (!file)
{ {
//try again other path, //try again other path,
//sight... visual studio leaves the current working directory in the projectfiles folder //sight... visual studio leaves the current working directory in the projectfiles folder
//instead of executable folder. who wants this default behaviour?!? //instead of executable folder. who wants this default behaviour?!?
bspfilename = "../../BspDemo.bsp"; bspfilename = "../../BspDemo.bsp";
file = fopen(bspfilename,"r"); file = fopen(bspfilename,"r");
} }
if (!file) if (!file)
{ {
//try again other path, cmake needs 4 levels deep back... //try again other path, cmake needs 4 levels deep back...
bspfilename = "../../../../BspDemo.bsp"; bspfilename = "../../../../BspDemo.bsp";
file = fopen(bspfilename,"r"); file = fopen(bspfilename,"r");
} }
if (!file) if (!file)
{ {
//try again other path, //try again other path,
//sight... visual studio leaves the current working directory in the projectfiles folder //sight... visual studio leaves the current working directory in the projectfiles folder
//instead of executable folder. who wants this default behaviour?!? //instead of executable folder. who wants this default behaviour?!?
bspfilename = "BspDemo.bsp"; bspfilename = "BspDemo.bsp";
file = fopen(bspfilename,"r"); file = fopen(bspfilename,"r");
} }
if (file) if (file)
{ {
BspLoader bspLoader; BspLoader bspLoader;
int size=0; int size=0;
if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET)) { /* File operations denied? ok, just close and return failure */ if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET)) { /* File operations denied? ok, just close and return failure */
printf("Error: cannot get filesize from %s\n", bspfilename); printf("Error: cannot get filesize from %s\n", bspfilename);
} else } else
{ {
//how to detect file size? //how to detect file size?
memoryBuffer = malloc(size+1); memoryBuffer = malloc(size+1);
fread(memoryBuffer,1,size,file); fread(memoryBuffer,1,size,file);
bspLoader.loadBSPFile( memoryBuffer); bspLoader.loadBSPFile( memoryBuffer);
BspToBulletConverter bsp2bullet(this); BspToBulletConverter bsp2bullet(this);
float bspScaling = 0.1f; float bspScaling = 0.1f;
bsp2bullet.convertBsp(bspLoader,bspScaling); bsp2bullet.convertBsp(bspLoader,bspScaling);
} }
fclose(file); fclose(file);
} }
#endif #endif
clientResetScene(); clientResetScene();
} }
void BspDemo::clientMoveAndDisplay() void BspDemo::clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float dt = getDeltaTimeMicroseconds() * 0.000001f; float dt = getDeltaTimeMicroseconds() * 0.000001f;
m_dynamicsWorld->stepSimulation(dt); m_dynamicsWorld->stepSimulation(dt);
//optional but useful: debug drawing //optional but useful: debug drawing
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
renderme(); renderme();
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
void BspDemo::displayCallback(void) { void BspDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderme(); renderme();
//optional but useful: debug drawing //optional but useful: debug drawing
if (m_dynamicsWorld) if (m_dynamicsWorld)
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
//some code that de-mangles the windows filename passed in as argument //some code that de-mangles the windows filename passed in as argument
char cleaned_filename[512]; char cleaned_filename[512];
char* getLastFileName() char* getLastFileName()
{ {
return cleaned_filename; return cleaned_filename;
} }
char* makeExeToBspFilename(const char* lpCmdLine) char* makeExeToBspFilename(const char* lpCmdLine)
{ {
// We might get a windows-style path on the command line, this can mess up the DOM which expects // We might get a windows-style path on the command line, this can mess up the DOM which expects
// all paths to be URI's. This block of code does some conversion to try and make the input // all paths to be URI's. This block of code does some conversion to try and make the input
// compliant without breaking the ability to accept a properly formatted URI. Right now this only // compliant without breaking the ability to accept a properly formatted URI. Right now this only
// displays the first filename // displays the first filename
const char *in = lpCmdLine; const char *in = lpCmdLine;
char* out = cleaned_filename; char* out = cleaned_filename;
*out = '\0'; *out = '\0';
// If the first character is a ", skip it (filenames with spaces in them are quoted) // If the first character is a ", skip it (filenames with spaces in them are quoted)
if(*in == '\"') if(*in == '\"')
{ {
in++; in++;
} }
int i; int i;
for(i =0; i<512; i++) for(i =0; i<512; i++)
{ {
//if we get '.' we stop as well, unless it's the first character. Then we add .bsp as extension //if we get '.' we stop as well, unless it's the first character. Then we add .bsp as extension
// If we hit a null or a quote, stop copying. This will get just the first filename. // If we hit a null or a quote, stop copying. This will get just the first filename.
if(i && (in[0] == '.') && (in[1] == 'e') && (in[2] == 'x') && (in[3] == 'e')) if(i && (in[0] == '.') && (in[1] == 'e') && (in[2] == 'x') && (in[3] == 'e'))
break; break;
// If we hit a null or a quote, stop copying. This will get just the first filename. // If we hit a null or a quote, stop copying. This will get just the first filename.
if(*in == '\0' || *in == '\"') if(*in == '\0' || *in == '\"')
break; break;
// Copy while swapping backslashes for forward ones // Copy while swapping backslashes for forward ones
if(*in == '\\') if(*in == '\\')
{ {
*out = '/'; *out = '/';
} }
else else
{ {
*out = *in; *out = *in;
} }
in++; in++;
out++; out++;
} }
*(out++) = '.'; *(out++) = '.';
*(out++) = 'b'; *(out++) = 'b';
*(out++) = 's'; *(out++) = 's';
*(out++) = 'p'; *(out++) = 'p';
*(out++) = 0; *(out++) = 0;
return cleaned_filename; return cleaned_filename;
} }

View File

@@ -1,71 +1,71 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BSP_DEMO_H #ifndef BSP_DEMO_H
#define BSP_DEMO_H #define BSP_DEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
///BspDemo shows the convex collision detection, by converting a Quake BSP file into convex objects and allowing interaction with boxes. ///BspDemo shows the convex collision detection, by converting a Quake BSP file into convex objects and allowing interaction with boxes.
class BspDemo : public GlutDemoApplication class BspDemo : public GlutDemoApplication
{ {
public: public:
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
virtual ~BspDemo(); virtual ~BspDemo();
virtual void initPhysics(); virtual void initPhysics();
void initPhysics(const char* bspfilename); void initPhysics(const char* bspfilename);
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
static DemoApplication* Create() static DemoApplication* Create()
{ {
BspDemo* demo = new BspDemo; BspDemo* demo = new BspDemo;
demo->myinit(); demo->myinit();
demo->initPhysics("BspDemo.bsp"); demo->initPhysics("BspDemo.bsp");
return demo; return demo;
} }
}; };
#endif //BSP_DEMO_H #endif //BSP_DEMO_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,295 +1,295 @@
/* /*
=========================================================================== ===========================================================================
Copyright (C) 1999-2005 Id Software, Inc. Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code. This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU bteral Public License as and/or modify it under the terms of the GNU bteral Public License as
published by the Free Software Foundation; either version 2 of the License, published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version. or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be 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 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU bteral Public License for more details. GNU bteral Public License for more details.
You should have received a copy of the GNU bteral Public License You should have received a copy of the GNU bteral Public License
along with Foobar; if not, write to the Free Software along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
=========================================================================== ===========================================================================
*/ */
#ifndef BSP_LOADER_H #ifndef BSP_LOADER_H
#define BSP_LOADER_H #define BSP_LOADER_H
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
#define BSPMAXTOKEN 1024 #define BSPMAXTOKEN 1024
#define BSPMAX_KEY 32 #define BSPMAX_KEY 32
#define BSPMAX_VALUE 1024 #define BSPMAX_VALUE 1024
#define BSPCONTENTS_SOLID 1 #define BSPCONTENTS_SOLID 1
#define BSPCONTENTS_AREAPORTAL 0x8000 #define BSPCONTENTS_AREAPORTAL 0x8000
#define BSPLUMP_ENTITIES 0 #define BSPLUMP_ENTITIES 0
#define BSPLUMP_SHADERS 1 #define BSPLUMP_SHADERS 1
#define BSPLUMP_PLANES 2 #define BSPLUMP_PLANES 2
#define BSPLUMP_NODES 3 #define BSPLUMP_NODES 3
#define BSPLUMP_LEAFS 4 #define BSPLUMP_LEAFS 4
#define BSPLUMP_LEAFSURFACES 5 #define BSPLUMP_LEAFSURFACES 5
#define BSPLUMP_LEAFBRUSHES 6 #define BSPLUMP_LEAFBRUSHES 6
#define LUMP_MODELS 7 #define LUMP_MODELS 7
#define LUMP_BRUSHES 8 #define LUMP_BRUSHES 8
#define LUMP_BRUSHSIDES 9 #define LUMP_BRUSHSIDES 9
#define LUMP_DRAWVERTS 10 #define LUMP_DRAWVERTS 10
#define LUMP_DRAWINDEXES 11 #define LUMP_DRAWINDEXES 11
#define LUMP_SURFACES 13 #define LUMP_SURFACES 13
#define LUMP_LIGHTMAPS 14 #define LUMP_LIGHTMAPS 14
#define LUMP_LIGHTGRID 15 #define LUMP_LIGHTGRID 15
#define LUMP_VISIBILITY 16 #define LUMP_VISIBILITY 16
#define HEADER_LUMPS 17 #define HEADER_LUMPS 17
#define MAX_QPATH 64 #define MAX_QPATH 64
typedef struct { typedef struct {
int fileofs, filelen; int fileofs, filelen;
} BSPLump; } BSPLump;
typedef float BSPVector3[3]; typedef float BSPVector3[3];
typedef struct { typedef struct {
int ident; int ident;
int version; int version;
BSPLump lumps[HEADER_LUMPS]; BSPLump lumps[HEADER_LUMPS];
} BSPHeader; } BSPHeader;
typedef struct { typedef struct {
float mins[3], maxs[3]; float mins[3], maxs[3];
int firstSurface, numSurfaces; int firstSurface, numSurfaces;
int firstBrush, numBrushes; int firstBrush, numBrushes;
} BSPModel; } BSPModel;
typedef struct { typedef struct {
char shader[MAX_QPATH]; char shader[MAX_QPATH];
int surfaceFlags; int surfaceFlags;
int contentFlags; int contentFlags;
} BSPShader; } BSPShader;
typedef struct { typedef struct {
float normal[3]; float normal[3];
float dist; float dist;
} BSPPlane; } BSPPlane;
typedef struct { typedef struct {
int planeNum; int planeNum;
int children[2]; int children[2];
int mins[3]; int mins[3];
int maxs[3]; int maxs[3];
} BSPNode; } BSPNode;
typedef struct { typedef struct {
int cluster; int cluster;
int area; int area;
int mins[3]; int mins[3];
int maxs[3]; int maxs[3];
int firstLeafSurface; int firstLeafSurface;
int numLeafSurfaces; int numLeafSurfaces;
int firstLeafBrush; int firstLeafBrush;
int numLeafBrushes; int numLeafBrushes;
} BSPLeaf; } BSPLeaf;
typedef struct { typedef struct {
int planeNum; int planeNum;
int shaderNum; int shaderNum;
} BSPBrushSide; } BSPBrushSide;
typedef struct { typedef struct {
int firstSide; int firstSide;
int numSides; int numSides;
int shaderNum; int shaderNum;
} BSPBrush; } BSPBrush;
typedef struct BSPPair { typedef struct BSPPair {
struct BSPPair *next; struct BSPPair *next;
char *key; char *key;
char *value; char *value;
} BSPKeyValuePair; } BSPKeyValuePair;
typedef struct { typedef struct {
BSPVector3 origin; BSPVector3 origin;
struct bspbrush_s *brushes; struct bspbrush_s *brushes;
struct parseMesh_s *patches; struct parseMesh_s *patches;
int firstDrawSurf; int firstDrawSurf;
BSPKeyValuePair *epairs; BSPKeyValuePair *epairs;
} BSPEntity; } BSPEntity;
typedef enum { typedef enum {
MST_BAD, MST_BAD,
MST_PLANAR, MST_PLANAR,
MST_PATCH, MST_PATCH,
MST_TRIANGLE_SOUP, MST_TRIANGLE_SOUP,
MST_FLARE MST_FLARE
} BSPMapSurface; } BSPMapSurface;
typedef struct { typedef struct {
int shaderNum; int shaderNum;
int fogNum; int fogNum;
int surfaceType; int surfaceType;
int firstVert; int firstVert;
int numVerts; int numVerts;
int firstIndex; int firstIndex;
int numIndexes; int numIndexes;
int lightmapNum; int lightmapNum;
int lightmapX, lightmapY; int lightmapX, lightmapY;
int lightmapWidth, lightmapHeight; int lightmapWidth, lightmapHeight;
BSPVector3 lightmapOrigin; BSPVector3 lightmapOrigin;
BSPVector3 lightmapVecs[3]; BSPVector3 lightmapVecs[3];
int patchWidth; int patchWidth;
int patchHeight; int patchHeight;
} BSPSurface; } BSPSurface;
///GPL code from IdSofware to parse a Quake 3 BSP file ///GPL code from IdSofware to parse a Quake 3 BSP file
///check that your platform define __BIG_ENDIAN__ correctly (in BspLoader.cpp) ///check that your platform define __BIG_ENDIAN__ correctly (in BspLoader.cpp)
class BspLoader class BspLoader
{ {
int m_Endianness; int m_Endianness;
public: public:
BspLoader(); BspLoader();
bool loadBSPFile( void* memoryBuffer); bool loadBSPFile( void* memoryBuffer);
const char* getValueForKey( const BSPEntity *ent, const char *key ) const; const char* getValueForKey( const BSPEntity *ent, const char *key ) const;
bool getVectorForKey( const BSPEntity *ent, const char *key, BSPVector3 vec ); bool getVectorForKey( const BSPEntity *ent, const char *key, BSPVector3 vec );
float getFloatForKey( const BSPEntity *ent, const char *key ); float getFloatForKey( const BSPEntity *ent, const char *key );
void parseEntities( void ); void parseEntities( void );
bool findVectorByName(float* outvec,const char* name); bool findVectorByName(float* outvec,const char* name);
const BSPEntity * getEntityByValue( const char* name, const char* value); const BSPEntity * getEntityByValue( const char* name, const char* value);
protected: protected:
void parseFromMemory (char *buffer, int size); void parseFromMemory (char *buffer, int size);
bool isEndOfScript (bool crossline); bool isEndOfScript (bool crossline);
bool getToken (bool crossline); bool getToken (bool crossline);
char *copystring(const char *s); char *copystring(const char *s);
void stripTrailing( char *e ); void stripTrailing( char *e );
BSPKeyValuePair * parseEpair( void ); BSPKeyValuePair * parseEpair( void );
bool parseEntity( void ); bool parseEntity( void );
short isLittleShort (short l); short isLittleShort (short l);
int isLittleLong (int l); int isLittleLong (int l);
float isLittleFloat (float l); float isLittleFloat (float l);
int isBigLong (int l); int isBigLong (int l);
short isBigShort (short l); short isBigShort (short l);
float isBigFloat (float l); float isBigFloat (float l);
void swapBlock( int *block, int sizeOfBlock ); void swapBlock( int *block, int sizeOfBlock );
int copyLump( BSPHeader *header, int lump, void *dest, int size ); int copyLump( BSPHeader *header, int lump, void *dest, int size );
void swapBSPFile( void ); void swapBSPFile( void );
public: //easier for conversion public: //easier for conversion
int m_num_entities; int m_num_entities;
btAlignedObjectArray<BSPEntity> m_entities; btAlignedObjectArray<BSPEntity> m_entities;
int m_nummodels; int m_nummodels;
btAlignedObjectArray<BSPModel> m_dmodels; btAlignedObjectArray<BSPModel> m_dmodels;
int m_numShaders; int m_numShaders;
btAlignedObjectArray<BSPShader> m_dshaders; btAlignedObjectArray<BSPShader> m_dshaders;
int m_entdatasize; int m_entdatasize;
btAlignedObjectArray<char> m_dentdata; btAlignedObjectArray<char> m_dentdata;
int m_numleafs; int m_numleafs;
btAlignedObjectArray<BSPLeaf> m_dleafs; btAlignedObjectArray<BSPLeaf> m_dleafs;
int m_numplanes; int m_numplanes;
btAlignedObjectArray<BSPPlane> m_dplanes; btAlignedObjectArray<BSPPlane> m_dplanes;
int m_numnodes; int m_numnodes;
btAlignedObjectArray<BSPNode> m_dnodes; btAlignedObjectArray<BSPNode> m_dnodes;
int m_numleafsurfaces; int m_numleafsurfaces;
btAlignedObjectArray<int> m_dleafsurfaces; btAlignedObjectArray<int> m_dleafsurfaces;
int m_numleafbrushes; int m_numleafbrushes;
btAlignedObjectArray<int> m_dleafbrushes; btAlignedObjectArray<int> m_dleafbrushes;
int m_numbrushes; int m_numbrushes;
btAlignedObjectArray<BSPBrush> m_dbrushes; btAlignedObjectArray<BSPBrush> m_dbrushes;
int m_numbrushsides; int m_numbrushsides;
btAlignedObjectArray<BSPBrushSide> m_dbrushsides; btAlignedObjectArray<BSPBrushSide> m_dbrushsides;
int m_numLightBytes; int m_numLightBytes;
btAlignedObjectArray<unsigned char> m_lightBytes; btAlignedObjectArray<unsigned char> m_lightBytes;
int m_numGridPoints; int m_numGridPoints;
btAlignedObjectArray<unsigned char> m_gridData; btAlignedObjectArray<unsigned char> m_gridData;
int m_numVisBytes; int m_numVisBytes;
btAlignedObjectArray<unsigned char> m_visBytes; btAlignedObjectArray<unsigned char> m_visBytes;
int m_numDrawIndexes; int m_numDrawIndexes;
btAlignedObjectArray<int> m_drawIndexes; btAlignedObjectArray<int> m_drawIndexes;
int m_numDrawSurfaces; int m_numDrawSurfaces;
btAlignedObjectArray<BSPSurface> m_drawSurfaces; btAlignedObjectArray<BSPSurface> m_drawSurfaces;
enum enum
{ {
BSP_LITTLE_ENDIAN = 0, BSP_LITTLE_ENDIAN = 0,
BSP_BIG_ENDIAN = 1 BSP_BIG_ENDIAN = 1
}; };
//returns machines big endian / little endian //returns machines big endian / little endian
// //
int getMachineEndianness(); int getMachineEndianness();
inline int machineEndianness() inline int machineEndianness()
{ {
return m_Endianness; return m_Endianness;
} }
}; };
#endif //BSP_LOADER_H #endif //BSP_LOADER_H

View File

@@ -1,60 +1,60 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppBspPhysicsDemo ADD_EXECUTABLE(AppBspPhysicsDemo
main.cpp main.cpp
BspDemo.cpp BspDemo.cpp
BspLoader.cpp BspLoader.cpp
BspConverter.cpp BspConverter.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppBspPhysicsDemo TARGET AppBspPhysicsDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppBspPhysicsDemo TARGET AppBspPhysicsDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppBspPhysicsDemo TARGET AppBspPhysicsDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/BspDemo.bsp ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/BspDemo.bsp ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppBspPhysicsDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppBspPhysicsDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppBspPhysicsDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppBspPhysicsDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppBspPhysicsDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppBspPhysicsDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,57 +1,57 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppCcdPhysicsDemo ADD_EXECUTABLE(AppCcdPhysicsDemo
main.cpp main.cpp
CcdPhysicsDemo.cpp CcdPhysicsDemo.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppCcdPhysicsDemo ADD_EXECUTABLE(AppCcdPhysicsDemo
main.cpp main.cpp
CcdPhysicsDemo.cpp CcdPhysicsDemo.cpp
) )
ENDIF() ENDIF()
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCcdPhysicsDemo TARGET AppCcdPhysicsDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCcdPhysicsDemo TARGET AppCcdPhysicsDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppCcdPhysicsDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppCcdPhysicsDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppCcdPhysicsDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppCcdPhysicsDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppCcdPhysicsDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppCcdPhysicsDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,83 +1,83 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CCD_PHYSICS_DEMO_H #ifndef CCD_PHYSICS_DEMO_H
#define CCD_PHYSICS_DEMO_H #define CCD_PHYSICS_DEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
///CcdPhysicsDemo shows basic stacking using Bullet physics, and allows toggle of Ccd (using key '1') ///CcdPhysicsDemo shows basic stacking using Bullet physics, and allows toggle of Ccd (using key '1')
class CcdPhysicsDemo : public GlutDemoApplication class CcdPhysicsDemo : public GlutDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
#ifdef USE_PARALLEL_DISPATCHER #ifdef USE_PARALLEL_DISPATCHER
#ifdef WIN32 #ifdef WIN32
class Win32ThreadSupport* m_threadSupportCollision; class Win32ThreadSupport* m_threadSupportCollision;
class Win32ThreadSupport* m_threadSupportSolver; class Win32ThreadSupport* m_threadSupportSolver;
#endif #endif
#endif #endif
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btCollisionAlgorithmCreateFunc* m_boxBoxCF; btCollisionAlgorithmCreateFunc* m_boxBoxCF;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
public: public:
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual ~CcdPhysicsDemo() virtual ~CcdPhysicsDemo()
{ {
exitPhysics(); exitPhysics();
} }
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
void createStack( btCollisionShape* boxShape, float halfCubeSize, int size, float zPos ); void createStack( btCollisionShape* boxShape, float halfCubeSize, int size, float zPos );
static DemoApplication* Create() static DemoApplication* Create()
{ {
CcdPhysicsDemo* demo = new CcdPhysicsDemo; CcdPhysicsDemo* demo = new CcdPhysicsDemo;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
#endif //CCD_PHYSICS_DEMO_H #endif //CCD_PHYSICS_DEMO_H

View File

@@ -1,75 +1,75 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
SET(CharacterDemo_SRCS SET(CharacterDemo_SRCS
DynamicCharacterController.cpp DynamicCharacterController.cpp
DynamicCharacterController.h DynamicCharacterController.h
CharacterDemo.cpp CharacterDemo.cpp
CharacterDemo.h CharacterDemo.h
../BspDemo/BspConverter.cpp ../BspDemo/BspConverter.cpp
../BspDemo/BspConverter.h ../BspDemo/BspConverter.h
../BspDemo/BspLoader.cpp ../BspDemo/BspLoader.cpp
../BspDemo/BspLoader.h ../BspDemo/BspLoader.h
main.cpp main.cpp
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppCharacterDemo ADD_EXECUTABLE(AppCharacterDemo
${CharacterDemo_SRCS} ${CharacterDemo_SRCS}
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppCharacterDemo ADD_EXECUTABLE(AppCharacterDemo
${CharacterDemo_SRCS} ${CharacterDemo_SRCS}
) )
ENDIF() ENDIF()
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCharacterDemo TARGET AppCharacterDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCharacterDemo TARGET AppCharacterDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCharacterDemo TARGET AppCharacterDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/BspDemo.bsp ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/BspDemo.bsp ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppCharacterDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppCharacterDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppCharacterDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppCharacterDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppCharacterDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppCharacterDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

File diff suppressed because it is too large Load Diff

View File

@@ -1,153 +1,153 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CHARACTER_DEMO_H #ifndef CHARACTER_DEMO_H
#define CHARACTER_DEMO_H #define CHARACTER_DEMO_H
///DYNAMIC_CHARACTER_CONTROLLER is not fully implemented yet at the moment ///DYNAMIC_CHARACTER_CONTROLLER is not fully implemented yet at the moment
//#define DYNAMIC_CHARACTER_CONTROLLER 1 //#define DYNAMIC_CHARACTER_CONTROLLER 1
#include "BulletCollision/CollisionShapes/btConvexHullShape.h" #include "BulletCollision/CollisionShapes/btConvexHullShape.h"
class btCharacterControllerInterface; class btCharacterControllerInterface;
class btDynamicCharacterController; class btDynamicCharacterController;
class btKinematicCharacterController; class btKinematicCharacterController;
class btCollisionShape; class btCollisionShape;
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
///CharacterDemo shows how to setup and use the built-in raycast vehicle ///CharacterDemo shows how to setup and use the built-in raycast vehicle
class CharacterDemo : public GlutDemoApplication class CharacterDemo : public GlutDemoApplication
{ {
public: public:
#ifdef DYNAMIC_CHARACTER_CONTROLLER #ifdef DYNAMIC_CHARACTER_CONTROLLER
btCharacterControllerInterface* m_character; btCharacterControllerInterface* m_character;
#else #else
btKinematicCharacterController* m_character; btKinematicCharacterController* m_character;
class btPairCachingGhostObject* m_ghostObject; class btPairCachingGhostObject* m_ghostObject;
#endif #endif
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
class btBroadphaseInterface* m_overlappingPairCache; class btBroadphaseInterface* m_overlappingPairCache;
class btCollisionDispatcher* m_dispatcher; class btCollisionDispatcher* m_dispatcher;
class btConstraintSolver* m_constraintSolver; class btConstraintSolver* m_constraintSolver;
class btDefaultCollisionConfiguration* m_collisionConfiguration; class btDefaultCollisionConfiguration* m_collisionConfiguration;
class btTriangleIndexVertexArray* m_indexVertexArrays; class btTriangleIndexVertexArray* m_indexVertexArrays;
btVector3* m_vertices; btVector3* m_vertices;
void debugDrawContacts(); void debugDrawContacts();
float m_cameraHeight; float m_cameraHeight;
float m_minCameraDistance; float m_minCameraDistance;
float m_maxCameraDistance; float m_maxCameraDistance;
CharacterDemo(); CharacterDemo();
virtual ~CharacterDemo(); virtual ~CharacterDemo();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void clientResetScene(); virtual void clientResetScene();
virtual void displayCallback(); virtual void displayCallback();
///a very basic camera following the character ///a very basic camera following the character
virtual void updateCamera(); virtual void updateCamera();
virtual void specialKeyboard(int key, int x, int y); virtual void specialKeyboard(int key, int x, int y);
virtual void specialKeyboardUp(int key, int x, int y); virtual void specialKeyboardUp(int key, int x, int y);
void renderme(); void renderme();
void initPhysics(); void initPhysics();
static DemoApplication* Create() static DemoApplication* Create()
{ {
CharacterDemo* demo = new CharacterDemo(); CharacterDemo* demo = new CharacterDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
#define QUAKE_BSP_IMPORTING 1 #define QUAKE_BSP_IMPORTING 1
#ifdef QUAKE_BSP_IMPORTING #ifdef QUAKE_BSP_IMPORTING
#include "../BspDemo/BspLoader.h" #include "../BspDemo/BspLoader.h"
#include "../BspDemo/BspConverter.h" #include "../BspDemo/BspConverter.h"
class BspToBulletConverter : public BspConverter class BspToBulletConverter : public BspConverter
{ {
CharacterDemo* m_demoApp; CharacterDemo* m_demoApp;
public: public:
BspToBulletConverter(CharacterDemo* demoApp) BspToBulletConverter(CharacterDemo* demoApp)
:m_demoApp(demoApp) :m_demoApp(demoApp)
{ {
} }
virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation) virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation)
{ {
///perhaps we can do something special with entities (isEntity) ///perhaps we can do something special with entities (isEntity)
///like adding a collision Triggering (as example) ///like adding a collision Triggering (as example)
if (vertices.size() > 0) if (vertices.size() > 0)
{ {
float mass = 0.f; float mass = 0.f;
btTransform startTransform; btTransform startTransform;
//can use a shift //can use a shift
startTransform.setIdentity(); startTransform.setIdentity();
startTransform.setOrigin(btVector3(0,-10.0f,0.0f)); startTransform.setOrigin(btVector3(0,-10.0f,0.0f));
//this create an internal copy of the vertices //this create an internal copy of the vertices
for (int i = 0; i < vertices.size(); i++) for (int i = 0; i < vertices.size(); i++)
{ {
vertices[i] *= btScalar(0.5); vertices[i] *= btScalar(0.5);
float t = vertices[i].getZ() * btScalar(0.75); float t = vertices[i].getZ() * btScalar(0.75);
vertices[i].setZ(-vertices[i].getY()); vertices[i].setZ(-vertices[i].getY());
vertices[i].setY(t); vertices[i].setY(t);
} }
btCollisionShape* shape = new btConvexHullShape(&(vertices[0].getX()),vertices.size()); btCollisionShape* shape = new btConvexHullShape(&(vertices[0].getX()),vertices.size());
m_demoApp->m_collisionShapes.push_back(shape); m_demoApp->m_collisionShapes.push_back(shape);
//btRigidBody* body = m_demoApp->localCreateRigidBody(mass, startTransform,shape); //btRigidBody* body = m_demoApp->localCreateRigidBody(mass, startTransform,shape);
m_demoApp->localCreateRigidBody(mass, startTransform,shape); m_demoApp->localCreateRigidBody(mass, startTransform,shape);
} }
} }
}; };
#endif //QUAKE_BSP_IMPORTING #endif //QUAKE_BSP_IMPORTING
#endif //CHARACTER_DEMO_H #endif //CHARACTER_DEMO_H

View File

@@ -1,204 +1,204 @@
#include "BulletCollision/CollisionShapes/btMultiSphereShape.h" #include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
#include "BulletDynamics/Dynamics/btRigidBody.h" #include "BulletDynamics/Dynamics/btRigidBody.h"
#include "BulletCollision/CollisionDispatch/btCollisionWorld.h" #include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
#include "LinearMath/btDefaultMotionState.h" #include "LinearMath/btDefaultMotionState.h"
#include "DynamicCharacterController.h" #include "DynamicCharacterController.h"
DynamicCharacterController::DynamicCharacterController () DynamicCharacterController::DynamicCharacterController ()
{ {
m_rayLambda[0] = 1.0; m_rayLambda[0] = 1.0;
m_rayLambda[1] = 1.0; m_rayLambda[1] = 1.0;
m_halfHeight = 1.0; m_halfHeight = 1.0;
m_turnAngle = 0.0; m_turnAngle = 0.0;
m_maxLinearVelocity = 10.0; m_maxLinearVelocity = 10.0;
m_walkVelocity = 8.0; // meters/sec m_walkVelocity = 8.0; // meters/sec
m_turnVelocity = 1.0; // radians/sec m_turnVelocity = 1.0; // radians/sec
m_shape = NULL; m_shape = NULL;
m_rigidBody = NULL; m_rigidBody = NULL;
} }
DynamicCharacterController::~DynamicCharacterController () DynamicCharacterController::~DynamicCharacterController ()
{ {
} }
void DynamicCharacterController::setup (btScalar height, btScalar width, btScalar stepHeight) void DynamicCharacterController::setup (btScalar height, btScalar width, btScalar stepHeight)
{ {
btVector3 spherePositions[2]; btVector3 spherePositions[2];
btScalar sphereRadii[2]; btScalar sphereRadii[2];
sphereRadii[0] = width; sphereRadii[0] = width;
sphereRadii[1] = width; sphereRadii[1] = width;
spherePositions[0] = btVector3 (0.0, (height/btScalar(2.0) - width), 0.0); spherePositions[0] = btVector3 (0.0, (height/btScalar(2.0) - width), 0.0);
spherePositions[1] = btVector3 (0.0, (-height/btScalar(2.0) + width), 0.0); spherePositions[1] = btVector3 (0.0, (-height/btScalar(2.0) + width), 0.0);
m_halfHeight = height/btScalar(2.0); m_halfHeight = height/btScalar(2.0);
m_shape = new btMultiSphereShape (&spherePositions[0], &sphereRadii[0], 2); m_shape = new btMultiSphereShape (&spherePositions[0], &sphereRadii[0], 2);
btTransform startTransform; btTransform startTransform;
startTransform.setIdentity (); startTransform.setIdentity ();
startTransform.setOrigin (btVector3(0.0, 2.0, 0.0)); startTransform.setOrigin (btVector3(0.0, 2.0, 0.0));
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo cInfo(1.0, myMotionState, m_shape); btRigidBody::btRigidBodyConstructionInfo cInfo(1.0, myMotionState, m_shape);
m_rigidBody = new btRigidBody(cInfo); m_rigidBody = new btRigidBody(cInfo);
// kinematic vs. static doesn't work // kinematic vs. static doesn't work
//m_rigidBody->setCollisionFlags( m_rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); //m_rigidBody->setCollisionFlags( m_rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
m_rigidBody->setSleepingThresholds (0.0, 0.0); m_rigidBody->setSleepingThresholds (0.0, 0.0);
m_rigidBody->setAngularFactor (0.0); m_rigidBody->setAngularFactor (0.0);
} }
void DynamicCharacterController::destroy () void DynamicCharacterController::destroy ()
{ {
if (m_shape) if (m_shape)
{ {
delete m_shape; delete m_shape;
} }
if (m_rigidBody) if (m_rigidBody)
{ {
delete m_rigidBody; delete m_rigidBody;
m_rigidBody = 0; m_rigidBody = 0;
} }
} }
btCollisionObject* DynamicCharacterController::getCollisionObject () btCollisionObject* DynamicCharacterController::getCollisionObject ()
{ {
return m_rigidBody; return m_rigidBody;
} }
void DynamicCharacterController::preStep (const btCollisionWorld* collisionWorld) void DynamicCharacterController::preStep (const btCollisionWorld* collisionWorld)
{ {
btTransform xform; btTransform xform;
m_rigidBody->getMotionState()->getWorldTransform (xform); m_rigidBody->getMotionState()->getWorldTransform (xform);
btVector3 down = -xform.getBasis()[1]; btVector3 down = -xform.getBasis()[1];
btVector3 forward = xform.getBasis()[2]; btVector3 forward = xform.getBasis()[2];
down.normalize (); down.normalize ();
forward.normalize(); forward.normalize();
m_raySource[0] = xform.getOrigin(); m_raySource[0] = xform.getOrigin();
m_raySource[1] = xform.getOrigin(); m_raySource[1] = xform.getOrigin();
m_rayTarget[0] = m_raySource[0] + down * m_halfHeight * btScalar(1.1); m_rayTarget[0] = m_raySource[0] + down * m_halfHeight * btScalar(1.1);
m_rayTarget[1] = m_raySource[1] + forward * m_halfHeight * btScalar(1.1); m_rayTarget[1] = m_raySource[1] + forward * m_halfHeight * btScalar(1.1);
class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback
{ {
public: public:
ClosestNotMe (btRigidBody* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)) ClosestNotMe (btRigidBody* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
{ {
m_me = me; m_me = me;
} }
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace) virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
{ {
if (rayResult.m_collisionObject == m_me) if (rayResult.m_collisionObject == m_me)
return 1.0; return 1.0;
return ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace return ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace
); );
} }
protected: protected:
btRigidBody* m_me; btRigidBody* m_me;
}; };
ClosestNotMe rayCallback(m_rigidBody); ClosestNotMe rayCallback(m_rigidBody);
int i = 0; int i = 0;
for (i = 0; i < 2; i++) for (i = 0; i < 2; i++)
{ {
rayCallback.m_closestHitFraction = 1.0; rayCallback.m_closestHitFraction = 1.0;
collisionWorld->rayTest (m_raySource[i], m_rayTarget[i], rayCallback); collisionWorld->rayTest (m_raySource[i], m_rayTarget[i], rayCallback);
if (rayCallback.hasHit()) if (rayCallback.hasHit())
{ {
m_rayLambda[i] = rayCallback.m_closestHitFraction; m_rayLambda[i] = rayCallback.m_closestHitFraction;
} else { } else {
m_rayLambda[i] = 1.0; m_rayLambda[i] = 1.0;
} }
} }
} }
void DynamicCharacterController::playerStep (const btCollisionWorld* dynaWorld,btScalar dt, void DynamicCharacterController::playerStep (const btCollisionWorld* dynaWorld,btScalar dt,
int forward, int forward,
int backward, int backward,
int left, int left,
int right, int right,
int jump) int jump)
{ {
btTransform xform; btTransform xform;
m_rigidBody->getMotionState()->getWorldTransform (xform); m_rigidBody->getMotionState()->getWorldTransform (xform);
/* Handle turning */ /* Handle turning */
if (left) if (left)
m_turnAngle -= dt * m_turnVelocity; m_turnAngle -= dt * m_turnVelocity;
if (right) if (right)
m_turnAngle += dt * m_turnVelocity; m_turnAngle += dt * m_turnVelocity;
xform.setRotation (btQuaternion (btVector3(0.0, 1.0, 0.0), m_turnAngle)); xform.setRotation (btQuaternion (btVector3(0.0, 1.0, 0.0), m_turnAngle));
btVector3 linearVelocity = m_rigidBody->getLinearVelocity(); btVector3 linearVelocity = m_rigidBody->getLinearVelocity();
btScalar speed = m_rigidBody->getLinearVelocity().length(); btScalar speed = m_rigidBody->getLinearVelocity().length();
btVector3 forwardDir = xform.getBasis()[2]; btVector3 forwardDir = xform.getBasis()[2];
forwardDir.normalize (); forwardDir.normalize ();
btVector3 walkDirection = btVector3(0.0, 0.0, 0.0); btVector3 walkDirection = btVector3(0.0, 0.0, 0.0);
btScalar walkSpeed = m_walkVelocity * dt; btScalar walkSpeed = m_walkVelocity * dt;
if (forward) if (forward)
walkDirection += forwardDir; walkDirection += forwardDir;
if (backward) if (backward)
walkDirection -= forwardDir; walkDirection -= forwardDir;
if (!forward && !backward && onGround()) if (!forward && !backward && onGround())
{ {
/* Dampen when on the ground and not being moved by the player */ /* Dampen when on the ground and not being moved by the player */
linearVelocity *= btScalar(0.2); linearVelocity *= btScalar(0.2);
m_rigidBody->setLinearVelocity (linearVelocity); m_rigidBody->setLinearVelocity (linearVelocity);
} else { } else {
if (speed < m_maxLinearVelocity) if (speed < m_maxLinearVelocity)
{ {
btVector3 velocity = linearVelocity + walkDirection * walkSpeed; btVector3 velocity = linearVelocity + walkDirection * walkSpeed;
m_rigidBody->setLinearVelocity (velocity); m_rigidBody->setLinearVelocity (velocity);
} }
} }
m_rigidBody->getMotionState()->setWorldTransform (xform); m_rigidBody->getMotionState()->setWorldTransform (xform);
m_rigidBody->setCenterOfMassTransform (xform); m_rigidBody->setCenterOfMassTransform (xform);
} }
bool DynamicCharacterController::canJump () const bool DynamicCharacterController::canJump () const
{ {
return onGround(); return onGround();
} }
void DynamicCharacterController::jump () void DynamicCharacterController::jump ()
{ {
if (!canJump()) if (!canJump())
return; return;
btTransform xform; btTransform xform;
m_rigidBody->getMotionState()->getWorldTransform (xform); m_rigidBody->getMotionState()->getWorldTransform (xform);
btVector3 up = xform.getBasis()[1]; btVector3 up = xform.getBasis()[1];
up.normalize (); up.normalize ();
btScalar magnitude = (btScalar(1.0)/m_rigidBody->getInvMass()) * btScalar(8.0); btScalar magnitude = (btScalar(1.0)/m_rigidBody->getInvMass()) * btScalar(8.0);
m_rigidBody->applyCentralImpulse (up * magnitude); m_rigidBody->applyCentralImpulse (up * magnitude);
} }
bool DynamicCharacterController::onGround () const bool DynamicCharacterController::onGround () const
{ {
return m_rayLambda[0] < btScalar(1.0); return m_rayLambda[0] < btScalar(1.0);
} }
void DynamicCharacterController::reset () void DynamicCharacterController::reset ()
{ {
} }
void DynamicCharacterController::warp (const btVector3& origin) void DynamicCharacterController::warp (const btVector3& origin)
{ {
} }
void DynamicCharacterController::registerPairCacheAndDispatcher (btOverlappingPairCache* pairCache, btCollisionDispatcher* dispatcher) void DynamicCharacterController::registerPairCacheAndDispatcher (btOverlappingPairCache* pairCache, btCollisionDispatcher* dispatcher)
{ {
} }

View File

@@ -1,55 +1,55 @@
#ifndef CHARACTER_CONTROLLER_H #ifndef CHARACTER_CONTROLLER_H
#define CHARACTER_CONTROLLER_H #define CHARACTER_CONTROLLER_H
#include "LinearMath/btVector3.h" #include "LinearMath/btVector3.h"
#include "BulletDynamics/Character/btCharacterControllerInterface.h" #include "BulletDynamics/Character/btCharacterControllerInterface.h"
class btCollisionShape; class btCollisionShape;
class btRigidBody; class btRigidBody;
class btCollisionWorld; class btCollisionWorld;
///DynamicCharacterController is obsolete/unsupported at the moment ///DynamicCharacterController is obsolete/unsupported at the moment
class DynamicCharacterController : public btCharacterControllerInterface class DynamicCharacterController : public btCharacterControllerInterface
{ {
protected: protected:
btScalar m_halfHeight; btScalar m_halfHeight;
btCollisionShape* m_shape; btCollisionShape* m_shape;
btRigidBody* m_rigidBody; btRigidBody* m_rigidBody;
btVector3 m_raySource[2]; btVector3 m_raySource[2];
btVector3 m_rayTarget[2]; btVector3 m_rayTarget[2];
btScalar m_rayLambda[2]; btScalar m_rayLambda[2];
btVector3 m_rayNormal[2]; btVector3 m_rayNormal[2];
btScalar m_turnAngle; btScalar m_turnAngle;
btScalar m_maxLinearVelocity; btScalar m_maxLinearVelocity;
btScalar m_walkVelocity; btScalar m_walkVelocity;
btScalar m_turnVelocity; btScalar m_turnVelocity;
public: public:
DynamicCharacterController (); DynamicCharacterController ();
~DynamicCharacterController (); ~DynamicCharacterController ();
void setup (btScalar height = 2.0, btScalar width = 0.25, btScalar stepHeight = 0.25); void setup (btScalar height = 2.0, btScalar width = 0.25, btScalar stepHeight = 0.25);
void destroy (); void destroy ();
virtual void reset (); virtual void reset ();
virtual void warp (const btVector3& origin); virtual void warp (const btVector3& origin);
virtual void registerPairCacheAndDispatcher (btOverlappingPairCache* pairCache, btCollisionDispatcher* dispatcher); virtual void registerPairCacheAndDispatcher (btOverlappingPairCache* pairCache, btCollisionDispatcher* dispatcher);
btCollisionObject* getCollisionObject (); btCollisionObject* getCollisionObject ();
void preStep (const btCollisionWorld* collisionWorld); void preStep (const btCollisionWorld* collisionWorld);
void playerStep (const btCollisionWorld* collisionWorld,btScalar dt, void playerStep (const btCollisionWorld* collisionWorld,btScalar dt,
int forward, int forward,
int backward, int backward,
int left, int left,
int right, int right,
int jump); int jump);
bool canJump () const; bool canJump () const;
void jump (); void jump ();
bool onGround () const; bool onGround () const;
}; };
#endif #endif

View File

@@ -1,36 +1,36 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppCollisionDemo ADD_EXECUTABLE(AppCollisionDemo
CollisionDemo.cpp CollisionDemo.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppCollisionDemo ADD_EXECUTABLE(AppCollisionDemo
CollisionDemo.cpp CollisionDemo.cpp
) )
ENDIF() ENDIF()
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppCollisionDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppCollisionDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppCollisionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppCollisionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppCollisionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppCollisionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,34 +1,34 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef COLLISION_DEMO_H #ifndef COLLISION_DEMO_H
#define COLLISION_DEMO_H #define COLLISION_DEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
///CollisionDemo shows the low-level direct access to GJK ///CollisionDemo shows the low-level direct access to GJK
class CollisionDemo : public GlutDemoApplication class CollisionDemo : public GlutDemoApplication
{ {
public: public:
void initPhysics(); void initPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
}; };
#endif //COLLISION_DEMO_H #endif //COLLISION_DEMO_H

View File

@@ -1,77 +1,77 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
IF (USE_GLUT) IF (USE_GLUT)
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppCollisionInterfaceDemo ADD_EXECUTABLE(AppCollisionInterfaceDemo
CollisionInterfaceDemo.cpp CollisionInterfaceDemo.cpp
CollisionInterfaceDemo.h CollisionInterfaceDemo.h
main.cpp main.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppCollisionInterfaceDemo ADD_EXECUTABLE(AppCollisionInterfaceDemo
CollisionInterfaceDemo.cpp CollisionInterfaceDemo.cpp
CollisionInterfaceDemo.h CollisionInterfaceDemo.h
main.cpp main.cpp
) )
ENDIF() ENDIF()
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCollisionInterfaceDemo TARGET AppCollisionInterfaceDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppCollisionInterfaceDemo TARGET AppCollisionInterfaceDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
ELSE (USE_GLUT) ELSE (USE_GLUT)
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppCollisionInterfaceDemo ADD_EXECUTABLE(AppCollisionInterfaceDemo
WIN32 WIN32
CollisionInterfaceDemo.cpp CollisionInterfaceDemo.cpp
CollisionInterfaceDemo.h CollisionInterfaceDemo.h
Win32CollisionInterfaceDemo.cpp Win32CollisionInterfaceDemo.cpp
../OpenGL/Win32AppMain.cpp ../OpenGL/Win32AppMain.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ENDIF (USE_GLUT) ENDIF (USE_GLUT)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppCollisionInterfaceDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppCollisionInterfaceDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppCollisionInterfaceDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppCollisionInterfaceDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppCollisionInterfaceDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppCollisionInterfaceDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,42 +1,42 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef COLLISION_INTERFACE_DEMO_H #ifndef COLLISION_INTERFACE_DEMO_H
#define COLLISION_INTERFACE_DEMO_H #define COLLISION_INTERFACE_DEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
///CollisionInterfaceDemo shows how to use the collision detection without dynamics (btCollisionWorld/CollisionObject) ///CollisionInterfaceDemo shows how to use the collision detection without dynamics (btCollisionWorld/CollisionObject)
class CollisionInterfaceDemo : public PlatformDemoApplication class CollisionInterfaceDemo : public PlatformDemoApplication
{ {
public: public:
void initPhysics(); void initPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
virtual void clientResetScene(); virtual void clientResetScene();
}; };
#endif //COLLISION_INTERFACE_DEMO_H #endif //COLLISION_INTERFACE_DEMO_H

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "CollisionInterfaceDemo.h" #include "CollisionInterfaceDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new CollisionInterfaceDemo(); return new CollisionInterfaceDemo();
} }
#endif #endif

View File

@@ -1,19 +1,19 @@
#include "CollisionInterfaceDemo.h" #include "CollisionInterfaceDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
int screenWidth = 640; int screenWidth = 640;
int screenHeight = 480; int screenHeight = 480;
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
CollisionInterfaceDemo* collisionInterfaceDemo = new CollisionInterfaceDemo(); CollisionInterfaceDemo* collisionInterfaceDemo = new CollisionInterfaceDemo();
collisionInterfaceDemo->initPhysics(); collisionInterfaceDemo->initPhysics();
collisionInterfaceDemo->clientResetScene(); collisionInterfaceDemo->clientResetScene();
return glutmain(argc, argv,screenWidth,screenHeight,"Collision Interface Demo",collisionInterfaceDemo); return glutmain(argc, argv,screenWidth,screenHeight,"Collision Interface Demo",collisionInterfaceDemo);
} }

View File

@@ -1,48 +1,48 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppConcaveConvexCastDemo ADD_EXECUTABLE(AppConcaveConvexCastDemo
ConcaveConvexcastDemo.cpp ConcaveConvexcastDemo.cpp
main.cpp main.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConcaveConvexCastDemo TARGET AppConcaveConvexCastDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConcaveConvexCastDemo TARGET AppConcaveConvexCastDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppConcaveConvexCastDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppConcaveConvexCastDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppConcaveConvexCastDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppConcaveConvexCastDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppConcaveConvexCastDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppConcaveConvexCastDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

File diff suppressed because it is too large Load Diff

View File

@@ -1,84 +1,84 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CONCAVE_CONVEXCAST_DEMO_H #ifndef CONCAVE_CONVEXCAST_DEMO_H
#define CONCAVE_CONVEXCAST_DEMO_H #define CONCAVE_CONVEXCAST_DEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
class btTriangleIndexVertexArray; class btTriangleIndexVertexArray;
///ConcaveRaycaseDemo shows usage of static concave triangle meshes ///ConcaveRaycaseDemo shows usage of static concave triangle meshes
///It also shows per-triangle material (friction/restitution) through CustomMaterialCombinerCallback ///It also shows per-triangle material (friction/restitution) through CustomMaterialCombinerCallback
class ConcaveConvexcastDemo : public GlutDemoApplication class ConcaveConvexcastDemo : public GlutDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btTriangleIndexVertexArray* m_indexVertexArrays; btTriangleIndexVertexArray* m_indexVertexArrays;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
bool m_animatedMesh; bool m_animatedMesh;
public: public:
ConcaveConvexcastDemo() : m_animatedMesh(true) ConcaveConvexcastDemo() : m_animatedMesh(true)
{ {
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual ~ConcaveConvexcastDemo() virtual ~ConcaveConvexcastDemo()
{ {
exitPhysics(); exitPhysics();
} }
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
//to show refit works //to show refit works
void setVertexPositions(float waveheight, float offset); void setVertexPositions(float waveheight, float offset);
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
static DemoApplication* Create() static DemoApplication* Create()
{ {
ConcaveConvexcastDemo* demo = new ConcaveConvexcastDemo(); ConcaveConvexcastDemo* demo = new ConcaveConvexcastDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
}; };
}; };
#endif //CONCAVE_CONVEXCAST_DEMO_H #endif //CONCAVE_CONVEXCAST_DEMO_H

View File

@@ -1,91 +1,91 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CONCAVE_DEMO_H #ifndef CONCAVE_DEMO_H
#define CONCAVE_DEMO_H #define CONCAVE_DEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
class btTriangleIndexVertexArray; class btTriangleIndexVertexArray;
///ConcaveDemo shows usage of static concave triangle meshes ///ConcaveDemo shows usage of static concave triangle meshes
///It also shows per-triangle material (friction/restitution) through CustomMaterialCombinerCallback ///It also shows per-triangle material (friction/restitution) through CustomMaterialCombinerCallback
class ConcaveDemo : public PlatformDemoApplication class ConcaveDemo : public PlatformDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btTriangleIndexVertexArray* m_indexVertexArrays; btTriangleIndexVertexArray* m_indexVertexArrays;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
bool m_animatedMesh; bool m_animatedMesh;
public: public:
ConcaveDemo() : m_animatedMesh(true) ConcaveDemo() : m_animatedMesh(true)
{ {
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual ~ConcaveDemo() virtual ~ConcaveDemo()
{ {
exitPhysics(); exitPhysics();
} }
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
//to show refit works //to show refit works
void setVertexPositions(float waveheight, float offset); void setVertexPositions(float waveheight, float offset);
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
static DemoApplication* Create() static DemoApplication* Create()
{ {
ConcaveDemo* demo = new ConcaveDemo(); ConcaveDemo* demo = new ConcaveDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
}; };
}; };
#endif //CONCAVE_DEMO_H #endif //CONCAVE_DEMO_H

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "ConcaveDemo.h" #include "ConcaveDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new ConcaveDemo(); return new ConcaveDemo();
} }
#endif #endif

View File

@@ -1,39 +1,39 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppConcaveRayCastDemo ADD_EXECUTABLE(AppConcaveRayCastDemo
ConcaveRaycastDemo.cpp ConcaveRaycastDemo.cpp
main.cpp main.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ELSE() ELSE()
ADD_EXECUTABLE(AppConcaveRayCastDemo ADD_EXECUTABLE(AppConcaveRayCastDemo
ConcaveRaycastDemo.cpp ConcaveRaycastDemo.cpp
main.cpp main.cpp
) )
ENDIF() ENDIF()
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppConcaveRayCastDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppConcaveRayCastDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppConcaveRayCastDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppConcaveRayCastDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppConcaveRayCastDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppConcaveRayCastDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,493 +1,493 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "LinearMath/btIDebugDraw.h" #include "LinearMath/btIDebugDraw.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "ConcaveRaycastDemo.h" #include "ConcaveRaycastDemo.h"
#include "GL_ShapeDrawer.h" #include "GL_ShapeDrawer.h"
#include "GlutStuff.h" #include "GlutStuff.h"
//#define BATCH_RAYCASTER //#define BATCH_RAYCASTER
#ifdef BATCH_RAYCASTER #ifdef BATCH_RAYCASTER
#include "BulletMultiThreaded/SpuBatchRaycaster.h" #include "BulletMultiThreaded/SpuBatchRaycaster.h"
static SpuBatchRaycaster* gBatchRaycaster = NULL; static SpuBatchRaycaster* gBatchRaycaster = NULL;
#endif #endif
#ifdef USE_LIBSPE2 #ifdef USE_LIBSPE2
#include "BulletMultiThreaded/SpuLibspe2Support.h" #include "BulletMultiThreaded/SpuLibspe2Support.h"
#elif defined (_WIN32) #elif defined (_WIN32)
#include "BulletMultiThreaded/Win32ThreadSupport.h" #include "BulletMultiThreaded/Win32ThreadSupport.h"
#else #else
//other platforms run the parallel code sequentially (until pthread support or other parallel implementation is added) //other platforms run the parallel code sequentially (until pthread support or other parallel implementation is added)
#include "BulletMultiThreaded/SequentialThreadSupport.h" #include "BulletMultiThreaded/SequentialThreadSupport.h"
#endif //USE_LIBSPE2 #endif //USE_LIBSPE2
static btVector3* gVertices=0; static btVector3* gVertices=0;
static int* gIndices=0; static int* gIndices=0;
static btBvhTriangleMeshShape* trimeshShape =0; static btBvhTriangleMeshShape* trimeshShape =0;
static btRigidBody* staticBody = 0; static btRigidBody* staticBody = 0;
static float waveheight = 5.f; static float waveheight = 5.f;
const float TRIANGLE_SIZE=8.f; const float TRIANGLE_SIZE=8.f;
/* Scrolls back and forth over terrain */ /* Scrolls back and forth over terrain */
#define NUMRAYS_IN_BAR 100 #define NUMRAYS_IN_BAR 100
class btRaycastBar class btRaycastBar
{ {
public: public:
btVector3 source[NUMRAYS_IN_BAR]; btVector3 source[NUMRAYS_IN_BAR];
btVector3 dest[NUMRAYS_IN_BAR]; btVector3 dest[NUMRAYS_IN_BAR];
btVector3 direction[NUMRAYS_IN_BAR]; btVector3 direction[NUMRAYS_IN_BAR];
btVector3 hit[NUMRAYS_IN_BAR]; btVector3 hit[NUMRAYS_IN_BAR];
btVector3 normal[NUMRAYS_IN_BAR]; btVector3 normal[NUMRAYS_IN_BAR];
int frame_counter; int frame_counter;
int ms; int ms;
int sum_ms; int sum_ms;
int sum_ms_samples; int sum_ms_samples;
int min_ms; int min_ms;
int max_ms; int max_ms;
#ifdef USE_BT_CLOCK #ifdef USE_BT_CLOCK
btClock frame_timer; btClock frame_timer;
#endif //USE_BT_CLOCK #endif //USE_BT_CLOCK
btScalar dx; btScalar dx;
btScalar min_x; btScalar min_x;
btScalar max_x; btScalar max_x;
btScalar min_y; btScalar min_y;
btScalar max_y; btScalar max_y;
btScalar sign; btScalar sign;
btRaycastBar () btRaycastBar ()
{ {
ms = 0; ms = 0;
max_ms = 0; max_ms = 0;
min_ms = 9999.0; min_ms = 9999.0;
sum_ms_samples = 0; sum_ms_samples = 0;
sum_ms = 0; sum_ms = 0;
} }
btRaycastBar (bool unused, btScalar ray_length, btScalar min_z, btScalar max_z, btScalar min_y = -10, btScalar max_y = 10) btRaycastBar (bool unused, btScalar ray_length, btScalar min_z, btScalar max_z, btScalar min_y = -10, btScalar max_y = 10)
{ {
frame_counter = 0; frame_counter = 0;
ms = 0; ms = 0;
max_ms = 0; max_ms = 0;
min_ms = 9999.0; min_ms = 9999.0;
sum_ms_samples = 0; sum_ms_samples = 0;
sum_ms = 0; sum_ms = 0;
dx = 10.0; dx = 10.0;
min_x = -40; min_x = -40;
max_x = 20; max_x = 20;
this->min_y = min_y; this->min_y = min_y;
this->max_y = max_y; this->max_y = max_y;
sign = 1.0; sign = 1.0;
btScalar dalpha = 2*SIMD_2_PI/NUMRAYS_IN_BAR; btScalar dalpha = 2*SIMD_2_PI/NUMRAYS_IN_BAR;
for (int i = 0; i < NUMRAYS_IN_BAR; i++) for (int i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
btScalar z = (max_z-min_z)/btScalar(NUMRAYS_IN_BAR) * btScalar(i) + min_z; btScalar z = (max_z-min_z)/btScalar(NUMRAYS_IN_BAR) * btScalar(i) + min_z;
source[i] = btVector3(min_x, max_y, z); source[i] = btVector3(min_x, max_y, z);
dest[i] = btVector3(min_x + ray_length, min_y, z); dest[i] = btVector3(min_x + ray_length, min_y, z);
normal[i] = btVector3(1.0, 0.0, 0.0); normal[i] = btVector3(1.0, 0.0, 0.0);
} }
} }
btRaycastBar (btScalar ray_length, btScalar z, btScalar min_y = -1000, btScalar max_y = 10) btRaycastBar (btScalar ray_length, btScalar z, btScalar min_y = -1000, btScalar max_y = 10)
{ {
frame_counter = 0; frame_counter = 0;
ms = 0; ms = 0;
max_ms = 0; max_ms = 0;
min_ms = 9999.0; min_ms = 9999.0;
sum_ms_samples = 0; sum_ms_samples = 0;
sum_ms = 0; sum_ms = 0;
dx = 10.0; dx = 10.0;
min_x = -40; min_x = -40;
max_x = 20; max_x = 20;
this->min_y = min_y; this->min_y = min_y;
this->max_y = max_y; this->max_y = max_y;
sign = 1.0; sign = 1.0;
btScalar dalpha = 2*SIMD_2_PI/NUMRAYS_IN_BAR; btScalar dalpha = 2*SIMD_2_PI/NUMRAYS_IN_BAR;
for (int i = 0; i < NUMRAYS_IN_BAR; i++) for (int i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
btScalar alpha = dalpha * i; btScalar alpha = dalpha * i;
// rotate around by alpha degrees y // rotate around by alpha degrees y
btTransform tr (btQuaternion (btVector3(0.0, 1.0, 0.0), alpha)); btTransform tr (btQuaternion (btVector3(0.0, 1.0, 0.0), alpha));
direction[i] = btVector3(1.0, 0.0, 0.0); direction[i] = btVector3(1.0, 0.0, 0.0);
direction[i] = tr* direction[i]; direction[i] = tr* direction[i];
direction[i] = direction[i] * ray_length; direction[i] = direction[i] * ray_length;
source[i] = btVector3(min_x, max_y, z); source[i] = btVector3(min_x, max_y, z);
dest[i] = source[i] + direction[i]; dest[i] = source[i] + direction[i];
dest[i][1] = min_y; dest[i][1] = min_y;
normal[i] = btVector3(1.0, 0.0, 0.0); normal[i] = btVector3(1.0, 0.0, 0.0);
} }
} }
void move (btScalar dt) void move (btScalar dt)
{ {
if (dt > (1.0/60.0)) if (dt > (1.0/60.0))
dt = 1.0/60.0; dt = 1.0/60.0;
for (int i = 0; i < NUMRAYS_IN_BAR; i++) for (int i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
source[i][0] += dx * dt * sign; source[i][0] += dx * dt * sign;
dest[i][0] += dx * dt * sign; dest[i][0] += dx * dt * sign;
} }
if (source[0][0] < min_x) if (source[0][0] < min_x)
sign = 1.0; sign = 1.0;
else if (source[0][0] > max_x) else if (source[0][0] > max_x)
sign = -1.0; sign = -1.0;
} }
void cast (btCollisionWorld* cw) void cast (btCollisionWorld* cw)
{ {
#ifdef USE_BT_CLOCK #ifdef USE_BT_CLOCK
frame_timer.reset (); frame_timer.reset ();
#endif //USE_BT_CLOCK #endif //USE_BT_CLOCK
#ifdef BATCH_RAYCASTER #ifdef BATCH_RAYCASTER
if (!gBatchRaycaster) if (!gBatchRaycaster)
return; return;
gBatchRaycaster->clearRays (); gBatchRaycaster->clearRays ();
for (int i = 0; i < NUMRAYS_IN_BAR; i++) for (int i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
gBatchRaycaster->addRay (source[i], dest[i]); gBatchRaycaster->addRay (source[i], dest[i]);
} }
gBatchRaycaster->performBatchRaycast (); gBatchRaycaster->performBatchRaycast ();
for (int i = 0; i < gBatchRaycaster->getNumRays (); i++) for (int i = 0; i < gBatchRaycaster->getNumRays (); i++)
{ {
const SpuRaycastTaskWorkUnitOut& out = (*gBatchRaycaster)[i]; const SpuRaycastTaskWorkUnitOut& out = (*gBatchRaycaster)[i];
hit[i].setInterpolate3(source[i],dest[i],out.hitFraction); hit[i].setInterpolate3(source[i],dest[i],out.hitFraction);
normal[i] = out.hitNormal; normal[i] = out.hitNormal;
normal[i].normalize (); normal[i].normalize ();
} }
#else #else
for (int i = 0; i < NUMRAYS_IN_BAR; i++) for (int i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
btCollisionWorld::ClosestRayResultCallback cb(source[i], dest[i]); btCollisionWorld::ClosestRayResultCallback cb(source[i], dest[i]);
cw->rayTest (source[i], dest[i], cb); cw->rayTest (source[i], dest[i], cb);
if (cb.hasHit ()) if (cb.hasHit ())
{ {
hit[i] = cb.m_hitPointWorld; hit[i] = cb.m_hitPointWorld;
normal[i] = cb.m_hitNormalWorld; normal[i] = cb.m_hitNormalWorld;
normal[i].normalize (); normal[i].normalize ();
} else { } else {
hit[i] = dest[i]; hit[i] = dest[i];
normal[i] = btVector3(1.0, 0.0, 0.0); normal[i] = btVector3(1.0, 0.0, 0.0);
} }
} }
#ifdef USE_BT_CLOCK #ifdef USE_BT_CLOCK
ms += frame_timer.getTimeMilliseconds (); ms += frame_timer.getTimeMilliseconds ();
#endif //USE_BT_CLOCK #endif //USE_BT_CLOCK
frame_counter++; frame_counter++;
if (frame_counter > 50) if (frame_counter > 50)
{ {
min_ms = ms < min_ms ? ms : min_ms; min_ms = ms < min_ms ? ms : min_ms;
max_ms = ms > max_ms ? ms : max_ms; max_ms = ms > max_ms ? ms : max_ms;
sum_ms += ms; sum_ms += ms;
sum_ms_samples++; sum_ms_samples++;
btScalar mean_ms = (btScalar)sum_ms/(btScalar)sum_ms_samples; btScalar mean_ms = (btScalar)sum_ms/(btScalar)sum_ms_samples;
printf("%d rays in %d ms %d %d %f\n", NUMRAYS_IN_BAR * frame_counter, ms, min_ms, max_ms, mean_ms); printf("%d rays in %d ms %d %d %f\n", NUMRAYS_IN_BAR * frame_counter, ms, min_ms, max_ms, mean_ms);
ms = 0; ms = 0;
frame_counter = 0; frame_counter = 0;
} }
#endif #endif
} }
void draw () void draw ()
{ {
glDisable (GL_LIGHTING); glDisable (GL_LIGHTING);
glColor3f (0.0, 1.0, 0.0); glColor3f (0.0, 1.0, 0.0);
glBegin (GL_LINES); glBegin (GL_LINES);
int i; int i;
for (i = 0; i < NUMRAYS_IN_BAR; i++) for (i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
glVertex3f (source[i][0], source[i][1], source[i][2]); glVertex3f (source[i][0], source[i][1], source[i][2]);
glVertex3f (hit[i][0], hit[i][1], hit[i][2]); glVertex3f (hit[i][0], hit[i][1], hit[i][2]);
} }
glEnd (); glEnd ();
glColor3f (1.0, 1.0, 1.0); glColor3f (1.0, 1.0, 1.0);
glBegin (GL_LINES); glBegin (GL_LINES);
for (i = 0; i < NUMRAYS_IN_BAR; i++) for (i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
glVertex3f (hit[i][0], hit[i][1], hit[i][2]); glVertex3f (hit[i][0], hit[i][1], hit[i][2]);
glVertex3f (hit[i][0] + normal[i][0], hit[i][1] + normal[i][1], hit[i][2] + normal[i][2]); glVertex3f (hit[i][0] + normal[i][0], hit[i][1] + normal[i][1], hit[i][2] + normal[i][2]);
} }
glEnd (); glEnd ();
glColor3f (0.0, 1.0, 1.0); glColor3f (0.0, 1.0, 1.0);
glBegin (GL_POINTS); glBegin (GL_POINTS);
for ( i = 0; i < NUMRAYS_IN_BAR; i++) for ( i = 0; i < NUMRAYS_IN_BAR; i++)
{ {
glVertex3f (hit[i][0], hit[i][1], hit[i][2]); glVertex3f (hit[i][0], hit[i][1], hit[i][2]);
} }
glEnd (); glEnd ();
glEnable (GL_LIGHTING); glEnable (GL_LIGHTING);
} }
}; };
static btRaycastBar raycastBar; static btRaycastBar raycastBar;
const int NUM_VERTS_X = 30; const int NUM_VERTS_X = 30;
const int NUM_VERTS_Y = 30; const int NUM_VERTS_Y = 30;
const int totalVerts = NUM_VERTS_X*NUM_VERTS_Y; const int totalVerts = NUM_VERTS_X*NUM_VERTS_Y;
void ConcaveRaycastDemo::setVertexPositions(float waveheight, float offset) void ConcaveRaycastDemo::setVertexPositions(float waveheight, float offset)
{ {
int i; int i;
int j; int j;
for ( i=0;i<NUM_VERTS_X;i++) for ( i=0;i<NUM_VERTS_X;i++)
{ {
for (j=0;j<NUM_VERTS_Y;j++) for (j=0;j<NUM_VERTS_Y;j++)
{ {
gVertices[i+j*NUM_VERTS_X].setValue((i-NUM_VERTS_X*0.5f)*TRIANGLE_SIZE, gVertices[i+j*NUM_VERTS_X].setValue((i-NUM_VERTS_X*0.5f)*TRIANGLE_SIZE,
//0.f, //0.f,
waveheight*sinf((float)i+offset)*cosf((float)j+offset), waveheight*sinf((float)i+offset)*cosf((float)j+offset),
(j-NUM_VERTS_Y*0.5f)*TRIANGLE_SIZE); (j-NUM_VERTS_Y*0.5f)*TRIANGLE_SIZE);
} }
} }
} }
void ConcaveRaycastDemo::keyboardCallback(unsigned char key, int x, int y) void ConcaveRaycastDemo::keyboardCallback(unsigned char key, int x, int y)
{ {
if (key == 'g') if (key == 'g')
{ {
m_animatedMesh = !m_animatedMesh; m_animatedMesh = !m_animatedMesh;
if (m_animatedMesh) if (m_animatedMesh)
{ {
staticBody->setCollisionFlags( staticBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); staticBody->setCollisionFlags( staticBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
staticBody->setActivationState(DISABLE_DEACTIVATION); staticBody->setActivationState(DISABLE_DEACTIVATION);
} else } else
{ {
staticBody->setCollisionFlags( staticBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); staticBody->setCollisionFlags( staticBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
staticBody->forceActivationState(ACTIVE_TAG); staticBody->forceActivationState(ACTIVE_TAG);
} }
} }
DemoApplication::keyboardCallback(key,x,y); DemoApplication::keyboardCallback(key,x,y);
} }
void ConcaveRaycastDemo::initPhysics() void ConcaveRaycastDemo::initPhysics()
{ {
#define TRISIZE 10.f #define TRISIZE 10.f
int vertStride = sizeof(btVector3); int vertStride = sizeof(btVector3);
int indexStride = 3*sizeof(int); int indexStride = 3*sizeof(int);
const int totalTriangles = 2*(NUM_VERTS_X-1)*(NUM_VERTS_Y-1); const int totalTriangles = 2*(NUM_VERTS_X-1)*(NUM_VERTS_Y-1);
gVertices = new btVector3[totalVerts]; gVertices = new btVector3[totalVerts];
gIndices = new int[totalTriangles*3]; gIndices = new int[totalTriangles*3];
int i; int i;
setVertexPositions(waveheight,0.f); setVertexPositions(waveheight,0.f);
int index=0; int index=0;
for ( i=0;i<NUM_VERTS_X-1;i++) for ( i=0;i<NUM_VERTS_X-1;i++)
{ {
for (int j=0;j<NUM_VERTS_Y-1;j++) for (int j=0;j<NUM_VERTS_Y-1;j++)
{ {
gIndices[index++] = j*NUM_VERTS_X+i; gIndices[index++] = j*NUM_VERTS_X+i;
gIndices[index++] = j*NUM_VERTS_X+i+1; gIndices[index++] = j*NUM_VERTS_X+i+1;
gIndices[index++] = (j+1)*NUM_VERTS_X+i+1; gIndices[index++] = (j+1)*NUM_VERTS_X+i+1;
gIndices[index++] = j*NUM_VERTS_X+i; gIndices[index++] = j*NUM_VERTS_X+i;
gIndices[index++] = (j+1)*NUM_VERTS_X+i+1; gIndices[index++] = (j+1)*NUM_VERTS_X+i+1;
gIndices[index++] = (j+1)*NUM_VERTS_X+i; gIndices[index++] = (j+1)*NUM_VERTS_X+i;
} }
} }
m_indexVertexArrays = new btTriangleIndexVertexArray(totalTriangles, m_indexVertexArrays = new btTriangleIndexVertexArray(totalTriangles,
gIndices, gIndices,
indexStride, indexStride,
totalVerts,(btScalar*) &gVertices[0].x(),vertStride); totalVerts,(btScalar*) &gVertices[0].x(),vertStride);
bool useQuantizedAabbCompression = true; bool useQuantizedAabbCompression = true;
trimeshShape = new btBvhTriangleMeshShape(m_indexVertexArrays,useQuantizedAabbCompression); trimeshShape = new btBvhTriangleMeshShape(m_indexVertexArrays,useQuantizedAabbCompression);
m_collisionShapes.push_back(trimeshShape); m_collisionShapes.push_back(trimeshShape);
btCollisionShape* groundShape = trimeshShape; btCollisionShape* groundShape = trimeshShape;
m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_collisionConfiguration = new btDefaultCollisionConfiguration();
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
btVector3 worldMin(-1000,-1000,-1000); btVector3 worldMin(-1000,-1000,-1000);
btVector3 worldMax(1000,1000,1000); btVector3 worldMax(1000,1000,1000);
m_broadphase = new btAxisSweep3(worldMin,worldMax); m_broadphase = new btAxisSweep3(worldMin,worldMax);
m_solver = new btSequentialImpulseConstraintSolver(); m_solver = new btSequentialImpulseConstraintSolver();
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
float mass = 0.f; float mass = 0.f;
btTransform startTransform; btTransform startTransform;
startTransform.setIdentity(); startTransform.setIdentity();
startTransform.setOrigin(btVector3(0,-2,0)); startTransform.setOrigin(btVector3(0,-2,0));
btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1)); btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1));
m_collisionShapes.push_back(colShape); m_collisionShapes.push_back(colShape);
{ {
for (int i=0;i<10;i++) for (int i=0;i<10;i++)
{ {
//btCollisionShape* colShape = new btCapsuleShape(0.5,2.0);//boxShape = new btSphereShape(1.f); //btCollisionShape* colShape = new btCapsuleShape(0.5,2.0);//boxShape = new btSphereShape(1.f);
startTransform.setOrigin(btVector3(2*i,10,1)); startTransform.setOrigin(btVector3(2*i,10,1));
localCreateRigidBody(1, startTransform,colShape); localCreateRigidBody(1, startTransform,colShape);
} }
} }
startTransform.setIdentity(); startTransform.setIdentity();
staticBody = localCreateRigidBody(mass, startTransform,groundShape); staticBody = localCreateRigidBody(mass, startTransform,groundShape);
staticBody->setCollisionFlags(staticBody->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT); staticBody->setCollisionFlags(staticBody->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT);
#ifdef BATCH_RAYCASTER #ifdef BATCH_RAYCASTER
int maxNumOutstandingTasks = 4; int maxNumOutstandingTasks = 4;
#ifdef USE_WIN32_THREADING #ifdef USE_WIN32_THREADING
Win32ThreadSupport::Win32ThreadConstructionInfo tci("batch raycast", Win32ThreadSupport::Win32ThreadConstructionInfo tci("batch raycast",
processRaycastTask, processRaycastTask,
createRaycastLocalStoreMemory, createRaycastLocalStoreMemory,
maxNumOutstandingTasks); maxNumOutstandingTasks);
m_threadSupportRaycast = new Win32ThreadSupport(tci); m_threadSupportRaycast = new Win32ThreadSupport(tci);
printf("m_threadSupportRaycast = %p\n", m_threadSupportRaycast); printf("m_threadSupportRaycast = %p\n", m_threadSupportRaycast);
#endif #endif
gBatchRaycaster = new SpuBatchRaycaster (m_threadSupportRaycast, maxNumOutstandingTasks, m_dynamicsWorld->getCollisionObjectArray(), m_dynamicsWorld->getNumCollisionObjects()); gBatchRaycaster = new SpuBatchRaycaster (m_threadSupportRaycast, maxNumOutstandingTasks, m_dynamicsWorld->getCollisionObjectArray(), m_dynamicsWorld->getNumCollisionObjects());
#endif #endif
raycastBar = btRaycastBar (4000.0, 0.0); raycastBar = btRaycastBar (4000.0, 0.0);
//raycastBar = btRaycastBar (true, 40.0, -50.0, 50.0); //raycastBar = btRaycastBar (true, 40.0, -50.0, 50.0);
} }
void ConcaveRaycastDemo::clientMoveAndDisplay() void ConcaveRaycastDemo::clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float dt = getDeltaTimeMicroseconds() * 0.000001f; float dt = getDeltaTimeMicroseconds() * 0.000001f;
if (m_animatedMesh) if (m_animatedMesh)
{ {
static float offset=0.f; static float offset=0.f;
offset+=0.01f; offset+=0.01f;
setVertexPositions(waveheight,offset); setVertexPositions(waveheight,offset);
btVector3 worldMin(-1000,-1000,-1000); btVector3 worldMin(-1000,-1000,-1000);
btVector3 worldMax(1000,1000,1000); btVector3 worldMax(1000,1000,1000);
trimeshShape->refitTree(worldMin,worldMax); trimeshShape->refitTree(worldMin,worldMax);
//clear all contact points involving mesh proxy. Note: this is a slow/unoptimized operation. //clear all contact points involving mesh proxy. Note: this is a slow/unoptimized operation.
m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(staticBody->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher()); m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(staticBody->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher());
} }
m_dynamicsWorld->stepSimulation(dt); m_dynamicsWorld->stepSimulation(dt);
//optional but useful: debug drawing //optional but useful: debug drawing
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
raycastBar.move (dt); raycastBar.move (dt);
raycastBar.cast (m_dynamicsWorld); raycastBar.cast (m_dynamicsWorld);
renderme(); renderme();
raycastBar.draw (); raycastBar.draw ();
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
void ConcaveRaycastDemo::displayCallback(void) { void ConcaveRaycastDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderme(); renderme();
raycastBar.draw (); raycastBar.draw ();
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
void ConcaveRaycastDemo::exitPhysics() void ConcaveRaycastDemo::exitPhysics()
{ {
//cleanup in the reverse order of creation/initialization //cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them //remove the rigidbodies from the dynamics world and delete them
int i; int i;
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{ {
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj); btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState()) if (body && body->getMotionState())
{ {
delete body->getMotionState(); delete body->getMotionState();
} }
m_dynamicsWorld->removeCollisionObject( obj ); m_dynamicsWorld->removeCollisionObject( obj );
delete obj; delete obj;
} }
//delete collision shapes //delete collision shapes
for (int j=0;j<m_collisionShapes.size();j++) for (int j=0;j<m_collisionShapes.size();j++)
{ {
btCollisionShape* shape = m_collisionShapes[j]; btCollisionShape* shape = m_collisionShapes[j];
delete shape; delete shape;
} }
//delete dynamics world //delete dynamics world
delete m_dynamicsWorld; delete m_dynamicsWorld;
if (m_indexVertexArrays) if (m_indexVertexArrays)
delete m_indexVertexArrays; delete m_indexVertexArrays;
//delete solver //delete solver
delete m_solver; delete m_solver;
//delete broadphase //delete broadphase
delete m_broadphase; delete m_broadphase;
//delete dispatcher //delete dispatcher
delete m_dispatcher; delete m_dispatcher;
delete m_collisionConfiguration; delete m_collisionConfiguration;
delete[] gVertices; delete[] gVertices;
} }

View File

@@ -1,85 +1,85 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CONCAVE_RAYCAST_DEMO_H #ifndef CONCAVE_RAYCAST_DEMO_H
#define CONCAVE_RAYCAST_DEMO_H #define CONCAVE_RAYCAST_DEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
class btTriangleIndexVertexArray; class btTriangleIndexVertexArray;
///ConcaveRaycastDemo shows usage of static concave triangle meshes ///ConcaveRaycastDemo shows usage of static concave triangle meshes
class ConcaveRaycastDemo : public GlutDemoApplication class ConcaveRaycastDemo : public GlutDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btTriangleIndexVertexArray* m_indexVertexArrays; btTriangleIndexVertexArray* m_indexVertexArrays;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
class btThreadSupportInterface* m_threadSupportRaycast; class btThreadSupportInterface* m_threadSupportRaycast;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
bool m_animatedMesh; bool m_animatedMesh;
public: public:
ConcaveRaycastDemo() : m_animatedMesh(false) ConcaveRaycastDemo() : m_animatedMesh(false)
{ {
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual ~ConcaveRaycastDemo() virtual ~ConcaveRaycastDemo()
{ {
exitPhysics(); exitPhysics();
} }
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
//to show refit works //to show refit works
void setVertexPositions(float waveheight, float offset); void setVertexPositions(float waveheight, float offset);
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
static DemoApplication* Create() static DemoApplication* Create()
{ {
ConcaveRaycastDemo* demo = new ConcaveRaycastDemo(); ConcaveRaycastDemo* demo = new ConcaveRaycastDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
}; };
}; };
#endif //CONCAVE_RAYCAST_DEMO_H #endif //CONCAVE_RAYCAST_DEMO_H

View File

@@ -1,69 +1,69 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/src
${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletFileLoader ${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletFileLoader
${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletWorldImporter ${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletWorldImporter
) )
IF (USE_GLUT) IF (USE_GLUT)
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppConstraintDemo ADD_EXECUTABLE(AppConstraintDemo
ConstraintDemo.cpp ConstraintDemo.cpp
ConstraintDemo.h ConstraintDemo.h
main.cpp main.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConcaveDemo TARGET AppConcaveDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConcaveDemo TARGET AppConcaveDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
ELSE (USE_GLUT) ELSE (USE_GLUT)
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppConstraintDemo ADD_EXECUTABLE(AppConstraintDemo
WIN32 WIN32
../OpenGL/Win32AppMain.cpp ../OpenGL/Win32AppMain.cpp
Win32ConstraintDemo.cpp Win32ConstraintDemo.cpp
ConstraintDemo.cpp ConstraintDemo.cpp
ConstraintDemo.h ConstraintDemo.h
) )
ENDIF (USE_GLUT) ENDIF (USE_GLUT)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,72 +1,72 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CONSTRAINT_DEMO_H #ifndef CONSTRAINT_DEMO_H
#define CONSTRAINT_DEMO_H #define CONSTRAINT_DEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
///ConstraintDemo shows how to create a constraint, like Hinge or btGenericD6constraint ///ConstraintDemo shows how to create a constraint, like Hinge or btGenericD6constraint
class ConstraintDemo : public PlatformDemoApplication class ConstraintDemo : public PlatformDemoApplication
{ {
//keep track of variables to delete memory at the end //keep track of variables to delete memory at the end
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
class btBroadphaseInterface* m_overlappingPairCache; class btBroadphaseInterface* m_overlappingPairCache;
class btCollisionDispatcher* m_dispatcher; class btCollisionDispatcher* m_dispatcher;
class btConstraintSolver* m_constraintSolver; class btConstraintSolver* m_constraintSolver;
class btDefaultCollisionConfiguration* m_collisionConfiguration; class btDefaultCollisionConfiguration* m_collisionConfiguration;
void setupEmptyDynamicsWorld(); void setupEmptyDynamicsWorld();
public: public:
virtual ~ConstraintDemo(); virtual ~ConstraintDemo();
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
static DemoApplication* Create() static DemoApplication* Create()
{ {
ConstraintDemo* demo = new ConstraintDemo(); ConstraintDemo* demo = new ConstraintDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
// for cone-twist motor driving // for cone-twist motor driving
float m_Time; float m_Time;
class btConeTwistConstraint* m_ctc; class btConeTwistConstraint* m_ctc;
}; };
#endif //CONSTRAINT_DEMO_H #endif //CONSTRAINT_DEMO_H

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "ConstraintDemo.h" #include "ConstraintDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new ConstraintDemo(); return new ConstraintDemo();
} }
#endif #endif

View File

@@ -1,20 +1,20 @@
#include "ConstraintDemo.h" #include "ConstraintDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
GLDebugDrawer gDebugDrawer; GLDebugDrawer gDebugDrawer;
ConstraintDemo* constraintDemo = new ConstraintDemo(); ConstraintDemo* constraintDemo = new ConstraintDemo();
constraintDemo->initPhysics(); constraintDemo->initPhysics();
constraintDemo->getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); constraintDemo->getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);
constraintDemo->setDebugMode(btIDebugDraw::DBG_DrawConstraints+btIDebugDraw::DBG_DrawConstraintLimits); constraintDemo->setDebugMode(btIDebugDraw::DBG_DrawConstraints+btIDebugDraw::DBG_DrawConstraintLimits);
return glutmain(argc, argv,640,480,"Constraint Demo. http://www.continuousphysics.com/Bullet/phpBB2/",constraintDemo); return glutmain(argc, argv,640,480,"Constraint Demo. http://www.continuousphysics.com/Bullet/phpBB2/",constraintDemo);
} }

View File

@@ -1,47 +1,47 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppContinuousConvexCollisionDemo ADD_EXECUTABLE(AppContinuousConvexCollisionDemo
ContinuousConvexCollisionDemo.cpp ContinuousConvexCollisionDemo.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppContinuousConvexCollisionDemo TARGET AppContinuousConvexCollisionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppContinuousConvexCollisionDemo TARGET AppContinuousConvexCollisionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppContinuousConvexCollisionDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppContinuousConvexCollisionDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppContinuousConvexCollisionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppContinuousConvexCollisionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppContinuousConvexCollisionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppContinuousConvexCollisionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,36 +1,36 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CONTINUOUS_CONVEX_COLLISION_DEMO_H #ifndef CONTINUOUS_CONVEX_COLLISION_DEMO_H
#define CONTINUOUS_CONVEX_COLLISION_DEMO_H #define CONTINUOUS_CONVEX_COLLISION_DEMO_H
///ContinuousConvexCollisionDemo shows the working of the continuous collision detection, including linear and angular motion ///ContinuousConvexCollisionDemo shows the working of the continuous collision detection, including linear and angular motion
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
class btContinuousConvexCollisionDemo : public GlutDemoApplication class btContinuousConvexCollisionDemo : public GlutDemoApplication
{ {
public: public:
void initPhysics(); void initPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
}; };
#endif //CONTINUOUS_CONVEX_COLLISION_DEMO_H #endif //CONTINUOUS_CONVEX_COLLISION_DEMO_H

View File

@@ -1,82 +1,82 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# This is the variable for Windows. I use this to define the root of my directory structure. # This is the variable for Windows. I use this to define the root of my directory structure.
SET(GLUT_ROOT ${BULLET_PHYSICS_SOURCE_DIR}/Glut) SET(GLUT_ROOT ${BULLET_PHYSICS_SOURCE_DIR}/Glut)
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/src
${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
${BULLET_PHYSICS_SOURCE_DIR}/Extras/ConvexDecomposition ${BULLET_PHYSICS_SOURCE_DIR}/Extras/ConvexDecomposition
${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletFileLoader ${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletFileLoader
${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletWorldImporter ${BULLET_PHYSICS_SOURCE_DIR}/Extras/Serialize/BulletWorldImporter
) )
IF (USE_GLUT) IF (USE_GLUT)
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ConvexDecomposition ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ConvexDecomposition ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppConvexDecompositionDemo ADD_EXECUTABLE(AppConvexDecompositionDemo
main.cpp main.cpp
ConvexDecompositionDemo.cpp ConvexDecompositionDemo.cpp
ConvexDecompositionDemo.h ConvexDecompositionDemo.h
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConvexDecompositionDemo TARGET AppConvexDecompositionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConvexDecompositionDemo TARGET AppConvexDecompositionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
ELSE (USE_GLUT) ELSE (USE_GLUT)
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ConvexDecomposition ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletWorldImporter BulletDynamics BulletCollision LinearMath BulletFileLoader ConvexDecomposition ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppConvexDecompositionDemo ADD_EXECUTABLE(AppConvexDecompositionDemo
WIN32 WIN32
../OpenGL/Win32AppMain.cpp ../OpenGL/Win32AppMain.cpp
ConvexDecompositionDemo.cpp ConvexDecompositionDemo.cpp
ConvexDecompositionDemo.h ConvexDecompositionDemo.h
Win32ConvexDecompositionDemo.cpp Win32ConvexDecompositionDemo.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
ENDIF (USE_GLUT) ENDIF (USE_GLUT)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppConvexDecompositionDemo TARGET AppConvexDecompositionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/Demos/SerializeDemo/testFile.bullet ${CMAKE_CURRENT_BINARY_DIR}/testFile.bullet COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/Demos/SerializeDemo/testFile.bullet ${CMAKE_CURRENT_BINARY_DIR}/testFile.bullet
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/file.obj ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/file.obj ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppConvexDecompositionDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppConvexDecompositionDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppConvexDecompositionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppConvexDecompositionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppConvexDecompositionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppConvexDecompositionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

File diff suppressed because it is too large Load Diff

View File

@@ -1,88 +1,88 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CONVEX_DECOMPOSITION_DEMO_H #ifndef CONVEX_DECOMPOSITION_DEMO_H
#define CONVEX_DECOMPOSITION_DEMO_H #define CONVEX_DECOMPOSITION_DEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
class btTriangleMesh; class btTriangleMesh;
///ConvexDecompositionDemo shows automatic convex decomposition of a concave mesh ///ConvexDecompositionDemo shows automatic convex decomposition of a concave mesh
class ConvexDecompositionDemo : public PlatformDemoApplication class ConvexDecompositionDemo : public PlatformDemoApplication
{ {
void setupEmptyDynamicsWorld(); void setupEmptyDynamicsWorld();
public: public:
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btAlignedObjectArray<btTriangleMesh*> m_trimeshes; btAlignedObjectArray<btTriangleMesh*> m_trimeshes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
virtual void initPhysics(); virtual void initPhysics();
void initPhysics(const char* filename); void initPhysics(const char* filename);
void exitPhysics(); void exitPhysics();
virtual ~ConvexDecompositionDemo() virtual ~ConvexDecompositionDemo()
{ {
exitPhysics(); exitPhysics();
} }
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
static DemoApplication* Create() static DemoApplication* Create()
{ {
ConvexDecompositionDemo* demo = new ConvexDecompositionDemo(); ConvexDecompositionDemo* demo = new ConvexDecompositionDemo();
demo->myinit(); demo->myinit();
demo->initPhysics("file.obj"); demo->initPhysics("file.obj");
return demo; return demo;
} }
}; };
#endif //CONVEX_DECOMPOSITION_DEMO_H #endif //CONVEX_DECOMPOSITION_DEMO_H

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2010 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2010 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "ConvexDecompositionDemo.h" #include "ConvexDecompositionDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new ConvexDecompositionDemo(); return new ConvexDecompositionDemo();
} }
#endif #endif

View File

@@ -1,32 +1,32 @@
#include "ConvexDecompositionDemo.h" #include "ConvexDecompositionDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
GLDebugDrawer gDebugDrawer; GLDebugDrawer gDebugDrawer;
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
const char* filename = "file.obj"; const char* filename = "file.obj";
ConvexDecompositionDemo* convexDecompDemo = new ConvexDecompositionDemo(); ConvexDecompositionDemo* convexDecompDemo = new ConvexDecompositionDemo();
convexDecompDemo->initPhysics(filename); convexDecompDemo->initPhysics(filename);
convexDecompDemo->getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); convexDecompDemo->getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);
convexDecompDemo->clientResetScene(); convexDecompDemo->clientResetScene();
glutmain(argc, argv,640,480,"Bullet Physics Demo. http://www.continuousphysics.com/Bullet/phpBB2/",convexDecompDemo); glutmain(argc, argv,640,480,"Bullet Physics Demo. http://www.continuousphysics.com/Bullet/phpBB2/",convexDecompDemo);
delete convexDecompDemo; delete convexDecompDemo;
return 0; return 0;
} }

View File

@@ -1,49 +1,49 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppDoublePrecisionDemo ADD_EXECUTABLE(AppDoublePrecisionDemo
DoublePrecisionDemo.cpp DoublePrecisionDemo.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppDoublePrecisionDemo TARGET AppDoublePrecisionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppDoublePrecisionDemo TARGET AppDoublePrecisionDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppDoublePrecisionDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppDoublePrecisionDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppDoublePrecisionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppDoublePrecisionDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppDoublePrecisionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppDoublePrecisionDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,280 +1,280 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
/// ///
/// DoublePrecisionDemo shows high level usage of the Collision Detection. /// DoublePrecisionDemo shows high level usage of the Collision Detection.
/// ///
#include "GL_Simplex1to4.h" #include "GL_Simplex1to4.h"
//include common Bullet Collision Detection headerfiles //include common Bullet Collision Detection headerfiles
#include "btBulletCollisionCommon.h" #include "btBulletCollisionCommon.h"
#include "LinearMath/btIDebugDraw.h" #include "LinearMath/btIDebugDraw.h"
#include "GLDebugFont.h" #include "GLDebugFont.h"
#include "GL_ShapeDrawer.h" #include "GL_ShapeDrawer.h"
#include "DoublePrecisionDemo.h" #include "DoublePrecisionDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
btScalar yaw=btScalar(0.); btScalar yaw=btScalar(0.);
btScalar pitch=btScalar(0.); btScalar pitch=btScalar(0.);
btScalar roll=btScalar(0.); btScalar roll=btScalar(0.);
const int maxNumObjects = 4; const int maxNumObjects = 4;
const int numObjects = 2; const int numObjects = 2;
GL_Simplex1to4 simplex; GL_Simplex1to4 simplex;
btCollisionObject objects[maxNumObjects]; btCollisionObject objects[maxNumObjects];
btCollisionWorld* collisionWorld = 0; btCollisionWorld* collisionWorld = 0;
// so pixel ratio is 1:1 // so pixel ratio is 1:1
int screenWidth = 640; int screenWidth = 640;
int screenHeight = 640; int screenHeight = 640;
GLDebugDrawer debugDrawer; GLDebugDrawer debugDrawer;
const btScalar LARGE_DISTANCE_FROM_ORIGIN = btScalar(999999.0); const btScalar LARGE_DISTANCE_FROM_ORIGIN = btScalar(999999.0);
const btScalar VERY_SMALL_INCREMENT = btScalar(0.000009); const btScalar VERY_SMALL_INCREMENT = btScalar(0.000009);
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
DoublePrecisionDemo* doublePrecisionDemo = new DoublePrecisionDemo(); DoublePrecisionDemo* doublePrecisionDemo = new DoublePrecisionDemo();
doublePrecisionDemo->initPhysics(); doublePrecisionDemo->initPhysics();
doublePrecisionDemo->setCameraDistance(btScalar(2.0)); doublePrecisionDemo->setCameraDistance(btScalar(2.0));
doublePrecisionDemo->clientResetScene(); doublePrecisionDemo->clientResetScene();
return glutmain(argc, argv,screenWidth,screenHeight,"Double Precision Demo",doublePrecisionDemo); return glutmain(argc, argv,screenWidth,screenHeight,"Double Precision Demo",doublePrecisionDemo);
} }
void DoublePrecisionDemo::initPhysics() void DoublePrecisionDemo::initPhysics()
{ {
m_debugMode |= btIDebugDraw::DBG_DrawWireframe; m_debugMode |= btIDebugDraw::DBG_DrawWireframe;
btMatrix3x3 basisA; btMatrix3x3 basisA;
basisA.setIdentity(); basisA.setIdentity();
btMatrix3x3 basisB; btMatrix3x3 basisB;
basisB.setIdentity(); basisB.setIdentity();
objects[0].getWorldTransform().setBasis(basisA); objects[0].getWorldTransform().setBasis(basisA);
objects[1].getWorldTransform().setBasis(basisB); objects[1].getWorldTransform().setBasis(basisB);
btBoxShape* boxA = new btBoxShape(btVector3(0.5,0.5,0.5)); btBoxShape* boxA = new btBoxShape(btVector3(0.5,0.5,0.5));
btBoxShape* boxB = new btBoxShape(btVector3(0.5,0.5,0.5)); btBoxShape* boxB = new btBoxShape(btVector3(0.5,0.5,0.5));
objects[0].setCollisionShape(boxA);//&hullA; objects[0].setCollisionShape(boxA);//&hullA;
objects[1].setCollisionShape(boxB);//&hullB; objects[1].setCollisionShape(boxB);//&hullB;
btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btVector3 worldAabbMin(80000,80000,80000); btVector3 worldAabbMin(80000,80000,80000);
btVector3 worldAabbMax(120000,120000,120000); btVector3 worldAabbMax(120000,120000,120000);
btAxisSweep3* broadphase = new btAxisSweep3(worldAabbMin,worldAabbMax); btAxisSweep3* broadphase = new btAxisSweep3(worldAabbMin,worldAabbMax);
collisionWorld = new btCollisionWorld(dispatcher,broadphase,collisionConfiguration); collisionWorld = new btCollisionWorld(dispatcher,broadphase,collisionConfiguration);
collisionWorld->addCollisionObject(&objects[0]); collisionWorld->addCollisionObject(&objects[0]);
collisionWorld->addCollisionObject(&objects[1]); collisionWorld->addCollisionObject(&objects[1]);
} }
//to be implemented by the demo //to be implemented by the demo
void DoublePrecisionDemo::clientMoveAndDisplay() void DoublePrecisionDemo::clientMoveAndDisplay()
{ {
displayCallback(); displayCallback();
} }
static btVoronoiSimplexSolver sGjkSimplexSolver; static btVoronoiSimplexSolver sGjkSimplexSolver;
btSimplexSolverInterface& gGjkSimplexSolver = sGjkSimplexSolver; btSimplexSolverInterface& gGjkSimplexSolver = sGjkSimplexSolver;
void DoublePrecisionDemo::displayCallback(void) void DoublePrecisionDemo::displayCallback(void)
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
collisionWorld->getDispatchInfo().m_debugDraw = &debugDrawer; collisionWorld->getDispatchInfo().m_debugDraw = &debugDrawer;
if (collisionWorld) if (collisionWorld)
collisionWorld->performDiscreteCollisionDetection(); collisionWorld->performDiscreteCollisionDetection();
int i; int i;
btVector3 worldBoundsMin,worldBoundsMax; btVector3 worldBoundsMin,worldBoundsMax;
collisionWorld->getBroadphase()->getBroadphaseAabb(worldBoundsMin,worldBoundsMax); collisionWorld->getBroadphase()->getBroadphaseAabb(worldBoundsMin,worldBoundsMax);
///one way to draw all the contact points is iterating over contact manifolds / points: ///one way to draw all the contact points is iterating over contact manifolds / points:
int numManifolds = collisionWorld->getDispatcher()->getNumManifolds(); int numManifolds = collisionWorld->getDispatcher()->getNumManifolds();
for (i=0;i<numManifolds;i++) for (i=0;i<numManifolds;i++)
{ {
btPersistentManifold* contactManifold = collisionWorld->getDispatcher()->getManifoldByIndexInternal(i); btPersistentManifold* contactManifold = collisionWorld->getDispatcher()->getManifoldByIndexInternal(i);
btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1()); btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
contactManifold->refreshContactPoints(obA->getWorldTransform(),obB->getWorldTransform()); contactManifold->refreshContactPoints(obA->getWorldTransform(),obB->getWorldTransform());
int numContacts = contactManifold->getNumContacts(); int numContacts = contactManifold->getNumContacts();
for (int j=0;j<numContacts;j++) for (int j=0;j<numContacts;j++)
{ {
btManifoldPoint& pt = contactManifold->getContactPoint(j); btManifoldPoint& pt = contactManifold->getContactPoint(j);
glBegin(GL_LINES); glBegin(GL_LINES);
glColor3f(1, 1, 1); glColor3f(1, 1, 1);
btVector3 ptA = pt.getPositionWorldOnA() - m_cameraPosition; btVector3 ptA = pt.getPositionWorldOnA() - m_cameraPosition;
btVector3 ptB = pt.getPositionWorldOnB() - m_cameraPosition; btVector3 ptB = pt.getPositionWorldOnB() - m_cameraPosition;
glVertex3d(ptA.x(),ptA.y(),ptA.z()); glVertex3d(ptA.x(),ptA.y(),ptA.z());
glVertex3d(ptB.x(),ptB.y(),ptB.z()); glVertex3d(ptB.x(),ptB.y(),ptB.z());
glEnd(); glEnd();
} }
//you can un-comment out this line, and then all points are removed //you can un-comment out this line, and then all points are removed
//contactManifold->clearManifold(); //contactManifold->clearManifold();
} }
btScalar m[16]; btScalar m[16];
btTransform temp; btTransform temp;
btVector3 color; btVector3 color;
//int i; //int i;
for (i=0;i<numObjects;i++) for (i=0;i<numObjects;i++)
{ {
if (i % 2) if (i % 2)
{ {
color = btVector3(1,0,0); color = btVector3(1,0,0);
} }
else else
{ {
color = btVector3(0,0,1); color = btVector3(0,0,1);
} }
temp = objects[i].getWorldTransform(); temp = objects[i].getWorldTransform();
temp.setOrigin(temp.getOrigin() - m_cameraPosition); temp.setOrigin(temp.getOrigin() - m_cameraPosition);
temp.getOpenGLMatrix( m ); temp.getOpenGLMatrix( m );
m_shapeDrawer->drawOpenGL(m,objects[i].getCollisionShape(),color,getDebugMode(),worldBoundsMin,worldBoundsMax); m_shapeDrawer->drawOpenGL(m,objects[i].getCollisionShape(),color,getDebugMode(),worldBoundsMin,worldBoundsMax);
} }
objects[1].getWorldTransform().setOrigin(objects[1].getWorldTransform().getOrigin()+btVector3(-VERY_SMALL_INCREMENT,-VERY_SMALL_INCREMENT,0)); objects[1].getWorldTransform().setOrigin(objects[1].getWorldTransform().getOrigin()+btVector3(-VERY_SMALL_INCREMENT,-VERY_SMALL_INCREMENT,0));
objects[0].getWorldTransform().setOrigin(objects[0].getWorldTransform().getOrigin()+btVector3(VERY_SMALL_INCREMENT,VERY_SMALL_INCREMENT,0)); objects[0].getWorldTransform().setOrigin(objects[0].getWorldTransform().getOrigin()+btVector3(VERY_SMALL_INCREMENT,VERY_SMALL_INCREMENT,0));
float yStart = 20.f; float yStart = 20.f;
float yIncr = 20.f; float yIncr = 20.f;
char buf[124]; char buf[124];
glColor3f(0, 0, 0); glColor3f(0, 0, 0);
setOrthographicProjection(); setOrthographicProjection();
glRasterPos3f(10.0f,yStart,0); glRasterPos3f(10.0f,yStart,0);
#ifdef BT_USE_DOUBLE_PRECISION #ifdef BT_USE_DOUBLE_PRECISION
GLDebugDrawString(10.f,yStart,"Double Precision Mode"); GLDebugDrawString(10.f,yStart,"Double Precision Mode");
#else #else
GLDebugDrawString(10.f,yStart,"Single Precision Mode"); GLDebugDrawString(10.f,yStart,"Single Precision Mode");
#endif #endif
yStart += yIncr; yStart += yIncr;
glRasterPos3f(10.0f,yStart,0); glRasterPos3f(10.0f,yStart,0);
sprintf(buf,"Movement distance in x and y axis = %lf", VERY_SMALL_INCREMENT); sprintf(buf,"Movement distance in x and y axis = %lf", VERY_SMALL_INCREMENT);
GLDebugDrawString(10.f,yStart,buf); GLDebugDrawString(10.f,yStart,buf);
yStart += yIncr; yStart += yIncr;
glRasterPos3f(10.0f,yStart,0); glRasterPos3f(10.0f,yStart,0);
btScalar xValue = objects[0].getWorldTransform().getOrigin().x(); btScalar xValue = objects[0].getWorldTransform().getOrigin().x();
btScalar yValue = objects[0].getWorldTransform().getOrigin().y(); btScalar yValue = objects[0].getWorldTransform().getOrigin().y();
btScalar zValue = objects[0].getWorldTransform().getOrigin().z(); btScalar zValue = objects[0].getWorldTransform().getOrigin().z();
sprintf(buf,"Cube 0 location = ( %lf, %lf, %lf )", xValue, yValue, zValue); sprintf(buf,"Cube 0 location = ( %lf, %lf, %lf )", xValue, yValue, zValue);
GLDebugDrawString(10.f,yStart,buf); GLDebugDrawString(10.f,yStart,buf);
yStart += yIncr; yStart += yIncr;
xValue = objects[1].getWorldTransform().getOrigin().x(); xValue = objects[1].getWorldTransform().getOrigin().x();
yValue = objects[1].getWorldTransform().getOrigin().y(); yValue = objects[1].getWorldTransform().getOrigin().y();
zValue = objects[1].getWorldTransform().getOrigin().z(); zValue = objects[1].getWorldTransform().getOrigin().z();
glRasterPos3f(10.0f,yStart,0); glRasterPos3f(10.0f,yStart,0);
sprintf(buf,"Cube 1 location = ( %lf, %lf, %lf )", xValue, yValue, zValue); sprintf(buf,"Cube 1 location = ( %lf, %lf, %lf )", xValue, yValue, zValue);
GLDebugDrawString(10.f,yStart,buf); GLDebugDrawString(10.f,yStart,buf);
yStart += yIncr; yStart += yIncr;
glRasterPos3f(10.0f,yStart,0); glRasterPos3f(10.0f,yStart,0);
GLDebugDrawString(10.f,yStart,"w=toggle wireframe/solid"); GLDebugDrawString(10.f,yStart,"w=toggle wireframe/solid");
resetPerspectiveProjection(); resetPerspectiveProjection();
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
void DoublePrecisionDemo::clientResetScene() void DoublePrecisionDemo::clientResetScene()
{ {
objects[0].getWorldTransform().setOrigin(btVector3(LARGE_DISTANCE_FROM_ORIGIN,LARGE_DISTANCE_FROM_ORIGIN,LARGE_DISTANCE_FROM_ORIGIN)); objects[0].getWorldTransform().setOrigin(btVector3(LARGE_DISTANCE_FROM_ORIGIN,LARGE_DISTANCE_FROM_ORIGIN,LARGE_DISTANCE_FROM_ORIGIN));
objects[1].getWorldTransform().setOrigin(btVector3(LARGE_DISTANCE_FROM_ORIGIN-VERY_SMALL_INCREMENT,LARGE_DISTANCE_FROM_ORIGIN-VERY_SMALL_INCREMENT,LARGE_DISTANCE_FROM_ORIGIN)); objects[1].getWorldTransform().setOrigin(btVector3(LARGE_DISTANCE_FROM_ORIGIN-VERY_SMALL_INCREMENT,LARGE_DISTANCE_FROM_ORIGIN-VERY_SMALL_INCREMENT,LARGE_DISTANCE_FROM_ORIGIN));
} }
void DoublePrecisionDemo::updateCamera() void DoublePrecisionDemo::updateCamera()
{ {
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); glLoadIdentity();
// look at the stationary cube // look at the stationary cube
m_cameraTargetPosition = objects[0].getWorldTransform().getOrigin(); m_cameraTargetPosition = objects[0].getWorldTransform().getOrigin();
m_cameraPosition = m_cameraTargetPosition; m_cameraPosition = m_cameraTargetPosition;
m_cameraPosition[2] = m_cameraTargetPosition[2] - m_cameraDistance; m_cameraPosition[2] = m_cameraTargetPosition[2] - m_cameraDistance;
//update OpenGL camera settings //update OpenGL camera settings
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10000.0); glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10000.0);
// To not loose precision in the rendering process, we shift the object to the origin // To not loose precision in the rendering process, we shift the object to the origin
gluLookAt(0.0, 0.0, 0.0, gluLookAt(0.0, 0.0, 0.0,
m_cameraTargetPosition[0]-m_cameraPosition[0],m_cameraTargetPosition[1]-m_cameraPosition[1], m_cameraTargetPosition[2]-m_cameraPosition[2], m_cameraTargetPosition[0]-m_cameraPosition[0],m_cameraTargetPosition[1]-m_cameraPosition[1], m_cameraTargetPosition[2]-m_cameraPosition[2],
m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ()); m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
} }
void DoublePrecisionDemo::keyboardCallback(unsigned char key, int x, int y) void DoublePrecisionDemo::keyboardCallback(unsigned char key, int x, int y)
{ {
if (key == 'w') if (key == 'w')
{ {
if (m_debugMode & btIDebugDraw::DBG_DrawWireframe) if (m_debugMode & btIDebugDraw::DBG_DrawWireframe)
{ {
m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawWireframe); m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawWireframe);
m_debugMode |= btIDebugDraw::DBG_DrawAabb; m_debugMode |= btIDebugDraw::DBG_DrawAabb;
} }
else else
{ {
m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawAabb); m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawAabb);
m_debugMode |= btIDebugDraw::DBG_DrawWireframe; m_debugMode |= btIDebugDraw::DBG_DrawWireframe;
} }
return; return;
} }
DemoApplication::keyboardCallback(key, x, y); DemoApplication::keyboardCallback(key, x, y);
} }

View File

@@ -1,49 +1,49 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppMotorDemo ADD_EXECUTABLE(AppMotorDemo
MotorDemo.cpp MotorDemo.cpp
main.cpp main.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppMotorDemo TARGET AppMotorDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppMotorDemo TARGET AppMotorDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppMotorDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppMotorDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppMotorDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppMotorDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppMotorDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppMotorDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,468 +1,468 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Copyright (c) 2007 Erwin Coumans Bullet Continuous Collision Detection and Physics Library Copyright (c) 2007 Erwin Coumans
Motor Demo Motor Demo
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GL_ShapeDrawer.h" #include "GL_ShapeDrawer.h"
#include "LinearMath/btIDebugDraw.h" #include "LinearMath/btIDebugDraw.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "MotorDemo.h" #include "MotorDemo.h"
#ifndef M_PI #ifndef M_PI
#define M_PI 3.14159265358979323846 #define M_PI 3.14159265358979323846
#endif #endif
#ifndef M_PI_2 #ifndef M_PI_2
#define M_PI_2 1.57079632679489661923 #define M_PI_2 1.57079632679489661923
#endif #endif
#ifndef M_PI_4 #ifndef M_PI_4
#define M_PI_4 0.785398163397448309616 #define M_PI_4 0.785398163397448309616
#endif #endif
#ifndef M_PI_8 #ifndef M_PI_8
#define M_PI_8 0.5 * M_PI_4 #define M_PI_8 0.5 * M_PI_4
#endif #endif
// LOCAL FUNCTIONS // LOCAL FUNCTIONS
void vertex(btVector3 &v) void vertex(btVector3 &v)
{ {
glVertex3d(v.getX(), v.getY(), v.getZ()); glVertex3d(v.getX(), v.getY(), v.getZ());
} }
void drawFrame(btTransform &tr) void drawFrame(btTransform &tr)
{ {
const float fSize = 1.f; const float fSize = 1.f;
glBegin(GL_LINES); glBegin(GL_LINES);
// x // x
glColor3f(255.f,0,0); glColor3f(255.f,0,0);
btVector3 vX = tr*btVector3(fSize,0,0); btVector3 vX = tr*btVector3(fSize,0,0);
vertex(tr.getOrigin()); vertex(vX); vertex(tr.getOrigin()); vertex(vX);
// y // y
glColor3f(0,255.f,0); glColor3f(0,255.f,0);
btVector3 vY = tr*btVector3(0,fSize,0); btVector3 vY = tr*btVector3(0,fSize,0);
vertex(tr.getOrigin()); vertex(vY); vertex(tr.getOrigin()); vertex(vY);
// z // z
glColor3f(0,0,255.f); glColor3f(0,0,255.f);
btVector3 vZ = tr*btVector3(0,0,fSize); btVector3 vZ = tr*btVector3(0,0,fSize);
vertex(tr.getOrigin()); vertex(vZ); vertex(tr.getOrigin()); vertex(vZ);
glEnd(); glEnd();
} }
// /LOCAL FUNCTIONS // /LOCAL FUNCTIONS
#define NUM_LEGS 6 #define NUM_LEGS 6
#define BODYPART_COUNT 2 * NUM_LEGS + 1 #define BODYPART_COUNT 2 * NUM_LEGS + 1
#define JOINT_COUNT BODYPART_COUNT - 1 #define JOINT_COUNT BODYPART_COUNT - 1
class TestRig class TestRig
{ {
btDynamicsWorld* m_ownerWorld; btDynamicsWorld* m_ownerWorld;
btCollisionShape* m_shapes[BODYPART_COUNT]; btCollisionShape* m_shapes[BODYPART_COUNT];
btRigidBody* m_bodies[BODYPART_COUNT]; btRigidBody* m_bodies[BODYPART_COUNT];
btTypedConstraint* m_joints[JOINT_COUNT]; btTypedConstraint* m_joints[JOINT_COUNT];
btRigidBody* localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape) btRigidBody* localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape)
{ {
bool isDynamic = (mass != 0.f); bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0); btVector3 localInertia(0,0,0);
if (isDynamic) if (isDynamic)
shape->calculateLocalInertia(mass,localInertia); shape->calculateLocalInertia(mass,localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia);
btRigidBody* body = new btRigidBody(rbInfo); btRigidBody* body = new btRigidBody(rbInfo);
m_ownerWorld->addRigidBody(body); m_ownerWorld->addRigidBody(body);
return body; return body;
} }
public: public:
TestRig (btDynamicsWorld* ownerWorld, const btVector3& positionOffset, bool bFixed) TestRig (btDynamicsWorld* ownerWorld, const btVector3& positionOffset, bool bFixed)
: m_ownerWorld (ownerWorld) : m_ownerWorld (ownerWorld)
{ {
btVector3 vUp(0, 1, 0); btVector3 vUp(0, 1, 0);
// //
// Setup geometry // Setup geometry
// //
float fBodySize = 0.25f; float fBodySize = 0.25f;
float fLegLength = 0.45f; float fLegLength = 0.45f;
float fForeLegLength = 0.75f; float fForeLegLength = 0.75f;
m_shapes[0] = new btCapsuleShape(btScalar(fBodySize), btScalar(0.10)); m_shapes[0] = new btCapsuleShape(btScalar(fBodySize), btScalar(0.10));
int i; int i;
for ( i=0; i<NUM_LEGS; i++) for ( i=0; i<NUM_LEGS; i++)
{ {
m_shapes[1 + 2*i] = new btCapsuleShape(btScalar(0.10), btScalar(fLegLength)); m_shapes[1 + 2*i] = new btCapsuleShape(btScalar(0.10), btScalar(fLegLength));
m_shapes[2 + 2*i] = new btCapsuleShape(btScalar(0.08), btScalar(fForeLegLength)); m_shapes[2 + 2*i] = new btCapsuleShape(btScalar(0.08), btScalar(fForeLegLength));
} }
// //
// Setup rigid bodies // Setup rigid bodies
// //
float fHeight = 0.5; float fHeight = 0.5;
btTransform offset; offset.setIdentity(); btTransform offset; offset.setIdentity();
offset.setOrigin(positionOffset); offset.setOrigin(positionOffset);
// root // root
btVector3 vRoot = btVector3(btScalar(0.), btScalar(fHeight), btScalar(0.)); btVector3 vRoot = btVector3(btScalar(0.), btScalar(fHeight), btScalar(0.));
btTransform transform; btTransform transform;
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(vRoot); transform.setOrigin(vRoot);
if (bFixed) if (bFixed)
{ {
m_bodies[0] = localCreateRigidBody(btScalar(0.), offset*transform, m_shapes[0]); m_bodies[0] = localCreateRigidBody(btScalar(0.), offset*transform, m_shapes[0]);
} else } else
{ {
m_bodies[0] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[0]); m_bodies[0] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[0]);
} }
// legs // legs
for ( i=0; i<NUM_LEGS; i++) for ( i=0; i<NUM_LEGS; i++)
{ {
float fAngle = 2 * M_PI * i / NUM_LEGS; float fAngle = 2 * M_PI * i / NUM_LEGS;
float fSin = sin(fAngle); float fSin = sin(fAngle);
float fCos = cos(fAngle); float fCos = cos(fAngle);
transform.setIdentity(); transform.setIdentity();
btVector3 vBoneOrigin = btVector3(btScalar(fCos*(fBodySize+0.5*fLegLength)), btScalar(fHeight), btScalar(fSin*(fBodySize+0.5*fLegLength))); btVector3 vBoneOrigin = btVector3(btScalar(fCos*(fBodySize+0.5*fLegLength)), btScalar(fHeight), btScalar(fSin*(fBodySize+0.5*fLegLength)));
transform.setOrigin(vBoneOrigin); transform.setOrigin(vBoneOrigin);
// thigh // thigh
btVector3 vToBone = (vBoneOrigin - vRoot).normalize(); btVector3 vToBone = (vBoneOrigin - vRoot).normalize();
btVector3 vAxis = vToBone.cross(vUp); btVector3 vAxis = vToBone.cross(vUp);
transform.setRotation(btQuaternion(vAxis, M_PI_2)); transform.setRotation(btQuaternion(vAxis, M_PI_2));
m_bodies[1+2*i] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[1+2*i]); m_bodies[1+2*i] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[1+2*i]);
// shin // shin
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(fCos*(fBodySize+fLegLength)), btScalar(fHeight-0.5*fForeLegLength), btScalar(fSin*(fBodySize+fLegLength)))); transform.setOrigin(btVector3(btScalar(fCos*(fBodySize+fLegLength)), btScalar(fHeight-0.5*fForeLegLength), btScalar(fSin*(fBodySize+fLegLength))));
m_bodies[2+2*i] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[2+2*i]); m_bodies[2+2*i] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[2+2*i]);
} }
// Setup some damping on the m_bodies // Setup some damping on the m_bodies
for (i = 0; i < BODYPART_COUNT; ++i) for (i = 0; i < BODYPART_COUNT; ++i)
{ {
m_bodies[i]->setDamping(0.05, 0.85); m_bodies[i]->setDamping(0.05, 0.85);
m_bodies[i]->setDeactivationTime(0.8); m_bodies[i]->setDeactivationTime(0.8);
//m_bodies[i]->setSleepingThresholds(1.6, 2.5); //m_bodies[i]->setSleepingThresholds(1.6, 2.5);
m_bodies[i]->setSleepingThresholds(0.5f, 0.5f); m_bodies[i]->setSleepingThresholds(0.5f, 0.5f);
} }
// //
// Setup the constraints // Setup the constraints
// //
btHingeConstraint* hingeC; btHingeConstraint* hingeC;
//btConeTwistConstraint* coneC; //btConeTwistConstraint* coneC;
btTransform localA, localB, localC; btTransform localA, localB, localC;
for ( i=0; i<NUM_LEGS; i++) for ( i=0; i<NUM_LEGS; i++)
{ {
float fAngle = 2 * M_PI * i / NUM_LEGS; float fAngle = 2 * M_PI * i / NUM_LEGS;
float fSin = sin(fAngle); float fSin = sin(fAngle);
float fCos = cos(fAngle); float fCos = cos(fAngle);
// hip joints // hip joints
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.getBasis().setEulerZYX(0,-fAngle,0); localA.setOrigin(btVector3(btScalar(fCos*fBodySize), btScalar(0.), btScalar(fSin*fBodySize))); localA.getBasis().setEulerZYX(0,-fAngle,0); localA.setOrigin(btVector3(btScalar(fCos*fBodySize), btScalar(0.), btScalar(fSin*fBodySize)));
localB = m_bodies[1+2*i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA; localB = m_bodies[1+2*i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA;
hingeC = new btHingeConstraint(*m_bodies[0], *m_bodies[1+2*i], localA, localB); hingeC = new btHingeConstraint(*m_bodies[0], *m_bodies[1+2*i], localA, localB);
hingeC->setLimit(btScalar(-0.75 * M_PI_4), btScalar(M_PI_8)); hingeC->setLimit(btScalar(-0.75 * M_PI_4), btScalar(M_PI_8));
//hingeC->setLimit(btScalar(-0.1), btScalar(0.1)); //hingeC->setLimit(btScalar(-0.1), btScalar(0.1));
m_joints[2*i] = hingeC; m_joints[2*i] = hingeC;
m_ownerWorld->addConstraint(m_joints[2*i], true); m_ownerWorld->addConstraint(m_joints[2*i], true);
// knee joints // knee joints
localA.setIdentity(); localB.setIdentity(); localC.setIdentity(); localA.setIdentity(); localB.setIdentity(); localC.setIdentity();
localA.getBasis().setEulerZYX(0,-fAngle,0); localA.setOrigin(btVector3(btScalar(fCos*(fBodySize+fLegLength)), btScalar(0.), btScalar(fSin*(fBodySize+fLegLength)))); localA.getBasis().setEulerZYX(0,-fAngle,0); localA.setOrigin(btVector3(btScalar(fCos*(fBodySize+fLegLength)), btScalar(0.), btScalar(fSin*(fBodySize+fLegLength))));
localB = m_bodies[1+2*i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA; localB = m_bodies[1+2*i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA;
localC = m_bodies[2+2*i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA; localC = m_bodies[2+2*i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA;
hingeC = new btHingeConstraint(*m_bodies[1+2*i], *m_bodies[2+2*i], localB, localC); hingeC = new btHingeConstraint(*m_bodies[1+2*i], *m_bodies[2+2*i], localB, localC);
//hingeC->setLimit(btScalar(-0.01), btScalar(0.01)); //hingeC->setLimit(btScalar(-0.01), btScalar(0.01));
hingeC->setLimit(btScalar(-M_PI_8), btScalar(0.2)); hingeC->setLimit(btScalar(-M_PI_8), btScalar(0.2));
m_joints[1+2*i] = hingeC; m_joints[1+2*i] = hingeC;
m_ownerWorld->addConstraint(m_joints[1+2*i], true); m_ownerWorld->addConstraint(m_joints[1+2*i], true);
} }
} }
virtual ~TestRig () virtual ~TestRig ()
{ {
int i; int i;
// Remove all constraints // Remove all constraints
for ( i = 0; i < JOINT_COUNT; ++i) for ( i = 0; i < JOINT_COUNT; ++i)
{ {
m_ownerWorld->removeConstraint(m_joints[i]); m_ownerWorld->removeConstraint(m_joints[i]);
delete m_joints[i]; m_joints[i] = 0; delete m_joints[i]; m_joints[i] = 0;
} }
// Remove all bodies and shapes // Remove all bodies and shapes
for ( i = 0; i < BODYPART_COUNT; ++i) for ( i = 0; i < BODYPART_COUNT; ++i)
{ {
m_ownerWorld->removeRigidBody(m_bodies[i]); m_ownerWorld->removeRigidBody(m_bodies[i]);
delete m_bodies[i]->getMotionState(); delete m_bodies[i]->getMotionState();
delete m_bodies[i]; m_bodies[i] = 0; delete m_bodies[i]; m_bodies[i] = 0;
delete m_shapes[i]; m_shapes[i] = 0; delete m_shapes[i]; m_shapes[i] = 0;
} }
} }
btTypedConstraint** GetJoints() {return &m_joints[0];} btTypedConstraint** GetJoints() {return &m_joints[0];}
}; };
void motorPreTickCallback (btDynamicsWorld *world, btScalar timeStep) void motorPreTickCallback (btDynamicsWorld *world, btScalar timeStep)
{ {
MotorDemo* motorDemo = (MotorDemo*)world->getWorldUserInfo(); MotorDemo* motorDemo = (MotorDemo*)world->getWorldUserInfo();
motorDemo->setMotorTargets(timeStep); motorDemo->setMotorTargets(timeStep);
} }
void MotorDemo::initPhysics() void MotorDemo::initPhysics()
{ {
setTexturing(true); setTexturing(true);
setShadows(true); setShadows(true);
// Setup the basic world // Setup the basic world
m_Time = 0; m_Time = 0;
m_fCyclePeriod = 2000.f; // in milliseconds m_fCyclePeriod = 2000.f; // in milliseconds
// m_fMuscleStrength = 0.05f; // m_fMuscleStrength = 0.05f;
// new SIMD solver for joints clips accumulated impulse, so the new limits for the motor // new SIMD solver for joints clips accumulated impulse, so the new limits for the motor
// should be (numberOfsolverIterations * oldLimits) // should be (numberOfsolverIterations * oldLimits)
// currently solver uses 10 iterations, so: // currently solver uses 10 iterations, so:
m_fMuscleStrength = 0.5f; m_fMuscleStrength = 0.5f;
setCameraDistance(btScalar(5.)); setCameraDistance(btScalar(5.));
m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_collisionConfiguration = new btDefaultCollisionConfiguration();
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
btVector3 worldAabbMin(-10000,-10000,-10000); btVector3 worldAabbMin(-10000,-10000,-10000);
btVector3 worldAabbMax(10000,10000,10000); btVector3 worldAabbMax(10000,10000,10000);
m_broadphase = new btAxisSweep3 (worldAabbMin, worldAabbMax); m_broadphase = new btAxisSweep3 (worldAabbMin, worldAabbMax);
m_solver = new btSequentialImpulseConstraintSolver; m_solver = new btSequentialImpulseConstraintSolver;
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
m_dynamicsWorld->setInternalTickCallback(motorPreTickCallback,this,true); m_dynamicsWorld->setInternalTickCallback(motorPreTickCallback,this,true);
// Setup a big ground box // Setup a big ground box
{ {
btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.),btScalar(10.),btScalar(200.))); btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.),btScalar(10.),btScalar(200.)));
m_collisionShapes.push_back(groundShape); m_collisionShapes.push_back(groundShape);
btTransform groundTransform; btTransform groundTransform;
groundTransform.setIdentity(); groundTransform.setIdentity();
groundTransform.setOrigin(btVector3(0,-10,0)); groundTransform.setOrigin(btVector3(0,-10,0));
localCreateRigidBody(btScalar(0.),groundTransform,groundShape); localCreateRigidBody(btScalar(0.),groundTransform,groundShape);
} }
// Spawn one ragdoll // Spawn one ragdoll
btVector3 startOffset(1,0.5,0); btVector3 startOffset(1,0.5,0);
spawnTestRig(startOffset, false); spawnTestRig(startOffset, false);
startOffset.setValue(-2,0.5,0); startOffset.setValue(-2,0.5,0);
spawnTestRig(startOffset, true); spawnTestRig(startOffset, true);
clientResetScene(); clientResetScene();
} }
void MotorDemo::spawnTestRig(const btVector3& startOffset, bool bFixed) void MotorDemo::spawnTestRig(const btVector3& startOffset, bool bFixed)
{ {
TestRig* rig = new TestRig(m_dynamicsWorld, startOffset, bFixed); TestRig* rig = new TestRig(m_dynamicsWorld, startOffset, bFixed);
m_rigs.push_back(rig); m_rigs.push_back(rig);
} }
void PreStep() void PreStep()
{ {
} }
void MotorDemo::setMotorTargets(btScalar deltaTime) void MotorDemo::setMotorTargets(btScalar deltaTime)
{ {
float ms = deltaTime*1000000.; float ms = deltaTime*1000000.;
float minFPS = 1000000.f/60.f; float minFPS = 1000000.f/60.f;
if (ms > minFPS) if (ms > minFPS)
ms = minFPS; ms = minFPS;
m_Time += ms; m_Time += ms;
// //
// set per-frame sinusoidal position targets using angular motor (hacky?) // set per-frame sinusoidal position targets using angular motor (hacky?)
// //
for (int r=0; r<m_rigs.size(); r++) for (int r=0; r<m_rigs.size(); r++)
{ {
for (int i=0; i<2*NUM_LEGS; i++) for (int i=0; i<2*NUM_LEGS; i++)
{ {
btHingeConstraint* hingeC = static_cast<btHingeConstraint*>(m_rigs[r]->GetJoints()[i]); btHingeConstraint* hingeC = static_cast<btHingeConstraint*>(m_rigs[r]->GetJoints()[i]);
btScalar fCurAngle = hingeC->getHingeAngle(); btScalar fCurAngle = hingeC->getHingeAngle();
btScalar fTargetPercent = (int(m_Time / 1000) % int(m_fCyclePeriod)) / m_fCyclePeriod; btScalar fTargetPercent = (int(m_Time / 1000) % int(m_fCyclePeriod)) / m_fCyclePeriod;
btScalar fTargetAngle = 0.5 * (1 + sin(2 * M_PI * fTargetPercent)); btScalar fTargetAngle = 0.5 * (1 + sin(2 * M_PI * fTargetPercent));
btScalar fTargetLimitAngle = hingeC->getLowerLimit() + fTargetAngle * (hingeC->getUpperLimit() - hingeC->getLowerLimit()); btScalar fTargetLimitAngle = hingeC->getLowerLimit() + fTargetAngle * (hingeC->getUpperLimit() - hingeC->getLowerLimit());
btScalar fAngleError = fTargetLimitAngle - fCurAngle; btScalar fAngleError = fTargetLimitAngle - fCurAngle;
btScalar fDesiredAngularVel = 1000000.f * fAngleError/ms; btScalar fDesiredAngularVel = 1000000.f * fAngleError/ms;
hingeC->enableAngularMotor(true, fDesiredAngularVel, m_fMuscleStrength); hingeC->enableAngularMotor(true, fDesiredAngularVel, m_fMuscleStrength);
} }
} }
} }
void MotorDemo::clientMoveAndDisplay() void MotorDemo::clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//simple dynamics world doesn't handle fixed-time-stepping //simple dynamics world doesn't handle fixed-time-stepping
float deltaTime = getDeltaTimeMicroseconds()/1000000.f; float deltaTime = getDeltaTimeMicroseconds()/1000000.f;
if (m_dynamicsWorld) if (m_dynamicsWorld)
{ {
m_dynamicsWorld->stepSimulation(deltaTime); m_dynamicsWorld->stepSimulation(deltaTime);
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
} }
renderme(); renderme();
for (int i=2; i>=0 ;i--) for (int i=2; i>=0 ;i--)
{ {
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj); btRigidBody* body = btRigidBody::upcast(obj);
drawFrame(body->getWorldTransform()); drawFrame(body->getWorldTransform());
} }
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
void MotorDemo::displayCallback() void MotorDemo::displayCallback()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_dynamicsWorld) if (m_dynamicsWorld)
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
renderme(); renderme();
glFlush(); glFlush();
glutSwapBuffers(); glutSwapBuffers();
} }
void MotorDemo::keyboardCallback(unsigned char key, int x, int y) void MotorDemo::keyboardCallback(unsigned char key, int x, int y)
{ {
switch (key) switch (key)
{ {
case '+': case '=': case '+': case '=':
m_fCyclePeriod /= 1.1f; m_fCyclePeriod /= 1.1f;
if (m_fCyclePeriod < 1.f) if (m_fCyclePeriod < 1.f)
m_fCyclePeriod = 1.f; m_fCyclePeriod = 1.f;
break; break;
case '-': case '_': case '-': case '_':
m_fCyclePeriod *= 1.1f; m_fCyclePeriod *= 1.1f;
break; break;
case '[': case '[':
m_fMuscleStrength /= 1.1f; m_fMuscleStrength /= 1.1f;
break; break;
case ']': case ']':
m_fMuscleStrength *= 1.1f; m_fMuscleStrength *= 1.1f;
break; break;
default: default:
DemoApplication::keyboardCallback(key, x, y); DemoApplication::keyboardCallback(key, x, y);
} }
} }
void MotorDemo::exitPhysics() void MotorDemo::exitPhysics()
{ {
int i; int i;
for (i=0;i<m_rigs.size();i++) for (i=0;i<m_rigs.size();i++)
{ {
TestRig* rig = m_rigs[i]; TestRig* rig = m_rigs[i];
delete rig; delete rig;
} }
//cleanup in the reverse order of creation/initialization //cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them //remove the rigidbodies from the dynamics world and delete them
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{ {
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj); btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState()) if (body && body->getMotionState())
{ {
delete body->getMotionState(); delete body->getMotionState();
} }
m_dynamicsWorld->removeCollisionObject( obj ); m_dynamicsWorld->removeCollisionObject( obj );
delete obj; delete obj;
} }
//delete collision shapes //delete collision shapes
for (int j=0;j<m_collisionShapes.size();j++) for (int j=0;j<m_collisionShapes.size();j++)
{ {
btCollisionShape* shape = m_collisionShapes[j]; btCollisionShape* shape = m_collisionShapes[j];
delete shape; delete shape;
} }
//delete dynamics world //delete dynamics world
delete m_dynamicsWorld; delete m_dynamicsWorld;
//delete solver //delete solver
delete m_solver; delete m_solver;
//delete broadphase //delete broadphase
delete m_broadphase; delete m_broadphase;
//delete dispatcher //delete dispatcher
delete m_dispatcher; delete m_dispatcher;
delete m_collisionConfiguration; delete m_collisionConfiguration;
} }

View File

@@ -1,80 +1,80 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Copyright (c) 2007 Erwin Coumans Bullet Continuous Collision Detection and Physics Library Copyright (c) 2007 Erwin Coumans
Motor Demo Motor Demo
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef MOTORDEMO_H #ifndef MOTORDEMO_H
#define MOTORDEMO_H #define MOTORDEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
class MotorDemo : public GlutDemoApplication class MotorDemo : public GlutDemoApplication
{ {
float m_Time; float m_Time;
float m_fCyclePeriod; // in milliseconds float m_fCyclePeriod; // in milliseconds
float m_fMuscleStrength; float m_fMuscleStrength;
btAlignedObjectArray<class TestRig*> m_rigs; btAlignedObjectArray<class TestRig*> m_rigs;
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
public: public:
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual ~MotorDemo() virtual ~MotorDemo()
{ {
exitPhysics(); exitPhysics();
} }
void spawnTestRig(const btVector3& startOffset, bool bFixed); void spawnTestRig(const btVector3& startOffset, bool bFixed);
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
static DemoApplication* Create() static DemoApplication* Create()
{ {
MotorDemo* demo = new MotorDemo(); MotorDemo* demo = new MotorDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
void setMotorTargets(btScalar deltaTime); void setMotorTargets(btScalar deltaTime);
}; };
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,59 +1,59 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# This is the variable for Windows. I use this to define the root of my directory structure. # This is the variable for Windows. I use this to define the root of my directory structure.
SET(GLUT_ROOT ${BULLET_PHYSICS_SOURCE_DIR}/Glut) SET(GLUT_ROOT ${BULLET_PHYSICS_SOURCE_DIR}/Glut)
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
IF (WIN32) IF (WIN32)
ADD_EXECUTABLE(AppForkLiftDemo ADD_EXECUTABLE(AppForkLiftDemo
ForkLiftDemo.cpp ForkLiftDemo.cpp
main.cpp main.cpp
${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc ${BULLET_PHYSICS_SOURCE_DIR}/msvc/bullet.rc
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppForkLiftDemo TARGET AppForkLiftDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppForkLiftDemo TARGET AppForkLiftDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
ELSE() ELSE()
ADD_EXECUTABLE(AppForkLiftDemo ADD_EXECUTABLE(AppForkLiftDemo
ForkLiftDemo.cpp ForkLiftDemo.cpp
main.cpp main.cpp
) )
ENDIF() ENDIF()
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppForkLiftDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppForkLiftDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppForkLiftDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppForkLiftDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppForkLiftDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppForkLiftDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

File diff suppressed because it is too large Load Diff

View File

@@ -1,113 +1,113 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef FORKLIFT_DEMO_H #ifndef FORKLIFT_DEMO_H
#define FORKLIFT_DEMO_H #define FORKLIFT_DEMO_H
class btVehicleTuning; class btVehicleTuning;
struct btVehicleRaycaster; struct btVehicleRaycaster;
class btCollisionShape; class btCollisionShape;
#include "BulletDynamics/Vehicle/btRaycastVehicle.h" #include "BulletDynamics/Vehicle/btRaycastVehicle.h"
#include "BulletDynamics/ConstraintSolver/btHingeConstraint.h" #include "BulletDynamics/ConstraintSolver/btHingeConstraint.h"
#include "BulletDynamics/ConstraintSolver/btSliderConstraint.h" #include "BulletDynamics/ConstraintSolver/btSliderConstraint.h"
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
///VehicleDemo shows how to setup and use the built-in raycast vehicle ///VehicleDemo shows how to setup and use the built-in raycast vehicle
class ForkLiftDemo : public GlutDemoApplication class ForkLiftDemo : public GlutDemoApplication
{ {
public: public:
btRigidBody* m_carChassis; btRigidBody* m_carChassis;
//---------------------------- //----------------------------
btRigidBody* m_liftBody; btRigidBody* m_liftBody;
btVector3 m_liftStartPos; btVector3 m_liftStartPos;
btHingeConstraint* m_liftHinge; btHingeConstraint* m_liftHinge;
btRigidBody* m_forkBody; btRigidBody* m_forkBody;
btVector3 m_forkStartPos; btVector3 m_forkStartPos;
btSliderConstraint* m_forkSlider; btSliderConstraint* m_forkSlider;
btRigidBody* m_loadBody; btRigidBody* m_loadBody;
btVector3 m_loadStartPos; btVector3 m_loadStartPos;
void lockLiftHinge(void); void lockLiftHinge(void);
void lockForkSlider(void); void lockForkSlider(void);
bool m_useDefaultCamera; bool m_useDefaultCamera;
//---------------------------- //----------------------------
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
class btBroadphaseInterface* m_overlappingPairCache; class btBroadphaseInterface* m_overlappingPairCache;
class btCollisionDispatcher* m_dispatcher; class btCollisionDispatcher* m_dispatcher;
class btConstraintSolver* m_constraintSolver; class btConstraintSolver* m_constraintSolver;
class btDefaultCollisionConfiguration* m_collisionConfiguration; class btDefaultCollisionConfiguration* m_collisionConfiguration;
class btTriangleIndexVertexArray* m_indexVertexArrays; class btTriangleIndexVertexArray* m_indexVertexArrays;
btVector3* m_vertices; btVector3* m_vertices;
btRaycastVehicle::btVehicleTuning m_tuning; btRaycastVehicle::btVehicleTuning m_tuning;
btVehicleRaycaster* m_vehicleRayCaster; btVehicleRaycaster* m_vehicleRayCaster;
btRaycastVehicle* m_vehicle; btRaycastVehicle* m_vehicle;
btCollisionShape* m_wheelShape; btCollisionShape* m_wheelShape;
float m_cameraHeight; float m_cameraHeight;
float m_minCameraDistance; float m_minCameraDistance;
float m_maxCameraDistance; float m_maxCameraDistance;
ForkLiftDemo(); ForkLiftDemo();
virtual ~ForkLiftDemo(); virtual ~ForkLiftDemo();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void clientResetScene(); virtual void clientResetScene();
virtual void displayCallback(); virtual void displayCallback();
///a very basic camera following the vehicle ///a very basic camera following the vehicle
virtual void updateCamera(); virtual void updateCamera();
virtual void specialKeyboard(int key, int x, int y); virtual void specialKeyboard(int key, int x, int y);
virtual void specialKeyboardUp(int key, int x, int y); virtual void specialKeyboardUp(int key, int x, int y);
void renderme(); void renderme();
void initPhysics(); void initPhysics();
void termPhysics(); void termPhysics();
static DemoApplication* Create() static DemoApplication* Create()
{ {
ForkLiftDemo* demo = new ForkLiftDemo(); ForkLiftDemo* demo = new ForkLiftDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
#endif // FORKLIFT_DEMO_H #endif // FORKLIFT_DEMO_H

View File

@@ -1,135 +1,135 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Ragdoll Demo Ragdoll Demo
Copyright (c) 2007 Starbreeze Studios Copyright (c) 2007 Starbreeze Studios
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
Originally Written by: Marten Svanfeldt Originally Written by: Marten Svanfeldt
ReWritten by: Francisco Le<4C>n ReWritten by: Francisco Le<4C>n
*/ */
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GL_ShapeDrawer.h" #include "GL_ShapeDrawer.h"
#include "LinearMath/btIDebugDraw.h" #include "LinearMath/btIDebugDraw.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "GenericJointDemo.h" #include "GenericJointDemo.h"
GLDebugDrawer debugDrawer; GLDebugDrawer debugDrawer;
void GenericJointDemo::initPhysics() void GenericJointDemo::initPhysics()
{ {
setTexturing(true); setTexturing(true);
setShadows(true); setShadows(true);
// Setup the basic world // Setup the basic world
btDefaultCollisionConfiguration * collision_config = new btDefaultCollisionConfiguration(); btDefaultCollisionConfiguration * collision_config = new btDefaultCollisionConfiguration();
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collision_config); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collision_config);
btVector3 worldAabbMin(-10000,-10000,-10000); btVector3 worldAabbMin(-10000,-10000,-10000);
btVector3 worldAabbMax(10000,10000,10000); btVector3 worldAabbMax(10000,10000,10000);
btBroadphaseInterface* overlappingPairCache = new btAxisSweep3 (worldAabbMin, worldAabbMax); btBroadphaseInterface* overlappingPairCache = new btAxisSweep3 (worldAabbMin, worldAabbMax);
btConstraintSolver* constraintSolver = new btSequentialImpulseConstraintSolver; btConstraintSolver* constraintSolver = new btSequentialImpulseConstraintSolver;
m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,overlappingPairCache,constraintSolver,collision_config); m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,overlappingPairCache,constraintSolver,collision_config);
m_dynamicsWorld->setGravity(btVector3(0,-30,0)); m_dynamicsWorld->setGravity(btVector3(0,-30,0));
m_dynamicsWorld->setDebugDrawer(&debugDrawer); m_dynamicsWorld->setDebugDrawer(&debugDrawer);
// Setup a big ground box // Setup a big ground box
{ {
btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.),btScalar(10.),btScalar(200.))); btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.),btScalar(10.),btScalar(200.)));
btTransform groundTransform; btTransform groundTransform;
groundTransform.setIdentity(); groundTransform.setIdentity();
groundTransform.setOrigin(btVector3(0,-15,0)); groundTransform.setOrigin(btVector3(0,-15,0));
localCreateRigidBody(btScalar(0.),groundTransform,groundShape); localCreateRigidBody(btScalar(0.),groundTransform,groundShape);
} }
// Spawn one ragdoll // Spawn one ragdoll
spawnRagdoll(); spawnRagdoll();
clientResetScene(); clientResetScene();
} }
void GenericJointDemo::spawnRagdoll(bool random) void GenericJointDemo::spawnRagdoll(bool random)
{ {
RagDoll* ragDoll = new RagDoll (m_dynamicsWorld, btVector3 (0,0,10),5.f); RagDoll* ragDoll = new RagDoll (m_dynamicsWorld, btVector3 (0,0,10),5.f);
m_ragdolls.push_back(ragDoll); m_ragdolls.push_back(ragDoll);
} }
void GenericJointDemo::clientMoveAndDisplay() void GenericJointDemo::clientMoveAndDisplay()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//simple dynamics world doesn't handle fixed-time-stepping //simple dynamics world doesn't handle fixed-time-stepping
float ms = getDeltaTimeMicroseconds(); float ms = getDeltaTimeMicroseconds();
float minFPS = 1000000.f/60.f; float minFPS = 1000000.f/60.f;
if (ms > minFPS) if (ms > minFPS)
ms = minFPS; ms = minFPS;
if (m_dynamicsWorld) if (m_dynamicsWorld)
{ {
m_dynamicsWorld->stepSimulation(ms / 1000000.f); m_dynamicsWorld->stepSimulation(ms / 1000000.f);
//optional but useful: debug drawing //optional but useful: debug drawing
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
} }
renderme(); renderme();
glFlush(); glFlush();
swapBuffers(); swapBuffers();
} }
void GenericJointDemo::displayCallback() void GenericJointDemo::displayCallback()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_dynamicsWorld) if (m_dynamicsWorld)
m_dynamicsWorld->debugDrawWorld(); m_dynamicsWorld->debugDrawWorld();
renderme(); renderme();
glFlush(); glFlush();
swapBuffers(); swapBuffers();
} }
void GenericJointDemo::keyboardCallback(unsigned char key, int x, int y) void GenericJointDemo::keyboardCallback(unsigned char key, int x, int y)
{ {
switch (key) switch (key)
{ {
case 'e': case 'e':
spawnRagdoll(true); spawnRagdoll(true);
break; break;
default: default:
DemoApplication::keyboardCallback(key, x, y); DemoApplication::keyboardCallback(key, x, y);
} }
} }

View File

@@ -1,51 +1,51 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
GenericJointDemo GenericJointDemo
Copyright (c) 2007 Starbreeze Studios Copyright (c) 2007 Starbreeze Studios
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
Written by: Marten Svanfeldt Written by: Marten Svanfeldt
*/ */
#ifndef GENERIGJOINTDEMO_H #ifndef GENERIGJOINTDEMO_H
#define GENERIGJOINTDEMO_H #define GENERIGJOINTDEMO_H
#ifdef _WINDOWS #ifdef _WINDOWS
#include "Win32DemoApplication.h" #include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication #define PlatformDemoApplication Win32DemoApplication
#else #else
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication #define PlatformDemoApplication GlutDemoApplication
#endif #endif
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
#include "Ragdoll.h" #include "Ragdoll.h"
class GenericJointDemo : public PlatformDemoApplication class GenericJointDemo : public PlatformDemoApplication
{ {
btAlignedObjectArray<class RagDoll*> m_ragdolls; btAlignedObjectArray<class RagDoll*> m_ragdolls;
public: public:
void initPhysics(); void initPhysics();
void spawnRagdoll(bool random = false); void spawnRagdoll(bool random = false);
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
}; };
#endif #endif

View File

@@ -1,373 +1,373 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Ragdoll Demo Ragdoll Demo
Copyright (c) 2007 Starbreeze Studios Copyright (c) 2007 Starbreeze Studios
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
Written by: Marten Svanfeldt Written by: Marten Svanfeldt
*/ */
#include "Ragdoll.h" #include "Ragdoll.h"
//#define RIGID 1 //#define RIGID 1
RagDoll::RagDoll (btDynamicsWorld* ownerWorld, const btVector3& positionOffset, RagDoll::RagDoll (btDynamicsWorld* ownerWorld, const btVector3& positionOffset,
btScalar scale_ragdoll) : m_ownerWorld (ownerWorld) btScalar scale_ragdoll) : m_ownerWorld (ownerWorld)
{ {
// Setup the geometry // Setup the geometry
m_shapes[BODYPART_PELVIS] = new btCapsuleShape( m_shapes[BODYPART_PELVIS] = new btCapsuleShape(
btScalar(scale_ragdoll*0.15), btScalar(scale_ragdoll*0.20)); btScalar(scale_ragdoll*0.15), btScalar(scale_ragdoll*0.20));
m_shapes[BODYPART_SPINE] = new btCapsuleShape( m_shapes[BODYPART_SPINE] = new btCapsuleShape(
btScalar(scale_ragdoll*0.15), btScalar(scale_ragdoll*0.28)); btScalar(scale_ragdoll*0.15), btScalar(scale_ragdoll*0.28));
m_shapes[BODYPART_HEAD] = new btCapsuleShape(btScalar(scale_ragdoll*0.10), btScalar(scale_ragdoll*0.05)); m_shapes[BODYPART_HEAD] = new btCapsuleShape(btScalar(scale_ragdoll*0.10), btScalar(scale_ragdoll*0.05));
m_shapes[BODYPART_LEFT_UPPER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.07), btScalar(scale_ragdoll*0.45)); m_shapes[BODYPART_LEFT_UPPER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.07), btScalar(scale_ragdoll*0.45));
m_shapes[BODYPART_LEFT_LOWER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.37)); m_shapes[BODYPART_LEFT_LOWER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.37));
m_shapes[BODYPART_RIGHT_UPPER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.07), btScalar(scale_ragdoll*0.45)); m_shapes[BODYPART_RIGHT_UPPER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.07), btScalar(scale_ragdoll*0.45));
m_shapes[BODYPART_RIGHT_LOWER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.37)); m_shapes[BODYPART_RIGHT_LOWER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.37));
m_shapes[BODYPART_LEFT_UPPER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.33)); m_shapes[BODYPART_LEFT_UPPER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.33));
m_shapes[BODYPART_LEFT_LOWER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.04), btScalar(scale_ragdoll*0.25)); m_shapes[BODYPART_LEFT_LOWER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.04), btScalar(scale_ragdoll*0.25));
m_shapes[BODYPART_RIGHT_UPPER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.33)); m_shapes[BODYPART_RIGHT_UPPER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.33));
m_shapes[BODYPART_RIGHT_LOWER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.04), btScalar(scale_ragdoll*0.25)); m_shapes[BODYPART_RIGHT_LOWER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.04), btScalar(scale_ragdoll*0.25));
// Setup all the rigid bodies // Setup all the rigid bodies
btTransform offset; offset.setIdentity(); btTransform offset; offset.setIdentity();
offset.setOrigin(positionOffset); offset.setOrigin(positionOffset);
btTransform transform; btTransform transform;
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.), btScalar(0.)));
m_bodies[BODYPART_PELVIS] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_PELVIS]); m_bodies[BODYPART_PELVIS] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_PELVIS]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.2), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.2), btScalar(0.)));
m_bodies[BODYPART_SPINE] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_SPINE]); m_bodies[BODYPART_SPINE] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_SPINE]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.6), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.6), btScalar(0.)));
m_bodies[BODYPART_HEAD] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_HEAD]); m_bodies[BODYPART_HEAD] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_HEAD]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(0.65*scale_ragdoll), transform.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(0.65*scale_ragdoll),
btScalar(0.))); btScalar(0.)));
m_bodies[BODYPART_LEFT_UPPER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_LEG]); m_bodies[BODYPART_LEFT_UPPER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_LEG]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(0.2*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(0.2*scale_ragdoll), btScalar(0.)));
m_bodies[BODYPART_LEFT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_LEG]); m_bodies[BODYPART_LEFT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_LEG]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(0.65*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(0.65*scale_ragdoll), btScalar(0.)));
m_bodies[BODYPART_RIGHT_UPPER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_LEG]); m_bodies[BODYPART_RIGHT_UPPER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_LEG]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(0.2*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(0.2*scale_ragdoll), btScalar(0.)));
m_bodies[BODYPART_RIGHT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_LEG]); m_bodies[BODYPART_RIGHT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_LEG]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(-0.35*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(-0.35*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
transform.getBasis().setEulerZYX(0,0,SIMD_HALF_PI); transform.getBasis().setEulerZYX(0,0,SIMD_HALF_PI);
m_bodies[BODYPART_LEFT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_ARM]); m_bodies[BODYPART_LEFT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_ARM]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(-0.7*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(-0.7*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
transform.getBasis().setEulerZYX(0,0,SIMD_HALF_PI); transform.getBasis().setEulerZYX(0,0,SIMD_HALF_PI);
m_bodies[BODYPART_LEFT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_ARM]); m_bodies[BODYPART_LEFT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_ARM]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.35*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.35*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
transform.getBasis().setEulerZYX(0,0,-SIMD_HALF_PI); transform.getBasis().setEulerZYX(0,0,-SIMD_HALF_PI);
m_bodies[BODYPART_RIGHT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_ARM]); m_bodies[BODYPART_RIGHT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_ARM]);
transform.setIdentity(); transform.setIdentity();
transform.setOrigin(btVector3(btScalar(0.7*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.))); transform.setOrigin(btVector3(btScalar(0.7*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
transform.getBasis().setEulerZYX(0,0,-SIMD_HALF_PI); transform.getBasis().setEulerZYX(0,0,-SIMD_HALF_PI);
m_bodies[BODYPART_RIGHT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_ARM]); m_bodies[BODYPART_RIGHT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_ARM]);
// Setup some damping on the m_bodies // Setup some damping on the m_bodies
for (int i = 0; i < BODYPART_COUNT; ++i) for (int i = 0; i < BODYPART_COUNT; ++i)
{ {
m_bodies[i]->setDamping(0.05f, 0.85f); m_bodies[i]->setDamping(0.05f, 0.85f);
m_bodies[i]->setDeactivationTime(0.8f); m_bodies[i]->setDeactivationTime(0.8f);
m_bodies[i]->setSleepingThresholds(1.6f, 2.5f); m_bodies[i]->setSleepingThresholds(1.6f, 2.5f);
} }
///////////////////////////// SETTING THE CONSTRAINTS /////////////////////////////////////////////7777 ///////////////////////////// SETTING THE CONSTRAINTS /////////////////////////////////////////////7777
// Now setup the constraints // Now setup the constraints
btGeneric6DofConstraint * joint6DOF; btGeneric6DofConstraint * joint6DOF;
btTransform localA, localB; btTransform localA, localB;
bool useLinearReferenceFrameA = true; bool useLinearReferenceFrameA = true;
/// ******* SPINE HEAD ******** /// /// ******* SPINE HEAD ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.), btScalar(0.30*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.30*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_HEAD], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_HEAD], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.3f,-SIMD_EPSILON,-SIMD_PI*0.3f)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.3f,-SIMD_EPSILON,-SIMD_PI*0.3f));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.5f,SIMD_EPSILON,SIMD_PI*0.3f)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.5f,SIMD_EPSILON,SIMD_PI*0.3f));
#endif #endif
m_joints[JOINT_SPINE_HEAD] = joint6DOF; m_joints[JOINT_SPINE_HEAD] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_SPINE_HEAD], true); m_ownerWorld->addConstraint(m_joints[JOINT_SPINE_HEAD], true);
} }
/// *************************** /// /// *************************** ///
/// ******* LEFT SHOULDER ******** /// /// ******* LEFT SHOULDER ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(-0.2*scale_ragdoll), btScalar(0.15*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(-0.2*scale_ragdoll), btScalar(0.15*scale_ragdoll), btScalar(0.)));
localB.getBasis().setEulerZYX(SIMD_HALF_PI,0,-SIMD_HALF_PI); localB.getBasis().setEulerZYX(SIMD_HALF_PI,0,-SIMD_HALF_PI);
localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.18*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.18*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_LEFT_UPPER_ARM], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_LEFT_UPPER_ARM], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.8f,-SIMD_EPSILON,-SIMD_PI*0.5f)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.8f,-SIMD_EPSILON,-SIMD_PI*0.5f));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.8f,SIMD_EPSILON,SIMD_PI*0.5f)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.8f,SIMD_EPSILON,SIMD_PI*0.5f));
#endif #endif
m_joints[JOINT_LEFT_SHOULDER] = joint6DOF; m_joints[JOINT_LEFT_SHOULDER] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_SHOULDER], true); m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_SHOULDER], true);
} }
/// *************************** /// /// *************************** ///
/// ******* RIGHT SHOULDER ******** /// /// ******* RIGHT SHOULDER ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.2*scale_ragdoll), btScalar(0.15*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.2*scale_ragdoll), btScalar(0.15*scale_ragdoll), btScalar(0.)));
localB.getBasis().setEulerZYX(0,0,SIMD_HALF_PI); localB.getBasis().setEulerZYX(0,0,SIMD_HALF_PI);
localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.18*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.18*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_RIGHT_UPPER_ARM], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_RIGHT_UPPER_ARM], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.8f,-SIMD_EPSILON,-SIMD_PI*0.5f)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.8f,-SIMD_EPSILON,-SIMD_PI*0.5f));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.8f,SIMD_EPSILON,SIMD_PI*0.5f)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.8f,SIMD_EPSILON,SIMD_PI*0.5f));
#endif #endif
m_joints[JOINT_RIGHT_SHOULDER] = joint6DOF; m_joints[JOINT_RIGHT_SHOULDER] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_SHOULDER], true); m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_SHOULDER], true);
} }
/// *************************** /// /// *************************** ///
/// ******* LEFT ELBOW ******** /// /// ******* LEFT ELBOW ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_LEFT_UPPER_ARM], *m_bodies[BODYPART_LEFT_LOWER_ARM], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_LEFT_UPPER_ARM], *m_bodies[BODYPART_LEFT_LOWER_ARM], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON));
#endif #endif
m_joints[JOINT_LEFT_ELBOW] = joint6DOF; m_joints[JOINT_LEFT_ELBOW] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_ELBOW], true); m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_ELBOW], true);
} }
/// *************************** /// /// *************************** ///
/// ******* RIGHT ELBOW ******** /// /// ******* RIGHT ELBOW ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_RIGHT_UPPER_ARM], *m_bodies[BODYPART_RIGHT_LOWER_ARM], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_RIGHT_UPPER_ARM], *m_bodies[BODYPART_RIGHT_LOWER_ARM], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7,SIMD_EPSILON,SIMD_EPSILON));
#endif #endif
m_joints[JOINT_RIGHT_ELBOW] = joint6DOF; m_joints[JOINT_RIGHT_ELBOW] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_ELBOW], true); m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_ELBOW], true);
} }
/// *************************** /// /// *************************** ///
/// ******* PELVIS ******** /// /// ******* PELVIS ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.getBasis().setEulerZYX(0,SIMD_HALF_PI,0); localA.getBasis().setEulerZYX(0,SIMD_HALF_PI,0);
localA.setOrigin(btVector3(btScalar(0.), btScalar(0.15*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.), btScalar(0.15*scale_ragdoll), btScalar(0.)));
localB.getBasis().setEulerZYX(0,SIMD_HALF_PI,0); localB.getBasis().setEulerZYX(0,SIMD_HALF_PI,0);
localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.15*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.15*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_SPINE], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_SPINE], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.2,-SIMD_EPSILON,-SIMD_PI*0.3)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.2,-SIMD_EPSILON,-SIMD_PI*0.3));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.2,SIMD_EPSILON,SIMD_PI*0.6)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.2,SIMD_EPSILON,SIMD_PI*0.6));
#endif #endif
m_joints[JOINT_PELVIS_SPINE] = joint6DOF; m_joints[JOINT_PELVIS_SPINE] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_PELVIS_SPINE], true); m_ownerWorld->addConstraint(m_joints[JOINT_PELVIS_SPINE], true);
} }
/// *************************** /// /// *************************** ///
/// ******* LEFT HIP ******** /// /// ******* LEFT HIP ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(-0.10*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(-0.10*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(0.225*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.225*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_LEFT_UPPER_LEG], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_LEFT_UPPER_LEG], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_HALF_PI*0.5,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_HALF_PI*0.5,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_HALF_PI*0.8,SIMD_EPSILON,SIMD_HALF_PI*0.6f)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_HALF_PI*0.8,SIMD_EPSILON,SIMD_HALF_PI*0.6f));
#endif #endif
m_joints[JOINT_LEFT_HIP] = joint6DOF; m_joints[JOINT_LEFT_HIP] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_HIP], true); m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_HIP], true);
} }
/// *************************** /// /// *************************** ///
/// ******* RIGHT HIP ******** /// /// ******* RIGHT HIP ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(-0.10*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(-0.10*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(0.225*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.225*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_RIGHT_UPPER_LEG], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_RIGHT_UPPER_LEG], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_HALF_PI*0.5,-SIMD_EPSILON,-SIMD_HALF_PI*0.6f)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_HALF_PI*0.5,-SIMD_EPSILON,-SIMD_HALF_PI*0.6f));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_HALF_PI*0.8,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_HALF_PI*0.8,SIMD_EPSILON,SIMD_EPSILON));
#endif #endif
m_joints[JOINT_RIGHT_HIP] = joint6DOF; m_joints[JOINT_RIGHT_HIP] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_HIP], true); m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_HIP], true);
} }
/// *************************** /// /// *************************** ///
/// ******* LEFT KNEE ******** /// /// ******* LEFT KNEE ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_LEFT_UPPER_LEG], *m_bodies[BODYPART_LEFT_LOWER_LEG], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_LEFT_UPPER_LEG], *m_bodies[BODYPART_LEFT_LOWER_LEG], localA, localB,useLinearReferenceFrameA);
// //
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON));
#endif #endif
m_joints[JOINT_LEFT_KNEE] = joint6DOF; m_joints[JOINT_LEFT_KNEE] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_KNEE], true); m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_KNEE], true);
} }
/// *************************** /// /// *************************** ///
/// ******* RIGHT KNEE ******** /// /// ******* RIGHT KNEE ******** ///
{ {
localA.setIdentity(); localB.setIdentity(); localA.setIdentity(); localB.setIdentity();
localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225*scale_ragdoll), btScalar(0.))); localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225*scale_ragdoll), btScalar(0.)));
localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185*scale_ragdoll), btScalar(0.))); localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185*scale_ragdoll), btScalar(0.)));
joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_RIGHT_UPPER_LEG], *m_bodies[BODYPART_RIGHT_LOWER_LEG], localA, localB,useLinearReferenceFrameA); joint6DOF = new btGeneric6DofConstraint (*m_bodies[BODYPART_RIGHT_UPPER_LEG], *m_bodies[BODYPART_RIGHT_LOWER_LEG], localA, localB,useLinearReferenceFrameA);
#ifdef RIGID #ifdef RIGID
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else #else
joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON)); joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON)); joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON));
#endif #endif
m_joints[JOINT_RIGHT_KNEE] = joint6DOF; m_joints[JOINT_RIGHT_KNEE] = joint6DOF;
m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_KNEE], true); m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_KNEE], true);
} }
/// *************************** /// /// *************************** ///
} }
RagDoll::~RagDoll() RagDoll::~RagDoll()
{ {
int i; int i;
// Remove all constraints // Remove all constraints
for (i = 0; i < JOINT_COUNT; ++i) for (i = 0; i < JOINT_COUNT; ++i)
{ {
m_ownerWorld->removeConstraint(m_joints[i]); m_ownerWorld->removeConstraint(m_joints[i]);
delete m_joints[i]; m_joints[i] = 0; delete m_joints[i]; m_joints[i] = 0;
} }
// Remove all bodies and shapes // Remove all bodies and shapes
for (i = 0; i < BODYPART_COUNT; ++i) for (i = 0; i < BODYPART_COUNT; ++i)
{ {
m_ownerWorld->removeRigidBody(m_bodies[i]); m_ownerWorld->removeRigidBody(m_bodies[i]);
delete m_bodies[i]->getMotionState(); delete m_bodies[i]->getMotionState();
delete m_bodies[i]; m_bodies[i] = 0; delete m_bodies[i]; m_bodies[i] = 0;
delete m_shapes[i]; m_shapes[i] = 0; delete m_shapes[i]; m_shapes[i] = 0;
} }
} }
btRigidBody* RagDoll::localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape) btRigidBody* RagDoll::localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape)
{ {
bool isDynamic = (mass != 0.f); bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0); btVector3 localInertia(0,0,0);
if (isDynamic) if (isDynamic)
shape->calculateLocalInertia(mass,localInertia); shape->calculateLocalInertia(mass,localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia);
rbInfo.m_additionalDamping = true; rbInfo.m_additionalDamping = true;
btRigidBody* body = new btRigidBody(rbInfo); btRigidBody* body = new btRigidBody(rbInfo);
m_ownerWorld->addRigidBody(body); m_ownerWorld->addRigidBody(body);
return body; return body;
} }

View File

@@ -1,71 +1,71 @@
#ifndef RAGDOLL_H_INCLUDED #ifndef RAGDOLL_H_INCLUDED
#define RAGDOLL_H_INCLUDED #define RAGDOLL_H_INCLUDED
#include "DemoApplication.h" #include "DemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
class RagDoll class RagDoll
{ {
enum enum
{ {
BODYPART_PELVIS = 0, BODYPART_PELVIS = 0,
BODYPART_SPINE, BODYPART_SPINE,
BODYPART_HEAD, BODYPART_HEAD,
BODYPART_LEFT_UPPER_LEG, BODYPART_LEFT_UPPER_LEG,
BODYPART_LEFT_LOWER_LEG, BODYPART_LEFT_LOWER_LEG,
BODYPART_RIGHT_UPPER_LEG, BODYPART_RIGHT_UPPER_LEG,
BODYPART_RIGHT_LOWER_LEG, BODYPART_RIGHT_LOWER_LEG,
BODYPART_LEFT_UPPER_ARM, BODYPART_LEFT_UPPER_ARM,
BODYPART_LEFT_LOWER_ARM, BODYPART_LEFT_LOWER_ARM,
BODYPART_RIGHT_UPPER_ARM, BODYPART_RIGHT_UPPER_ARM,
BODYPART_RIGHT_LOWER_ARM, BODYPART_RIGHT_LOWER_ARM,
BODYPART_COUNT BODYPART_COUNT
}; };
enum enum
{ {
JOINT_PELVIS_SPINE = 0, JOINT_PELVIS_SPINE = 0,
JOINT_SPINE_HEAD, JOINT_SPINE_HEAD,
JOINT_LEFT_HIP, JOINT_LEFT_HIP,
JOINT_LEFT_KNEE, JOINT_LEFT_KNEE,
JOINT_RIGHT_HIP, JOINT_RIGHT_HIP,
JOINT_RIGHT_KNEE, JOINT_RIGHT_KNEE,
JOINT_LEFT_SHOULDER, JOINT_LEFT_SHOULDER,
JOINT_LEFT_ELBOW, JOINT_LEFT_ELBOW,
JOINT_RIGHT_SHOULDER, JOINT_RIGHT_SHOULDER,
JOINT_RIGHT_ELBOW, JOINT_RIGHT_ELBOW,
JOINT_COUNT JOINT_COUNT
}; };
btDynamicsWorld* m_ownerWorld; btDynamicsWorld* m_ownerWorld;
btCollisionShape* m_shapes[BODYPART_COUNT]; btCollisionShape* m_shapes[BODYPART_COUNT];
btRigidBody* m_bodies[BODYPART_COUNT]; btRigidBody* m_bodies[BODYPART_COUNT];
btTypedConstraint* m_joints[JOINT_COUNT]; btTypedConstraint* m_joints[JOINT_COUNT];
btRigidBody* localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape); btRigidBody* localCreateRigidBody (btScalar mass, const btTransform& startTransform, btCollisionShape* shape);
public: public:
RagDoll (btDynamicsWorld* ownerWorld, RagDoll (btDynamicsWorld* ownerWorld,
const btVector3& positionOffset, const btVector3& positionOffset,
btScalar scale_ragdoll = btScalar(1.0)); btScalar scale_ragdoll = btScalar(1.0));
~RagDoll (); ~RagDoll ();
}; };
#endif // RAGDOLL_H_INCLUDED #endif // RAGDOLL_H_INCLUDED

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "GenericJointDemo.h" #include "GenericJointDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new GenericJointDemo(); return new GenericJointDemo();
} }
#endif #endif

View File

@@ -1,28 +1,28 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2010 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2010 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "GenericJointDemo.h" #include "GenericJointDemo.h"
int main(int argc,char* argv[]) int main(int argc,char* argv[])
{ {
GenericJointDemo demoApp; GenericJointDemo demoApp;
// demoApp.configDebugDrawer(&debugDrawer); // demoApp.configDebugDrawer(&debugDrawer);
demoApp.initPhysics(); demoApp.initPhysics();
demoApp.setCameraDistance(btScalar(10.)); demoApp.setCameraDistance(btScalar(10.));
return glutmain(argc, argv,640,480,"Joint 6DOF - Sequencial Impulse Solver",&demoApp); return glutmain(argc, argv,640,480,"Joint 6DOF - Sequencial Impulse Solver",&demoApp);
} }

View File

@@ -1,25 +1,25 @@
#ifdef _WINDOWS #ifdef _WINDOWS
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "GimpactTestDemo.h" #include "GimpactTestDemo.h"
///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo ///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication* createDemo() DemoApplication* createDemo()
{ {
return new GimpactConcaveDemo(); return new GimpactConcaveDemo();
} }
#endif #endif

View File

@@ -1,48 +1,48 @@
# This is basically the overall name of the project in Visual Studio this is the name of the Solution File # This is basically the overall name of the project in Visual Studio this is the name of the Solution File
# For every executable you have with a main method you should have an add_executable line below. # For every executable you have with a main method you should have an add_executable line below.
# For every add executable line you should list every .cpp and .h file you have associated with that executable. # For every add executable line you should list every .cpp and .h file you have associated with that executable.
# You shouldn't have to modify anything below this line # You shouldn't have to modify anything below this line
######################################################## ########################################################
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL ${BULLET_PHYSICS_SOURCE_DIR}/src ${BULLET_PHYSICS_SOURCE_DIR}/Demos/OpenGL
) )
LINK_LIBRARIES( LINK_LIBRARIES(
OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} OpenGLSupport BulletDynamics BulletCollision LinearMath ${GLUT_glut_LIBRARY} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
) )
ADD_EXECUTABLE(AppLinearConvexCastDemo ADD_EXECUTABLE(AppLinearConvexCastDemo
LinearConvexCastDemo.cpp LinearConvexCastDemo.cpp
main.cpp main.cpp
) )
IF (WIN32) IF (WIN32)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppLinearConvexCastDemo TARGET AppLinearConvexCastDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/glut64.dll ${CMAKE_CURRENT_BINARY_DIR}
) )
ELSE(CMAKE_CL_64) ELSE(CMAKE_CL_64)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET AppLinearConvexCastDemo TARGET AppLinearConvexCastDemo
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${BULLET_PHYSICS_SOURCE_DIR}/GLUT32.DLL ${CMAKE_CURRENT_BINARY_DIR}
) )
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES) ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF(WIN32) ENDIF(WIN32)
IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppLinearConvexCastDemo PROPERTIES DEBUG_POSTFIX "_Debug") SET_TARGET_PROPERTIES(AppLinearConvexCastDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppLinearConvexCastDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel") SET_TARGET_PROPERTIES(AppLinearConvexCastDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppLinearConvexCastDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo") SET_TARGET_PROPERTIES(AppLinearConvexCastDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES) ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@@ -1,44 +1,44 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef LINEAR_CONVEX_CAST_DEMO_H #ifndef LINEAR_CONVEX_CAST_DEMO_H
#define LINEAR_CONVEX_CAST_DEMO_H #define LINEAR_CONVEX_CAST_DEMO_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
///LinearConvexCastDemo shows the working of the object sweep / pure-linear continuous collision detection query ///LinearConvexCastDemo shows the working of the object sweep / pure-linear continuous collision detection query
class LinearConvexCastDemo : public GlutDemoApplication class LinearConvexCastDemo : public GlutDemoApplication
{ {
public: public:
virtual ~LinearConvexCastDemo(); virtual ~LinearConvexCastDemo();
void initPhysics(); void initPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
static DemoApplication* Create() static DemoApplication* Create()
{ {
LinearConvexCastDemo* demo = new LinearConvexCastDemo(); LinearConvexCastDemo* demo = new LinearConvexCastDemo();
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
return demo; return demo;
} }
}; };
#endif //LINEAR_CONVEX_CAST_DEMO_H #endif //LINEAR_CONVEX_CAST_DEMO_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,99 +1,99 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BASIC_DEMO_H #ifndef BASIC_DEMO_H
#define BASIC_DEMO_H #define BASIC_DEMO_H
#include "DemoApplication.h" #include "DemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h" #include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
//#include "btCudaDemoPairCache.h" //#include "btCudaDemoPairCache.h"
//#include <vector_types.h> //#include <vector_types.h>
#endif //BT_USE_CUDA #endif //BT_USE_CUDA
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
///BasicDemo is good starting point for learning the code base and porting. ///BasicDemo is good starting point for learning the code base and porting.
class BasicDemo : public GlutDemoApplication class BasicDemo : public GlutDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
int m_mouseButtons; int m_mouseButtons;
int m_mouseOldX; int m_mouseOldX;
int m_mouseOldY; int m_mouseOldY;
public: public:
BasicDemo() BasicDemo()
{ {
} }
virtual ~BasicDemo() virtual ~BasicDemo()
{ {
exitPhysics(); exitPhysics();
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
///don't shoot a box in this demo ;-) ///don't shoot a box in this demo ;-)
virtual void shootBox(const btVector3& dest) {} virtual void shootBox(const btVector3& dest) {}
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
virtual void clientResetScene(); virtual void clientResetScene();
static DemoApplication* Create() static DemoApplication* Create()
{ {
BasicDemo* demo = new BasicDemo; BasicDemo* demo = new BasicDemo;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
demo->m_mouseButtons = 0; demo->m_mouseButtons = 0;
demo->m_mouseOldX = 0; demo->m_mouseOldX = 0;
demo->m_mouseOldY = 0; demo->m_mouseOldY = 0;
return demo; return demo;
} }
void DrawConstraintInfo(); void DrawConstraintInfo();
void outputDebugInfo(int & xOffset,int & yStart, int yIncr); void outputDebugInfo(int & xOffset,int & yStart, int yIncr);
virtual void renderme(); virtual void renderme();
void addCollisionShape(btCollisionShape* pShape) { m_collisionShapes.push_back(pShape); } void addCollisionShape(btCollisionShape* pShape) { m_collisionShapes.push_back(pShape); }
}; };
#endif //BASIC_DEMO_H #endif //BASIC_DEMO_H

View File

@@ -1,30 +1,30 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "LinearMath/btQuickprof.h" #include "LinearMath/btQuickprof.h"
#include "LinearMath/btScalar.h" #include "LinearMath/btScalar.h"
#include "btGpuDemo2dSharedTypes.h" #include "btGpuDemo2dSharedTypes.h"
#include "BulletMultiThreaded/btGpuDefines.h" #include "BulletMultiThreaded/btGpuDefines.h"
#include "BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#include "btGpuDemo2dSharedCode.h" #include "btGpuDemo2dSharedCode.h"

View File

@@ -1,497 +1,497 @@
/* /*
Impulse based Rigid body simulation using CUDA Impulse based Rigid body simulation using CUDA
Copyright (c) 2007 Takahiro Harada http://www.iii.u-tokyo.ac.jp/~takahiroharada/projects/impulseCUDA.html Copyright (c) 2007 Takahiro Harada http://www.iii.u-tokyo.ac.jp/~takahiroharada/projects/impulseCUDA.html
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#define USE_FRICTION 1 #define USE_FRICTION 1
#define FRICTION_BOX_GROUND_FACT 0.05f #define FRICTION_BOX_GROUND_FACT 0.05f
#define FRICTION_BOX_BOX_FACT 0.05f #define FRICTION_BOX_BOX_FACT 0.05f
#define USE_CENTERS 1 #define USE_CENTERS 1
//#include "LinearMath/btMinMax.h" //#include "LinearMath/btMinMax.h"
//---------- C o n s t r a i n t s o l v e r d e m o ---------------------------- //---------- C o n s t r a i n t s o l v e r d e m o ----------------------------
#define MAX_VTX_PER_OBJ 8 #define MAX_VTX_PER_OBJ 8
/* /*
BT_GPU___device__ void kill_me() BT_GPU___device__ void kill_me()
{ {
char* badPtr = (char*)0xFFFFFFFF; char* badPtr = (char*)0xFFFFFFFF;
*badPtr = 10; *badPtr = 10;
} }
*/ */
BT_GPU___global__ void clearAccumulationOfLambdaDtD(float* lambdaDtBox, int numConstraints, int numContPoints) BT_GPU___global__ void clearAccumulationOfLambdaDtD(float* lambdaDtBox, int numConstraints, int numContPoints)
{ {
int index = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x; int index = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x;
if(index < numConstraints) if(index < numConstraints)
{ {
for(int i=0; i < numContPoints; i++) for(int i=0; i < numContPoints; i++)
lambdaDtBox[numContPoints * index + i] = 0; lambdaDtBox[numContPoints * index + i] = 0;
} }
} }
#define SPHERE_FACT 1.0f #define SPHERE_FACT 1.0f
BT_GPU___device__ void testSphSph(float3 aPos, float3 bPos, float radA, float radB, float4* pOut) BT_GPU___device__ void testSphSph(float3 aPos, float3 bPos, float radA, float radB, float4* pOut)
{ {
float3 del = bPos - aPos; float3 del = bPos - aPos;
float dist = BT_GPU_dot(del, del); float dist = BT_GPU_dot(del, del);
dist = sqrtf(dist); dist = sqrtf(dist);
float maxD = radA + radB; float maxD = radA + radB;
if(dist > maxD) if(dist > maxD)
{ {
return; return;
} }
float penetration = (radA + radB - dist) * SPHERE_FACT; float penetration = (radA + radB - dist) * SPHERE_FACT;
// float penetration = (dist - radA - radB) * SPHERE_FACT; // float penetration = (dist - radA - radB) * SPHERE_FACT;
float3 normal; float3 normal;
if(dist > 0.f) if(dist > 0.f)
{ {
float fact = -1.0f/dist; float fact = -1.0f/dist;
// float fact = 1.0f/dist; // float fact = 1.0f/dist;
normal = del * fact; normal = del * fact;
} }
else else
{ {
normal = BT_GPU_make_float3(1.f, 0.f, 0.f); normal = BT_GPU_make_float3(1.f, 0.f, 0.f);
} }
// float3 contact = (bPos + aPos + normal * (radB - radA)) * 0.5f; // float3 contact = (bPos + aPos + normal * (radB - radA)) * 0.5f;
float3 tmp = (normal * radA); float3 tmp = (normal * radA);
float3 contact = aPos - tmp; float3 contact = aPos - tmp;
// now add point // now add point
int numPoints = 0; int numPoints = 0;
for(int i = 0; i < MAX_VTX_PER_OBJ; i++) for(int i = 0; i < MAX_VTX_PER_OBJ; i++)
{ {
if(pOut[i*2].w >= 0.f) if(pOut[i*2].w >= 0.f)
{ {
numPoints++; numPoints++;
} }
} }
if(numPoints < MAX_VTX_PER_OBJ) if(numPoints < MAX_VTX_PER_OBJ)
{ {
pOut[numPoints * 2] = BT_GPU_make_float42(contact, penetration); pOut[numPoints * 2] = BT_GPU_make_float42(contact, penetration);
pOut[numPoints * 2 + 1] = BT_GPU_make_float42(normal, 0.f); pOut[numPoints * 2 + 1] = BT_GPU_make_float42(normal, 0.f);
} }
} // testSphSph() } // testSphSph()
BT_GPU___global__ void setConstraintDataD(int2 *constraints, BT_GPU___global__ void setConstraintDataD(int2 *constraints,
int numConstraints, int numConstraints,
float4 *pos, float4 *pos,
float *rotation, float *rotation,
char* shapes, char* shapes,
int2* shapeIds, int2* shapeIds,
btCudaPartProps pProp, btCudaPartProps pProp,
float4 *contact) float4 *contact)
{ {
int idx = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x; int idx = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x;
int aId,bId; int aId,bId;
float3 aPos,bPos; float3 aPos,bPos;
// float positionConstraint; // float positionConstraint;
// float3 normal; // float3 normal;
float aRot,bRot; float aRot,bRot;
float sideLength2 = pProp.m_diameter*0.5f/sqrt(2.0f); float sideLength2 = pProp.m_diameter*0.5f/sqrt(2.0f);
if(idx < numConstraints) if(idx < numConstraints)
{ {
aId=constraints[idx].x; aId=constraints[idx].x;
bId=constraints[idx].y; bId=constraints[idx].y;
aPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,aId)); aPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,aId));
bPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,bId)); bPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,bId));
aRot= rotation[aId]; aRot= rotation[aId];
bRot= rotation[bId]; bRot= rotation[bId];
float cosA = cosf(aRot); float cosA = cosf(aRot);
float sinA = sinf(aRot); float sinA = sinf(aRot);
float cosB = cosf(bRot); float cosB = cosf(bRot);
float sinB = sinf(bRot); float sinB = sinf(bRot);
float4* shapeA = (float4*)(shapes + shapeIds[aId].x); float4* shapeA = (float4*)(shapes + shapeIds[aId].x);
int numSphA = shapeIds[aId].y; int numSphA = shapeIds[aId].y;
float4* shapeB = (float4*)(shapes + shapeIds[bId].x); float4* shapeB = (float4*)(shapes + shapeIds[bId].x);
int numSphB = shapeIds[bId].y; int numSphB = shapeIds[bId].y;
int i, j; int i, j;
float3 ai = BT_GPU_make_float3(cosA, sinA, 0.f); float3 ai = BT_GPU_make_float3(cosA, sinA, 0.f);
float3 aj = BT_GPU_make_float3(-sinA, cosA, 0.f); float3 aj = BT_GPU_make_float3(-sinA, cosA, 0.f);
float3 bi = BT_GPU_make_float3(cosB, sinB, 0.f); float3 bi = BT_GPU_make_float3(cosB, sinB, 0.f);
float3 bj = BT_GPU_make_float3(-sinB, cosB, 0.f); float3 bj = BT_GPU_make_float3(-sinB, cosB, 0.f);
float4* pOut = contact + idx * MAX_VTX_PER_OBJ * 2; float4* pOut = contact + idx * MAX_VTX_PER_OBJ * 2;
for(i = 0; i < MAX_VTX_PER_OBJ; i++) for(i = 0; i < MAX_VTX_PER_OBJ; i++)
{ {
pOut[i * 2].w = -1.f; pOut[i * 2].w = -1.f;
pOut[i * 2 + 1].w = 0.f; pOut[i * 2 + 1].w = 0.f;
} }
for(i = 0; i < numSphA; i++) for(i = 0; i < numSphA; i++)
{ {
float3 va = aPos; float3 va = aPos;
float3 tmp = ai * shapeA[i].x; float3 tmp = ai * shapeA[i].x;
float3 tmp2 = aj * shapeA[i].y; float3 tmp2 = aj * shapeA[i].y;
va += tmp; va += tmp;
va += tmp2; va += tmp2;
float radA = shapeA[i].w; float radA = shapeA[i].w;
for(j = 0; j < numSphB; j++) for(j = 0; j < numSphB; j++)
{ {
float3 vb = bPos; float3 vb = bPos;
float3 tmp =bi * shapeB[j].x; float3 tmp =bi * shapeB[j].x;
float3 tmp2 = bj * shapeB[j].y; float3 tmp2 = bj * shapeB[j].y;
vb += tmp; vb += tmp;
vb += tmp2; vb += tmp2;
float radB = shapeB[j].w; float radB = shapeB[j].w;
testSphSph(va, vb, radA, radB, pOut); testSphSph(va, vb, radA, radB, pOut);
} }
} }
} }
} }
BT_GPU___device__ float computeImpulse1(float3 rVel, BT_GPU___device__ float computeImpulse1(float3 rVel,
float positionConstraint, float positionConstraint,
float3 cNormal, float3 cNormal,
float dt) float dt)
{ {
// const float collisionConstant = 0.1f; // const float collisionConstant = 0.1f;
// const float baumgarteConstant = 0.5f; // const float baumgarteConstant = 0.5f;
// const float penetrationError = 0.02f; // const float penetrationError = 0.02f;
const float collisionConstant = -0.1f; const float collisionConstant = -0.1f;
const float baumgarteConstant = 0.3f; const float baumgarteConstant = 0.3f;
const float penetrationError = 0.02f; const float penetrationError = 0.02f;
float lambdaDt=0; float lambdaDt=0;
float3 impulse=BT_GPU_make_float3(0.f,0.f,0.f); float3 impulse=BT_GPU_make_float3(0.f,0.f,0.f);
if(positionConstraint > 0) if(positionConstraint > 0)
return lambdaDt; return lambdaDt;
// positionConstraint = btMin(0.0f,positionConstraint+penetrationError); // positionConstraint = btMin(0.0f,positionConstraint+penetrationError);
positionConstraint = (positionConstraint+penetrationError) < 0.f ? (positionConstraint+penetrationError) : 0.0f; positionConstraint = (positionConstraint+penetrationError) < 0.f ? (positionConstraint+penetrationError) : 0.0f;
lambdaDt = -(BT_GPU_dot(cNormal,rVel)*(1+collisionConstant)); lambdaDt = -(BT_GPU_dot(cNormal,rVel)*(1+collisionConstant));
lambdaDt -= (baumgarteConstant/dt*positionConstraint); lambdaDt -= (baumgarteConstant/dt*positionConstraint);
return lambdaDt; return lambdaDt;
} }
BT_GPU___global__ void collisionWithWallBoxD(float4 *pos, BT_GPU___global__ void collisionWithWallBoxD(float4 *pos,
float4 *vel, float4 *vel,
float *rotation, float *rotation,
float *angVel, float *angVel,
char* shapes, char* shapes,
int2* shapeIds, int2* shapeIds,
float* invMass, float* invMass,
btCudaPartProps pProp, btCudaPartProps pProp,
btCudaBoxProps gProp, btCudaBoxProps gProp,
int nParticles, int nParticles,
float dt) float dt)
{ {
int idx = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x; int idx = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x;
float3 aPos; float3 aPos;
float aRot; float aRot;
float positionConstraint; float positionConstraint;
float3 impulse; float3 impulse;
if((idx > 0) && (idx < nParticles)) if((idx > 0) && (idx < nParticles))
{ {
float inv_mass = invMass[idx]; float inv_mass = invMass[idx];
if(inv_mass <= 0.f) if(inv_mass <= 0.f)
{ {
return; return;
} }
aPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,idx)); aPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,idx));
aRot=rotation[idx]; aRot=rotation[idx];
float4* shape = (float4*)(shapes + shapeIds[idx].x); float4* shape = (float4*)(shapes + shapeIds[idx].x);
int numSph = shapeIds[idx].y; int numSph = shapeIds[idx].y;
float cosA = cosf(aRot); float cosA = cosf(aRot);
float sinA = sinf(aRot); float sinA = sinf(aRot);
float3 ai = BT_GPU_make_float3(cosA, sinA, 0.f); float3 ai = BT_GPU_make_float3(cosA, sinA, 0.f);
float3 aj = BT_GPU_make_float3(-sinA, cosA, 0.f); float3 aj = BT_GPU_make_float3(-sinA, cosA, 0.f);
for(int iVtx=0;iVtx < numSph; iVtx++){ for(int iVtx=0;iVtx < numSph; iVtx++){
float3 aVel = BT_GPU_make_float3(vel[idx].x, vel[idx].y, vel[idx].z); float3 aVel = BT_GPU_make_float3(vel[idx].x, vel[idx].y, vel[idx].z);
float aAngVel = angVel[idx]; float aAngVel = angVel[idx];
float3 rerVertex = ai * shape[iVtx].x; float3 rerVertex = ai * shape[iVtx].x;
float3 tmp = aj * shape[iVtx].y; float3 tmp = aj * shape[iVtx].y;
rerVertex += tmp; rerVertex += tmp;
float3 vPos = aPos + rerVertex; float3 vPos = aPos + rerVertex;
float rad = shape[iVtx].w; float rad = shape[iVtx].w;
float3 vVel =aVel+BT_GPU_cross(BT_GPU_make_float3(0.0f,0.0f,aAngVel),rerVertex); float3 vVel =aVel+BT_GPU_cross(BT_GPU_make_float3(0.0f,0.0f,aAngVel),rerVertex);
// float restitution=1.0; // float restitution=1.0;
float restitution=0.3f; float restitution=0.3f;
{ {
positionConstraint =vPos.y - rad - gProp.minY; positionConstraint =vPos.y - rad - gProp.minY;
impulse =BT_GPU_make_float31(0.0f); impulse =BT_GPU_make_float31(0.0f);
if(positionConstraint < 0) if(positionConstraint < 0)
{ {
float3 groundNormal; float3 groundNormal;
groundNormal = BT_GPU_make_float3(0.0f,1.0f,0.0f); groundNormal = BT_GPU_make_float3(0.0f,1.0f,0.0f);
impulse =groundNormal* impulse =groundNormal*
restitution * computeImpulse1(vVel,positionConstraint, restitution * computeImpulse1(vVel,positionConstraint,
groundNormal, groundNormal,
dt); dt);
#if USE_FRICTION // only with ground for now #if USE_FRICTION // only with ground for now
float3 lat_vel = vVel - groundNormal * BT_GPU_dot(groundNormal,vVel); float3 lat_vel = vVel - groundNormal * BT_GPU_dot(groundNormal,vVel);
float lat_vel_len = BT_GPU_dot(lat_vel, lat_vel); float lat_vel_len = BT_GPU_dot(lat_vel, lat_vel);
if (lat_vel_len > 0) if (lat_vel_len > 0)
{ {
lat_vel_len = sqrtf(lat_vel_len); lat_vel_len = sqrtf(lat_vel_len);
lat_vel *= 1.f/lat_vel_len; lat_vel *= 1.f/lat_vel_len;
float3 tmp = lat_vel * BT_GPU_dot(lat_vel, vVel) * FRICTION_BOX_GROUND_FACT; float3 tmp = lat_vel * BT_GPU_dot(lat_vel, vVel) * FRICTION_BOX_GROUND_FACT;
impulse -= tmp; impulse -= tmp;
} }
#endif //USE_FRICTION #endif //USE_FRICTION
float4 tmp = BT_GPU_make_float42(impulse,0.0f); float4 tmp = BT_GPU_make_float42(impulse,0.0f);
vel[idx] += tmp; vel[idx] += tmp;
float tmp2 = BT_GPU_cross(rerVertex,impulse).z; float tmp2 = BT_GPU_cross(rerVertex,impulse).z;
angVel[idx] += tmp2; angVel[idx] += tmp2;
} }
} }
{ {
positionConstraint =vPos.x - rad - gProp.minX; positionConstraint =vPos.x - rad - gProp.minX;
impulse =BT_GPU_make_float31(0.0f); impulse =BT_GPU_make_float31(0.0f);
if(positionConstraint < 0){ if(positionConstraint < 0){
impulse =BT_GPU_make_float3(1.0f,0.0f,0.0f)* restitution * impulse =BT_GPU_make_float3(1.0f,0.0f,0.0f)* restitution *
computeImpulse1(vVel,positionConstraint, computeImpulse1(vVel,positionConstraint,
BT_GPU_make_float3(1.0f,0.0f,0.0f), BT_GPU_make_float3(1.0f,0.0f,0.0f),
dt); dt);
float4 tmp = BT_GPU_make_float42(impulse,0.0f); float4 tmp = BT_GPU_make_float42(impulse,0.0f);
vel[idx] += tmp; vel[idx] += tmp;
angVel[idx] += BT_GPU_cross(rerVertex,impulse).z; angVel[idx] += BT_GPU_cross(rerVertex,impulse).z;
} }
} }
{ {
positionConstraint = gProp.maxX - vPos.x - rad; positionConstraint = gProp.maxX - vPos.x - rad;
impulse =BT_GPU_make_float31(0.0f); impulse =BT_GPU_make_float31(0.0f);
if(positionConstraint < 0){ if(positionConstraint < 0){
impulse =BT_GPU_make_float3(-1.0f,0.0f,0.0f)* restitution * impulse =BT_GPU_make_float3(-1.0f,0.0f,0.0f)* restitution *
computeImpulse1(vVel,positionConstraint, computeImpulse1(vVel,positionConstraint,
BT_GPU_make_float3(-1.0f,0.0f,0.0f), BT_GPU_make_float3(-1.0f,0.0f,0.0f),
dt); dt);
float4 tmp = BT_GPU_make_float42(impulse,0.0f); float4 tmp = BT_GPU_make_float42(impulse,0.0f);
vel[idx] += tmp; vel[idx] += tmp;
angVel[idx] += BT_GPU_cross(rerVertex,impulse).z; angVel[idx] += BT_GPU_cross(rerVertex,impulse).z;
} }
} }
} }
} }
} }
BT_GPU___device__ void collisionResolutionBox( int constrId, BT_GPU___device__ void collisionResolutionBox( int constrId,
int2* constraints, int2* constraints,
float4 *pos, float4 *pos,
float4 *vel, float4 *vel,
float *rotation, float *rotation,
float *angularVel, float *angularVel,
float *lambdaDtBox, float *lambdaDtBox,
float4* contact, float4* contact,
float* invMass, float* invMass,
btCudaPartProps pProp, btCudaPartProps pProp,
float dt) float dt)
{ {
#if 1 #if 1
float3 relVel; float3 relVel;
float3 impulse; float3 impulse;
float lambdaDt; float lambdaDt;
float positionConstraint; float positionConstraint;
int aId=constraints[constrId].x; int aId=constraints[constrId].x;
int bId=constraints[constrId].y; int bId=constraints[constrId].y;
float3 aPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,aId)); float3 aPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,aId));
float3 bPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,bId)); float3 bPos=BT_GPU_make_float34(BT_GPU_FETCH4(pos,bId));
float3 aVel=BT_GPU_make_float34(vel[aId]); float3 aVel=BT_GPU_make_float34(vel[aId]);
float3 bVel=BT_GPU_make_float34(vel[bId]); float3 bVel=BT_GPU_make_float34(vel[bId]);
float aAngVel=angularVel[aId]; float aAngVel=angularVel[aId];
float bAngVel=angularVel[bId]; float bAngVel=angularVel[bId];
float4* pCont = contact + constrId * MAX_VTX_PER_OBJ * 2; float4* pCont = contact + constrId * MAX_VTX_PER_OBJ * 2;
// test Vertices in A to Box B // test Vertices in A to Box B
for(int iVtx=0;iVtx<MAX_VTX_PER_OBJ;iVtx++){ for(int iVtx=0;iVtx<MAX_VTX_PER_OBJ;iVtx++){
float3 contactPoint = BT_GPU_make_float34(pCont[iVtx * 2]); float3 contactPoint = BT_GPU_make_float34(pCont[iVtx * 2]);
contactPoint = contactPoint - aPos; contactPoint = contactPoint - aPos;
positionConstraint = pCont[iVtx * 2].w; positionConstraint = pCont[iVtx * 2].w;
if(positionConstraint >= 0) if(positionConstraint >= 0)
{ {
float3 contactNormal = BT_GPU_make_float34(pCont[iVtx * 2 + 1]); float3 contactNormal = BT_GPU_make_float34(pCont[iVtx * 2 + 1]);
relVel=(aVel+BT_GPU_cross(BT_GPU_make_float3(0.0f,0.0f,aAngVel), relVel=(aVel+BT_GPU_cross(BT_GPU_make_float3(0.0f,0.0f,aAngVel),
contactPoint)) contactPoint))
-(bVel+BT_GPU_cross(BT_GPU_make_float3(0.0f,0.0f,bAngVel), -(bVel+BT_GPU_cross(BT_GPU_make_float3(0.0f,0.0f,bAngVel),
contactPoint+aPos-bPos)); contactPoint+aPos-bPos));
lambdaDt= computeImpulse1(relVel,-positionConstraint, lambdaDt= computeImpulse1(relVel,-positionConstraint,
contactNormal,dt); contactNormal,dt);
{ {
float rLambdaDt=lambdaDtBox[(MAX_VTX_PER_OBJ)*(2*constrId)+iVtx]; float rLambdaDt=lambdaDtBox[(MAX_VTX_PER_OBJ)*(2*constrId)+iVtx];
float pLambdaDt=rLambdaDt; float pLambdaDt=rLambdaDt;
// rLambdaDt=btMax(pLambdaDt+lambdaDt,0.0f); // rLambdaDt=btMax(pLambdaDt+lambdaDt,0.0f);
rLambdaDt=(pLambdaDt+lambdaDt) > 0.0f ? (pLambdaDt+lambdaDt) : 0.0f; rLambdaDt=(pLambdaDt+lambdaDt) > 0.0f ? (pLambdaDt+lambdaDt) : 0.0f;
lambdaDt=rLambdaDt-pLambdaDt; lambdaDt=rLambdaDt-pLambdaDt;
lambdaDtBox[(MAX_VTX_PER_OBJ)*(2*constrId)+iVtx]=rLambdaDt; lambdaDtBox[(MAX_VTX_PER_OBJ)*(2*constrId)+iVtx]=rLambdaDt;
} }
impulse= contactNormal*lambdaDt*0.5; impulse= contactNormal*lambdaDt*0.5;
#if USE_FRICTION #if USE_FRICTION
if(pCont[iVtx * 2 + 1].w <= 0) if(pCont[iVtx * 2 + 1].w <= 0)
{ {
float3 lat_vel = relVel - contactNormal * BT_GPU_dot(contactNormal, relVel); float3 lat_vel = relVel - contactNormal * BT_GPU_dot(contactNormal, relVel);
float lat_vel_len = BT_GPU_dot(lat_vel, lat_vel); float lat_vel_len = BT_GPU_dot(lat_vel, lat_vel);
if (lat_vel_len > 0) if (lat_vel_len > 0)
{ {
lat_vel_len = sqrtf(lat_vel_len); lat_vel_len = sqrtf(lat_vel_len);
lat_vel *= 1.f/lat_vel_len; lat_vel *= 1.f/lat_vel_len;
float3 tmp = lat_vel * BT_GPU_dot(lat_vel , relVel) * FRICTION_BOX_BOX_FACT; float3 tmp = lat_vel * BT_GPU_dot(lat_vel , relVel) * FRICTION_BOX_BOX_FACT;
impulse -= tmp; impulse -= tmp;
} }
} }
#endif //USE_FRICTION #endif //USE_FRICTION
if(aId && (invMass[aId] > 0.f)) if(aId && (invMass[aId] > 0.f))
{ {
aVel+= impulse; aVel+= impulse;
aAngVel+= BT_GPU_cross(contactPoint, impulse).z; aAngVel+= BT_GPU_cross(contactPoint, impulse).z;
} }
if(bId && (invMass[bId] > 0.f)) if(bId && (invMass[bId] > 0.f))
{ {
bVel-= impulse; bVel-= impulse;
bAngVel-= BT_GPU_cross(contactPoint+aPos-bPos, impulse).z; bAngVel-= BT_GPU_cross(contactPoint+aPos-bPos, impulse).z;
} }
} }
} }
vel[aId]=BT_GPU_make_float42(aVel,0.0f); vel[aId]=BT_GPU_make_float42(aVel,0.0f);
vel[bId]=BT_GPU_make_float42(bVel,0.0f); vel[bId]=BT_GPU_make_float42(bVel,0.0f);
angularVel[aId]=aAngVel; angularVel[aId]=aAngVel;
angularVel[bId]=bAngVel; angularVel[bId]=bAngVel;
#endif #endif
} }
BT_GPU___global__ void collisionBatchResolutionBoxD(int2 *constraints, BT_GPU___global__ void collisionBatchResolutionBoxD(int2 *constraints,
int *batch, int *batch,
int nConstraints, int nConstraints,
float4 *pos, float4 *pos,
float4 *vel, float4 *vel,
float *rotation, float *rotation,
float *angularVel, float *angularVel,
float *lambdaDtBox, float *lambdaDtBox,
float4* contact, float4* contact,
float* invMass, float* invMass,
btCudaPartProps pProp, btCudaPartProps pProp,
int iBatch, int iBatch,
float dt) float dt)
{ {
int k_idx = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x; int k_idx = BT_GPU___mul24(BT_GPU_blockIdx.x, BT_GPU_blockDim.x) + BT_GPU_threadIdx.x;
if(k_idx < nConstraints) if(k_idx < nConstraints)
{ {
int idx = batch[k_idx]; int idx = batch[k_idx];
collisionResolutionBox( idx, constraints, pos, vel, rotation, angularVel, lambdaDtBox, collisionResolutionBox( idx, constraints, pos, vel, rotation, angularVel, lambdaDtBox,
contact, invMass, pProp, dt); contact, invMass, pProp, dt);
} }
} }
extern "C" extern "C"
{ {
void BT_GPU_PREF(clearAccumulationOfLambdaDt(float* lambdaDtBox, int numConstraints, int numContPoints)) void BT_GPU_PREF(clearAccumulationOfLambdaDt(float* lambdaDtBox, int numConstraints, int numContPoints))
{ {
if(!numConstraints) if(!numConstraints)
{ {
return; return;
} }
int numThreads, numBlocks; int numThreads, numBlocks;
BT_GPU_PREF(computeGridSize)(numConstraints, 256, numBlocks, numThreads); BT_GPU_PREF(computeGridSize)(numConstraints, 256, numBlocks, numThreads);
// execute the kernel // execute the kernel
BT_GPU_EXECKERNEL(numBlocks, numThreads, clearAccumulationOfLambdaDtD, (lambdaDtBox, numConstraints, numContPoints)); BT_GPU_EXECKERNEL(numBlocks, numThreads, clearAccumulationOfLambdaDtD, (lambdaDtBox, numConstraints, numContPoints));
// check if kernel invocation generated an error // check if kernel invocation generated an error
BT_GPU_CHECK_ERROR("clearAccumulationOfLambdaDtD kernel execution failed"); BT_GPU_CHECK_ERROR("clearAccumulationOfLambdaDtD kernel execution failed");
} }
void BT_GPU_PREF(setConstraintData(void* constraints,int numConstraints,int numObjs,void* pos,float *rotation,char* shapes,void* shapeIds,btCudaPartProps pProp,void* contact)) void BT_GPU_PREF(setConstraintData(void* constraints,int numConstraints,int numObjs,void* pos,float *rotation,char* shapes,void* shapeIds,btCudaPartProps pProp,void* contact))
{ {
if(!numConstraints) if(!numConstraints)
{ {
return; return;
} }
int2* pConst = (int2*)constraints; int2* pConst = (int2*)constraints;
float4* pPos = (float4*)pos; float4* pPos = (float4*)pos;
float4* pCont = (float4*)contact; float4* pCont = (float4*)contact;
int2* pShapeIds = (int2*)shapeIds; int2* pShapeIds = (int2*)shapeIds;
BT_GPU_SAFE_CALL(BT_GPU_BindTexture(0, posTex, pPos, numObjs * sizeof(float4))); BT_GPU_SAFE_CALL(BT_GPU_BindTexture(0, posTex, pPos, numObjs * sizeof(float4)));
int numThreads, numBlocks; int numThreads, numBlocks;
BT_GPU_PREF(computeGridSize)(numConstraints, 256, numBlocks, numThreads); BT_GPU_PREF(computeGridSize)(numConstraints, 256, numBlocks, numThreads);
// execute the kernel // execute the kernel
BT_GPU_EXECKERNEL(numBlocks, numThreads, setConstraintDataD, (pConst,numConstraints,pPos,rotation,shapes,pShapeIds,pProp,pCont)); BT_GPU_EXECKERNEL(numBlocks, numThreads, setConstraintDataD, (pConst,numConstraints,pPos,rotation,shapes,pShapeIds,pProp,pCont));
BT_GPU_SAFE_CALL(BT_GPU_UnbindTexture(posTex)); BT_GPU_SAFE_CALL(BT_GPU_UnbindTexture(posTex));
// check if kernel invocation generated an error // check if kernel invocation generated an error
BT_GPU_CHECK_ERROR("setConstraintDataD kernel execution failed"); BT_GPU_CHECK_ERROR("setConstraintDataD kernel execution failed");
} }
void BT_GPU_PREF(collisionWithWallBox(void* pos,void* vel,float *rotation,float *angVel,char* shapes,void* shapeIds,void* invMass,btCudaPartProps pProp, btCudaBoxProps gProp,int numObjs,float dt)) void BT_GPU_PREF(collisionWithWallBox(void* pos,void* vel,float *rotation,float *angVel,char* shapes,void* shapeIds,void* invMass,btCudaPartProps pProp, btCudaBoxProps gProp,int numObjs,float dt))
{ {
if(!numObjs) if(!numObjs)
{ {
return; return;
} }
float4* pPos = (float4*)pos; float4* pPos = (float4*)pos;
float4* pVel = (float4*)vel; float4* pVel = (float4*)vel;
int2* pShapeIds = (int2*)shapeIds; int2* pShapeIds = (int2*)shapeIds;
float* pInvMass = (float*)invMass; float* pInvMass = (float*)invMass;
BT_GPU_SAFE_CALL(BT_GPU_BindTexture(0, posTex, pPos, numObjs * sizeof(float4))); BT_GPU_SAFE_CALL(BT_GPU_BindTexture(0, posTex, pPos, numObjs * sizeof(float4)));
int numThreads, numBlocks; int numThreads, numBlocks;
BT_GPU_PREF(computeGridSize)(numObjs, 256, numBlocks, numThreads); BT_GPU_PREF(computeGridSize)(numObjs, 256, numBlocks, numThreads);
// execute the kernel // execute the kernel
BT_GPU_EXECKERNEL(numBlocks, numThreads, collisionWithWallBoxD, (pPos,pVel,rotation,angVel,shapes, pShapeIds,pInvMass,pProp,gProp,numObjs,dt)); BT_GPU_EXECKERNEL(numBlocks, numThreads, collisionWithWallBoxD, (pPos,pVel,rotation,angVel,shapes, pShapeIds,pInvMass,pProp,gProp,numObjs,dt));
BT_GPU_SAFE_CALL(BT_GPU_UnbindTexture(posTex)); BT_GPU_SAFE_CALL(BT_GPU_UnbindTexture(posTex));
// check if kernel invocation generated an error // check if kernel invocation generated an error
BT_GPU_CHECK_ERROR("collisionWithWallBoxD kernel execution failed"); BT_GPU_CHECK_ERROR("collisionWithWallBoxD kernel execution failed");
} }
void BT_GPU_PREF(collisionBatchResolutionBox(void* constraints,int *batch,int numConstraints,int numObjs,void *pos,void *vel,float *rotation,float *angularVel,float *lambdaDtBox,void* contact,void* invMass,btCudaPartProps pProp,int iBatch,float dt)) void BT_GPU_PREF(collisionBatchResolutionBox(void* constraints,int *batch,int numConstraints,int numObjs,void *pos,void *vel,float *rotation,float *angularVel,float *lambdaDtBox,void* contact,void* invMass,btCudaPartProps pProp,int iBatch,float dt))
{ {
if(!numConstraints) if(!numConstraints)
{ {
return; return;
} }
int2* pConstr = (int2*)constraints; int2* pConstr = (int2*)constraints;
float4* pPos = (float4*)pos; float4* pPos = (float4*)pos;
float4* pVel = (float4*)vel; float4* pVel = (float4*)vel;
float4* pCont = (float4*)contact; float4* pCont = (float4*)contact;
float* pInvMass = (float*)invMass; float* pInvMass = (float*)invMass;
int numThreads, numBlocks; int numThreads, numBlocks;
BT_GPU_PREF(computeGridSize)(numConstraints, 128, numBlocks, numThreads); BT_GPU_PREF(computeGridSize)(numConstraints, 128, numBlocks, numThreads);
BT_GPU_SAFE_CALL(BT_GPU_BindTexture(0, posTex, pPos, numObjs * sizeof(float4))); BT_GPU_SAFE_CALL(BT_GPU_BindTexture(0, posTex, pPos, numObjs * sizeof(float4)));
// execute the kernel // execute the kernel
BT_GPU_EXECKERNEL(numBlocks, numThreads, collisionBatchResolutionBoxD, (pConstr,batch,numConstraints,pPos,pVel,rotation,angularVel,lambdaDtBox,pCont,pInvMass,pProp,iBatch,dt)); BT_GPU_EXECKERNEL(numBlocks, numThreads, collisionBatchResolutionBoxD, (pConstr,batch,numConstraints,pPos,pVel,rotation,angularVel,lambdaDtBox,pCont,pInvMass,pProp,iBatch,dt));
// check if kernel invocation generated an error // check if kernel invocation generated an error
BT_GPU_CHECK_ERROR("collisionBatchResolutionBox2D kernel execution failed"); BT_GPU_CHECK_ERROR("collisionBatchResolutionBox2D kernel execution failed");
BT_GPU_SAFE_CALL(BT_GPU_UnbindTexture(posTex)); BT_GPU_SAFE_CALL(BT_GPU_UnbindTexture(posTex));
} }
} // extern "C" } // extern "C"

View File

@@ -1,33 +1,33 @@
/* /*
Impulse based Rigid body simulation using CUDA Impulse based Rigid body simulation using CUDA
Copyright (c) 2007 Takahiro Harada http://www.iii.u-tokyo.ac.jp/~takahiroharada/projects/impulseCUDA.html Copyright (c) 2007 Takahiro Harada http://www.iii.u-tokyo.ac.jp/~takahiroharada/projects/impulseCUDA.html
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
//---------- C o n s t r a i n t s o l v e r d e m o ---------------------------- //---------- C o n s t r a i n t s o l v e r d e m o ----------------------------
extern "C" extern "C"
{ {
void BT_GPU_PREF(clearAccumulationOfLambdaDt(float* lambdaDtBox, int numConstraints, int numContPoints)); void BT_GPU_PREF(clearAccumulationOfLambdaDt(float* lambdaDtBox, int numConstraints, int numContPoints));
void BT_GPU_PREF(setConstraintData(void* constraints,int numConstraints,int numObjs,void* pos,float *rotation,char* shapes,void* shapeIds,btCudaPartProps pProp,void* oContact)); void BT_GPU_PREF(setConstraintData(void* constraints,int numConstraints,int numObjs,void* pos,float *rotation,char* shapes,void* shapeIds,btCudaPartProps pProp,void* oContact));
void BT_GPU_PREF(collisionWithWallBox(void* pos,void* vel,float *rotation,float *angVel,char* shapes,void* shapeIds,void* invMass,btCudaPartProps pProp,btCudaBoxProps gProp,int numObjs,float dt)); void BT_GPU_PREF(collisionWithWallBox(void* pos,void* vel,float *rotation,float *angVel,char* shapes,void* shapeIds,void* invMass,btCudaPartProps pProp,btCudaBoxProps gProp,int numObjs,float dt));
void BT_GPU_PREF(collisionBatchResolutionBox(void* constraints,int *batch,int numConstraints,int numObjs,void *pos,void *vel,float *rotation,float *angularVel,float *lambdaDtBox,void* contact,void* invMass,btCudaPartProps pProp,int iBatch,float dt)); void BT_GPU_PREF(collisionBatchResolutionBox(void* constraints,int *batch,int numConstraints,int numObjs,void *pos,void *vel,float *rotation,float *angularVel,float *lambdaDtBox,void* contact,void* invMass,btCudaPartProps pProp,int iBatch,float dt));
} // extern "C" } // extern "C"

View File

@@ -1,35 +1,35 @@
/* /*
Impulse based Rigid body simulation using CUDA Impulse based Rigid body simulation using CUDA
Copyright (c) 2007 Takahiro Harada http://www.iii.u-tokyo.ac.jp/~takahiroharada/projects/impulseCUDA.html Copyright (c) 2007 Takahiro Harada http://www.iii.u-tokyo.ac.jp/~takahiroharada/projects/impulseCUDA.html
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
//---------- C o n s t r a i n t s o l v e r d e m o ---------------------------- //---------- C o n s t r a i n t s o l v e r d e m o ----------------------------
struct btCudaPartProps struct btCudaPartProps
{ {
float m_mass; float m_mass;
float m_diameter; float m_diameter;
float m_restCoeff; float m_restCoeff;
}; };
struct btCudaBoxProps struct btCudaBoxProps
{ {
float minX; float minX;
float maxX; float maxX;
float minY; float minY;
float maxY; float maxY;
float minZ; float minZ;
float maxZ; float maxZ;
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -1,291 +1,291 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BT_CUDA_DEMO_DYNAMICS_WORLD_H #ifndef BT_CUDA_DEMO_DYNAMICS_WORLD_H
#define BT_CUDA_DEMO_DYNAMICS_WORLD_H #define BT_CUDA_DEMO_DYNAMICS_WORLD_H
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h" #include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
#include "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h" #include "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h"
//#define BT_USE_CUDA 1 //#define BT_USE_CUDA 1
// To enable CUDA : // To enable CUDA :
// 1. Uncomment //#define BT_USE_CUDA 1 // 1. Uncomment //#define BT_USE_CUDA 1
// 2. Build and add libbulletcuda (Extras/CUDA) to project // 2. Build and add libbulletcuda (Extras/CUDA) to project
// 3. Add $(CUDA_LIB_PATH) and cudart.lib to linker properties // 3. Add $(CUDA_LIB_PATH) and cudart.lib to linker properties
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
// #include "btCudaDemoPairCache.h" // #include "btCudaDemoPairCache.h"
// #include <vector_types.h> // #include <vector_types.h>
#include "BulletMultiThreaded/btGpuDefines.h" #include "BulletMultiThreaded/btGpuDefines.h"
#undef BT_GPU_PREF #undef BT_GPU_PREF
#define BT_GPU_PREF(func) btCuda_##func #define BT_GPU_PREF(func) btCuda_##func
#include "BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#else #else
#include "BulletMultiThreaded/btGpuDefines.h" #include "BulletMultiThreaded/btGpuDefines.h"
#include "../../src/BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "../../src/BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#endif #endif
#undef BT_GPU_PREF #undef BT_GPU_PREF
#include "btGpuDemo2dSharedTypes.h" #include "btGpuDemo2dSharedTypes.h"
#define CUDA_DEMO_DYNAMICS_WORLD_MAX_BATCHES 20 #define CUDA_DEMO_DYNAMICS_WORLD_MAX_BATCHES 20
#define CUDA_DEMO_DYNAMICS_WORLD_MAX_OBJS 1024 #define CUDA_DEMO_DYNAMICS_WORLD_MAX_OBJS 1024
#define CUDA_DEMO_DYNAMICS_WORLD_MAX_NEIGHBORS 24 #define CUDA_DEMO_DYNAMICS_WORLD_MAX_NEIGHBORS 24
#define CUDA_DEMO_DYNAMICS_WORLD_MAX_SPHERES_PER_OBJ 8 #define CUDA_DEMO_DYNAMICS_WORLD_MAX_SPHERES_PER_OBJ 8
class btGpuDemoDynamicsWorld; class btGpuDemoDynamicsWorld;
extern btGpuDemoDynamicsWorld* gpCudaDemoDynamicsWorld; // to access world members from pair cache extern btGpuDemoDynamicsWorld* gpCudaDemoDynamicsWorld; // to access world members from pair cache
class btGpuDemoDynamicsWorld : public btDiscreteDynamicsWorld class btGpuDemoDynamicsWorld : public btDiscreteDynamicsWorld
{ {
protected: protected:
int m_maxObjs; int m_maxObjs;
int m_maxNeighbors; int m_maxNeighbors;
int m_numObj; int m_numObj;
int m_numSimStep; int m_numSimStep;
bool m_useCPUSolver; bool m_useCPUSolver;
bool m_useBulletNarrowphase; bool m_useBulletNarrowphase;
float4* m_hPos; float4* m_hPos;
float* m_hRot; float* m_hRot;
float4* m_hVel; float4* m_hVel;
float* m_hAngVel; float* m_hAngVel;
float* m_hInvMass; float* m_hInvMass;
float* m_dInvMass; float* m_dInvMass;
bool m_copyMassDataToGPU; bool m_copyMassDataToGPU;
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
float4* m_dPos; float4* m_dPos;
float* m_dRot; float* m_dRot;
float4* m_dVel; float4* m_dVel;
float* m_dAngVel; float* m_dAngVel;
float4* m_dpPos; float4* m_dpPos;
float* m_dpRot; float* m_dpRot;
float4* m_dpVel; float4* m_dpVel;
float* m_dpAngVel; float* m_dpAngVel;
float4* m_dcPos; float4* m_dcPos;
float* m_dcRot; float* m_dcRot;
float4* m_dcVel; float4* m_dcVel;
float* m_dcAngVel; float* m_dcAngVel;
#endif //BT_USE_CUDA #endif //BT_USE_CUDA
btOverlappingPairCache* m_pairCache; btOverlappingPairCache* m_pairCache;
int* m_hConstraintBuffer; int* m_hConstraintBuffer;
int* m_hConstraintCounter; int* m_hConstraintCounter;
int m_maxBatches; int m_maxBatches;
int m_numBatches; int m_numBatches;
int m_totalNumConstraints; int m_totalNumConstraints;
int2* m_hIds; int2* m_hIds;
int* m_hBatchIds; int* m_hBatchIds;
int m_maxVtxPerObj; int m_maxVtxPerObj;
int2* m_dIds; int2* m_dIds;
int* m_dBatchIds; int* m_dBatchIds;
float* m_dLambdaDtBox; float* m_dLambdaDtBox;
float4* m_dContact; // 8 floats : pos.x, pos.y, pos.z, penetration, norm.x, norm.y, norm.z, reserved float4* m_dContact; // 8 floats : pos.x, pos.y, pos.z, penetration, norm.x, norm.y, norm.z, reserved
// ------------- these are only needed for CPU version and for debugging // ------------- these are only needed for CPU version and for debugging
float* m_hLambdaDtBox; float* m_hLambdaDtBox;
float4* m_hContact; // 8 floats : pos.x, pos.y, pos.z, penetration, norm.x, norm.y, norm.z, reserved float4* m_hContact; // 8 floats : pos.x, pos.y, pos.z, penetration, norm.x, norm.y, norm.z, reserved
// ------------- // -------------
btScalar m_objRad; btScalar m_objRad;
btVector3 m_worldMin; btVector3 m_worldMin;
btVector3 m_worldMax; btVector3 m_worldMax;
int* m_hConstraintUsed; int* m_hConstraintUsed;
// shape buffer // shape buffer
int m_maxShapeBufferSize; int m_maxShapeBufferSize;
int m_firstFreeShapeBufferOffset; int m_firstFreeShapeBufferOffset;
char* m_hShapeBuffer; // (pos.x, pos.y, pos.z, radius) char* m_hShapeBuffer; // (pos.x, pos.y, pos.z, radius)
char* m_dShapeBuffer;//pointer in device memory char* m_dShapeBuffer;//pointer in device memory
int2* m_hShapeIds; int2* m_hShapeIds;
int2* m_dShapeIds; int2* m_dShapeIds;
bool m_copyShapeDataToGPU; bool m_copyShapeDataToGPU;
void initShapeBuffer(int maxShapeBufferSize); void initShapeBuffer(int maxShapeBufferSize);
void freeShapeBuffer(); void freeShapeBuffer();
void sendShapeDataToGpu(); void sendShapeDataToGpu();
int m_numNonContactConstraints; int m_numNonContactConstraints;
void grabNonContactConstraintData(); void grabNonContactConstraintData();
void grabP2PConstraintData(btPoint2PointConstraint* ct); void grabP2PConstraintData(btPoint2PointConstraint* ct);
public: public:
int m_numInBatches[CUDA_DEMO_DYNAMICS_WORLD_MAX_BATCHES]; int m_numInBatches[CUDA_DEMO_DYNAMICS_WORLD_MAX_BATCHES];
void addSphere(btVector3& pos, btScalar rad); void addSphere(btVector3& pos, btScalar rad);
void addMultiShereObject(int numSpheres, int objIndex); void addMultiShereObject(int numSpheres, int objIndex);
btGpuDemoDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration, btGpuDemoDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration,
int maxObjs = CUDA_DEMO_DYNAMICS_WORLD_MAX_OBJS, int maxNeighbors = CUDA_DEMO_DYNAMICS_WORLD_MAX_NEIGHBORS) int maxObjs = CUDA_DEMO_DYNAMICS_WORLD_MAX_OBJS, int maxNeighbors = CUDA_DEMO_DYNAMICS_WORLD_MAX_NEIGHBORS)
: btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration) : btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration)
{ {
m_maxObjs = maxObjs; m_maxObjs = maxObjs;
m_maxNeighbors = maxNeighbors; m_maxNeighbors = maxNeighbors;
m_useCPUSolver = false; m_useCPUSolver = false;
m_pairCache = pairCache->getOverlappingPairCache(); m_pairCache = pairCache->getOverlappingPairCache();
int sz = m_maxObjs * m_maxNeighbors; int sz = m_maxObjs * m_maxNeighbors;
m_hConstraintBuffer = new int[sz]; m_hConstraintBuffer = new int[sz];
m_hConstraintCounter = new int[m_maxObjs]; m_hConstraintCounter = new int[m_maxObjs];
m_maxBatches = CUDA_DEMO_DYNAMICS_WORLD_MAX_BATCHES; m_maxBatches = CUDA_DEMO_DYNAMICS_WORLD_MAX_BATCHES;
m_hIds = new int2[sz]; m_hIds = new int2[sz];
m_hBatchIds = new int[sz]; m_hBatchIds = new int[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
{ {
m_hBatchIds[i] = -1; m_hBatchIds[i] = -1;
} }
m_hPos = new float4[m_maxObjs]; m_hPos = new float4[m_maxObjs];
m_hVel = new float4[m_maxObjs]; m_hVel = new float4[m_maxObjs];
m_hRot = new float[m_maxObjs]; m_hRot = new float[m_maxObjs];
m_hAngVel = new float[m_maxObjs]; m_hAngVel = new float[m_maxObjs];
m_hInvMass = new float[m_maxObjs]; m_hInvMass = new float[m_maxObjs];
m_maxVtxPerObj = 8; m_maxVtxPerObj = 8;
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
btCuda_allocateArray((void**)&m_dPos, sizeof(float4) * m_maxObjs); btCuda_allocateArray((void**)&m_dPos, sizeof(float4) * m_maxObjs);
btCuda_allocateArray((void**)&m_dRot, sizeof(float) * m_maxObjs); btCuda_allocateArray((void**)&m_dRot, sizeof(float) * m_maxObjs);
btCuda_allocateArray((void**)&m_dVel, sizeof(float4) * m_maxObjs); btCuda_allocateArray((void**)&m_dVel, sizeof(float4) * m_maxObjs);
btCuda_allocateArray((void**)&m_dAngVel, sizeof(float) * m_maxObjs); btCuda_allocateArray((void**)&m_dAngVel, sizeof(float) * m_maxObjs);
btCuda_allocateArray((void**)&m_dpPos, sizeof(float4) * m_maxObjs); btCuda_allocateArray((void**)&m_dpPos, sizeof(float4) * m_maxObjs);
btCuda_allocateArray((void**)&m_dpRot, sizeof(float) * m_maxObjs); btCuda_allocateArray((void**)&m_dpRot, sizeof(float) * m_maxObjs);
btCuda_allocateArray((void**)&m_dpVel, sizeof(float4) * m_maxObjs); btCuda_allocateArray((void**)&m_dpVel, sizeof(float4) * m_maxObjs);
btCuda_allocateArray((void**)&m_dpAngVel, sizeof(float) * m_maxObjs); btCuda_allocateArray((void**)&m_dpAngVel, sizeof(float) * m_maxObjs);
btCuda_allocateArray((void**)&m_dInvMass, sizeof(float) * m_maxObjs); btCuda_allocateArray((void**)&m_dInvMass, sizeof(float) * m_maxObjs);
btCuda_allocateArray((void**)&m_dIds, sizeof(int2) * sz); btCuda_allocateArray((void**)&m_dIds, sizeof(int2) * sz);
btCuda_allocateArray((void**)&m_dBatchIds, sizeof(int) * sz); btCuda_allocateArray((void**)&m_dBatchIds, sizeof(int) * sz);
btCuda_allocateArray((void**)&m_dLambdaDtBox, sizeof(float) * sz * m_maxVtxPerObj); btCuda_allocateArray((void**)&m_dLambdaDtBox, sizeof(float) * sz * m_maxVtxPerObj);
btCuda_allocateArray((void**)&m_dContact, sizeof(float) * sz * m_maxVtxPerObj * 8); btCuda_allocateArray((void**)&m_dContact, sizeof(float) * sz * m_maxVtxPerObj * 8);
// btCuda_allocateArray((void**)&m_dPositionConstraint, sizeof(float) * sz * m_maxVtxPerObj * 2); // btCuda_allocateArray((void**)&m_dPositionConstraint, sizeof(float) * sz * m_maxVtxPerObj * 2);
// btCuda_allocateArray((void**)&m_dNormal, sizeof(float3) * sz * m_maxVtxPerObj * 2); // btCuda_allocateArray((void**)&m_dNormal, sizeof(float3) * sz * m_maxVtxPerObj * 2);
#endif //BT_USE_CUDA #endif //BT_USE_CUDA
m_hLambdaDtBox = new float[sz * m_maxVtxPerObj]; m_hLambdaDtBox = new float[sz * m_maxVtxPerObj];
m_hContact = new float4[sz * m_maxVtxPerObj * 2]; m_hContact = new float4[sz * m_maxVtxPerObj * 2];
// m_hPositionConstraint = new float[sz * m_maxVtxPerObj * 2]; // m_hPositionConstraint = new float[sz * m_maxVtxPerObj * 2];
// m_hNormal = new float3[sz * m_maxVtxPerObj * 2]; // m_hNormal = new float3[sz * m_maxVtxPerObj * 2];
m_numSimStep = 0; m_numSimStep = 0;
m_objRad = 1.0f; m_objRad = 1.0f;
m_hConstraintUsed = new int[sz]; m_hConstraintUsed = new int[sz];
gpCudaDemoDynamicsWorld = this; gpCudaDemoDynamicsWorld = this;
m_totalNumConstraints = 0; m_totalNumConstraints = 0;
initShapeBuffer(m_maxObjs * CUDA_DEMO_DYNAMICS_WORLD_MAX_SPHERES_PER_OBJ * sizeof(float) * 4); initShapeBuffer(m_maxObjs * CUDA_DEMO_DYNAMICS_WORLD_MAX_SPHERES_PER_OBJ * sizeof(float) * 4);
m_copyMassDataToGPU = true; m_copyMassDataToGPU = true;
} }
virtual ~btGpuDemoDynamicsWorld() virtual ~btGpuDemoDynamicsWorld()
{ {
delete [] m_hConstraintBuffer; delete [] m_hConstraintBuffer;
delete [] m_hConstraintCounter; delete [] m_hConstraintCounter;
delete [] m_hIds; delete [] m_hIds;
delete [] m_hBatchIds; delete [] m_hBatchIds;
delete [] m_hPos; delete [] m_hPos;
delete [] m_hRot; delete [] m_hRot;
delete [] m_hVel; delete [] m_hVel;
delete [] m_hAngVel; delete [] m_hAngVel;
delete [] m_hInvMass; delete [] m_hInvMass;
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
btCuda_freeArray(m_dPos); btCuda_freeArray(m_dPos);
btCuda_freeArray(m_dRot); btCuda_freeArray(m_dRot);
btCuda_freeArray(m_dVel); btCuda_freeArray(m_dVel);
btCuda_freeArray(m_dAngVel); btCuda_freeArray(m_dAngVel);
btCuda_freeArray(m_dpPos); btCuda_freeArray(m_dpPos);
btCuda_freeArray(m_dpRot); btCuda_freeArray(m_dpRot);
btCuda_freeArray(m_dpVel); btCuda_freeArray(m_dpVel);
btCuda_freeArray(m_dpAngVel); btCuda_freeArray(m_dpAngVel);
btCuda_freeArray(m_dInvMass); btCuda_freeArray(m_dInvMass);
btCuda_freeArray(m_dIds); btCuda_freeArray(m_dIds);
btCuda_freeArray(m_dBatchIds); btCuda_freeArray(m_dBatchIds);
btCuda_freeArray(m_dLambdaDtBox); btCuda_freeArray(m_dLambdaDtBox);
btCuda_freeArray(m_dContact); btCuda_freeArray(m_dContact);
#endif //BT_USE_CUDA #endif //BT_USE_CUDA
delete [] m_hLambdaDtBox; delete [] m_hLambdaDtBox;
delete [] m_hContact; delete [] m_hContact;
delete [] m_hConstraintUsed; delete [] m_hConstraintUsed;
gpCudaDemoDynamicsWorld = NULL; gpCudaDemoDynamicsWorld = NULL;
freeShapeBuffer(); freeShapeBuffer();
} }
virtual void calculateSimulationIslands() virtual void calculateSimulationIslands()
{ {
} }
virtual void solveConstraints(btContactSolverInfo& solverInfo); virtual void solveConstraints(btContactSolverInfo& solverInfo);
void solveConstraints2(btContactSolverInfo& solverInfo); void solveConstraints2(btContactSolverInfo& solverInfo);
void solveConstraintsCPU2(btContactSolverInfo& solverInfo); void solveConstraintsCPU2(btContactSolverInfo& solverInfo);
void debugDrawConstraints(int selectedBatch, const float* pColorTab); void debugDrawConstraints(int selectedBatch, const float* pColorTab);
void setObjRad(btScalar rad) { m_objRad = rad; } void setObjRad(btScalar rad) { m_objRad = rad; }
void setWorldMin(const btVector3& worldMin) { m_worldMin = worldMin; } void setWorldMin(const btVector3& worldMin) { m_worldMin = worldMin; }
void setWorldMax(const btVector3& worldMax) { m_worldMax = worldMax; } void setWorldMax(const btVector3& worldMax) { m_worldMax = worldMax; }
void grabData(); void grabData();
void grabContactData(); void grabContactData();
void copyDataToGPU(); void copyDataToGPU();
void setConstraintData(btCudaPartProps& partProps); void setConstraintData(btCudaPartProps& partProps);
void copyDataFromGPU(); void copyDataFromGPU();
void writebackData(); void writebackData();
void setUseCPUSolver(bool useCPU) { m_useCPUSolver = useCPU; } void setUseCPUSolver(bool useCPU) { m_useCPUSolver = useCPU; }
void setUseBulletNarrowphase(bool useBulletNarrowphase) {m_useBulletNarrowphase = useBulletNarrowphase; } void setUseBulletNarrowphase(bool useBulletNarrowphase) {m_useBulletNarrowphase = useBulletNarrowphase; }
void createBatches2(); void createBatches2();
int2* getIdsPtr() { return m_hIds; } int2* getIdsPtr() { return m_hIds; }
void setTotalNumConstraints(int totalNumConstraints) { m_totalNumConstraints = totalNumConstraints; } void setTotalNumConstraints(int totalNumConstraints) { m_totalNumConstraints = totalNumConstraints; }
int getTotalNumConstraints() { return m_totalNumConstraints; } int getTotalNumConstraints() { return m_totalNumConstraints; }
}; };
#endif //BT_CUDA_DEMO_DYNAMICS_WORLD_H #endif //BT_CUDA_DEMO_DYNAMICS_WORLD_H

View File

@@ -1,76 +1,76 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "btGpuDemoPairCache.h" #include "btGpuDemoPairCache.h"
#include "btGpuDemoDynamicsWorld.h" #include "btGpuDemoDynamicsWorld.h"
void btGpuDemoPairCache::processAllOverlappingPairs(btOverlapCallback* callback, btDispatcher* dispatcher) void btGpuDemoPairCache::processAllOverlappingPairs(btOverlapCallback* callback, btDispatcher* dispatcher)
{ {
int sz = m_maxProxies * m_maxNeighbors; int sz = m_maxProxies * m_maxNeighbors;
int numContConstraints = 0; int numContConstraints = 0;
int2* pIds = gpCudaDemoDynamicsWorld->getIdsPtr(); int2* pIds = gpCudaDemoDynamicsWorld->getIdsPtr();
for(int idx = 0; idx < sz; idx++) for(int idx = 0; idx < sz; idx++)
{ {
int neigh = m_hNeighbors[idx]; int neigh = m_hNeighbors[idx];
if(neigh >= 0) if(neigh >= 0)
{ {
int i=idx / m_maxNeighbors; int i=idx / m_maxNeighbors;
int j=idx % m_maxNeighbors; int j=idx % m_maxNeighbors;
pIds[numContConstraints].x = i; pIds[numContConstraints].x = i;
pIds[numContConstraints].y = m_hNeighbors[i * m_maxNeighbors + j]; pIds[numContConstraints].y = m_hNeighbors[i * m_maxNeighbors + j];
numContConstraints++; numContConstraints++;
} }
} }
gpCudaDemoDynamicsWorld->setTotalNumConstraints(numContConstraints); gpCudaDemoDynamicsWorld->setTotalNumConstraints(numContConstraints);
} }
// this will be called for each overlapping pair if collision detection uses pairCache other than btGpuDemoPairCache // this will be called for each overlapping pair if collision detection uses pairCache other than btGpuDemoPairCache
// IMPORTANT : m_numConstraints in gpCudaDemoDynamicsWorld is set to 0 at start of simulation step // IMPORTANT : m_numConstraints in gpCudaDemoDynamicsWorld is set to 0 at start of simulation step
// IMPORTANT : companionIds for all objects should be properly set at start of simulation step // IMPORTANT : companionIds for all objects should be properly set at start of simulation step
void cudaDemoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo) void cudaDemoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo)
{ {
btCollisionObject* colObj0 = (btCollisionObject*)collisionPair.m_pProxy0->m_clientObject; btCollisionObject* colObj0 = (btCollisionObject*)collisionPair.m_pProxy0->m_clientObject;
btCollisionObject* colObj1 = (btCollisionObject*)collisionPair.m_pProxy1->m_clientObject; btCollisionObject* colObj1 = (btCollisionObject*)collisionPair.m_pProxy1->m_clientObject;
if (dispatcher.needsCollision(colObj0,colObj1)) if (dispatcher.needsCollision(colObj0,colObj1))
{ {
// int id0 = collisionPair.m_pProxy0->m_uniqueId - 2; // int id0 = collisionPair.m_pProxy0->m_uniqueId - 2;
// int id1 = collisionPair.m_pProxy1->m_uniqueId - 2; // int id1 = collisionPair.m_pProxy1->m_uniqueId - 2;
// cannot use m_uniqueId : it may be altered by broadphase code // cannot use m_uniqueId : it may be altered by broadphase code
// so we'll use companionIds set on the initialization stage // so we'll use companionIds set on the initialization stage
unsigned int id0 = colObj0->getCompanionId(); unsigned int id0 = colObj0->getCompanionId();
unsigned int id1 = colObj1->getCompanionId(); unsigned int id1 = colObj1->getCompanionId();
if(id0 > id1) if(id0 > id1)
{ {
int tmp = id0; id0 = id1; id1 = tmp; int tmp = id0; id0 = id1; id1 = tmp;
} }
int totalNumConstraints = gpCudaDemoDynamicsWorld->getTotalNumConstraints(); int totalNumConstraints = gpCudaDemoDynamicsWorld->getTotalNumConstraints();
int2* pIds = gpCudaDemoDynamicsWorld->getIdsPtr(); int2* pIds = gpCudaDemoDynamicsWorld->getIdsPtr();
pIds += totalNumConstraints; pIds += totalNumConstraints;
pIds->x = id0; pIds->x = id0;
pIds->y = id1; pIds->y = id1;
totalNumConstraints++; totalNumConstraints++;
gpCudaDemoDynamicsWorld->setTotalNumConstraints(totalNumConstraints); gpCudaDemoDynamicsWorld->setTotalNumConstraints(totalNumConstraints);
} }
} // cudaDemoNearCallback() } // cudaDemoNearCallback()

View File

@@ -1,136 +1,136 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef CUDA_DEMO_PAIR_CACHE_H #ifndef CUDA_DEMO_PAIR_CACHE_H
#define CUDA_DEMO_PAIR_CACHE_H #define CUDA_DEMO_PAIR_CACHE_H
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
class btGpuDemoPairCache : public btNullPairCache class btGpuDemoPairCache : public btNullPairCache
{ {
public: public:
int m_maxProxies; int m_maxProxies;
int m_maxNeighbors; int m_maxNeighbors;
int* m_hNeighbors; int* m_hNeighbors;
int m_numPairs; int m_numPairs;
int m_numSmallProxies; int m_numSmallProxies;
int m_maxSmallProxies; int m_maxSmallProxies;
btGpuDemoPairCache(int maxProxies, int maxNeighbors, int maxSmallProxies) btGpuDemoPairCache(int maxProxies, int maxNeighbors, int maxSmallProxies)
{ {
m_maxProxies = maxProxies; m_maxProxies = maxProxies;
m_maxNeighbors = maxNeighbors; m_maxNeighbors = maxNeighbors;
m_maxSmallProxies = maxSmallProxies; m_maxSmallProxies = maxSmallProxies;
int sz = maxProxies * maxNeighbors; int sz = maxProxies * maxNeighbors;
m_hNeighbors = new int [sz]; m_hNeighbors = new int [sz];
reset(); reset();
} }
~btGpuDemoPairCache() ~btGpuDemoPairCache()
{ {
delete [] m_hNeighbors; delete [] m_hNeighbors;
} }
void reset(void) void reset(void)
{ {
int sz = m_maxProxies * m_maxNeighbors; int sz = m_maxProxies * m_maxNeighbors;
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
{ {
m_hNeighbors[i] = -1; m_hNeighbors[i] = -1;
} }
m_numPairs = 0; m_numPairs = 0;
} }
virtual int getNumOverlappingPairs() const virtual int getNumOverlappingPairs() const
{ {
return m_numPairs; return m_numPairs;
//return 0; // to skip btSimulationIslandManager::findUnions() //return 0; // to skip btSimulationIslandManager::findUnions()
} }
virtual void processAllOverlappingPairs(btOverlapCallback* callback, btDispatcher* dispatcher); virtual void processAllOverlappingPairs(btOverlapCallback* callback, btDispatcher* dispatcher);
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1)
{ {
int id0 = proxy0->m_uniqueId - 2; int id0 = proxy0->m_uniqueId - 2;
int id1 = proxy1->m_uniqueId - 2; int id1 = proxy1->m_uniqueId - 2;
if(id0 >= m_maxSmallProxies) if(id0 >= m_maxSmallProxies)
{ {
id0 -= m_maxSmallProxies - m_numSmallProxies; id0 -= m_maxSmallProxies - m_numSmallProxies;
} }
if(id1 >= m_maxSmallProxies) if(id1 >= m_maxSmallProxies)
{ {
id1 -= m_maxSmallProxies - m_numSmallProxies; id1 -= m_maxSmallProxies - m_numSmallProxies;
} }
if(id0 > id1) if(id0 > id1)
{ {
int tmp = id0; id0 = id1; id1 = tmp; int tmp = id0; id0 = id1; id1 = tmp;
} }
int offs = id0 * m_maxNeighbors; int offs = id0 * m_maxNeighbors;
int i; int i;
for(i = 0; i < m_maxNeighbors; i++) for(i = 0; i < m_maxNeighbors; i++)
{ {
if(m_hNeighbors[offs + i] < 0) if(m_hNeighbors[offs + i] < 0)
{ {
m_hNeighbors[offs + i] = id1; m_hNeighbors[offs + i] = id1;
m_numPairs++; m_numPairs++;
break; break;
} }
} }
// btAssert(i < m_maxNeighbors); // btAssert(i < m_maxNeighbors);
return 0; return 0;
} }
virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1,btDispatcher* /*dispatcher*/) virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1,btDispatcher* /*dispatcher*/)
{ {
int id0 = proxy0->m_uniqueId - 2; int id0 = proxy0->m_uniqueId - 2;
int id1 = proxy1->m_uniqueId - 2; int id1 = proxy1->m_uniqueId - 2;
if(id0 >= m_maxSmallProxies) if(id0 >= m_maxSmallProxies)
{ {
id0 -= m_maxSmallProxies - m_numSmallProxies; id0 -= m_maxSmallProxies - m_numSmallProxies;
} }
if(id1 >= m_maxSmallProxies) if(id1 >= m_maxSmallProxies)
{ {
id1 -= m_maxSmallProxies - m_numSmallProxies; id1 -= m_maxSmallProxies - m_numSmallProxies;
} }
if(id0 > id1) if(id0 > id1)
{ {
int tmp = id0; id0 = id1; id1 = tmp; int tmp = id0; id0 = id1; id1 = tmp;
} }
int offs = id0 * m_maxNeighbors; int offs = id0 * m_maxNeighbors;
int i; int i;
for(i = 0; i < m_maxNeighbors; i++) for(i = 0; i < m_maxNeighbors; i++)
{ {
if(m_hNeighbors[offs + i] == id1) if(m_hNeighbors[offs + i] == id1)
{ {
m_hNeighbors[offs + i] = -1; m_hNeighbors[offs + i] = -1;
m_numPairs--; m_numPairs--;
break; break;
} }
} }
// btAssert(i < m_maxNeighbors); // btAssert(i < m_maxNeighbors);
return 0; return 0;
} }
}; };
extern void cudaDemoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo); extern void cudaDemoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo);
#endif //CUDA_DEMO_PAIR_CACHE_H #endif //CUDA_DEMO_PAIR_CACHE_H

View File

@@ -1,62 +1,62 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BasicDemo.h" #include "BasicDemo.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "LinearMath/btHashMap.h" #include "LinearMath/btHashMap.h"
class OurValue class OurValue
{ {
int m_uid; int m_uid;
public: public:
OurValue(const btVector3& initialPos) OurValue(const btVector3& initialPos)
:m_position(initialPos) :m_position(initialPos)
{ {
static int gUid=0; static int gUid=0;
m_uid=gUid; m_uid=gUid;
gUid++; gUid++;
} }
btVector3 m_position; btVector3 m_position;
int getUid() const int getUid() const
{ {
return m_uid; return m_uid;
} }
}; };
GLDebugDrawer gDebugDrawer; GLDebugDrawer gDebugDrawer;
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
BasicDemo ccdDemo; BasicDemo ccdDemo;
ccdDemo.initPhysics(); ccdDemo.initPhysics();
ccdDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); ccdDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);
#ifdef CHECK_MEMORY_LEAKS #ifdef CHECK_MEMORY_LEAKS
ccdDemo.exitPhysics(); ccdDemo.exitPhysics();
#else #else
return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&ccdDemo); return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&ccdDemo);
#endif #endif
//default glut doesn't return from mainloop //default glut doesn't return from mainloop
return 0; return 0;
} }

View File

@@ -1,264 +1,264 @@
#include "oecakeLoader.h" #include "oecakeLoader.h"
#include <stdio.h> //printf debugging #include <stdio.h> //printf debugging
#include <stdlib.h> #include <stdlib.h>
btCompoundShape* shiftTransform(btCompoundShape* boxCompound,btScalar mass,btTransform& shift) btCompoundShape* shiftTransform(btCompoundShape* boxCompound,btScalar mass,btTransform& shift)
{ {
btTransform principal; btTransform principal;
btVector3 principalInertia; btVector3 principalInertia;
btScalar* masses = new btScalar[boxCompound->getNumChildShapes()]; btScalar* masses = new btScalar[boxCompound->getNumChildShapes()];
for (int j=0;j<boxCompound->getNumChildShapes();j++) for (int j=0;j<boxCompound->getNumChildShapes();j++)
{ {
//evenly distribute mass //evenly distribute mass
masses[j]=mass/boxCompound->getNumChildShapes(); masses[j]=mass/boxCompound->getNumChildShapes();
} }
boxCompound->calculatePrincipalAxisTransform(masses,principal,principalInertia); boxCompound->calculatePrincipalAxisTransform(masses,principal,principalInertia);
///create a new compound with world transform/center of mass properly aligned with the principal axis ///create a new compound with world transform/center of mass properly aligned with the principal axis
///non-recursive compound shapes perform better ///non-recursive compound shapes perform better
//#define USE_RECURSIVE_COMPOUND 1 //#define USE_RECURSIVE_COMPOUND 1
#ifdef USE_RECURSIVE_COMPOUND #ifdef USE_RECURSIVE_COMPOUND
btCompoundShape* newCompound = new btCompoundShape(); btCompoundShape* newCompound = new btCompoundShape();
newCompound->addChildShape(principal.inverse(),boxCompound); newCompound->addChildShape(principal.inverse(),boxCompound);
m_collisionShapes.push_back(newCompound); m_collisionShapes.push_back(newCompound);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,newCompound,principalInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,newCompound,principalInertia);
#else #else
#ifdef CHANGE_COMPOUND_INPLACE #ifdef CHANGE_COMPOUND_INPLACE
for (int i=0;i<boxCompound->getNumChildShapes();i++) for (int i=0;i<boxCompound->getNumChildShapes();i++)
{ {
btTransform newChildTransform = principal.inverse()*boxCompound->getChildTransform(i); btTransform newChildTransform = principal.inverse()*boxCompound->getChildTransform(i);
///updateChildTransform is really slow, because it re-calculates the AABB each time. todo: add option to disable this update ///updateChildTransform is really slow, because it re-calculates the AABB each time. todo: add option to disable this update
boxCompound->updateChildTransform(i,newChildTransform); boxCompound->updateChildTransform(i,newChildTransform);
} }
if (isDynamic) if (isDynamic)
boxCompound->calculateLocalInertia(mass,localInertia); boxCompound->calculateLocalInertia(mass,localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,boxCompound,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,boxCompound,localInertia);
#else #else
///creation is faster using a new compound to store the shifted children ///creation is faster using a new compound to store the shifted children
btCompoundShape* newBoxCompound = new btCompoundShape(); btCompoundShape* newBoxCompound = new btCompoundShape();
for (int i=0;i<boxCompound->getNumChildShapes();i++) for (int i=0;i<boxCompound->getNumChildShapes();i++)
{ {
btTransform newChildTransform = principal.inverse()*boxCompound->getChildTransform(i); btTransform newChildTransform = principal.inverse()*boxCompound->getChildTransform(i);
///updateChildTransform is really slow, because it re-calculates the AABB each time. todo: add option to disable this update ///updateChildTransform is really slow, because it re-calculates the AABB each time. todo: add option to disable this update
newBoxCompound->addChildShape(newChildTransform,boxCompound->getChildShape(i)); newBoxCompound->addChildShape(newChildTransform,boxCompound->getChildShape(i));
} }
#endif #endif
#endif//USE_RECURSIVE_COMPOUND #endif//USE_RECURSIVE_COMPOUND
shift = principal; shift = principal;
return newBoxCompound; return newBoxCompound;
} }
void BasicOECakeReader::addParticle(int materialType, int pIndex, int pColor, float pPosX, float pPosY,float radius) void BasicOECakeReader::addParticle(int materialType, int pIndex, int pColor, float pPosX, float pPosY,float radius)
{ {
//determine that we have a new shape? //determine that we have a new shape?
if (m_particlePositions.size()) if (m_particlePositions.size())
{ {
if ( if (
(materialType != m_materialType) (materialType != m_materialType)
|| ||
(pIndex != m_particleObjectIndex) (pIndex != m_particleObjectIndex)
) )
{ {
convertParticleGroup(); convertParticleGroup();
} }
} }
//add to array //add to array
m_materialType = materialType; m_materialType = materialType;
m_particleObjectIndex = pIndex; m_particleObjectIndex = pIndex;
m_particleColor = pColor; m_particleColor = pColor;
m_particlePositions.push_back(btVector3(pPosX,pPosY,0.)); m_particlePositions.push_back(btVector3(pPosX,pPosY,0.));
m_particleRadii.push_back(radius); m_particleRadii.push_back(radius);
} }
void BasicOECakeReader::convertParticleGroup() void BasicOECakeReader::convertParticleGroup()
{ {
printf("found a particle group of %d particles\n",m_particlePositions.size()); printf("found a particle group of %d particles\n",m_particlePositions.size());
if (m_particlePositions.size()>0) if (m_particlePositions.size()>0)
{ {
addNewCollisionShape(m_particlePositions.size(),&m_particlePositions[0],&m_particleRadii[0],m_materialType,m_particleObjectIndex,m_particleColor); addNewCollisionShape(m_particlePositions.size(),&m_particlePositions[0],&m_particleRadii[0],m_materialType,m_particleObjectIndex,m_particleColor);
m_particlePositions.clear(); m_particlePositions.clear();
m_particleRadii.clear(); m_particleRadii.clear();
} }
} }
void BasicOECakeReader::addNewCollisionShape(int numParticles, btVector3* particlePositions, btScalar* radii, int materialType, int objectIndex,int color ) void BasicOECakeReader::addNewCollisionShape(int numParticles, btVector3* particlePositions, btScalar* radii, int materialType, int objectIndex,int color )
{ {
//create Bullet stuff //create Bullet stuff
btCompoundShape* colShape = 0; btCompoundShape* colShape = 0;
btScalar mass; btScalar mass;
bool addConstraint = false; bool addConstraint = false;
if (materialType&0x800000) if (materialType&0x800000)
{ {
addConstraint = true; addConstraint = true;
} }
if ((materialType & 0x20000) ||(materialType & 0x12)) if ((materialType & 0x20000) ||(materialType & 0x12))
{ {
mass = 1.f; mass = 1.f;
} else } else
{ {
mass = 0.f; mass = 0.f;
} }
btTransform startTransform; btTransform startTransform;
startTransform.setIdentity(); startTransform.setIdentity();
int numCurSpheres = 0; int numCurSpheres = 0;
{ {
btTransform localTrans; btTransform localTrans;
localTrans.setIdentity(); localTrans.setIdentity();
//static //static
btCompoundShape* compound = new btCompoundShape(); btCompoundShape* compound = new btCompoundShape();
for (int i=0;i<numParticles;i++) for (int i=0;i<numParticles;i++)
{ {
numCurSpheres++; numCurSpheres++;
localTrans.setOrigin(particlePositions[i]); localTrans.setOrigin(particlePositions[i]);
btSphereShape* particle = new btSphereShape(radii[i]); btSphereShape* particle = new btSphereShape(radii[i]);
compound->addChildShape(localTrans,particle); compound->addChildShape(localTrans,particle);
if (mass==0.f && (numCurSpheres>=7)) if (mass==0.f && (numCurSpheres>=7))
{ {
createBodyForCompoundShape(compound,false,startTransform,mass); createBodyForCompoundShape(compound,false,startTransform,mass);
compound = new btCompoundShape(); compound = new btCompoundShape();
numCurSpheres = 0; numCurSpheres = 0;
} }
} }
if (mass) if (mass)
{ {
//shift the center of mass, based on all spheres //shift the center of mass, based on all spheres
btCompoundShape* newCompound = shiftTransform(compound,mass,startTransform); btCompoundShape* newCompound = shiftTransform(compound,mass,startTransform);
colShape = newCompound; colShape = newCompound;
} else } else
{ {
//use unmodified //use unmodified
colShape = compound; colShape = compound;
} }
} }
btDefaultMotionState* myMotionState = 0; btDefaultMotionState* myMotionState = 0;
if (colShape && numCurSpheres) if (colShape && numCurSpheres)
{ {
createBodyForCompoundShape(colShape,addConstraint,startTransform,mass); createBodyForCompoundShape(colShape,addConstraint,startTransform,mass);
} }
} }
int BasicOECakeReader::processLine(char * buffer, int size) int BasicOECakeReader::processLine(char * buffer, int size)
{ {
int numBytesRead = 0; int numBytesRead = 0;
if (buffer[0] == 'p') if (buffer[0] == 'p')
{ {
int materialType; int materialType;
int particleObjectIndex; int particleObjectIndex;
int particleColor; int particleColor;
int dummy1; int dummy1;
float particlePosX; float particlePosX;
float particlePosY; float particlePosY;
if (sscanf (buffer, "p %x %x %x %x %f %f", &materialType,&particleObjectIndex,&dummy1, &particleColor, &particlePosX, &particlePosY) == 6) if (sscanf (buffer, "p %x %x %x %x %f %f", &materialType,&particleObjectIndex,&dummy1, &particleColor, &particlePosX, &particlePosY) == 6)
{ {
addParticle(materialType,particleObjectIndex,particleColor,particlePosX,particlePosY); addParticle(materialType,particleObjectIndex,particleColor,particlePosX,particlePosY);
} }
else else
{ {
printf("ERROR: invalid line (%s)\n", buffer); printf("ERROR: invalid line (%s)\n", buffer);
} }
} }
while (*buffer != '\n' && size != 0) while (*buffer != '\n' && size != 0)
{ {
buffer++; buffer++;
numBytesRead++; numBytesRead++;
} }
if (buffer[0]==0x0a) if (buffer[0]==0x0a)
{ {
buffer++; buffer++;
numBytesRead++; numBytesRead++;
} }
return numBytesRead; return numBytesRead;
} }
bool BasicOECakeReader::processFile(char * fileName) bool BasicOECakeReader::processFile(char * fileName)
{ {
FILE * fp = fopen(fileName, "rb"); FILE * fp = fopen(fileName, "rb");
if (fp == NULL) if (fp == NULL)
{ {
printf("ERROR: file(%s) not found", fileName); printf("ERROR: file(%s) not found", fileName);
return false; return false;
} }
int size; int size;
if (fseek(fp, 0, SEEK_END) || (size = ftell(fp)) == EOF || fseek(fp, 0, SEEK_SET)) if (fseek(fp, 0, SEEK_END) || (size = ftell(fp)) == EOF || fseek(fp, 0, SEEK_SET))
{ {
printf("ERROR: problem reading file(%s)", fileName); printf("ERROR: problem reading file(%s)", fileName);
fclose(fp); fclose(fp);
return false; return false;
} }
else else
{ {
rewind (fp); rewind (fp);
char * buffer = (char *) malloc(size+1); char * buffer = (char *) malloc(size+1);
memset(buffer,0,size); memset(buffer,0,size);
if (fread(buffer,1,size,fp) != size) if (fread(buffer,1,size,fp) != size)
{ {
printf("Error reading file %s!\n",fileName); printf("Error reading file %s!\n",fileName);
fclose(fp); fclose(fp);
return false; return false;
} }
int totalBytesRead = 0; int totalBytesRead = 0;
while(totalBytesRead<size) while(totalBytesRead<size)
{ {
int remainingSize = size-totalBytesRead; int remainingSize = size-totalBytesRead;
if (remainingSize<1229) if (remainingSize<1229)
{ {
printf(".."); printf("..");
} }
totalBytesRead +=processLine(&buffer[totalBytesRead],remainingSize); totalBytesRead +=processLine(&buffer[totalBytesRead],remainingSize);
} }
} }
convertParticleGroup(); convertParticleGroup();
fclose(fp); fclose(fp);
return false; return false;
} }

View File

@@ -1,35 +1,35 @@
#ifndef OE_CAKE_LOADER_H #ifndef OE_CAKE_LOADER_H
#define OE_CAKE_LOADER_H #define OE_CAKE_LOADER_H
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
class BasicOECakeReader class BasicOECakeReader
{ {
int m_materialType; int m_materialType;
int m_particleObjectIndex; int m_particleObjectIndex;
int m_particleColor; int m_particleColor;
btAlignedObjectArray<btVector3> m_particlePositions; btAlignedObjectArray<btVector3> m_particlePositions;
btAlignedObjectArray<btScalar> m_particleRadii; btAlignedObjectArray<btScalar> m_particleRadii;
void addParticle(int materialType, int pIndex, int pColor, float pPosX, float pPosY, float radius=1); void addParticle(int materialType, int pIndex, int pColor, float pPosX, float pPosY, float radius=1);
virtual void addNewCollisionShape(int numParticles, btVector3* particlePositions, btScalar* radii, int materialType, int objectIndex,int color ); virtual void addNewCollisionShape(int numParticles, btVector3* particlePositions, btScalar* radii, int materialType, int objectIndex,int color );
int processLine(char * buffer, int size); int processLine(char * buffer, int size);
void convertParticleGroup(); void convertParticleGroup();
public: public:
BasicOECakeReader() BasicOECakeReader()
{ {
} }
bool processFile(char * fileName); bool processFile(char * fileName);
virtual void createBodyForCompoundShape(btCompoundShape* compound,bool addConstraint,const btTransform& worldTransform, btScalar mass) = 0; virtual void createBodyForCompoundShape(btCompoundShape* compound,bool addConstraint,const btTransform& worldTransform, btScalar mass) = 0;
}; };
#endif //OE_CAKE_LOADER_H #endif //OE_CAKE_LOADER_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,93 +1,93 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BASIC_DEMO3D_H #ifndef BASIC_DEMO3D_H
#define BASIC_DEMO3D_H #define BASIC_DEMO3D_H
#include "GlutDemoApplication.h" #include "GlutDemoApplication.h"
#include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btAlignedObjectArray.h"
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h" #include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
class btBroadphaseInterface; class btBroadphaseInterface;
class btCollisionShape; class btCollisionShape;
class btOverlappingPairCache; class btOverlappingPairCache;
class btCollisionDispatcher; class btCollisionDispatcher;
class btConstraintSolver; class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc; struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration; class btDefaultCollisionConfiguration;
///BasicDemo is good starting point for learning the code base and porting. ///BasicDemo is good starting point for learning the code base and porting.
class BasicDemo3D : public GlutDemoApplication class BasicDemo3D : public GlutDemoApplication
{ {
//keep the collision shapes, for deletion/cleanup //keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase; btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher; btCollisionDispatcher* m_dispatcher;
btConstraintSolver* m_solver; btConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration; btDefaultCollisionConfiguration* m_collisionConfiguration;
int m_mouseButtons; int m_mouseButtons;
int m_mouseOldX; int m_mouseOldX;
int m_mouseOldY; int m_mouseOldY;
public: public:
BasicDemo3D() BasicDemo3D()
{ {
} }
virtual ~BasicDemo3D() virtual ~BasicDemo3D()
{ {
exitPhysics(); exitPhysics();
} }
void initPhysics(); void initPhysics();
void exitPhysics(); void exitPhysics();
virtual void clientMoveAndDisplay(); virtual void clientMoveAndDisplay();
virtual void displayCallback(); virtual void displayCallback();
virtual void keyboardCallback(unsigned char key, int x, int y); virtual void keyboardCallback(unsigned char key, int x, int y);
virtual void mouseFunc(int button, int state, int x, int y); virtual void mouseFunc(int button, int state, int x, int y);
virtual void mouseMotionFunc(int x,int y); virtual void mouseMotionFunc(int x,int y);
virtual void clientResetScene(); virtual void clientResetScene();
static DemoApplication* Create() static DemoApplication* Create()
{ {
BasicDemo3D* demo = new BasicDemo3D; BasicDemo3D* demo = new BasicDemo3D;
demo->myinit(); demo->myinit();
demo->initPhysics(); demo->initPhysics();
demo->m_mouseButtons = 0; demo->m_mouseButtons = 0;
demo->m_mouseOldX = 0; demo->m_mouseOldX = 0;
demo->m_mouseOldY = 0; demo->m_mouseOldY = 0;
return demo; return demo;
} }
void DrawConstraintInfo(); void DrawConstraintInfo();
void outputDebugInfo(int & xOffset,int & yStart, int yIncr); void outputDebugInfo(int & xOffset,int & yStart, int yIncr);
virtual void renderme(); virtual void renderme();
void setWireMode(bool wireOnOff); void setWireMode(bool wireOnOff);
}; };
#endif //BASIC_DEMO3D_H #endif //BASIC_DEMO3D_H

View File

@@ -1,32 +1,32 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
#include "LinearMath/btQuickprof.h" #include "LinearMath/btQuickprof.h"
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
#include "btGpuDemo3dSharedTypes.h" #include "btGpuDemo3dSharedTypes.h"
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
#include "BulletMultiThreaded/btGpuDefines.h" #include "BulletMultiThreaded/btGpuDefines.h"
#include "BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#include "btGpuDemo3dSharedCode.h" #include "btGpuDemo3dSharedCode.h"
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------

File diff suppressed because it is too large Load Diff

View File

@@ -1,38 +1,38 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//---------- C o n s t r a i n t s o l v e r d e m o ---------------------------- //---------- C o n s t r a i n t s o l v e r d e m o ----------------------------
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
extern "C" extern "C"
{ {
void BT_GPU_PREF(clearAccumulationOfLambdaDt(float* lambdaDtBox, int numConstraints, int numContPoints)); void BT_GPU_PREF(clearAccumulationOfLambdaDt(float* lambdaDtBox, int numConstraints, int numContPoints));
void BT_GPU_PREF(collisionWithWallBox3D(void* trans,void* vel,void* angVel,btCudaPartProps pProp, btCudaBoxProps gProp,int numObjs,float dt)); void BT_GPU_PREF(collisionWithWallBox3D(void* trans,void* vel,void* angVel,btCudaPartProps pProp, btCudaBoxProps gProp,int numObjs,float dt));
void BT_GPU_PREF(collisionBatchResolutionBox3D(void* constraints,int *batch,int numConstraints,void *trans,void *vel, void BT_GPU_PREF(collisionBatchResolutionBox3D(void* constraints,int *batch,int numConstraints,void *trans,void *vel,
void *angularVel,float *lambdaDtBox,float *positionConstraint,void* normal,void* contact, void *angularVel,float *lambdaDtBox,float *positionConstraint,void* normal,void* contact,
btCudaPartProps pProp,int iBatch,float dt)); btCudaPartProps pProp,int iBatch,float dt));
void BT_GPU_PREF(integrVel(float* pForceTorqueDamp, float* pInvInertiaMass, void* pVel, void* pAngVel, float timeStep, unsigned int numBodies)); void BT_GPU_PREF(integrVel(float* pForceTorqueDamp, float* pInvInertiaMass, void* pVel, void* pAngVel, float timeStep, unsigned int numBodies));
void BT_GPU_PREF(integrTrans(void* trans, void* vel, void* angVel, float timeStep, int numBodies)); void BT_GPU_PREF(integrTrans(void* trans, void* vel, void* angVel, float timeStep, int numBodies));
} // extern "C" } // extern "C"
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------

View File

@@ -1,39 +1,39 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//---------- C o n s t r a i n t s o l v e r d e m o ---------------------------- //---------- C o n s t r a i n t s o l v e r d e m o ----------------------------
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
struct btCudaPartProps struct btCudaPartProps
{ {
float m_mass; float m_mass;
float m_diameter; float m_diameter;
float m_restCoeff; float m_restCoeff;
}; };
struct btCudaBoxProps struct btCudaBoxProps
{ {
float minX; float minX;
float maxX; float maxX;
float minY; float minY;
float maxY; float maxY;
float minZ; float minZ;
float maxZ; float maxZ;
}; };
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------

File diff suppressed because it is too large Load Diff

View File

@@ -1,252 +1,252 @@
/* /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#ifndef BT_CUDA_DEMO_DYNAMICS_WORLD3D_H #ifndef BT_CUDA_DEMO_DYNAMICS_WORLD3D_H
#define BT_CUDA_DEMO_DYNAMICS_WORLD3D_H #define BT_CUDA_DEMO_DYNAMICS_WORLD3D_H
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h" #include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
//#define BT_USE_CUDA 1 //#define BT_USE_CUDA 1
// To enable CUDA : // To enable CUDA :
// 1. Uncomment //#define BT_USE_CUDA 1 // 1. Uncomment //#define BT_USE_CUDA 1
// 2. Build and add libbulletcuda (Extras/CUDA) to project // 2. Build and add libbulletcuda (Extras/CUDA) to project
// 3. Add $(CUDA_LIB_PATH) and cudart.lib to linker properties // 3. Add $(CUDA_LIB_PATH) and cudart.lib to linker properties
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
#include "BulletMultiThreaded/btGpuDefines.h" #include "BulletMultiThreaded/btGpuDefines.h"
#undef BT_GPU_PREF #undef BT_GPU_PREF
#define BT_GPU_PREF(func) btCuda_##func #define BT_GPU_PREF(func) btCuda_##func
#include "BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#else #else
#include "BulletMultiThreaded/btGpuDefines.h" #include "BulletMultiThreaded/btGpuDefines.h"
#include "../../src/BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "../../src/BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#endif #endif
#undef BT_GPU_PREF #undef BT_GPU_PREF
#if 0 // ### #if 0 // ###
#include <vector_types.h> #include <vector_types.h>
#define BT_GPU_PREF(func) btCuda_##func #define BT_GPU_PREF(func) btCuda_##func
#include "../../src/BulletMultiThreaded/btGpuUtilsSharedDefs.h" #include "../../src/BulletMultiThreaded/btGpuUtilsSharedDefs.h"
#undef BT_GPU_PREF #undef BT_GPU_PREF
#endif #endif
#include "btGpuDemo3dSharedTypes.h" #include "btGpuDemo3dSharedTypes.h"
//#define CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES 20 //#define CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES 20
#define CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES 15 #define CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES 15
class btCudaDemoDynamicsWorld3D : public btDiscreteDynamicsWorld class btCudaDemoDynamicsWorld3D : public btDiscreteDynamicsWorld
{ {
protected: protected:
int m_maxObj; int m_maxObj;
int m_maxNeihbors; int m_maxNeihbors;
int m_maxConstr; int m_maxConstr;
int m_maxPointsPerConstr; int m_maxPointsPerConstr;
int m_numObj; int m_numObj;
int m_numSimStep; int m_numSimStep;
bool m_useCPUSolver; bool m_useCPUSolver;
bool m_useSeqImpSolver; bool m_useSeqImpSolver;
bool m_useCudaMotIntegr; bool m_useCudaMotIntegr;
bool m_copyIntegrDataToGPU; bool m_copyIntegrDataToGPU;
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
float4* m_dTrans; float4* m_dTrans;
float4* m_dVel; float4* m_dVel;
float4* m_dAngVel; float4* m_dAngVel;
int2* m_dIds; int2* m_dIds;
int* m_dBatchIds; int* m_dBatchIds;
float* m_dLambdaDtBox; float* m_dLambdaDtBox;
float* m_dPositionConstraint; float* m_dPositionConstraint;
float3* m_dNormal; float3* m_dNormal;
float3* m_dContact; float3* m_dContact;
float* m_dForceTorqueDamp; float* m_dForceTorqueDamp;
float* m_dInvInertiaMass; float* m_dInvInertiaMass;
#endif #endif
float4* m_hTrans; float4* m_hTrans;
float4* m_hVel; float4* m_hVel;
float4* m_hAngVel; float4* m_hAngVel;
int* m_hConstraintBuffer; int* m_hConstraintBuffer;
int* m_hConstraintCounter; int* m_hConstraintCounter;
int m_maxBatches; int m_maxBatches;
int m_numBatches; int m_numBatches;
int m_numConstraints; int m_numConstraints;
int2* m_hIds; int2* m_hIds;
int* m_hBatchIds; int* m_hBatchIds;
int m_maxVtxPerObj; int m_maxVtxPerObj;
// ------------- these are only needed for CPU version and for debugging // ------------- these are only needed for CPU version and for debugging
float* m_hLambdaDtBox; float* m_hLambdaDtBox;
float* m_hPositionConstraint; float* m_hPositionConstraint;
float3* m_hNormal; float3* m_hNormal;
float3* m_hContact; float3* m_hContact;
// ------------- // -------------
btScalar m_objRad; btScalar m_objRad;
btVector3 m_worldMin; btVector3 m_worldMin;
btVector3 m_worldMax; btVector3 m_worldMax;
//------------------------------- //-------------------------------
int* m_hConstraintUsed; int* m_hConstraintUsed;
//------------------------------- //-------------------------------
float* m_hForceTorqueDamp; float* m_hForceTorqueDamp;
float* m_hInvInertiaMass; float* m_hInvInertiaMass;
public: public:
int m_numInBatches[CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES]; int m_numInBatches[CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES];
btCudaDemoDynamicsWorld3D(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration, int maxPointsPerConstr = 4) btCudaDemoDynamicsWorld3D(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration, int maxPointsPerConstr = 4)
: btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration) : btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration)
{ {
m_useCPUSolver = false; m_useCPUSolver = false;
m_useSeqImpSolver = false; m_useSeqImpSolver = false;
m_useCudaMotIntegr = true; m_useCudaMotIntegr = true;
m_copyIntegrDataToGPU = true; m_copyIntegrDataToGPU = true;
m_maxObj = 32768; m_maxObj = 32768;
m_maxNeihbors = 26; m_maxNeihbors = 26;
m_maxConstr = m_maxObj * m_maxNeihbors; m_maxConstr = m_maxObj * m_maxNeihbors;
int sz = m_maxConstr; int sz = m_maxConstr;
m_hConstraintBuffer = new int[sz]; m_hConstraintBuffer = new int[sz];
m_hConstraintCounter = new int[m_maxObj]; m_hConstraintCounter = new int[m_maxObj];
m_maxBatches = CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES; m_maxBatches = CUDA_DEMO_DYNAMICS_WORLD3D_MAX_BATCHES;
m_hIds = new int2[sz]; m_hIds = new int2[sz];
m_hBatchIds = new int[sz]; m_hBatchIds = new int[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
{ {
m_hBatchIds[i] = -1; m_hBatchIds[i] = -1;
} }
m_hTrans = new float4[m_maxObj * 4]; m_hTrans = new float4[m_maxObj * 4];
m_hVel = new float4[m_maxObj]; m_hVel = new float4[m_maxObj];
m_hAngVel = new float4[m_maxObj]; m_hAngVel = new float4[m_maxObj];
m_maxPointsPerConstr = maxPointsPerConstr; m_maxPointsPerConstr = maxPointsPerConstr;
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
btCuda_allocateArray((void**)&m_dTrans, sizeof(float4) * m_maxObj * 4); btCuda_allocateArray((void**)&m_dTrans, sizeof(float4) * m_maxObj * 4);
btCuda_allocateArray((void**)&m_dVel, sizeof(float4) * m_maxObj); btCuda_allocateArray((void**)&m_dVel, sizeof(float4) * m_maxObj);
btCuda_allocateArray((void**)&m_dAngVel, sizeof(float4) * m_maxObj); btCuda_allocateArray((void**)&m_dAngVel, sizeof(float4) * m_maxObj);
btCuda_allocateArray((void**)&m_dIds, sizeof(int2) * sz); btCuda_allocateArray((void**)&m_dIds, sizeof(int2) * sz);
btCuda_allocateArray((void**)&m_dBatchIds, sizeof(int) * sz); btCuda_allocateArray((void**)&m_dBatchIds, sizeof(int) * sz);
btCuda_allocateArray((void**)&m_dLambdaDtBox, sizeof(float) * sz * m_maxPointsPerConstr); btCuda_allocateArray((void**)&m_dLambdaDtBox, sizeof(float) * sz * m_maxPointsPerConstr);
btCuda_allocateArray((void**)&m_dPositionConstraint, sizeof(float) * sz * m_maxPointsPerConstr); btCuda_allocateArray((void**)&m_dPositionConstraint, sizeof(float) * sz * m_maxPointsPerConstr);
btCuda_allocateArray((void**)&m_dNormal, sizeof(float3) * sz * m_maxPointsPerConstr); btCuda_allocateArray((void**)&m_dNormal, sizeof(float3) * sz * m_maxPointsPerConstr);
btCuda_allocateArray((void**)&m_dContact, sizeof(float3) * sz * m_maxPointsPerConstr); btCuda_allocateArray((void**)&m_dContact, sizeof(float3) * sz * m_maxPointsPerConstr);
btCuda_allocateArray((void**)&m_dForceTorqueDamp, sizeof(float) * m_maxObj * 4 * 2); btCuda_allocateArray((void**)&m_dForceTorqueDamp, sizeof(float) * m_maxObj * 4 * 2);
btCuda_allocateArray((void**)&m_dInvInertiaMass, sizeof(float) * m_maxObj * 4 * 3); btCuda_allocateArray((void**)&m_dInvInertiaMass, sizeof(float) * m_maxObj * 4 * 3);
#endif #endif
m_hLambdaDtBox = new float[sz * m_maxPointsPerConstr]; m_hLambdaDtBox = new float[sz * m_maxPointsPerConstr];
m_hPositionConstraint = new float[sz * m_maxPointsPerConstr]; m_hPositionConstraint = new float[sz * m_maxPointsPerConstr];
m_hNormal = new float3[sz * m_maxPointsPerConstr]; m_hNormal = new float3[sz * m_maxPointsPerConstr];
m_hContact = new float3[sz * m_maxPointsPerConstr]; m_hContact = new float3[sz * m_maxPointsPerConstr];
m_numSimStep = 0; m_numSimStep = 0;
m_objRad = 1.0f; m_objRad = 1.0f;
m_hConstraintUsed = new int[sz]; m_hConstraintUsed = new int[sz];
m_hForceTorqueDamp = new float[m_maxObj * 4 * 2]; m_hForceTorqueDamp = new float[m_maxObj * 4 * 2];
m_hInvInertiaMass = new float[4 * m_maxObj * 3]; m_hInvInertiaMass = new float[4 * m_maxObj * 3];
} }
virtual ~btCudaDemoDynamicsWorld3D() virtual ~btCudaDemoDynamicsWorld3D()
{ {
delete [] m_hConstraintBuffer; delete [] m_hConstraintBuffer;
delete [] m_hConstraintCounter; delete [] m_hConstraintCounter;
delete [] m_hIds; delete [] m_hIds;
delete [] m_hBatchIds; delete [] m_hBatchIds;
delete [] m_hTrans; delete [] m_hTrans;
delete [] m_hVel; delete [] m_hVel;
delete [] m_hAngVel; delete [] m_hAngVel;
delete [] m_hLambdaDtBox; delete [] m_hLambdaDtBox;
delete [] m_hPositionConstraint; delete [] m_hPositionConstraint;
delete [] m_hNormal; delete [] m_hNormal;
delete [] m_hContact; delete [] m_hContact;
delete [] m_hConstraintUsed; delete [] m_hConstraintUsed;
delete [] m_hForceTorqueDamp; delete [] m_hForceTorqueDamp;
delete [] m_hInvInertiaMass; delete [] m_hInvInertiaMass;
#ifdef BT_USE_CUDA #ifdef BT_USE_CUDA
btCuda_freeArray(m_dTrans); btCuda_freeArray(m_dTrans);
btCuda_freeArray(m_dVel); btCuda_freeArray(m_dVel);
btCuda_freeArray(m_dAngVel); btCuda_freeArray(m_dAngVel);
btCuda_freeArray(m_dIds); btCuda_freeArray(m_dIds);
btCuda_freeArray(m_dBatchIds); btCuda_freeArray(m_dBatchIds);
btCuda_freeArray(m_dLambdaDtBox); btCuda_freeArray(m_dLambdaDtBox);
btCuda_freeArray(m_dPositionConstraint); btCuda_freeArray(m_dPositionConstraint);
btCuda_freeArray(m_dNormal); btCuda_freeArray(m_dNormal);
btCuda_freeArray(m_dContact); btCuda_freeArray(m_dContact);
btCuda_freeArray(m_dForceTorqueDamp); btCuda_freeArray(m_dForceTorqueDamp);
btCuda_freeArray(m_dInvInertiaMass); btCuda_freeArray(m_dInvInertiaMass);
#endif #endif
} }
virtual void calculateSimulationIslands() virtual void calculateSimulationIslands()
{ {
if(m_useSeqImpSolver) if(m_useSeqImpSolver)
{ {
btDiscreteDynamicsWorld::calculateSimulationIslands(); btDiscreteDynamicsWorld::calculateSimulationIslands();
} }
} }
virtual void solveConstraints(btContactSolverInfo& solverInfo); virtual void solveConstraints(btContactSolverInfo& solverInfo);
virtual void predictUnconstraintMotion(btScalar timeStep); virtual void predictUnconstraintMotion(btScalar timeStep);
virtual void integrateTransforms(btScalar timeStep); virtual void integrateTransforms(btScalar timeStep);
void solveConstraintsCPU(btContactSolverInfo& solverInfo); void solveConstraintsCPU(btContactSolverInfo& solverInfo);
void debugDrawConstraints(int selectedBatch, const float* pColorTab); void debugDrawConstraints(int selectedBatch, const float* pColorTab);
void setObjRad(btScalar rad) { m_objRad = rad; } void setObjRad(btScalar rad) { m_objRad = rad; }
void setWorldMin(const btVector3& worldMin) { m_worldMin = worldMin; } void setWorldMin(const btVector3& worldMin) { m_worldMin = worldMin; }
void setWorldMax(const btVector3& worldMax) { m_worldMax = worldMax; } void setWorldMax(const btVector3& worldMax) { m_worldMax = worldMax; }
void grabData(); void grabData();
void grabObjData(); void grabObjData();
void grabConstrData(); void grabConstrData();
void createBatches(); void createBatches();
void copyDataToGPU(); void copyDataToGPU();
void copyDataFromGPU(); void copyDataFromGPU();
void writebackData(); void writebackData();
void setUseCPUSolver(bool useCPU) { m_useCPUSolver = useCPU; } void setUseCPUSolver(bool useCPU) { m_useCPUSolver = useCPU; }
void setUseSeqImpSolver(bool useSeqImpSolver) { m_useSeqImpSolver = useSeqImpSolver; } void setUseSeqImpSolver(bool useSeqImpSolver) { m_useSeqImpSolver = useSeqImpSolver; }
void setUseCudaMotIntegr(bool useCudaMotIntegr) { m_useCudaMotIntegr = useCudaMotIntegr; } void setUseCudaMotIntegr(bool useCudaMotIntegr) { m_useCudaMotIntegr = useCudaMotIntegr; }
void resetScene(void) { m_copyIntegrDataToGPU = true; } void resetScene(void) { m_copyIntegrDataToGPU = true; }
}; };
#endif //BT_CUDA_DEMO_DYNAMICS_WORLD3D_H #endif //BT_CUDA_DEMO_DYNAMICS_WORLD3D_H

View File

@@ -1,61 +1,61 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
*/ */
#include "BasicDemo3d.h" #include "BasicDemo3d.h"
#include "GlutStuff.h" #include "GlutStuff.h"
#include "GLDebugDrawer.h" #include "GLDebugDrawer.h"
#include "btBulletDynamicsCommon.h" #include "btBulletDynamicsCommon.h"
#include "LinearMath/btHashMap.h" #include "LinearMath/btHashMap.h"
class OurValue class OurValue
{ {
int m_uid; int m_uid;
public: public:
OurValue(const btVector3& initialPos) OurValue(const btVector3& initialPos)
:m_position(initialPos) :m_position(initialPos)
{ {
static int gUid=0; static int gUid=0;
m_uid=gUid; m_uid=gUid;
gUid++; gUid++;
} }
btVector3 m_position; btVector3 m_position;
int getUid() const int getUid() const
{ {
return m_uid; return m_uid;
} }
}; };
int main(int argc,char** argv) int main(int argc,char** argv)
{ {
GLDebugDrawer gDebugDrawer; GLDebugDrawer gDebugDrawer;
BasicDemo3D ccdDemo; BasicDemo3D ccdDemo;
ccdDemo.initPhysics(); ccdDemo.initPhysics();
ccdDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer); ccdDemo.getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);
ccdDemo.setWireMode(false); ccdDemo.setWireMode(false);
#ifdef CHECK_MEMORY_LEAKS #ifdef CHECK_MEMORY_LEAKS
ccdDemo.exitPhysics(); ccdDemo.exitPhysics();
#else #else
return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&ccdDemo); return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.com",&ccdDemo);
#endif #endif
//default glut doesn't return from mainloop //default glut doesn't return from mainloop
return 0; return 0;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,243 +1,243 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
Experimental Buoyancy fluid demo written by John McCutchan Experimental Buoyancy fluid demo written by John McCutchan
*/ */
#ifndef __HFFLUID_H #ifndef __HFFLUID_H
#define __HFFLUID_H #define __HFFLUID_H
#include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btTriangleCallback.h" #include "BulletCollision/CollisionShapes/btTriangleCallback.h"
class btPersistentManifold; class btPersistentManifold;
class btManifoldResult; class btManifoldResult;
// FIX AABB calculation for whole btHfFluid shape // FIX AABB calculation for whole btHfFluid shape
// Fix flags and fill ratio // Fix flags and fill ratio
// -> Figure out the constants used in flags and fill ratio code // -> Figure out the constants used in flags and fill ratio code
// Fix volume removal // Fix volume removal
// add buoyant convex vs. convex / concave // add buoyant convex vs. convex / concave
// add buoyant concave support (try bunny model) // add buoyant concave support (try bunny model)
///experimental buyancy fluid demo ///experimental buyancy fluid demo
class btHfFluid : public btCollisionObject class btHfFluid : public btCollisionObject
{ {
public: public:
btHfFluid (btScalar gridCellWidth, int numNodesWidth, int numNodesLength); btHfFluid (btScalar gridCellWidth, int numNodesWidth, int numNodesLength);
~btHfFluid (); ~btHfFluid ();
void predictMotion(btScalar dt); void predictMotion(btScalar dt);
/* Prep does some initial setup of the height field fluid. /* Prep does some initial setup of the height field fluid.
* You should call this at initialization time. * You should call this at initialization time.
*/ */
void prep (); void prep ();
static const btHfFluid* upcast(const btCollisionObject* colObj) static const btHfFluid* upcast(const btCollisionObject* colObj)
{ {
if (colObj->getInternalType()==CO_HF_FLUID) if (colObj->getInternalType()==CO_HF_FLUID)
return (const btHfFluid*)colObj; return (const btHfFluid*)colObj;
return 0; return 0;
} }
static btHfFluid* upcast(btCollisionObject* colObj) static btHfFluid* upcast(btCollisionObject* colObj)
{ {
if (colObj->getInternalType()==CO_HF_FLUID) if (colObj->getInternalType()==CO_HF_FLUID)
return (btHfFluid*)colObj; return (btHfFluid*)colObj;
return 0; return 0;
} }
// //
// ::btCollisionObject // ::btCollisionObject
// //
virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const
{ {
aabbMin = m_aabbMin; aabbMin = m_aabbMin;
aabbMax = m_aabbMax; aabbMax = m_aabbMax;
} }
int getNumNodesWidth () const { return m_numNodesWidth; } int getNumNodesWidth () const { return m_numNodesWidth; }
int getNumNodesLength () const { return m_numNodesLength; } int getNumNodesLength () const { return m_numNodesLength; }
btScalar getGridCellWidth () const { return m_gridCellWidth; } btScalar getGridCellWidth () const { return m_gridCellWidth; }
btScalar widthPos (int i) const; btScalar widthPos (int i) const;
btScalar lengthPos (int j) const; btScalar lengthPos (int j) const;
int arrayIndex (int i, int j) const; int arrayIndex (int i, int j) const;
int arrayIndex (btScalar i, btScalar j) const; int arrayIndex (btScalar i, btScalar j) const;
int arrayIndex (unsigned int i, unsigned int j) const; int arrayIndex (unsigned int i, unsigned int j) const;
const btScalar* getHeightArray () const; const btScalar* getHeightArray () const;
const btScalar* getGroundArray () const; const btScalar* getGroundArray () const;
const btScalar* getEtaArray () const; const btScalar* getEtaArray () const;
const btScalar* getVelocityUArray () const; const btScalar* getVelocityUArray () const;
const btScalar* getVelocityVArray () const; const btScalar* getVelocityVArray () const;
const bool* getFlagsArray () const; const bool* getFlagsArray () const;
void setFluidHeight (int x, int y, btScalar height); void setFluidHeight (int x, int y, btScalar height);
void setFluidHeight (int index, btScalar height); void setFluidHeight (int index, btScalar height);
void addFluidHeight (int x, int y, btScalar height); void addFluidHeight (int x, int y, btScalar height);
void addDisplaced (int i, int j, btScalar r); void addDisplaced (int i, int j, btScalar r);
void getAabbForColumn (int x, int y, btVector3& aabbMin, btVector3& aabbMax); void getAabbForColumn (int x, int y, btVector3& aabbMin, btVector3& aabbMax);
btScalar* getHeightArray (); btScalar* getHeightArray ();
btScalar* getGroundArray (); btScalar* getGroundArray ();
btScalar* getEtaArray (); btScalar* getEtaArray ();
btScalar* getVelocityUArray (); btScalar* getVelocityUArray ();
btScalar* getVelocityVArray (); btScalar* getVelocityVArray ();
bool* getFlagsArray (); bool* getFlagsArray ();
void foreachGroundTriangle(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax); void foreachGroundTriangle(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax);
class btHfFluidColumnCallback class btHfFluidColumnCallback
{ {
public: public:
btHfFluidColumnCallback () {} btHfFluidColumnCallback () {}
virtual ~btHfFluidColumnCallback () {} virtual ~btHfFluidColumnCallback () {}
virtual bool processColumn (btHfFluid* fluid, int w, int l) virtual bool processColumn (btHfFluid* fluid, int w, int l)
{ {
return true; // keep going return true; // keep going
} }
}; };
void foreachFluidColumn (btHfFluidColumnCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax); void foreachFluidColumn (btHfFluidColumnCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax);
void foreachSurfaceTriangle (btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax); void foreachSurfaceTriangle (btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax);
protected: protected:
int m_numNodesWidth; int m_numNodesWidth;
int m_numNodesLength; int m_numNodesLength;
btScalar m_gridCellWidth; btScalar m_gridCellWidth;
btScalar m_gridWidth; btScalar m_gridWidth;
btScalar m_gridLength; btScalar m_gridLength;
btScalar m_gridCellWidthInv; btScalar m_gridCellWidthInv;
btVector3 m_aabbMin; btVector3 m_aabbMin;
btVector3 m_aabbMax; btVector3 m_aabbMax;
void setGridDimensions (btScalar gridCellWidth, void setGridDimensions (btScalar gridCellWidth,
int numNodesWidth, int numNodesLength); int numNodesWidth, int numNodesLength);
btScalar bilinearInterpolate (const btScalar* array, btScalar i, btScalar j); btScalar bilinearInterpolate (const btScalar* array, btScalar i, btScalar j);
btScalar advect (const btScalar* array, btScalar i, btScalar j, btScalar di, btScalar dj, btScalar dt); btScalar advect (const btScalar* array, btScalar i, btScalar j, btScalar di, btScalar dj, btScalar dt);
void advectEta (btScalar dt); void advectEta (btScalar dt);
void updateHeight (btScalar dt); void updateHeight (btScalar dt);
void advectVelocityU (btScalar dt); void advectVelocityU (btScalar dt);
void advectVelocityV (btScalar dt); void advectVelocityV (btScalar dt);
void updateVelocity (btScalar dt); void updateVelocity (btScalar dt);
void transferDisplaced (btScalar dt); void transferDisplaced (btScalar dt);
void setReflectBoundaryLeft (); void setReflectBoundaryLeft ();
void setReflectBoundaryRight (); void setReflectBoundaryRight ();
void setReflectBoundaryTop (); void setReflectBoundaryTop ();
void setReflectBoundaryBottom (); void setReflectBoundaryBottom ();
void setAbsorbBoundaryLeft (btScalar dt); void setAbsorbBoundaryLeft (btScalar dt);
void setAbsorbBoundaryRight (btScalar dt); void setAbsorbBoundaryRight (btScalar dt);
void setAbsorbBoundaryTop (btScalar dt); void setAbsorbBoundaryTop (btScalar dt);
void setAbsorbBoundaryBottom (btScalar dt); void setAbsorbBoundaryBottom (btScalar dt);
void computeFlagsAndFillRatio (); void computeFlagsAndFillRatio ();
btScalar computeHmin (int i, int j); btScalar computeHmin (int i, int j);
btScalar computeHmax (int i, int j); btScalar computeHmax (int i, int j);
btScalar computeEtaMax (int i, int j); btScalar computeEtaMax (int i, int j);
void allocateArrays (); void allocateArrays ();
void debugTests (); void debugTests ();
btScalar* m_temp; // temp btScalar* m_temp; // temp
int m_heightIndex; int m_heightIndex;
btScalar* m_height[2]; btScalar* m_height[2];
btScalar* m_ground; btScalar* m_ground;
btScalar* m_eta; // height - ground btScalar* m_eta; // height - ground
btScalar* m_u[2]; btScalar* m_u[2];
btScalar* m_v[2]; btScalar* m_v[2];
int m_rIndex; int m_rIndex;
btScalar* m_r[2]; btScalar* m_r[2];
int m_velocityIndex; int m_velocityIndex;
bool* m_flags; bool* m_flags;
btScalar* m_fillRatio; btScalar* m_fillRatio;
// tweakables // tweakables
btScalar m_globalVelocityU; btScalar m_globalVelocityU;
btScalar m_globalVelocityV; btScalar m_globalVelocityV;
btScalar m_gravity; btScalar m_gravity;
btScalar m_volumeDisplacementScale; btScalar m_volumeDisplacementScale;
btScalar m_horizontalVelocityScale; btScalar m_horizontalVelocityScale;
btScalar m_epsHeight; btScalar m_epsHeight;
btScalar m_epsEta; btScalar m_epsEta;
public: public:
// You can enforce a global velocity at the surface of the fluid // You can enforce a global velocity at the surface of the fluid
// default: 0.0 and 0.0 // default: 0.0 and 0.0
void setGlobaVelocity (btScalar globalVelocityU, btScalar globalVelocityV); void setGlobaVelocity (btScalar globalVelocityU, btScalar globalVelocityV);
void getGlobalVelocity (btScalar& globalVelocityU, btScalar& globalVelocityV) const; void getGlobalVelocity (btScalar& globalVelocityU, btScalar& globalVelocityV) const;
// Control force of gravity, should match physics world // Control force of gravity, should match physics world
// default: -10.0 // default: -10.0
void setGravity (btScalar gravity); void setGravity (btScalar gravity);
btScalar getGravity () const; btScalar getGravity () const;
// When a body is submerged into the fluid, the displaced fluid // When a body is submerged into the fluid, the displaced fluid
// is spread to adjacent cells. You can control the percentage of this // is spread to adjacent cells. You can control the percentage of this
// by setting this value between 0.0 and 1.0 // by setting this value between 0.0 and 1.0
// default: 0.5 // default: 0.5
void setVolumeDisplacementScale (btScalar volumeDisplacementScale); void setVolumeDisplacementScale (btScalar volumeDisplacementScale);
btScalar getVolumeDisplacementScale () const; btScalar getVolumeDisplacementScale () const;
// The horizontal velocity of the fluid can influence bodies submerged // The horizontal velocity of the fluid can influence bodies submerged
// in the fluid. You can control how much influence by setting this // in the fluid. You can control how much influence by setting this
// between 0.0 and 1.0 // between 0.0 and 1.0
// default: 0.5 // default: 0.5
void setHorizontalVelocityScale (btScalar horizontalVelocityScale); void setHorizontalVelocityScale (btScalar horizontalVelocityScale);
btScalar getHorizontalVelocityScale () const; btScalar getHorizontalVelocityScale () const;
}; };
class btRigidBody; class btRigidBody;
class btIDebugDraw; class btIDebugDraw;
class btHfFluidBuoyantConvexShape; class btHfFluidBuoyantConvexShape;
class btHfFluidColumnRigidBodyCallback : public btHfFluid::btHfFluidColumnCallback class btHfFluidColumnRigidBodyCallback : public btHfFluid::btHfFluidColumnCallback
{ {
protected: protected:
btRigidBody* m_rigidBody; btRigidBody* m_rigidBody;
btHfFluidBuoyantConvexShape* m_buoyantShape; btHfFluidBuoyantConvexShape* m_buoyantShape;
btIDebugDraw* m_debugDraw; btIDebugDraw* m_debugDraw;
int m_numVoxels; int m_numVoxels;
btVector3* m_voxelPositionsXformed; btVector3* m_voxelPositionsXformed;
bool* m_voxelSubmerged; bool* m_voxelSubmerged;
btVector3 m_aabbMin; btVector3 m_aabbMin;
btVector3 m_aabbMax; btVector3 m_aabbMax;
btScalar m_volume; btScalar m_volume;
btScalar m_density; btScalar m_density;
btScalar m_floatyness; btScalar m_floatyness;
public: public:
btHfFluidColumnRigidBodyCallback (btRigidBody* rigidBody, btIDebugDraw* debugDraw, btScalar density, btScalar floatyness); btHfFluidColumnRigidBodyCallback (btRigidBody* rigidBody, btIDebugDraw* debugDraw, btScalar density, btScalar floatyness);
~btHfFluidColumnRigidBodyCallback (); ~btHfFluidColumnRigidBodyCallback ();
bool processColumn (btHfFluid* fluid, int w, int l); bool processColumn (btHfFluid* fluid, int w, int l);
btScalar getVolume () const { return m_volume; } btScalar getVolume () const { return m_volume; }
}; };
#endif #endif

View File

@@ -1,195 +1,195 @@
/* /*
Bullet Continuous Collision Detection and Physics Library Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied warranty. 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. 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, Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely, including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions: 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. 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. 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. 3. This notice may not be removed or altered from any source distribution.
Experimental Buoyancy fluid demo written by John McCutchan Experimental Buoyancy fluid demo written by John McCutchan
*/ */
#include <stdio.h> #include <stdio.h>
#include "LinearMath/btAabbUtil2.h" #include "LinearMath/btAabbUtil2.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" #include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
#include "btHfFluidBuoyantConvexShape.h" #include "btHfFluidBuoyantConvexShape.h"
btHfFluidBuoyantConvexShape::btHfFluidBuoyantConvexShape (btConvexShape* convexShape) btHfFluidBuoyantConvexShape::btHfFluidBuoyantConvexShape (btConvexShape* convexShape)
{ {
m_convexShape = convexShape; m_convexShape = convexShape;
m_shapeType = HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE; m_shapeType = HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE;
m_radius = btScalar(0.f); m_radius = btScalar(0.f);
m_numVoxels = 0; m_numVoxels = 0;
m_voxelPositions = NULL; m_voxelPositions = NULL;
m_totalVolume = btScalar(0.0f); m_totalVolume = btScalar(0.0f);
m_floatyness = btScalar(1.5f); m_floatyness = btScalar(1.5f);
} }
btHfFluidBuoyantConvexShape::~btHfFluidBuoyantConvexShape () btHfFluidBuoyantConvexShape::~btHfFluidBuoyantConvexShape ()
{ {
if (m_voxelPositions) if (m_voxelPositions)
btAlignedFree (m_voxelPositions); btAlignedFree (m_voxelPositions);
} }
void btHfFluidBuoyantConvexShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const void btHfFluidBuoyantConvexShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{ {
return m_convexShape->getAabb (t, aabbMin, aabbMax); return m_convexShape->getAabb (t, aabbMin, aabbMax);
} }
void btHfFluidBuoyantConvexShape::setMargin(btScalar margin) void btHfFluidBuoyantConvexShape::setMargin(btScalar margin)
{ {
m_convexShape->setMargin (margin); m_convexShape->setMargin (margin);
} }
void btHfFluidBuoyantConvexShape::setLocalScaling(const btVector3& scaling) void btHfFluidBuoyantConvexShape::setLocalScaling(const btVector3& scaling)
{ {
m_convexShape->setLocalScaling (scaling); m_convexShape->setLocalScaling (scaling);
} }
const char* btHfFluidBuoyantConvexShape::getName() const const char* btHfFluidBuoyantConvexShape::getName() const
{ {
return "HF_FLUID_BUOYANT_CONVEX_SHAPE"; return "HF_FLUID_BUOYANT_CONVEX_SHAPE";
} }
const btVector3& btHfFluidBuoyantConvexShape::getLocalScaling() const const btVector3& btHfFluidBuoyantConvexShape::getLocalScaling() const
{ {
return m_convexShape->getLocalScaling(); return m_convexShape->getLocalScaling();
} }
void btHfFluidBuoyantConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const void btHfFluidBuoyantConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{ {
m_convexShape->calculateLocalInertia (mass, inertia); m_convexShape->calculateLocalInertia (mass, inertia);
} }
btScalar btHfFluidBuoyantConvexShape::getMargin() const btScalar btHfFluidBuoyantConvexShape::getMargin() const
{ {
return m_convexShape->getMargin(); return m_convexShape->getMargin();
} }
//must be above the machine epsilon //must be above the machine epsilon
#define REL_ERROR2 btScalar(1.0e-6) #define REL_ERROR2 btScalar(1.0e-6)
static bool intersect(btVoronoiSimplexSolver* simplexSolver, static bool intersect(btVoronoiSimplexSolver* simplexSolver,
const btTransform& transformA, const btTransform& transformA,
const btTransform& transformB, const btTransform& transformB,
btConvexShape* a, btConvexShape* a,
btConvexShape* b) btConvexShape* b)
{ {
btScalar squaredDistance = SIMD_INFINITY; btScalar squaredDistance = SIMD_INFINITY;
btTransform localTransA = transformA; btTransform localTransA = transformA;
btTransform localTransB = transformB; btTransform localTransB = transformB;
btVector3 positionOffset = (localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5); btVector3 positionOffset = (localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5);
localTransA.getOrigin() -= positionOffset; localTransA.getOrigin() -= positionOffset;
localTransB.getOrigin() -= positionOffset; localTransB.getOrigin() -= positionOffset;
btScalar delta = btScalar(0.); btScalar delta = btScalar(0.);
btVector3 v = btVector3(1.0f, 0.0f, 0.0f); btVector3 v = btVector3(1.0f, 0.0f, 0.0f);
simplexSolver->reset (); simplexSolver->reset ();
do do
{ {
btVector3 seperatingAxisInA = (-v)* transformA.getBasis(); btVector3 seperatingAxisInA = (-v)* transformA.getBasis();
btVector3 seperatingAxisInB = v* transformB.getBasis(); btVector3 seperatingAxisInB = v* transformB.getBasis();
btVector3 pInA = a->localGetSupportVertexNonVirtual(seperatingAxisInA); btVector3 pInA = a->localGetSupportVertexNonVirtual(seperatingAxisInA);
btVector3 qInB = b->localGetSupportVertexNonVirtual(seperatingAxisInB); btVector3 qInB = b->localGetSupportVertexNonVirtual(seperatingAxisInB);
btVector3 pWorld = localTransA(pInA); btVector3 pWorld = localTransA(pInA);
btVector3 qWorld = localTransB(qInB); btVector3 qWorld = localTransB(qInB);
btVector3 w = pWorld - qWorld; btVector3 w = pWorld - qWorld;
delta = v.dot(w); delta = v.dot(w);
// potential exit, they don't overlap // potential exit, they don't overlap
if ((delta > btScalar(0.0))) if ((delta > btScalar(0.0)))
{ {
return false; return false;
} }
if (simplexSolver->inSimplex (w)) if (simplexSolver->inSimplex (w))
{ {
return false; return false;
} }
simplexSolver->addVertex (w, pWorld, qWorld); simplexSolver->addVertex (w, pWorld, qWorld);
if (!simplexSolver->closest(v)) if (!simplexSolver->closest(v))
{ {
return false; return false;
} }
btScalar previousSquaredDistance = squaredDistance; btScalar previousSquaredDistance = squaredDistance;
squaredDistance = v.length2(); squaredDistance = v.length2();
if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance) if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance)
{ {
return false; return false;
} }
} while (!simplexSolver->fullSimplex() && squaredDistance > REL_ERROR2 * simplexSolver->maxVertex()); } while (!simplexSolver->fullSimplex() && squaredDistance > REL_ERROR2 * simplexSolver->maxVertex());
return true; return true;
} }
void btHfFluidBuoyantConvexShape::generateShape (btScalar radius, btScalar gap) void btHfFluidBuoyantConvexShape::generateShape (btScalar radius, btScalar gap)
{ {
btTransform T; btTransform T;
T.setIdentity (); T.setIdentity ();
btVector3 aabbMin, aabbMax; btVector3 aabbMin, aabbMax;
getAabb (T, aabbMin, aabbMax); getAabb (T, aabbMin, aabbMax);
m_radius = radius; m_radius = radius;
m_numVoxels = 0; m_numVoxels = 0;
btVoronoiSimplexSolver simplexSolver; btVoronoiSimplexSolver simplexSolver;
btSphereShape sphereShape(radius); btSphereShape sphereShape(radius);
btVector3* voxelPositions = (btVector3*)btAlignedAlloc (sizeof(btVector3)*MAX_VOXEL_DIMENSION*MAX_VOXEL_DIMENSION*MAX_VOXEL_DIMENSION,16); btVector3* voxelPositions = (btVector3*)btAlignedAlloc (sizeof(btVector3)*MAX_VOXEL_DIMENSION*MAX_VOXEL_DIMENSION*MAX_VOXEL_DIMENSION,16);
for (int i = 0; i < MAX_VOXEL_DIMENSION; i++) for (int i = 0; i < MAX_VOXEL_DIMENSION; i++)
{ {
for (int j = 0; j < MAX_VOXEL_DIMENSION; j++) for (int j = 0; j < MAX_VOXEL_DIMENSION; j++)
{ {
for (int k = 0; k < MAX_VOXEL_DIMENSION; k++) for (int k = 0; k < MAX_VOXEL_DIMENSION; k++)
{ {
btVector3 point; btVector3 point;
btTransform sT; btTransform sT;
sT.setIdentity (); sT.setIdentity ();
point.setX(aabbMin.getX() + (i * btScalar(2.0f) * radius) + (i * gap)); point.setX(aabbMin.getX() + (i * btScalar(2.0f) * radius) + (i * gap));
point.setY(aabbMin.getY() + (j * btScalar(2.0f) * radius) + (j * gap)); point.setY(aabbMin.getY() + (j * btScalar(2.0f) * radius) + (j * gap));
point.setZ(aabbMin.getZ() + (k * btScalar(2.0f) * radius) + (k * gap)); point.setZ(aabbMin.getZ() + (k * btScalar(2.0f) * radius) + (k * gap));
if (TestPointAgainstAabb2(aabbMin, aabbMax, point)) if (TestPointAgainstAabb2(aabbMin, aabbMax, point))
{ {
btTransform sT; btTransform sT;
sT.setIdentity (); sT.setIdentity ();
sT.setOrigin (point); sT.setOrigin (point);
if (intersect (&simplexSolver, T, sT, m_convexShape, &sphereShape)) if (intersect (&simplexSolver, T, sT, m_convexShape, &sphereShape))
{ {
voxelPositions[m_numVoxels] = point; voxelPositions[m_numVoxels] = point;
m_numVoxels++; m_numVoxels++;
} }
} }
} }
} }
} }
m_voxelPositions = (btVector3*)btAlignedAlloc (sizeof(btVector3)*m_numVoxels, 16); m_voxelPositions = (btVector3*)btAlignedAlloc (sizeof(btVector3)*m_numVoxels, 16);
for (int i = 0; i < m_numVoxels;i++) for (int i = 0; i < m_numVoxels;i++)
{ {
m_voxelPositions[i] = voxelPositions[i]; m_voxelPositions[i] = voxelPositions[i];
} }
btAlignedFree (voxelPositions); btAlignedFree (voxelPositions);
m_volumePerVoxel = btScalar(4.0f)/btScalar(3.0f)*SIMD_PI*radius*radius*radius; m_volumePerVoxel = btScalar(4.0f)/btScalar(3.0f)*SIMD_PI*radius*radius*radius;
m_totalVolume = m_numVoxels * m_volumePerVoxel; m_totalVolume = m_numVoxels * m_volumePerVoxel;
m_radius = radius; m_radius = radius;
} }

Some files were not shown because too many files have changed in this diff Show More