This commit is contained in:
Erwin Coumans (Google) 2014-09-01 09:21:26 -07:00
commit 58d7a7b9d5
158 changed files with 10227 additions and 8272 deletions

View File

@ -60,7 +60,7 @@ IF(MSVC)
IF (NOT USE_MSVC_RUNTIME_LIBRARY_DLL)
#We statically link to reduce dependancies
FOREACH(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
FOREACH(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO )
IF(${flag_var} MATCHES "/MD")
STRING(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
ENDIF(${flag_var} MATCHES "/MD")
@ -231,18 +231,30 @@ IF (APPLE)
ENDIF()
OPTION(BUILD_BULLET3 "Set when you want to build Bullet 3" ON)
IF(BUILD_BULLET3)
OPTION(BUILD_BULLET3_DEMOS "Set when you want to build the Bullet 3 demos" ON)
IF(APPLE)
MESSAGE("Mac OSX Version is ${_CURRENT_OSX_VERSION}")
IF(_CURRENT_OSX_VERSION VERSION_LESS 10.9)
MESSAGE("Mac OSX below 10.9 has no OpenGL 3 support so please disable the BUILD_OPENGL3_DEMOS option")
#unset(BUILD_OPENGL3_DEMOS CACHE)
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build the OpenGL3+ demos" OFF)
ELSE()
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build the OpenGL3+ demos" ON)
ENDIF()
ELSE()
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build Bullet 3 OpenGL3+ demos" ON)
ENDIF()
ELSE(BUILD_BULLET3)
unset(BUILD_BULLET3_DEMOS CACHE)
OPTION(BUILD_BULLET3_DEMOS "Set when you want to build the Bullet 3 demos" OFF)
unset(BUILD_OPENGL3_DEMOS CACHE)
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build Bullet 3 OpenGL3+ demos" OFF)
ENDIF(BUILD_BULLET3)
IF(BUILD_BULLET3_DEMOS)
IF(BUILD_OPENGL3_DEMOS)
IF(EXISTS ${BULLET_PHYSICS_SOURCE_DIR}/Demos3 AND IS_DIRECTORY ${BULLET_PHYSICS_SOURCE_DIR}/Demos3)
SUBDIRS(Demos3)
SUBDIRS(btgui)
ENDIF()
ENDIF(BUILD_BULLET3_DEMOS)
ENDIF(BUILD_OPENGL3_DEMOS)
OPTION(BUILD_EXTRAS "Set when you want to build the extras" ON)
IF(BUILD_EXTRAS)
@ -267,10 +279,10 @@ ENDIF()
IF(INSTALL_LIBS)
SET (LIB_SUFFIX "" CACHE STRING "Define suffix of directory name (32/64)" )
SET (LIB_DESTINATION "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}" CACHE STRING "Library directory name")
SET (LIB_DESTINATION "lib${LIB_SUFFIX}" CACHE STRING "Library directory name")
## the following are directories where stuff will be installed to
SET(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/include/bullet/" CACHE PATH "The subdirectory to the header prefix")
SET(PKGCONFIG_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/pkgconfig/" CACHE STRING "Base directory for pkgconfig files")
SET(INCLUDE_INSTALL_DIR "include/bullet/" CACHE PATH "The subdirectory to the header prefix")
SET(PKGCONFIG_INSTALL_PREFIX "lib${LIB_SUFFIX}/pkgconfig/" CACHE STRING "Base directory for pkgconfig files")
IF(NOT WIN32)
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/bullet.pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/bullet.pc @ONLY)
INSTALL(
@ -297,7 +309,7 @@ list (APPEND BULLET_LIBRARIES LinearMath)
list (APPEND BULLET_LIBRARIES BulletCollision)
list (APPEND BULLET_LIBRARIES BulletDynamics)
list (APPEND BULLET_LIBRARIES BulletSoftBody)
set (BULLET_USE_FILE ${CMAKE_INSTALL_PREFIX}/${BULLET_CONFIG_CMAKE_PATH}/UseBullet.cmake)
set (BULLET_USE_FILE ${BULLET_CONFIG_CMAKE_PATH}/UseBullet.cmake)
configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/BulletConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/BulletConfig.cmake
@ONLY ESCAPE_QUOTES

View File

@ -68,4 +68,4 @@ IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppBasicDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppBasicDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppBasicDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@ -24,18 +24,12 @@ IF (USE_GLUT)
SET(SharedDemoSubdirs OpenGL )
ENDIF(BUILD_CPU_DEMOS)
IF(BUILD_MULTITHREADING)
SUBDIRS( MultiThreadedDemo OpenCLClothDemo )
ENDIF(BUILD_MULTITHREADING)
SUBDIRS(
${SharedDemoSubdirs}
Benchmarks
)
IF(BUILD_MULTITHREADING)
SUBDIRS( ThreadingDemo VectorAdd_OpenCL )
ENDIF()
ENDIF(GLUT_FOUND)
ELSE (USE_GLUT)

View File

@ -0,0 +1,298 @@
#ifndef COMMON_MULTI_BODY_SETUP_H
#define COMMON_MULTI_BODY_SETUP_H
//todo: replace this 'btBulletDynamicsCommon.h' header with specific used header files
#include "btBulletDynamicsCommon.h"
#include "CommonPhysicsSetup.h"
#include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
struct CommonMultiBodySetup : public CommonPhysicsSetup
{
//keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher;
btMultiBodyConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration;
btMultiBodyDynamicsWorld* m_dynamicsWorld;
//data for picking objects
class btRigidBody* m_pickedBody;
class btTypedConstraint* m_pickedConstraint;
class btMultiBodyPoint2Point* m_pickingMultiBodyPoint2Point;
btVector3 m_oldPickingPos;
btVector3 m_hitPos;
btScalar m_oldPickingDist;
bool m_prevCanSleep;
CommonMultiBodySetup()
:m_broadphase(0),
m_dispatcher(0),
m_solver(0),
m_collisionConfiguration(0),
m_dynamicsWorld(0),
m_pickedBody(0),
m_pickedConstraint(0),
m_pickingMultiBodyPoint2Point(0),
m_prevCanSleep(false)
{
}
virtual void createEmptyDynamicsWorld()
{
///collision configuration contains default setup for memory, collision setup
m_collisionConfiguration = new btDefaultCollisionConfiguration();
//m_collisionConfiguration->setConvexConvexMultipointIterations();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
m_broadphase = new btDbvtBroadphase();
m_solver = new btMultiBodyConstraintSolver;
m_dynamicsWorld = new btMultiBodyDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
m_dynamicsWorld->setGravity(btVector3(0, -10, 0));
}
virtual void stepSimulation(float deltaTime)
{
if (m_dynamicsWorld)
{
m_dynamicsWorld->stepSimulation(deltaTime);
}
}
virtual void exitPhysics()
{
removePickingConstraint();
//cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them
if (m_dynamicsWorld)
{
int i;
for (i = m_dynamicsWorld->getNumConstraints() - 1; i >= 0; i--)
{
m_dynamicsWorld->removeConstraint(m_dynamicsWorld->getConstraint(i));
}
for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState())
{
delete body->getMotionState();
}
m_dynamicsWorld->removeCollisionObject(obj);
delete obj;
}
}
//delete collision shapes
for (int j = 0; j<m_collisionShapes.size(); j++)
{
btCollisionShape* shape = m_collisionShapes[j];
delete shape;
}
m_collisionShapes.clear();
delete m_dynamicsWorld;
delete m_solver;
delete m_broadphase;
delete m_dispatcher;
delete m_collisionConfiguration;
}
virtual void syncPhysicsToGraphics(GraphicsPhysicsBridge& gfxBridge)
{
if (m_dynamicsWorld)
{
gfxBridge.syncPhysicsToGraphics(m_dynamicsWorld);
}
}
virtual void debugDraw()
{
if (m_dynamicsWorld)
{
m_dynamicsWorld->debugDrawWorld();
}
}
virtual bool pickBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_dynamicsWorld==0)
return false;
btCollisionWorld::ClosestRayResultCallback rayCallback(rayFromWorld, rayToWorld);
m_dynamicsWorld->rayTest(rayFromWorld, rayToWorld, rayCallback);
if (rayCallback.hasHit())
{
btVector3 pickPos = rayCallback.m_hitPointWorld;
btRigidBody* body = (btRigidBody*)btRigidBody::upcast(rayCallback.m_collisionObject);
if (body)
{
//other exclusions?
if (!(body->isStaticObject() || body->isKinematicObject()))
{
m_pickedBody = body;
m_pickedBody->setActivationState(DISABLE_DEACTIVATION);
//printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());
btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;
btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body, localPivot);
m_dynamicsWorld->addConstraint(p2p, true);
m_pickedConstraint = p2p;
btScalar mousePickClamping = 30.f;
p2p->m_setting.m_impulseClamp = mousePickClamping;
//very weak constraint for picking
p2p->m_setting.m_tau = 0.001f;
}
} else
{
btMultiBodyLinkCollider* multiCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(rayCallback.m_collisionObject);
if (multiCol && multiCol->m_multiBody)
{
m_prevCanSleep = multiCol->m_multiBody->getCanSleep();
multiCol->m_multiBody->setCanSleep(false);
btVector3 pivotInA = multiCol->m_multiBody->worldPosToLocal(multiCol->m_link, pickPos);
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(multiCol->m_multiBody,multiCol->m_link,0,pivotInA,pickPos);
//if you add too much energy to the system, causing high angular velocities, simulation 'explodes'
//see also http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=4&t=949
//so we try to avoid it by clamping the maximum impulse (force) that the mouse pick can apply
//it is not satisfying, hopefully we find a better solution (higher order integrator, using joint friction using a zero-velocity target motor with limited force etc?)
btScalar scaling=1;
p2p->setMaxAppliedImpulse(2*scaling);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*) m_dynamicsWorld;
world->addMultiBodyConstraint(p2p);
m_pickingMultiBodyPoint2Point =p2p;
}
}
// pickObject(pickPos, rayCallback.m_collisionObject);
m_oldPickingPos = rayToWorld;
m_hitPos = pickPos;
m_oldPickingDist = (pickPos - rayFromWorld).length();
// printf("hit !\n");
//add p2p
}
return false;
}
virtual bool movePickedBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_pickedBody && m_pickedConstraint)
{
btPoint2PointConstraint* pickCon = static_cast<btPoint2PointConstraint*>(m_pickedConstraint);
if (pickCon)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld-rayFromWorld;
dir.normalize();
dir *= m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
pickCon->setPivotB(newPivotB);
}
}
if (m_pickingMultiBodyPoint2Point)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld-rayFromWorld;
dir.normalize();
dir *= m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
m_pickingMultiBodyPoint2Point->setPivotInB(newPivotB);
}
return false;
}
virtual void removePickingConstraint()
{
if (m_pickedConstraint)
{
m_dynamicsWorld->removeConstraint(m_pickedConstraint);
delete m_pickedConstraint;
m_pickedConstraint = 0;
m_pickedBody = 0;
}
if (m_pickingMultiBodyPoint2Point)
{
m_pickingMultiBodyPoint2Point->getMultiBodyA()->setCanSleep(m_prevCanSleep);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*) m_dynamicsWorld;
world->removeMultiBodyConstraint(m_pickingMultiBodyPoint2Point);
delete m_pickingMultiBodyPoint2Point;
m_pickingMultiBodyPoint2Point = 0;
}
}
btBoxShape* createBoxShape(const btVector3& halfExtents)
{
btBoxShape* box = new btBoxShape(halfExtents);
return box;
}
btRigidBody* createRigidBody(float mass, const btTransform& startTransform, btCollisionShape* shape, const btVector4& color = btVector4(1, 0, 0, 1))
{
btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0, 0, 0);
if (isDynamic)
shape->calculateLocalInertia(mass, localInertia);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
#define USE_MOTIONSTATE 1
#ifdef USE_MOTIONSTATE
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia);
btRigidBody* body = new btRigidBody(cInfo);
//body->setContactProcessingThreshold(m_defaultContactProcessingThreshold);
#else
btRigidBody* body = new btRigidBody(mass, 0, shape, localInertia);
body->setWorldTransform(startTransform);
#endif//
body->setUserIndex(-1);
m_dynamicsWorld->addRigidBody(body);
return body;
}
};
#endif //COMMON_MULTI_BODY_SETUP_H

View File

@ -3,6 +3,7 @@
#define COMMON_PHYSICS_SETUP_H
class btRigidBody;
class btCollisionObject;
class btBoxShape;
class btTransform;
class btCollisionShape;
@ -18,6 +19,10 @@ struct GraphicsPhysicsBridge
virtual void createRigidBodyGraphicsObject(btRigidBody* body,const btVector3& color)
{
}
virtual void createCollisionObjectGraphicsObject(btCollisionObject* obj,const btVector3& color)
{
}
virtual void createCollisionShapeGraphicsObject(btCollisionShape* collisionShape)
{
}
@ -32,11 +37,11 @@ struct GraphicsPhysicsBridge
{
return 0;
}
virtual void setUpAxis(int axis)
{
}
};
struct CommonPhysicsSetup

View File

@ -49,4 +49,4 @@ IF (INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES DEBUG_POSTFIX "_Debug")
SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES MINSIZEREL_POSTFIX "_MinsizeRel")
SET_TARGET_PROPERTIES(AppConstraintDemo PROPERTIES RELWITHDEBINFO_POSTFIX "_RelWithDebugInfo")
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)
ENDIF(INTERNAL_ADD_POSTFIX_EXECUTABLE_NAMES)

View File

@ -443,7 +443,7 @@ void DemoApplication::keyboardCallback(unsigned char key, int x, int y)
m_debugMode |= btIDebugDraw::DBG_ProfileTimings;
break;
case '=':
case '\\':
{
int maxSerializeBufferSize = 1024*1024*5;
btDefaultSerializer* serializer = new btDefaultSerializer(maxSerializeBufferSize);

View File

@ -462,7 +462,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
{
const int s=x>>4;
const GLubyte b=180;
GLubyte c=b+((s+t&1)&1)*(255-b);
GLubyte c=b+((s+(t&1))&1)*(255-b);
pi[0]=pi[1]=pi[2]=pi[3]=c;pi+=3;
}
}
@ -518,7 +518,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
glColor3f(color.x(),color.y(), color.z());
bool useWireframeFallback = true;
//bool useWireframeFallback = true;
if (!(debugMode & btIDebugDraw::DBG_DrawWireframe))
{
@ -535,7 +535,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
const btSphereShape* sphereShape = static_cast<const btSphereShape*>(shape);
float radius = sphereShape->getMargin();//radius doesn't include the margin, so draw with margin
drawSphere(radius,10,10);
useWireframeFallback = false;
//useWireframeFallback = false;
break;
}
@ -586,7 +586,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
glEnd();
#endif
useWireframeFallback = false;
//useWireframeFallback = false;
break;
}
@ -617,7 +617,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
glTranslatef(0.0, 0.0, -0.5*height);
glutSolidCone(radius,height,10,10);
useWireframeFallback = false;
//useWireframeFallback = false;
break;
}

View File

@ -4,8 +4,8 @@ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
@ -17,6 +17,11 @@ subject to the following restrictions:
#include "DemoApplication.h"
#if !defined(_WIN32) && !defined(__APPLE__)
//assume linux workaround
//#include <pthread.h>
#endif
//glut is C code, this global gDemoApplication links glut to the C++ demo
static DemoApplication* gDemoApplication = 0;
@ -74,9 +79,17 @@ static void glutDisplayCallback(void)
//#include <GL/glut.h>
int glutmain(int argc, char **argv,int width,int height,const char* title,DemoApplication* demoApp) {
gDemoApplication = demoApp;
#if !defined(_WIN32) && !defined(__APPLE__)
//Access pthreads as a workaround for a bug in Linux/Ubuntu
//See https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-319/+bug/1248642
// int i=pthread_getconcurrency();
// printf("pthread_getconcurrency()=%d\n",i);
#endif
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowPosition(width/2, height/2);
@ -112,7 +125,7 @@ CGLSetParameter(cgl_context, kCGLCPSwapInterval, &swap_interval);
#endif
glutMainLoop();
return 0;
}

View File

@ -3,19 +3,59 @@
SerializeSetup::SerializeSetup()
{
}
SerializeSetup::~SerializeSetup()
{
}
void SerializeSetup::initPhysics(GraphicsPhysicsBridge& gfxBridge)
{
this->createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);
btBulletWorldImporter* importer = new btBulletWorldImporter(m_dynamicsWorld);
const char* filename = "testFile.bullet";
importer->loadFile(filename);
}
const char* someFileName="spider.bullet";
const char* prefix[]={"./","./data/","../data/","../../data/","../../../data/","../../../../data/"};
int numPrefixes = sizeof(prefix)/sizeof(const char*);
char relativeFileName[1024];
FILE* f=0;
bool fileFound = false;
int result = 0;
for (int i=0;!f && i<numPrefixes;i++)
{
sprintf(relativeFileName,"%s%s",prefix[i],someFileName);
f = fopen(relativeFileName,"rb");
if (f)
{
fileFound = true;
break;
}
}
if (f)
{
fclose(f);
}
importer->loadFile(relativeFileName);
//for now, guess the up axis from gravity
if (m_dynamicsWorld->getGravity()[1] == 0.f)
{
gfxBridge.setUpAxis(2);
} else
{
gfxBridge.setUpAxis(1);
}
}
void SerializeSetup::stepSimulation(float deltaTime)
{
CommonRigidBodySetup::stepSimulation(deltaTime);
}

View File

@ -7,8 +7,9 @@ class SerializeSetup : public CommonRigidBodySetup
public:
SerializeSetup();
virtual ~SerializeSetup();
virtual void initPhysics(GraphicsPhysicsBridge& gfxBridge);
virtual void stepSimulation(float deltaTime);
};
#endif //SERIALIZE_SETUP_H

View File

@ -34,7 +34,7 @@ function createDemos( demos, incdirs, linknames)
linkoptions { "-framework Carbon -framework OpenGL -framework AGL -framework Glut" }
configuration {"not Windows", "not MacOSX"}
links {"GL","GLU","glut"}
links {"GL","GLU","glut","pthread"}
configuration{}

View File

@ -14,10 +14,18 @@
#include "../bullet2/LuaDemo/LuaPhysicsSetup.h"
#include "../bullet2/ChainDemo/ChainDemo.h"
#include "../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.h"
#include "../../Demos/ConstraintDemo/ConstraintPhysicsSetup.h"
#include "../bullet2/ConstraintDemo/ConstraintPhysicsSetup.h"
#include "../ImportURDFDemo/ImportURDFSetup.h"
#include "../ImportObjDemo/ImportObjSetup.h"
#include "../ImportSTLDemo/ImportSTLSetup.h"
#include "../../Demos/SerializeDemo/SerializeSetup.h"
#include "../bullet2/MultiBodyDemo/TestJointTorqueSetup.h"
static BulletDemoInterface* TestJointTorqueCreateFunc(SimpleOpenGL3App* app)
{
CommonPhysicsSetup* physicsSetup = new TestJointTorqueSetup();
return new BasicDemo(app, physicsSetup);
}
static BulletDemoInterface* LuaDemoCreateFunc(SimpleOpenGL3App* app)
{
@ -36,7 +44,11 @@ static BulletDemoInterface* MyKinematicObjectCreateFunc(SimpleOpenGL3App* app)
CommonPhysicsSetup* physicsSetup = new KinematicObjectSetup();
return new BasicDemo(app, physicsSetup);
}
static BulletDemoInterface* MySerializeCreateFunc(SimpleOpenGL3App* app)
{
CommonPhysicsSetup* physicsSetup = new SerializeSetup();
return new BasicDemo(app, physicsSetup);
}
static BulletDemoInterface* MyConstraintCreateFunc(SimpleOpenGL3App* app)
{
CommonPhysicsSetup* physicsSetup = new ConstraintPhysicsSetup();
@ -70,7 +82,7 @@ struct BulletDemoEntry
static BulletDemoEntry allDemos[]=
{
//{"emptydemo",EmptyBulletDemo::MyCreateFunc},
{0,"API Demos", 0},
@ -82,10 +94,11 @@ static BulletDemoEntry allDemos[]=
{0,"File Formats", 0},
//@todo(erwincoumans) { 1, "bullet", MyImportSTLCreateFunc},
{ 1, ".bullet",MySerializeCreateFunc},
{ 1, "Wavefront Obj", MyImportObjCreateFunc},
{ 1, "URDF", MyImportUrdfCreateFunc },
{ 1, "STL", MyImportSTLCreateFunc},
/* {1,"ChainDemo",ChainDemo::MyCreateFunc},
// {0, "Stress tests", 0 },
@ -95,13 +108,15 @@ static BulletDemoEntry allDemos[]=
{1,"LemkeHingeDemo",HingeDemo::LemkeCreateFunc},
{1,"InertiaHingeDemo",HingeDemo::InertiaCreateFunc},
{1,"ABMHingeDemo",HingeDemo::FeatherstoneCreateFunc},
{1,"Ragdoll",RagDollDemo::MyCreateFunc},
*/
{ 0, "Multibody" ,0},
{1,"MultiBody1",FeatherstoneDemo1::MyCreateFunc},
// {"MultiBody2",FeatherstoneDemo2::MyCreateFunc},
{1,"MultiDofDemo",MultiDofDemo::MyCreateFunc},
{1,"TestJointTorque",TestJointTorqueCreateFunc},
};
@ -124,10 +139,15 @@ static int loadCurrentDemoEntry(const char* startFileName)
FILE* f = fopen(startFileName,"r");
if (f)
{
fscanf(f,"%d",&currentEntry);
int result;
result = fscanf(f,"%d",&currentEntry);
if (result)
{
return currentEntry;
}
fclose(f);
}
return currentEntry;
return 0;
};
#endif//BULLET_DEMO_ENTRIES_H

View File

@ -5,8 +5,7 @@ INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui
${BULLET_PHYSICS_SOURCE_DIR}/btgui/lua-5.2.3/src
)
SET(App_AllBullet2Demos_SRCS
main.cpp
BulletDemoInterface.h
@ -26,8 +25,16 @@ SET(App_AllBullet2Demos_SRCS
../../Demos/BasicDemo/BasicDemoPhysicsSetup.h
../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.cpp
../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.h
../../Demos/ConstraintDemo/ConstraintPhysicsSetup.cpp
../../Demos/ConstraintDemo/ConstraintPhysicsSetup.h
../../Demos/SerializeDemo/SerializeSetup.cpp
../../Extras/Serialize/BulletFileLoader/bChunk.cpp
../../Extras/Serialize/BulletFileLoader/bDNA.cpp
../../Extras/Serialize/BulletFileLoader/bFile.cpp
../../Extras/Serialize/BulletFileLoader/btBulletFile.cpp
../../Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.cpp
../../Extras/Serialize/BulletWorldImporter/btWorldImporter.cpp
../bullet2/MultiBodyDemo/TestJointTorqueSetup.cpp
../bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp
../bullet2/ConstraintDemo/ConstraintPhysicsSetup.h
../bullet2/FeatherstoneMultiBodyDemo/BulletMultiBodyDemos.cpp
../bullet2/FeatherstoneMultiBodyDemo/BulletMultiBodyDemos.h
../bullet2/FeatherstoneMultiBodyDemo/MultiDofDemo.cpp
@ -93,7 +100,13 @@ ELSE(WIN32)
MESSAGE(${COCOA})
link_libraries(${COCOA})
ELSE(APPLE)
LINK_LIBRARIES( pthread GLEW)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
LINK_LIBRARIES( pthread dl)
ENDIF(APPLE)
ENDIF(WIN32)

View File

@ -14,7 +14,7 @@ GraphingTexture::~GraphingTexture()
destroy();
}
bool GraphingTexture::destroy()
void GraphingTexture::destroy()
{
//TODO(erwincoumans) release memory etc...
m_width = 0;
@ -58,21 +58,18 @@ bool GraphingTexture::create(int texWidth, int texHeight)
glGenTextures(1,(GLuint*)&m_textureId);
uploadImageData();
return true;
}
void GraphingTexture::uploadImageData()
{
glBindTexture(GL_TEXTURE_2D,m_textureId);
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width,m_height,0,GL_RGBA,GL_UNSIGNED_BYTE,&m_imageData[0]);
glGenerateMipmap(GL_TEXTURE_2D);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}

View File

@ -14,7 +14,7 @@ struct GraphingTexture
virtual ~GraphingTexture();
bool create(int texWidth, int texHeight);
bool destroy();
void destroy();
void setPixel(int x, int y, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
{

View File

@ -124,7 +124,7 @@ void GwenParameterInterface::registerSliderFloatParameter(SliderParams& params)
pSlider->onValueChanged.Add( handler, &MySliderEventHandler<btScalar>::SliderMoved );
handler->SliderMoved(pSlider);
float v = pSlider->GetValue();
// float v = pSlider->GetValue();
m_gwenInternalData->m_curYposition+=22;
}

View File

@ -1,3 +1,4 @@
#include "GwenProfileWindow.h"
#include "../GpuDemos/gwenUserInterface.h"
#include "../GpuDemos/gwenInternalData.h"
#include "LinearMath/btQuickprof.h"
@ -27,7 +28,7 @@ protected:
void SliderMoved(Gwen::Controls::Base* pControl )
{
Gwen::Controls::Slider* pSlider = (Gwen::Controls::Slider*)pControl;
// Gwen::Controls::Slider* pSlider = (Gwen::Controls::Slider*)pControl;
//this->m_app->scaleYoungModulus(pSlider->GetValue());
// printf("Slider Value: %.2f", pSlider->GetValue() );
}
@ -35,8 +36,8 @@ protected:
void OnCheckChangedStiffnessWarping (Gwen::Controls::Base* pControl)
{
Gwen::Controls::CheckBox* labeled = (Gwen::Controls::CheckBox* )pControl;
bool checked = labeled->IsChecked();
// Gwen::Controls::CheckBox* labeled = (Gwen::Controls::CheckBox* )pControl;
// bool checked = labeled->IsChecked();
//m_app->m_stiffness_warp_on = checked;
}
public:
@ -148,13 +149,13 @@ public:
void UpdateText(CProfileIterator* profileIterator, bool idle)
{
static bool update=true;
// static bool update=true;
m_ctrl->SetBounds(0,0,this->GetInnerBounds().w,this->GetInnerBounds().h);
// if (!update)
// return;
update=false;
// update=false;
static int test = 1;
@ -170,18 +171,18 @@ public:
{
//recompute profiling data, and store profile strings
char blockTime[128];
// char blockTime[128];
double totalTime = 0;
// double totalTime = 0;
int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset();
// int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset();
profileIterator->First();
double parent_time = profileIterator->Is_Root() ? time_since_reset : profileIterator->Get_Current_Parent_Total_Time();
Gwen::Controls::TreeNode* curParent = m_node;
// Gwen::Controls::TreeNode* curParent = m_node;
double accumulated_time = dumpRecursive(profileIterator,m_node);

View File

@ -1,8 +1,7 @@
#ifndef GWEN_PROFILE_WINDOW_H
#define GWEN_PROFILE_WINDOW_H
struct MyProfileWindow* setupProfileWindow(struct GwenInternalData* data);
class MyProfileWindow* setupProfileWindow(struct GwenInternalData* data);
void processProfileData(MyProfileWindow* window, bool idle);
void profileWindowSetVisible(MyProfileWindow* window, bool visible);
void destroyProfileWindow(MyProfileWindow* window);

View File

@ -78,7 +78,7 @@ public:
}
};
struct MyGraphWindow* setupTextureWindow(const MyGraphInput& input)
MyGraphWindow* setupTextureWindow(const MyGraphInput& input)
{
MyGraphWindow* graphWindow = new MyGraphWindow(input);
MyMenuItems2* menuItems = new MyMenuItems2(graphWindow);

View File

@ -25,7 +25,7 @@ struct MyGraphInput
{
}
};
struct MyGraphWindow* setupTextureWindow(const MyGraphInput& input);
class MyGraphWindow* setupTextureWindow(const MyGraphInput& input);
void destroyTextureWindow(MyGraphWindow* window);

View File

@ -24,9 +24,11 @@ static b3AlignedObjectArray<const char*> allNames;
bool drawGUI=true;
extern bool useShadowMap;
static bool wireframe=false;
static bool pauseSimulation=false;
static bool pauseSimulation=false;//true;
int midiBaseIndex = 176;
//#include <float.h>
//unsigned int fp_control_state = _controlfp(_EM_INEXACT, _MCW_EM);
#ifdef B3_USE_MIDI
#include "../../btgui/MidiTest/RtMidi.h"
@ -179,6 +181,32 @@ static void MyMouseButtonCallback(int button, int state, float x, float y)
#include <string.h>
void openURDFDemo(const char* filename)
{
if (sCurrentDemo)
{
sCurrentDemo->exitPhysics();
app->m_instancingRenderer->removeAllInstances();
delete sCurrentDemo;
sCurrentDemo=0;
}
app->m_parameterInterface->removeAllParameters();
ImportUrdfDemo* physicsSetup = new ImportUrdfDemo();
physicsSetup->setFileName(filename);
sCurrentDemo = new BasicDemo(app, physicsSetup);
if (sCurrentDemo)
{
sCurrentDemo->initPhysics();
}
}
void selectDemo(int demoIndex)
{
sCurrentDemoIndex = demoIndex;
@ -238,13 +266,13 @@ struct MyMenuItemHander :public Gwen::Event::Handler
void onButtonA(Gwen::Controls::Base* pControl)
{
const Gwen::String& name = pControl->GetName();
//const Gwen::String& name = pControl->GetName();
Gwen::Controls::TreeNode* node = (Gwen::Controls::TreeNode*)pControl;
Gwen::Controls::Label* l = node->GetButton();
// Gwen::Controls::Label* l = node->GetButton();
Gwen::UnicodeString la = node->GetButton()->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
// const char* ha = laa.c_str();
//printf("selected %s\n", ha);
//int dep = but->IsDepressed();
@ -257,7 +285,7 @@ struct MyMenuItemHander :public Gwen::Event::Handler
Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
//const char* ha = laa.c_str();
selectDemo(sCurrentHightlighted);
@ -265,10 +293,10 @@ struct MyMenuItemHander :public Gwen::Event::Handler
}
void onButtonC(Gwen::Controls::Base* pControl)
{
Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
// Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
// Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
// Gwen::String laa = Gwen::Utility::UnicodeToString(la);
// const char* ha = laa.c_str();
// printf("onButtonC ! %s\n", ha);
@ -314,7 +342,8 @@ struct GL3TexLoader : public MyTextureLoader
virtual void LoadTexture( Gwen::Texture* pTexture )
{
const char* n = pTexture->name.Get().c_str();
Gwen::String namestr = pTexture->name.Get();
const char* n = namestr.c_str();
GLint* texIdPtr = m_hashMap[n];
if (texIdPtr)
{
@ -326,6 +355,18 @@ struct GL3TexLoader : public MyTextureLoader
}
};
void fileOpenCallback()
{
char filename[1024];
int len = app->m_window->fileOpenDialog(filename,1024);
if (len)
{
//todo(erwincoumans) check if it is actually URDF
//printf("file open:%s\n", filename);
openURDFDemo(filename);
}
}
extern float shadowMapWorldSize;
int main(int argc, char* argv[])
@ -334,7 +375,7 @@ int main(int argc, char* argv[])
b3Clock clock;
float dt = 1./120.f;
//float dt = 1./120.f;
int width = 1024;
int height=768;
@ -348,8 +389,7 @@ int main(int argc, char* argv[])
app->m_window->setKeyboardCallback(MyKeyboardCallback);
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
sth_stash* fontstash=app->getFontStash();
gui = new GwenUserInterface;
@ -376,7 +416,8 @@ int main(int argc, char* argv[])
gt->create(256,256);
int texId = gt->getTextureId();
myTexLoader->m_hashMap.insert("graph1", texId);
MyGraphWindow* gw = setupTextureWindow(input);
//MyGraphWindow* gw =
setupTextureWindow(input);
}
if (1)
{
@ -403,7 +444,8 @@ int main(int argc, char* argv[])
int texId = gt->getTextureId();
input.m_xPos = width-input.m_width;
myTexLoader->m_hashMap.insert("graph2", texId);
MyGraphWindow* gw = setupTextureWindow(input);
//MyGraphWindow* gw =
setupTextureWindow(input);
}
//destroyTextureWindow(gw);
@ -414,8 +456,8 @@ int main(int argc, char* argv[])
int numDemos = sizeof(allDemos)/sizeof(BulletDemoEntry);
char nodeText[1024];
int curDemo = 0;
//char nodeText[1024];
//int curDemo = 0;
int selectedDemo = loadCurrentDemoEntry(startFileName);
Gwen::Controls::TreeNode* curNode = tree;
MyMenuItemHander* handler2 = new MyMenuItemHander(-1);
@ -472,12 +514,12 @@ int main(int argc, char* argv[])
*/
unsigned long int prevTimeInMicroseconds = clock.getTimeMicroseconds();
gui->registerFileOpenCallback(fileOpenCallback);
do
{
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
app->m_instancingRenderer->init();
DrawGridData dg;
dg.upAxis = app->getUpAxis();

View File

@ -44,14 +44,23 @@
"../bullet2/BasicDemo/Bullet2RigidBodyDemo.h",
"../bullet2/LuaDemo/LuaPhysicsSetup.cpp",
"../bullet2/LuaDemo/LuaPhysicsSetup.h",
"../bullet2/MultiBodyDemo/TestJointTorqueSetup.cpp",
"../bullet2/MultiBodyDemo/TestJointTorqueSetup.h",
-- "../DifferentialGearDemo/DifferentialGearSetup.cpp",
-- "../DifferentialGearDemo/DifferentialGearSetup.h",
"../../Demos/BasicDemo/BasicDemoPhysicsSetup.cpp",
"../../Demos/BasicDemo/BasicDemoPhysicsSetup.h",
"../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.cpp",
"../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.h",
"../../Demos/ConstraintDemo/ConstraintPhysicsSetup.cpp",
"../../Demos/ConstraintDemo/ConstraintPhysicsSetup.h",
"../../Demos/SerializeDemo/SerializeSetup.cpp",
"../../Extras/Serialize/BulletFileLoader/bChunk.cpp",
"../../Extras/Serialize/BulletFileLoader/bDNA.cpp",
"../../Extras/Serialize/BulletFileLoader/bFile.cpp",
"../../Extras/Serialize/BulletFileLoader/btBulletFile.cpp",
"../../Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.cpp",
"../../Extras/Serialize/BulletWorldImporter/btWorldImporter.cpp",
"../bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp",
"../bullet2/ConstraintDemo/ConstraintPhysicsSetup.h",
"../ImportURDFDemo/ImportURDFSetup.cpp",
"../ImportObjDemo/ImportObjSetup.cpp",
"../ImportSTLDemo/ImportSTLSetup.cpp",
@ -106,5 +115,5 @@ if os.is("Linux") then
initX11()
end
if os.is("MacOSX") then
links{"Cocoa.framework"}
links{"Cocoa.framework"}
end

View File

@ -144,7 +144,7 @@ int main(int argc, char* argv[])
}
if (majorGlVersion>=3 && wci.m_openglVersion>=3)
{
float retinaScale = 1.f;
// float retinaScale = 1.f;
#ifndef __APPLE__
#ifndef _WIN32
@ -154,14 +154,15 @@ int main(int argc, char* argv[])
glewInit();
#endif
//we ned to call glGetError twice, because of some Ubuntu/Intel/OpenGL issue
//we need to call glGetError twice, because of some Ubuntu/Intel/OpenGL issue
GLuint err = glGetError();
err = glGetError();
btAssert(err==GL_NO_ERROR);
glGetError();
glGetError();
btAssert(glGetError()==GL_NO_ERROR);
retinaScale = window->getRetinaScale();
//retinaScale = window->getRetinaScale();
//primRenderer = new GLPrimitiveRenderer(sWidth,sHeight);
//sth_stash* font = initFont(primRenderer );

View File

@ -1,5 +1,5 @@
if (OPENGL_FOUND)
if (BUILD_BULLET3_DEMOS)
if (BUILD_OPENGL3_DEMOS)
SUBDIRS( AllBullet2Demos GpuDemos SimpleOpenGL3 )
endif(BUILD_BULLET3_DEMOS)
endif(BUILD_OPENGL3_DEMOS)
endif(OPENGL_FOUND)

View File

@ -50,7 +50,16 @@ ELSE(WIN32)
MESSAGE(${COCOA})
link_libraries(${COCOA})
ELSE(APPLE)
LINK_LIBRARIES( GLEW X11 pthread dl)
SET(App_Bullet3_OpenCL_Demos_SRCS ${App_Bullet3_OpenCL_Demos_SRCS} ${App_Bullet3_OpenCL_Demos_Common_SRCS} ../../btgui/OpenGLWindow/GlewWindows/glew.c)
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( X11 pthread dl)
ENDIF(APPLE)
ENDIF(WIN32)

View File

@ -5,7 +5,7 @@
#include "Bullet3OpenCL/Initialize/b3OpenCLUtils.h"
#define MSTRINGIFY(A) #A
static char* particleKernelsString =
static const char* particleKernelsString =
#include "ParticleKernels.cl"
#define INTEROPKERNEL_SRC_PATH "demo/gpudemo/ParticleKernels.cl"
@ -40,7 +40,7 @@ static char* particleKernelsString =
//#define NUM_PARTICLES_Y 30
//#define NUM_PARTICLES_Z 30
B3_ATTRIBUTE_ALIGNED16(struct) b3SimParams
{
@ -48,7 +48,7 @@ B3_ATTRIBUTE_ALIGNED16(struct) b3SimParams
b3Vector3 m_gravity;
float m_worldMin[4];
float m_worldMax[4];
float m_particleRad;
float m_globalDamping;
float m_boundaryDamping;
@ -59,7 +59,7 @@ B3_ATTRIBUTE_ALIGNED16(struct) b3SimParams
float m_attraction;
float m_dummy;
b3SimParams()
{
m_gravity.setValue(0,-.3,0.f);
@ -83,7 +83,7 @@ B3_ATTRIBUTE_ALIGNED16(struct) b3SimParams
struct ParticleInternalData
{
cl_kernel m_updatePositionsKernel;
cl_kernel m_updatePositionsKernel2;
@ -92,7 +92,7 @@ struct ParticleInternalData
cl_kernel m_collideParticlesKernel;
b3GpuSapBroadphase* m_broadphaseGPU;
cl_mem m_clPositionBuffer;
@ -102,7 +102,7 @@ struct ParticleInternalData
b3AlignedObjectArray<b3SimParams> m_simParamCPU;
b3OpenCLArray<b3SimParams>* m_simParamGPU;
ParticleInternalData()
:
@ -144,7 +144,7 @@ void ParticleDemo::exitCL()
clReleaseKernel(m_data->m_updateAabbsKernel);
clReleaseKernel(m_data->m_collideParticlesKernel);
}
GpuDemo::exitCL();
}
@ -158,12 +158,12 @@ void ParticleDemo::setupScene(const ConstructionInfo& ci)
{
initCL(ci.preferredOpenCLDeviceIndex,ci.preferredOpenCLPlatformIndex);
int numParticles = NUM_PARTICLES_X*NUM_PARTICLES_Y*NUM_PARTICLES_Z;
int maxObjects = NUM_PARTICLES_X*NUM_PARTICLES_Y*NUM_PARTICLES_Z+1024;
int maxPairsSmallProxy = 32;
float radius = m_data->m_simParamCPU[0].m_particleRad;
@ -219,15 +219,15 @@ void ParticleDemo::setupScene(const ConstructionInfo& ci)
float position[4] = {0,0,0,0};
float quaternion[4] = {0,0,0,1};
float scaling[4] = {radius,radius,radius,1};
int userIndex = 0;
int totalParticles = NUM_PARTICLES_X*NUM_PARTICLES_Y*NUM_PARTICLES_Z;
int curColor = 0;
b3Vector4 colors[4] =
b3Vector4 colors[4] =
{
b3MakeVector4(1,1,1,1),
b3MakeVector4(1,1,0.3,1),
@ -241,9 +241,9 @@ void ParticleDemo::setupScene(const ConstructionInfo& ci)
float angle = b3RandRange(-B3_PI, B3_PI);
for (int ii=0;ii<totalParticles;ii++)
{
float arg = b3RandRange(-B3_PI,B3_PI);
float rad = m_data->m_simParamCPU[0].m_particleRad;
position[0] = arg*b3Cos(arg + angle);
position[1] = 3.0f + arg;
@ -255,8 +255,8 @@ void ParticleDemo::setupScene(const ConstructionInfo& ci)
int id = m_instancingRenderer->registerGraphicsInstance(shapeId,position,quaternion,color,scaling);
void* userPtr = (void*)userIndex;
int collidableIndex = userIndex;
b3Vector3 aabbMin,aabbMax;
b3Vector3 particleRadius=b3MakeVector3(rad,rad,rad);
@ -268,7 +268,7 @@ void ParticleDemo::setupScene(const ConstructionInfo& ci)
angle += b3RandRange(-(float)B3_PI, (float)B3_PI);
}
}
m_data->m_broadphaseGPU->writeAabbsToGpu();
@ -291,7 +291,7 @@ void ParticleDemo::exitPhysics()
void ParticleDemo::renderScene()
{
if (m_instancingRenderer)
{
m_instancingRenderer->renderScene();
@ -315,7 +315,7 @@ void ParticleDemo::clientMoveAndDisplay()
assert(err==GL_NO_ERROR);
glFinish();
#if 1
@ -326,10 +326,10 @@ void ParticleDemo::clientMoveAndDisplay()
bool useCpu = false;
if (useCpu)
{
float* posBuffer = (float*)hostPtr;
for (int i=0;i<numParticles;i++)
{
posBuffer[i*4+1] += 0.1;
@ -350,19 +350,19 @@ void ParticleDemo::clientMoveAndDisplay()
);
clFinish(m_clData->m_clQueue);
}
if (0)
{
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL( m_data->m_velocitiesGPU->getBufferCL(), true ),
b3BufferInfoCL( m_data->m_clPositionBuffer)
};
b3LauncherCL launcher(m_clData->m_clQueue, m_data->m_updatePositionsKernel,"m_updatePositionsKernel" );
launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(b3BufferInfoCL) );
@ -370,18 +370,18 @@ void ParticleDemo::clientMoveAndDisplay()
launcher.launch1D( numParticles);
clFinish(m_clData->m_clQueue);
}
if (1)
{
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL( m_data->m_clPositionBuffer),
b3BufferInfoCL( m_data->m_velocitiesGPU->getBufferCL() ),
b3BufferInfoCL( m_data->m_simParamGPU->getBufferCL(),true)
};
b3LauncherCL launcher(m_clData->m_clQueue, m_data->m_updatePositionsKernel2 ,"m_updatePositionsKernel2");
launcher.setConst( numParticles);
@ -391,21 +391,21 @@ void ParticleDemo::clientMoveAndDisplay()
launcher.launch1D( numParticles);
clFinish(m_clData->m_clQueue);
}
if (0)
{
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL( m_data->m_clPositionBuffer),
b3BufferInfoCL( m_data->m_broadphaseGPU->getAabbBufferWS()),
};
b3LauncherCL launcher(m_clData->m_clQueue, m_data->m_updateAabbsKernel,"m_updateAabbsKernel" );
launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(b3BufferInfoCL) );
launcher.setConst( m_data->m_simParamCPU[0].m_particleRad);
launcher.setConst( numParticles);
launcher.launch1D( numParticles);
clFinish(m_clData->m_clQueue);
}
@ -422,12 +422,12 @@ void ParticleDemo::clientMoveAndDisplay()
if (numPairsGPU)
{
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL bInfo[] = {
b3BufferInfoCL( m_data->m_clPositionBuffer),
b3BufferInfoCL( m_data->m_velocitiesGPU->getBufferCL() ),
b3BufferInfoCL( m_data->m_broadphaseGPU->getOverlappingPairBuffer(),true),
};
b3LauncherCL launcher(m_clData->m_clQueue, m_data->m_collideParticlesKernel,"m_collideParticlesKernel");
launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(b3BufferInfoCL) );
launcher.setConst( numPairsGPU);
@ -450,15 +450,15 @@ void ParticleDemo::clientMoveAndDisplay()
//clReleaseMemObject(clBuffer);
clFinish(m_clData->m_clQueue);
}
}
#endif
glUnmapBuffer( GL_ARRAY_BUFFER);
glFlush();
}

View File

@ -40,6 +40,7 @@ struct GwenInternalData
Gwen::Controls::TabButton* m_explorerPage;
Gwen::Controls::TreeControl* m_explorerTreeCtrl;
Gwen::Controls::MenuItem* m_viewMenu;
class MyMenuItems* m_menuItems;
int m_curYposition;

View File

@ -44,13 +44,23 @@ class MyMenuItems : public Gwen::Controls::Base
{
public:
MyMenuItems() :Gwen::Controls::Base(0)
b3FileOpenCallback m_fileOpenCallback;
MyMenuItems() :Gwen::Controls::Base(0),m_fileOpenCallback(0)
{
}
void myQuitApp( Gwen::Controls::Base* pControl )
{
exit(0);
}
void fileOpen( Gwen::Controls::Base* pControl )
{
if (m_fileOpenCallback)
{
(*m_fileOpenCallback)();
}
}
};
struct MyTestMenuBar : public Gwen::Controls::MenuStrip
@ -58,17 +68,20 @@ struct MyTestMenuBar : public Gwen::Controls::MenuStrip
Gwen::Controls::MenuItem* m_fileMenu;
Gwen::Controls::MenuItem* m_viewMenu;
MyMenuItems* m_menuItems;
MyTestMenuBar(Gwen::Controls::Base* pParent)
:Gwen::Controls::MenuStrip(pParent)
{
// Gwen::Controls::MenuStrip* menu = new Gwen::Controls::MenuStrip( pParent );
{
MyMenuItems* menuItems = new MyMenuItems;
m_menuItems = new MyMenuItems;
m_fileMenu = AddItem( L"File" );
m_fileMenu->GetMenu()->AddItem(L"Quit",menuItems,(Gwen::Event::Handler::Function)&MyMenuItems::myQuitApp);
m_viewMenu = AddItem( L"View" );
m_fileMenu->GetMenu()->AddItem(L"Open",m_menuItems,(Gwen::Event::Handler::Function)&MyMenuItems::fileOpen);
m_fileMenu->GetMenu()->AddItem(L"Quit",m_menuItems,(Gwen::Event::Handler::Function)&MyMenuItems::myQuitApp);
m_viewMenu = AddItem( L"View" );
}
}
@ -120,7 +133,7 @@ struct MyButtonHander :public Gwen::Event::Handler
void onButtonA( Gwen::Controls::Base* pControl )
{
Gwen::Controls::Button* but = (Gwen::Controls::Button*) pControl;
int dep = but->IsDepressed();
// int dep = but->IsDepressed();
int tog = but->GetToggleState();
if (m_data->m_toggleButtonCallback)
(*m_data->m_toggleButtonCallback)(m_buttonId,tog);
@ -142,6 +155,11 @@ void GwenUserInterface::setStatusBarMessage(const char* message, bool isLeft)
}
}
void GwenUserInterface::registerFileOpenCallback(b3FileOpenCallback callback)
{
m_data->m_menuItems->m_fileOpenCallback = callback;
}
void GwenUserInterface::init(int width, int height,struct sth_stash* stash,float retinaScale)
{
m_data->m_curYposition = 20;
@ -157,6 +175,10 @@ void GwenUserInterface::init(int width, int height,struct sth_stash* stash,float
MyTestMenuBar* menubar = new MyTestMenuBar(m_data->pCanvas);
m_data->m_viewMenu = menubar->m_viewMenu;
m_data->m_menuItems = menubar->m_menuItems;
Gwen::Controls::StatusBar* bar = new Gwen::Controls::StatusBar(m_data->pCanvas);
m_data->m_rightStatusBar = new Gwen::Controls::Label( bar );
m_data->m_rightStatusBar->SetWidth(width/2);

View File

@ -5,7 +5,7 @@ struct GwenInternalData;
typedef void (*b3ComboBoxCallback) (int combobox, const char* item);
typedef void (*b3ToggleButtonCallback)(int button, int state);
typedef void (*b3FileOpenCallback)();
class GwenUserInterface
@ -40,6 +40,8 @@ class GwenUserInterface
void setStatusBarMessage(const char* message, bool isLeft=true);
void registerFileOpenCallback(b3FileOpenCallback callback);
GwenInternalData* getInternalData()
{
return m_data;

View File

@ -55,8 +55,8 @@ bool dump_timings = false;
int maxFrameCount = 102;
extern char OpenSansData[];
extern char* gPairBenchFileName;
extern float shadowMapWidth;
extern float shadowMapHeight;
extern int shadowMapWidth;
extern int shadowMapHeight;
extern bool gDebugLauncherCL;
extern bool gAllowCpuOpenCL;
extern bool gUseLargeBatches;
@ -94,7 +94,8 @@ static int loadCurrentDemoEntry(const char* startFileName)
FILE* f = fopen(startFileName,"r");
if (f)
{
fscanf(f,"%d",&currentEntry);
int bytesScanned;
bytesScanned = fscanf(f,"%d",&currentEntry);
fclose(f);
}
return currentEntry;
@ -130,20 +131,20 @@ int selectedDemo = 1;
GpuDemo::CreateFunc* allDemos[]=
{
//ConcaveCompound2Scene::MyCreateFunc,
//ConcaveSphereScene::MyCreateFunc,
// ConcaveSphereScene::MyCreateFunc,
ConcaveScene::MyCreateFunc,
GpuBoxPlaneScene::MyCreateFunc,
GpuConstraintsDemo::MyCreateFunc,
//GpuConvexPlaneScene::MyCreateFunc,
@ -155,14 +156,14 @@ GpuDemo::CreateFunc* allDemos[]=
GpuSphereScene::MyCreateFunc,
ConcaveSphereScene::MyCreateFunc,
ConcaveCompoundScene::MyCreateFunc,
//GpuTetraScene::MyCreateFunc,
@ -170,7 +171,7 @@ GpuDemo::CreateFunc* allDemos[]=
Bullet2FileDemo::MyCreateFunc,
PairBench::MyCreateFunc,
GpuRaytraceScene::MyCreateFunc,
@ -534,7 +535,7 @@ FILE* defaultOutput = stdout;
void myprintf(const char* msg)
{
fprintf(defaultOutput,msg);
fprintf(defaultOutput,"%s",msg);
}
@ -560,7 +561,7 @@ void writeTextureToPng(int textureWidth, int textureHeight, const char* fileName
char* pixels = (char*)malloc(textureWidth*textureHeight*numComponents);
err=glGetError();
assert(err==GL_NO_ERROR);
for (int j=0;j<textureHeight;j++)
{
for (int i=0;i<textureWidth;i++)
@ -576,7 +577,7 @@ void writeTextureToPng(int textureWidth, int textureHeight, const char* fileName
{
//swap the pixels
unsigned char tmp;
for (int j=0;j<textureHeight/2;j++)
{
for (int i=0;i<textureWidth;i++)
@ -591,9 +592,9 @@ void writeTextureToPng(int textureWidth, int textureHeight, const char* fileName
}
}
}
stbi_write_png(fileName, textureWidth,textureHeight, numComponents, pixels, textureWidth*numComponents);
free(pixels);
free(orgPixels);
@ -615,7 +616,7 @@ int main(int argc, char* argv[])
int sz6 = sizeof(b3Transform);
//b3OpenCLUtils::setCachePath("/Users/erwincoumans/develop/mycache");
b3SetCustomEnterProfileZoneFunc(b3ProfileManager::Start_Profile);
b3SetCustomLeaveProfileZoneFunc(b3ProfileManager::Stop_Profile);
@ -699,7 +700,7 @@ int main(int argc, char* argv[])
gDebugForceLoadingFromSource = args.CheckCmdLineFlag("load_cl_kernels_from_disk");
gDebugSkipLoadingBinary = args.CheckCmdLineFlag("disable_cached_cl_kernels");
#ifndef B3_NO_PROFILE
b3ProfileManager::Reset();
@ -719,7 +720,7 @@ int main(int argc, char* argv[])
window->setWindowTitle("Bullet 3.x GPU Rigid Body http://bulletphysics.org");
printf("-----------------------------------------------------\n");
#ifndef __APPLE__
@ -732,7 +733,7 @@ int main(int argc, char* argv[])
GLPrimitiveRenderer prim(g_OpenGLWidth,g_OpenGLHeight);
stash = initFont(&prim);
@ -782,7 +783,7 @@ int main(int argc, char* argv[])
glClearColor(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);//|GL_STENCIL_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
sth_begin_draw(stash);
//sth_draw_text(stash, droidRegular,12.f, dx, dy-50, "How does this OpenGL True Type font look? ", &dx,width,height);
int spacing = 0;//g_OpenGLHeight;
@ -820,13 +821,13 @@ int main(int argc, char* argv[])
for (int i=0;i<nummsg;i++)
{
char txt[512];
sprintf(txt,msg[i]);
sprintf(txt,"%s",msg[i]);
//sth_draw_text(stash, droidRegular,i, 10, dy-spacing, txt, &dx,g_OpenGLWidth,g_OpenGLHeight);
sth_draw_text(stash, droidRegular,fontSize, 10, spacing, txt, &dx,g_OpenGLWidth,g_OpenGLHeight);
spacing+=fontSize;
fontSize = 32;
}
sth_end_draw(stash);
sth_flush_draw(stash);
window->endRendering();
@ -852,7 +853,7 @@ int main(int argc, char* argv[])
// demo->myinit();
bool useGpu = false;
//int maxObjectCapacity=128*1024;
int maxObjectCapacity=1024*1024;
maxObjectCapacity = b3Max(maxObjectCapacity,ci.arraySizeX*ci.arraySizeX*ci.arraySizeX+10);
@ -874,7 +875,7 @@ int main(int argc, char* argv[])
printf("-----------------------------------------------------\n");
@ -883,14 +884,14 @@ int main(int argc, char* argv[])
if (benchmark)
{
char prefixFileName[1024];
char csvFileName[1024];
char detailsFileName[1024];
b3OpenCLDeviceInfo info;
b3OpenCLUtils::getDeviceInfo(demo->getInternalData()->m_clDevice,&info);
//todo: move this time stuff into the Platform/Window class
#ifdef _WIN32
SYSTEMTIME time;
@ -906,11 +907,11 @@ int main(int argc, char* argv[])
}
sprintf(prefixFileName,"%s_%s_%s_%d_%d_%d_date_%d-%d-%d_time_%d-%d-%d",info.m_deviceName,buf,demoNames[selectedDemo],ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ,time.wDay,time.wMonth,time.wYear,time.wHour,time.wMinute,time.wSecond);
#else
timeval now;
gettimeofday(&now,0);
struct tm* ptm;
ptm = localtime (&now.tv_sec);
char buf[1024];
@ -926,7 +927,7 @@ int main(int argc, char* argv[])
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec);
#endif
sprintf(csvFileName,"%s.csv",prefixFileName);
@ -944,7 +945,7 @@ int main(int argc, char* argv[])
// fprintf(f,"%s (%dx%dx%d=%d),\n", g_deviceName,ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ,ci.arraySizeX*ci.arraySizeY*ci.arraySizeZ);
}
fprintf(defaultOutput,"Demo settings:\n");
fprintf(defaultOutput," SelectedDemo=%d, demoname = %s\n", selectedDemo, demo->getName());
fprintf(defaultOutput," x_dim=%d, y_dim=%d, z_dim=%d\n",ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ);
@ -971,7 +972,7 @@ int main(int argc, char* argv[])
if (exportFrame || exportMovie)
{
if (!renderTexture)
{
renderTexture = new GLRenderToTexture();
@ -993,10 +994,10 @@ int main(int argc, char* argv[])
renderTexture->init(g_OpenGLWidth,g_OpenGLHeight,renderTextureId, RENDERTEXTURE_COLOR);
}
bool result = renderTexture->enable();
}
}
err = glGetError();
assert(err==GL_NO_ERROR);
@ -1052,10 +1053,10 @@ int main(int argc, char* argv[])
}
*/
if (exportFrame || exportMovie)
{
char fileName[1024];
sprintf(fileName,"screenShot%d.png",frameIndex++);
writeTextureToPng(g_OpenGLWidth,g_OpenGLHeight,fileName);
@ -1085,7 +1086,7 @@ int main(int argc, char* argv[])
B3_PROFILE("glFinish");
}
if (dump_timings)
{
@ -1147,7 +1148,7 @@ int main(int argc, char* argv[])
{
delete gui;
gui=0;

View File

@ -27,7 +27,7 @@ extern bool enableExperimentalCpuConcaveCollision;
#include "Bullet3OpenCL/RigidBody/b3GpuRigidBodyPipeline.h"
#include "Bullet3OpenCL/RigidBody/b3GpuNarrowPhase.h"
///work-in-progress
///work-in-progress
///This ReadBulletSample is kept as simple as possible without dependencies to the Bullet SDK.
///It can be used to load .bullet data for other physics SDKs
///For a more complete example how to load and convert Bullet data using the Bullet SDK check out
@ -66,23 +66,23 @@ void createScene( GLInstancingRenderer& renderer,b3GpuNarrowPhase& np, b3GpuRigi
//const char* fileName="../../bin/1000 convex.bullet";
//const char* fileName="../../bin/1000 stack.bullet";
//const char* fileName="../../bin/3000 fall.bullet";
//const char* fileName="../../bin/testFile.bullet";
FILE* f = fopen(fileName,"rb");
if (f)
{
fclose(f);
bool verboseDumpAllTypes = false;
bParse::b3BulletFile* bulletFile2 = new bParse::b3BulletFile(fileName);
bool ok = (bulletFile2->getFlags()& bParse::FD_OK)!=0;
if (ok)
bulletFile2->parse(verboseDumpAllTypes);
else
@ -99,7 +99,7 @@ void createScene( GLInstancingRenderer& renderer,b3GpuNarrowPhase& np, b3GpuRigi
printf("Error parsing file %s.\n",fileName);
exit(0);
}
if (verboseDumpAllTypes)
{
bulletFile2->dumpChunks(bulletFile2->getFileDNA());
@ -107,7 +107,7 @@ void createScene( GLInstancingRenderer& renderer,b3GpuNarrowPhase& np, b3GpuRigi
b3BulletDataExtractor extractor(renderer,np,rbWorld);
extractor.convertAllObjects(bulletFile2);
delete bulletFile2;
return;
@ -163,7 +163,7 @@ CONCAVE_SHAPES_START_HERE,
GIMPACT_SHAPE_PROXYTYPE,
///Multimaterial mesh
MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE,
EMPTY_SHAPE_PROXYTYPE,
STATIC_PLANE_PROXYTYPE,
CUSTOM_CONCAVE_SHAPE_TYPE,
@ -177,7 +177,7 @@ CONCAVE_SHAPES_END_HERE,
INVALID_SHAPE_PROXYTYPE,
MAX_BROADPHASE_COLLISION_TYPES
};
b3BulletDataExtractor::b3BulletDataExtractor(GLInstancingRenderer& renderer, b3GpuNarrowPhase& np, b3GpuRigidBodyPipeline& rbWorld)
@ -214,7 +214,7 @@ void b3BulletDataExtractor::convertAllObjects(bParse::b3BulletFile* bulletFile2)
for (i=0;i<bulletFile2->m_rigidBodies.size();i++)
{
Bullet3SerializeBullet2::b3RigidBodyFloatData* colObjData = (Bullet3SerializeBullet2::b3RigidBodyFloatData*)bulletFile2->m_rigidBodies[i];
Bullet3SerializeBullet2::b3CollisionShapeData* shapeData = (Bullet3SerializeBullet2::b3CollisionShapeData*)colObjData->m_collisionObjectData.m_collisionShape;
for (int j=0;j<m_instanceGroups.size();j++)
@ -237,7 +237,7 @@ void b3BulletDataExtractor::convertAllObjects(bParse::b3BulletFile* bulletFile2)
for (int j=0;j<m_instanceGroups[i]->m_rigidBodies.size();j++)
{
Bullet3SerializeBullet2::b3RigidBodyFloatData* colObjData = (Bullet3SerializeBullet2::b3RigidBodyFloatData*)m_instanceGroups[i]->m_rigidBodies[j];
b3Matrix3x3 mat;
mat.deSerializeFloat((const b3Matrix3x3FloatData&)colObjData->m_collisionObjectData.m_worldTransform.m_basis);
b3Quaternion orn;
@ -259,23 +259,23 @@ void b3BulletDataExtractor::convertAllObjects(bParse::b3BulletFile* bulletFile2)
}
if (keepStaticObjects || colObjData->m_inverseMass!=0.f)
{
m_rbPipeline.registerPhysicsInstance(mass,pos,quaternion,m_instanceGroups[i]->m_collisionShapeIndex,0,true);
m_renderer.registerGraphicsInstance(m_instanceGroups[i]->m_collisionShapeIndex,pos,quaternion,color,m_graphicsShapes[i]->m_scaling);
}
}
}
}
for (i=0;i<bulletFile2->m_collisionObjects.size();i++)
{
}
m_rbPipeline.writeAllInstancesToGpu();
}
@ -303,7 +303,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
case CONVEX_HULL_SHAPE_PROXYTYPE:
{
Bullet3SerializeBullet2::b3ConvexInternalShapeData* bsd = (Bullet3SerializeBullet2::b3ConvexInternalShapeData*)shapeData;
switch (shapeData->m_shapeType)
{
case BOX_SHAPE_PROXYTYPE:
@ -331,7 +331,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
b3Vector3 pt = b3MakeVector3(convexData->m_unscaledPointsFloatPtr[i].m_floats[0],
convexData->m_unscaledPointsFloatPtr[i].m_floats[1],
convexData->m_unscaledPointsFloatPtr[i].m_floats[2]);//convexData->m_unscaledPointsFloatPtr[i].m_floats[3]);
tmpPoints.push_back(pt*localScaling);
}
}
@ -378,7 +378,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
}
};
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
@ -408,9 +408,9 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
}
};
break;
}
case MULTI_SPHERE_SHAPE_PROXYTYPE:
@ -426,7 +426,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
shape = new b3MultiSphereShape(&tmpPos[0],&radii[0],numSpheres);
break;
}
#endif
default:
@ -453,13 +453,13 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
//dat.
}
///trimesh->m_meshInterface.m_meshPartsPtr
//trimesh->m_meshInterface.m_scaling
}
//trimesh->m_meshInterface
//b3TriangleIndexVertexArray* meshInterface = createMeshInterface(trimesh->m_meshInterface);
//scaling
//b3Vector3 scaling; scaling.deSerializeFloat(trimesh->m_meshInterface.m_scaling);
@ -489,7 +489,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
{
printf("error: couldn't create childShape for compoundShape\n");
}
}
shape = compoundShape;
@ -519,7 +519,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
{
return 0;
}
#endif
#endif
default:
{
printf("unsupported shape type (%d)\n",shapeData->m_shapeType);
@ -527,7 +527,7 @@ int b3BulletDataExtractor::convertCollisionShape( Bullet3SerializeBullet2::b3Co
}
return shapeIndex;
}
int b3BulletDataExtractor::createBoxShape( const Bullet3SerializeBullet2::b3Vector3FloatData& halfDimensions, const Bullet3SerializeBullet2::b3Vector3FloatData& localScaling, float collisionMargin)
@ -544,7 +544,7 @@ int b3BulletDataExtractor::createBoxShape( const Bullet3SerializeBullet2::b3Vect
{
int numVertices = sizeof(cube_vertices)/strideInBytes;
int numIndices = sizeof(cube_indices)/sizeof(int);
GraphicsShape* gfxShape = new GraphicsShape;
gfxShape->m_vertices = cube_vertices;
gfxShape->m_numvertices = numVertices;
@ -569,7 +569,7 @@ int b3BulletDataExtractor::createSphereShape( float radius, const Bullet3Seriali
int b3BulletDataExtractor::createPlaneShape( const Bullet3SerializeBullet2::b3Vector3FloatData& planeNormal, float planeConstant, const Bullet3SerializeBullet2::b3Vector3FloatData& localScaling)
{
printf("createPlaneShape with normal %f,%f,%f and planeConstant\n",planeNormal.m_floats[0], planeNormal.m_floats[1],planeNormal.m_floats[2],planeConstant);
printf("createPlaneShape with normal %f,%f,%f and planeConstant %f\n",planeNormal.m_floats[0], planeNormal.m_floats[1],planeNormal.m_floats[2],planeConstant);
return -1;
}
@ -582,7 +582,7 @@ GraphicsShape* b3BulletDataExtractor::createGraphicsShapeFromConvexHull(const b3
b3ConvexUtility* utilPtr = new b3ConvexUtility();
bool merge = true;
utilPtr->initializePolyhedralFeatures(tmpPoints,numPoints,merge);
b3AlignedObjectArray<GraphicsVertex>* vertices = new b3AlignedObjectArray<GraphicsVertex>;
{
int numVertices = utilPtr->m_vertices.size();
@ -594,7 +594,7 @@ GraphicsShape* b3BulletDataExtractor::createGraphicsShapeFromConvexHull(const b3
b3Vector3 normal=b3MakeVector3(face.m_plane[0],face.m_plane[1],face.m_plane[2]);
if (face.m_indices.size()>2)
{
GraphicsVertex vtx;
const b3Vector3& orgVertex = utilPtr->m_vertices[face.m_indices[0]];
vtx.xyzw[0] = orgVertex[0];vtx.xyzw[1] = orgVertex[1];vtx.xyzw[2] = orgVertex[2];vtx.xyzw[3] = 0.f;
@ -602,7 +602,7 @@ GraphicsShape* b3BulletDataExtractor::createGraphicsShapeFromConvexHull(const b3
vtx.uv[0] = 0.5f;vtx.uv[1] = 0.5f;
int newvtxindex0 = vertices->size();
vertices->push_back(vtx);
for (int j=1;j<face.m_indices.size()-1;j++)
{
indicesPtr->push_back(newvtxindex0);
@ -630,15 +630,15 @@ GraphicsShape* b3BulletDataExtractor::createGraphicsShapeFromConvexHull(const b3
}
}
}
GraphicsShape* gfxShape = new GraphicsShape;
gfxShape->m_vertices = &vertices->at(0).xyzw[0];
gfxShape->m_numvertices = vertices->size();
gfxShape->m_indices = &indicesPtr->at(0);
gfxShape->m_numIndices = indicesPtr->size();
for (int i=0;i<4;i++)
gfxShape->m_scaling[i] = 1;//bake the scaling into the vertices
gfxShape->m_scaling[i] = 1;//bake the scaling into the vertices
return gfxShape;
}
}
}

View File

@ -27,13 +27,13 @@
GLInstanceGraphicsShape* createGraphicsShapeFromWavefrontObj(std::vector<tinyobj::shape_t>& shapes)
{
b3AlignedObjectArray<GLInstanceVertex>* vertices = new b3AlignedObjectArray<GLInstanceVertex>;
{
// int numVertices = obj->vertexCount;
// int numIndices = 0;
b3AlignedObjectArray<int>* indicesPtr = new b3AlignedObjectArray<int>;
for (int s=0;s<shapes.size();s++)
{
tinyobj::shape_t& shape = shapes[s];
@ -42,18 +42,18 @@ GLInstanceGraphicsShape* createGraphicsShapeFromWavefrontObj(std::vector<tinyobj
for (int f=0;f<faceCount;f+=3)
{
//b3Vector3 normal(face.m_plane[0],face.m_plane[1],face.m_plane[2]);
if (1)
{
b3Vector3 normal=b3MakeVector3(0,1,0);
int vtxBaseIndex = vertices->size();
indicesPtr->push_back(vtxBaseIndex);
indicesPtr->push_back(vtxBaseIndex+1);
indicesPtr->push_back(vtxBaseIndex+2);
GLInstanceVertex vtx0;
vtx0.xyzw[0] = shape.mesh.positions[shape.mesh.indices[f]*3+0];
vtx0.xyzw[1] = shape.mesh.positions[shape.mesh.indices[f]*3+1];
@ -101,15 +101,15 @@ GLInstanceGraphicsShape* createGraphicsShapeFromWavefrontObj(std::vector<tinyobj
}
}
}
GLInstanceGraphicsShape* gfxShape = new GLInstanceGraphicsShape;
gfxShape->m_vertices = vertices;
gfxShape->m_numvertices = vertices->size();
gfxShape->m_indices = indicesPtr;
gfxShape->m_numIndices = indicesPtr->size();
for (int i=0;i<4;i++)
gfxShape->m_scaling[i] = 1;//bake the scaling into the vertices
gfxShape->m_scaling[i] = 1;//bake the scaling into the vertices
return gfxShape;
}
}
@ -117,15 +117,15 @@ GLInstanceGraphicsShape* createGraphicsShapeFromWavefrontObj(std::vector<tinyobj
void ConcaveScene::createConcaveMesh(const ConstructionInfo& ci, const char* fileName, const b3Vector3& shift, const b3Vector3& scaling)
{
char relativeFileName[1024];
const char* prefix[]={"./data/","../data/","../../data/","../../../data/","../../../../data/"};
int prefixIndex=-1;
{
int numPrefixes = sizeof(prefix)/sizeof(char*);
for (int i=0;i<numPrefixes;i++)
@ -145,7 +145,7 @@ void ConcaveScene::createConcaveMesh(const ConstructionInfo& ci, const char* fil
if (prefixIndex<0)
return;
int index=10;
{
@ -154,7 +154,7 @@ void ConcaveScene::createConcaveMesh(const ConstructionInfo& ci, const char* fil
std::string err = tinyobj::LoadObj(shapes, relativeFileName, prefix[prefixIndex]);
GLInstanceGraphicsShape* shape = createGraphicsShapeFromWavefrontObj(shapes);
b3AlignedObjectArray<b3Vector3> verts;
for (int i=0;i<shape->m_numvertices;i++)
@ -167,9 +167,9 @@ void ConcaveScene::createConcaveMesh(const ConstructionInfo& ci, const char* fil
shape->m_vertices->at(i).xyzw[2]);
verts.push_back(vtx*scaling);
}
int colIndex = m_data->m_np->registerConcaveMesh(&verts,shape->m_indices,b3MakeVector3(1,1,1));
{
int strideInBytes = 9*sizeof(float);
int numVertices = sizeof(cube_vertices)/strideInBytes;
@ -180,10 +180,10 @@ void ConcaveScene::createConcaveMesh(const ConstructionInfo& ci, const char* fil
int shapeId = ci.m_instancingRenderer->registerShape(&shape->m_vertices->at(0).xyzw[0], shape->m_numvertices, &shape->m_indices->at(0), shape->m_numIndices);
b3Quaternion orn(0,0,0,1);
b3Vector4 color=b3MakeVector4(0.3,0.3,1,1.f);//0.5);//1.f
{
float mass = 0.f;
b3Vector3 position=b3MakeVector3(0,0,0);
@ -200,8 +200,8 @@ void ConcaveScene::createConcaveMesh(const ConstructionInfo& ci, const char* fil
}
}
}
@ -218,11 +218,11 @@ void ConcaveScene::setupScene(const ConstructionInfo& ci)
//char* fileName = "teddy.obj";//"plane.obj";
// char* fileName = "sponza_closed.obj";//"plane.obj";
//char* fileName = "leoTest1.obj";
char* fileName = "samurai_monastry.obj";
const char* fileName = "samurai_monastry.obj";
// char* fileName = "teddy2_VHACD_CHs.obj";
b3Vector3 shift1=b3MakeVector3(0,0,0);//0,230,80);//150,-100,-120);
b3Vector4 scaling=b3MakeVector4(10,10,10,1);
// createConcaveMesh(ci,"plane100.obj",shift1,scaling);
@ -233,8 +233,8 @@ void ConcaveScene::setupScene(const ConstructionInfo& ci)
// b3Vector3 shift3(130,-150,-75);//0,230,80);//150,-100,-120);
// createConcaveMesh(ci,"leoTest1.obj",shift3,scaling);
createConcaveMesh(ci,fileName,shift1,scaling);
createConcaveMesh(ci,fileName,shift1,scaling);
} else
{
@ -250,17 +250,17 @@ void ConcaveScene::setupScene(const ConstructionInfo& ci)
int colIndex = m_data->m_np->registerConvexHullShape(&cube_vertices[0],strideInBytes,numVertices, scaling);
b3Vector3 position=b3MakeVector3(0,-2,0);
b3Quaternion orn(0,0,0,1);
b3Vector4 color=b3MakeVector4(0,0,1,1);
int id = ci.m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
int pid = m_data->m_rigidBodyPipeline->registerPhysicsInstance(0.f,position,orn,colIndex,index,false);
}
}
createDynamicObjects(ci);
m_data->m_rigidBodyPipeline->writeAllInstancesToGpu();
float camPos[4]={0,0,0,0};//65.5,4.5,65.5,0};
@ -285,15 +285,15 @@ void ConcaveScene::createDynamicObjects(const ConstructionInfo& ci)
int shapeId = ci.m_instancingRenderer->registerShape(&cube_vertices[0],numVertices,cube_indices,numIndices);
int group=1;
int mask=1;
int index=0;
if (1)
{
int curColor = 0;
b3Vector4 colors[4] =
b3Vector4 colors[4] =
{
b3MakeVector4(1,1,1,1),
b3MakeVector4(1,1,0.3,1),
@ -345,14 +345,14 @@ void ConcaveScene::createDynamicObjects(const ConstructionInfo& ci)
23+j*CONCAVE_GAPY,
-(ci.arraySizeZ/2)*CONCAVE_GAPZ+k*CONCAVE_GAPZ);
b3Quaternion orn(0,0,0,1);
b3Vector4 color = colors[curColor];
curColor++;
curColor&=3;
int id = ci.m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
int pid = m_data->m_rigidBodyPipeline->registerPhysicsInstance(mass,position,orn,colIndex,index,false);
index++;
}
}
@ -377,10 +377,10 @@ void ConcaveCompoundScene::setupScene(const ConstructionInfo& ci)
void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
{
char* fileName = "teddy2_VHACD_CHs.obj";
const char* fileName = "teddy2_VHACD_CHs.obj";
//char* fileName = "cube_offset.obj";
b3Vector3 shift=b3MakeVector3(0,0,0);//0,230,80);//150,-100,-120);
b3Vector4 scaling=b3MakeVector4(1,1,1,1);
const char* prefix[]={"./data/","../data/","../../data/","../../../data/","../../../../data/"};
@ -388,12 +388,12 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
char relativeFileName[1024];
{
int numPrefixes = sizeof(prefix)/sizeof(char*);
for (int i=0;i<numPrefixes;i++)
{
sprintf(relativeFileName,"%s%s",prefix[i],fileName);
FILE* f = 0;
f = fopen(relativeFileName,"r");
@ -422,7 +422,7 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
b3AlignedObjectArray<GLInstanceVertex> vertexArray;
b3AlignedObjectArray<int> indexArray;
//int shapeId = ci.m_instancingRenderer->registerShape(&cube_vertices[0],numVertices,cube_indices,numIndices);
@ -436,8 +436,8 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
b3Assert(stride2 == strideInBytes);
{
b3AlignedObjectArray<b3GpuChildShape> childShapes;
int numChildShapes = shapes.size();
@ -455,7 +455,7 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
//for now, only support polyhedral child shapes
b3GpuChildShape child;
b3Vector3 pos=b3MakeVector3(0,0,0);
b3Quaternion orn(0,0,0,1);
for (int v=0;v<4;v++)
@ -463,21 +463,21 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
child.m_childPosition[v] = pos[v];
child.m_childOrientation[v] = orn[v];
}
b3Transform tr;
tr.setIdentity();
tr.setOrigin(pos);
tr.setRotation(orn);
int baseIndex = vertexArray.size();
for (int f=0;f<numFaces;f++)
{
for (int i=0;i<3;i++)
{
indexArray.push_back(baseIndex+shape.mesh.indices[f*3+i]);
}
}
b3Vector3 center=b3MakeVector3(0,0,0);
@ -488,8 +488,8 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
for (int v=0;v<numVertices;v++)
{
GLInstanceVertex vert;
vert.uv[0] = 0.5f;
vert.uv[1] = 0.5f;
@ -540,20 +540,20 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
colIndex = childColIndex;
}
colIndex= m_data->m_np->registerCompoundShape(&childShapes);
}
//int shapeId = ci.m_instancingRenderer->registerShape(&cube_vertices[0],numVertices,cube_indices,numIndices);
int shapeId = ci.m_instancingRenderer->registerShape(&vertexArray[0].xyzw[0],vertexArray.size(),&indexArray[0],indexArray.size());
b3Vector4 colors[4] =
b3Vector4 colors[4] =
{
b3MakeVector4(1,0,0,1),
b3MakeVector4(0,1,0,1),
b3MakeVector4(0,0,1,1),
b3MakeVector4(0,1,1,1),
};
int curColor = 0;
for (int i=0;i<1;i++)//ci.arraySizeX;i++)
{
@ -569,14 +569,14 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
// b3Quaternion orn(0,0,0,1);
b3Quaternion orn(b3MakeVector3(0,0,1),1.8);
b3Vector4 color = colors[curColor];
curColor++;
curColor&=3;
b3Vector4 scaling=b3MakeVector4(1,1,1,1);
int id = ci.m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
int pid = m_data->m_rigidBodyPipeline->registerPhysicsInstance(mass,position,orn,colIndex,index,false);
index++;
}
}
@ -588,14 +588,14 @@ void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
void ConcaveCompoundScene::createDynamicObjects(const ConstructionInfo& ci)
{
int strideInBytes = 9*sizeof(float);
int numVertices = sizeof(cube_vertices)/strideInBytes;
int numIndices = sizeof(cube_indices)/sizeof(int);
b3AlignedObjectArray<GLInstanceVertex> vertexArray;
b3AlignedObjectArray<int> indexArray;
//int shapeId = ci.m_instancingRenderer->registerShape(&cube_vertices[0],numVertices,cube_indices,numIndices);
int group=1;
@ -610,14 +610,14 @@ void ConcaveCompoundScene::createDynamicObjects(const ConstructionInfo& ci)
{
int childColIndex = m_data->m_np->registerConvexHullShape(&cube_vertices[0],strideInBytes,numVertices, scaling);
b3Vector3 childPositions[3] = {
b3MakeVector3(0,-2,0),
b3MakeVector3(0,0,0),
b3MakeVector3(0,0,2)
};
b3AlignedObjectArray<b3GpuChildShape> childShapes;
int numChildShapes = 3;
for (int i=0;i<numChildShapes;i++)
@ -657,20 +657,20 @@ b3Vector3 childPositions[3] = {
}
colIndex= m_data->m_np->registerCompoundShape(&childShapes);
}
//int shapeId = ci.m_instancingRenderer->registerShape(&cube_vertices[0],numVertices,cube_indices,numIndices);
int shapeId = ci.m_instancingRenderer->registerShape(&vertexArray[0].xyzw[0],vertexArray.size(),&indexArray[0],indexArray.size());
b3Vector4 colors[4] =
b3Vector4 colors[4] =
{
b3MakeVector4(1,0,0,1),
b3MakeVector4(0,1,0,1),
b3MakeVector4(0,0,1,1),
b3MakeVector4(0,1,1,1),
};
int curColor = 0;
for (int i=0;i<ci.arraySizeX;i++)
{
@ -684,14 +684,14 @@ b3Vector3 childPositions[3] = {
b3Vector3 position=b3MakeVector3((-ci.arraySizeX/2+i)*ci.gapX,50+j*ci.gapY,(-ci.arraySizeZ/2+k)*ci.gapZ);
//b3Quaternion orn(0,0,0,1);
b3Quaternion orn(b3MakeVector3(1,0,0),0.7);
b3Vector4 color = colors[curColor];
curColor++;
curColor&=3;
b3Vector4 scaling=b3MakeVector4(1,1,1,1);
int id = ci.m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
int pid = m_data->m_rigidBodyPipeline->registerPhysicsInstance(mass,position,orn,colIndex,index,false);
index++;
}
}
@ -714,7 +714,7 @@ void ConcaveSphereScene::setupScene(const ConstructionInfo& ci)
void ConcaveSphereScene::createDynamicObjects(const ConstructionInfo& ci)
{
b3Vector4 colors[4] =
b3Vector4 colors[4] =
{
b3MakeVector4(1,0,0,1),
b3MakeVector4(0,1,0,1),
@ -737,20 +737,20 @@ void ConcaveSphereScene::createDynamicObjects(const ConstructionInfo& ci)
{
float mass = 1.f;
b3Vector3 position=b3MakeVector3(-(ci.arraySizeX/2)*8+i*8,50+j*8,-(ci.arraySizeZ/2)*8+k*8);
//b3Vector3 position(0,-41,0);//0,0,0);//i*radius*3,-41+j*radius*3,k*radius*3);
b3Quaternion orn(0,0,0,1);
b3Vector4 color = colors[curColor];
curColor++;
curColor&=3;
b3Vector4 scaling=b3MakeVector4(radius,radius,radius,1);
int id = ci.m_instancingRenderer->registerGraphicsInstance(prevGraphicsShapeIndex,position,orn,color,scaling);
int pid = m_data->m_rigidBodyPipeline->registerPhysicsInstance(mass,position,orn,colIndex,index,false);
index++;
}
}

View File

@ -28,7 +28,7 @@ static GLInstanceGraphicsShape* gCreateGraphicsShapeFromWavefrontObj(std::vector
// int numIndices = 0;
b3AlignedObjectArray<int>* indicesPtr = new b3AlignedObjectArray<int>;
for (int s=0;s<shapes.size();s++)
for (int s=0;s<(int)shapes.size();s++)
{
tinyobj::shape_t& shape = shapes[s];
int faceCount = shape.mesh.indices.size();
@ -151,7 +151,7 @@ void ImportObjDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
btVector3 shift(0,0,0);
btVector3 scaling(1,1,1);
int index=10;
// int index=10;
{
@ -172,7 +172,8 @@ void ImportObjDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
int shapeId = m_app->m_instancingRenderer->registerShape(&gfxShape->m_vertices->at(0).xyzw[0], gfxShape->m_numvertices, &gfxShape->m_indices->at(0), gfxShape->m_numIndices);
int id = m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
//int id =
m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
/*

View File

@ -4,6 +4,7 @@
#include "OpenGLWindow/GLInstanceGraphicsShape.h"
#include "btBulletDynamicsCommon.h"
#include "OpenGLWindow/SimpleOpenGL3App.h"
#include "LoadMeshFromSTL.h"
ImportSTLDemo::ImportSTLDemo(SimpleOpenGL3App* app)
:m_app(app)
@ -16,97 +17,6 @@ ImportSTLDemo::~ImportSTLDemo()
}
struct MySTLTriangle
{
float normal[3];
float vertex0[3];
float vertex1[3];
float vertex2[3];
};
GLInstanceGraphicsShape* LoadMeshFromSTL(const char* relativeFileName)
{
GLInstanceGraphicsShape* shape = 0;
FILE* file = fopen(relativeFileName,"rb");
if (file)
{
int size=0;
if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET))
{
printf("Error: Cannot access file to determine size of %s\n", relativeFileName);
} else
{
if (size)
{
printf("Open STL file of %d bytes\n",size);
char* memoryBuffer = new char[size+1];
int actualBytesRead = fread(memoryBuffer,1,size,file);
if (actualBytesRead!=size)
{
printf("Error reading from file %s",relativeFileName);
} else
{
int numTriangles = *(int*)&memoryBuffer[80];
if (numTriangles)
{
shape = new GLInstanceGraphicsShape;
// b3AlignedObjectArray<GLInstanceVertex>* m_vertices;
// int m_numvertices;
// b3AlignedObjectArray<int>* m_indices;
// int m_numIndices;
// float m_scaling[4];
shape->m_scaling[0] = 1;
shape->m_scaling[1] = 1;
shape->m_scaling[2] = 1;
shape->m_scaling[3] = 1;
int index = 0;
shape->m_indices = new b3AlignedObjectArray<int>();
shape->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
for (int i=0;i<numTriangles;i++)
{
char* curPtr = &memoryBuffer[84+i*50];
MySTLTriangle* tri = (MySTLTriangle*) curPtr;
GLInstanceVertex v0,v1,v2;
if (i==numTriangles-2)
{
printf("!\n");
}
v0.uv[0] = v1.uv[0] = v2.uv[0] = 0.5;
v0.uv[1] = v1.uv[1] = v2.uv[1] = 0.5;
for (int v=0;v<3;v++)
{
v0.xyzw[v] = tri->vertex0[v];
v1.xyzw[v] = tri->vertex1[v];
v2.xyzw[v] = tri->vertex2[v];
v0.normal[v] = v1.normal[v] = v2.normal[v] = tri->normal[v];
}
v0.xyzw[3] = v1.xyzw[3] = v2.xyzw[3] = 0.f;
shape->m_vertices->push_back(v0);
shape->m_vertices->push_back(v1);
shape->m_vertices->push_back(v2);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
}
}
}
delete[] memoryBuffer;
}
}
fclose(file);
}
shape->m_numIndices = shape->m_indices->size();
shape->m_numvertices = shape->m_vertices->size();
return shape;
}
void ImportSTLDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
@ -143,7 +53,7 @@ void ImportSTLDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
btVector3 shift(0,0,0);
btVector3 scaling(10,10,10);
int index=10;
// int index=10;
{
@ -161,7 +71,8 @@ void ImportSTLDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
int shapeId = m_app->m_instancingRenderer->registerShape(&gfxShape->m_vertices->at(0).xyzw[0], gfxShape->m_numvertices, &gfxShape->m_indices->at(0), gfxShape->m_numIndices);
int id = m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
// int id =
m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
/*

View File

@ -0,0 +1,101 @@
#ifndef LOAD_MESH_FROM_STL_H
#define LOAD_MESH_FROM_STL_H
#include "OpenGLWindow/GLInstanceGraphicsShape.h"
#include <stdio.h> //fopen
#include "Bullet3Common/b3AlignedObjectArray.h"
struct MySTLTriangle
{
float normal[3];
float vertex0[3];
float vertex1[3];
float vertex2[3];
};
static GLInstanceGraphicsShape* LoadMeshFromSTL(const char* relativeFileName)
{
GLInstanceGraphicsShape* shape = 0;
FILE* file = fopen(relativeFileName,"rb");
if (file)
{
int size=0;
if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET))
{
printf("Error: Cannot access file to determine size of %s\n", relativeFileName);
} else
{
if (size)
{
printf("Open STL file of %d bytes\n",size);
char* memoryBuffer = new char[size+1];
int actualBytesRead = fread(memoryBuffer,1,size,file);
if (actualBytesRead!=size)
{
printf("Error reading from file %s",relativeFileName);
} else
{
int numTriangles = *(int*)&memoryBuffer[80];
if (numTriangles)
{
shape = new GLInstanceGraphicsShape;
// b3AlignedObjectArray<GLInstanceVertex>* m_vertices;
// int m_numvertices;
// b3AlignedObjectArray<int>* m_indices;
// int m_numIndices;
// float m_scaling[4];
shape->m_scaling[0] = 1;
shape->m_scaling[1] = 1;
shape->m_scaling[2] = 1;
shape->m_scaling[3] = 1;
int index = 0;
shape->m_indices = new b3AlignedObjectArray<int>();
shape->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
for (int i=0;i<numTriangles;i++)
{
char* curPtr = &memoryBuffer[84+i*50];
MySTLTriangle* tri = (MySTLTriangle*) curPtr;
GLInstanceVertex v0,v1,v2;
if (i==numTriangles-2)
{
printf("!\n");
}
v0.uv[0] = v1.uv[0] = v2.uv[0] = 0.5;
v0.uv[1] = v1.uv[1] = v2.uv[1] = 0.5;
for (int v=0;v<3;v++)
{
v0.xyzw[v] = tri->vertex0[v];
v1.xyzw[v] = tri->vertex1[v];
v2.xyzw[v] = tri->vertex2[v];
v0.normal[v] = v1.normal[v] = v2.normal[v] = tri->normal[v];
}
v0.xyzw[3] = v1.xyzw[3] = v2.xyzw[3] = 0.f;
shape->m_vertices->push_back(v0);
shape->m_vertices->push_back(v1);
shape->m_vertices->push_back(v2);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
}
}
}
delete[] memoryBuffer;
}
}
fclose(file);
}
shape->m_numIndices = shape->m_indices->size();
shape->m_numvertices = shape->m_vertices->size();
return shape;
}
#endif //LOAD_MESH_FROM_STL_H

View File

@ -1,6 +1,9 @@
#include "ImportURDFSetup.h"
#include "BulletDynamics/ConstraintSolver/btGeneric6DofSpring2Constraint.h"
#include "Bullet3Common/b3FileUtils.h"
#include "../ImportSTLDemo/LoadMeshFromSTL.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
static int bodyCollisionFilterGroup=btBroadphaseProxy::CharacterFilter;
static int bodyCollisionFilterMask=btBroadphaseProxy::AllFilter&(~btBroadphaseProxy::CharacterFilter);
@ -9,7 +12,7 @@ static bool enableConstraints = true;//false;
ImportUrdfDemo::ImportUrdfDemo()
{
sprintf(m_fileName,"r2d2.urdf");
}
ImportUrdfDemo::~ImportUrdfDemo()
@ -18,7 +21,10 @@ ImportUrdfDemo::~ImportUrdfDemo()
}
void ImportUrdfDemo::setFileName(const char* urdfFileName)
{
memcpy(m_fileName,urdfFileName,strlen(urdfFileName)+1);
}
#include "urdf/urdfdom/urdf_parser/include/urdf_parser/urdf_parser.h"
@ -59,6 +65,8 @@ void printTree(my_shared_ptr<const Link> link,int level = 0)
struct URDF_LinkInformation
{
const Link* m_thisLink;
int m_linkIndex;
int m_parentIndex;
btTransform m_localInertialFrame;
btTransform m_localVisualFrame;
@ -66,7 +74,7 @@ struct URDF_LinkInformation
btRigidBody* m_bulletRigidBody;
virtual ~URDF_LinkInformation()
{
printf("~\n");
printf("~\n");
}
};
@ -80,9 +88,385 @@ struct URDF2BulletMappings
{
btHashMap<btHashPtr /*to Link*/, URDF_LinkInformation*> m_link2rigidbody;
btHashMap<btHashPtr /*to Joint*/, btTypedConstraint*> m_joint2Constraint;
btAlignedObjectArray<btTransform> m_linkLocalInertiaTransforms;//Body transform is in center of mass, aligned with Principal Moment Of Inertia;
btAlignedObjectArray<btScalar> m_linkMasses;
btAlignedObjectArray<btVector3> m_linkLocalDiagonalInertiaTensors;
btAlignedObjectArray<btTransform> m_jointTransforms;//for root, it is identity
btAlignedObjectArray<int> m_parentIndices;//for root, it is identity
btAlignedObjectArray<btVector3> m_jointAxisArray;
btAlignedObjectArray<btTransform> m_jointOffsetInParent;
btAlignedObjectArray<btTransform> m_jointOffsetInChild;
btAlignedObjectArray<int> m_jointTypeArray;
};
void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhysicsBridge& gfxBridge, const btTransform& parentTransformInWorldSpace, btDiscreteDynamicsWorld* world, URDF2BulletMappings& mappings)
btCollisionShape* convertVisualToCollisionShape(const Visual* visual, const char* pathPrefix)
{
btCollisionShape* shape = 0;
switch (visual->geometry->type)
{
case Geometry::CYLINDER:
{
printf("processing a cylinder\n");
urdf::Cylinder* cyl = (urdf::Cylinder*)visual->geometry.get();
btAlignedObjectArray<btVector3> vertices;
//int numVerts = sizeof(barrel_vertices)/(9*sizeof(float));
int numSteps = 32;
for (int i=0;i<numSteps;i++)
{
btVector3 vert(cyl->radius*btSin(SIMD_2_PI*(float(i)/numSteps)),cyl->radius*btCos(SIMD_2_PI*(float(i)/numSteps)),cyl->length/2.);
vertices.push_back(vert);
vert[2] = -cyl->length/2.;
vertices.push_back(vert);
}
btConvexHullShape* cylZShape = new btConvexHullShape(&vertices[0].x(), vertices.size(), sizeof(btVector3));
cylZShape->initializePolyhedralFeatures();
//btVector3 halfExtents(cyl->radius,cyl->radius,cyl->length/2.);
//btCylinderShapeZ* cylZShape = new btCylinderShapeZ(halfExtents);
cylZShape->setMargin(0.001);
shape = cylZShape;
break;
}
case Geometry::BOX:
{
printf("processing a box\n");
urdf::Box* box = (urdf::Box*)visual->geometry.get();
btVector3 extents(box->dim.x,box->dim.y,box->dim.z);
btBoxShape* boxShape = new btBoxShape(extents*0.5f);
shape = boxShape;
shape ->setMargin(0.001);
break;
}
case Geometry::SPHERE:
{
printf("processing a sphere\n");
urdf::Sphere* sphere = (urdf::Sphere*)visual->geometry.get();
btScalar radius = sphere->radius;
btSphereShape* sphereShape = new btSphereShape(radius);
shape = sphereShape;
shape ->setMargin(0.001);
break;
break;
}
case Geometry::MESH:
{
if (visual->name.length())
{
printf("visual->name=%s\n",visual->name.c_str());
}
if (visual->geometry)
{
const urdf::Mesh* mesh = (const urdf::Mesh*) visual->geometry.get();
if (mesh->filename.length())
{
const char* filename = mesh->filename.c_str();
printf("mesh->filename=%s\n",filename);
char fullPath[1024];
sprintf(fullPath,"%s%s",pathPrefix,filename);
FILE* f = fopen(fullPath,"rb");
if (f)
{
fclose(f);
GLInstanceGraphicsShape* glmesh = LoadMeshFromSTL(fullPath);
if (glmesh && (glmesh->m_numvertices>0))
{
printf("extracted %d verticed from STL file %s\n", glmesh->m_numvertices,fullPath);
//int shapeId = m_glApp->m_instancingRenderer->registerShape(&gvertices[0].pos[0],gvertices.size(),&indices[0],indices.size());
//convex->setUserIndex(shapeId);
btAlignedObjectArray<btVector3> convertedVerts;
convertedVerts.reserve(glmesh->m_numvertices);
for (int i=0;i<glmesh->m_numvertices;i++)
{
convertedVerts.push_back(btVector3(glmesh->m_vertices->at(i).xyzw[0],glmesh->m_vertices->at(i).xyzw[1],glmesh->m_vertices->at(i).xyzw[2]));
}
//btConvexHullShape* cylZShape = new btConvexHullShape(&glmesh->m_vertices->at(0).xyzw[0], glmesh->m_numvertices, sizeof(GLInstanceVertex));
btConvexHullShape* cylZShape = new btConvexHullShape(&convertedVerts[0].getX(), convertedVerts.size(), sizeof(btVector3));
//cylZShape->initializePolyhedralFeatures();
//btVector3 halfExtents(cyl->radius,cyl->radius,cyl->length/2.);
//btCylinderShapeZ* cylZShape = new btCylinderShapeZ(halfExtents);
cylZShape->setMargin(0.001);
shape = cylZShape;
} else
{
printf("issue extracting mesh from STL file %s\n", fullPath);
}
} else
{
printf("mesh geometry not found %s\n",fullPath);
}
}
}
break;
}
default:
{
printf("Error: unknown visual geometry type\n");
}
}
return shape;
}
btMultiBody* URDF2BulletMultiBody(my_shared_ptr<const Link> link, GraphicsPhysicsBridge& gfxBridge, const btTransform& parentTransformInWorldSpace, btMultiBodyDynamicsWorld* world, URDF2BulletMappings& mappings, const char* pathPrefix, btMultiBody* mb, int totalNumJoints)
{
btScalar mass = 0.f;
btTransform localInertialTransform; localInertialTransform.setIdentity();
btVector3 localInertiaDiagonal(0,0,0);
{
if ((*link).inertial)
{
mass = (*link).inertial->mass;
btMatrix3x3 inertiaMat;
inertiaMat.setIdentity();
inertiaMat.setValue(
(*link).inertial->ixx,(*link).inertial->ixy,(*link).inertial->ixz,
(*link).inertial->ixy,(*link).inertial->iyy,(*link).inertial->iyz,
(*link).inertial->ixz,(*link).inertial->iyz,(*link).inertial->izz);
btScalar threshold = 0.00001f;
int maxSteps=20;
btMatrix3x3 inertia2PrincipalAxis;
inertiaMat.diagonalize(inertia2PrincipalAxis,threshold,maxSteps);
localInertiaDiagonal.setValue(inertiaMat[0][0],inertiaMat[1][1],inertiaMat[2][2]);
btVector3 inertiaLocalCOM((*link).inertial->origin.position.x,(*link).inertial->origin.position.y,(*link).inertial->origin.position.z);
localInertialTransform.setOrigin(inertiaLocalCOM);
btQuaternion inertiaOrn((*link).inertial->origin.rotation.x,(*link).inertial->origin.rotation.y,(*link).inertial->origin.rotation.z,(*link).inertial->origin.rotation.w);
btMatrix3x3 inertiaOrnMat(inertiaOrn);
if (mass > 0 && (localInertiaDiagonal[0]==0.f || localInertiaDiagonal[1] == 0.f
|| localInertiaDiagonal[2] == 0.f))
{
b3Warning("Error: inertia should not be zero if mass is positive\n");
localInertiaDiagonal.setMax(btVector3(0.1,0.1,0.1));
localInertialTransform.setIdentity();//.setBasis(inertiaOrnMat);
}
else
{
localInertialTransform.setBasis(inertiaOrnMat*inertia2PrincipalAxis);
}
}
}
btTransform linkTransformInWorldSpace;
int parentIndex = -1;
const Link* parentLink = (*link).getParent();
if (parentLink)
{
parentIndex = parentLink->m_link_index;
btAssert(parentIndex>=0);
}
int linkIndex = mappings.m_linkMasses.size();
btTransform parent2joint;
if ((*link).parent_joint)
{
const urdf::Vector3 pos = (*link).parent_joint->parent_to_joint_origin_transform.position;
const urdf::Rotation orn = (*link).parent_joint->parent_to_joint_origin_transform.rotation;
parent2joint.setOrigin(btVector3(pos.x,pos.y,pos.z));
parent2joint.setRotation(btQuaternion(orn.x,orn.y,orn.z,orn.w));
linkTransformInWorldSpace =parentTransformInWorldSpace*parent2joint;
} else
{
linkTransformInWorldSpace = parentTransformInWorldSpace;
btAssert(mb==0);
bool multiDof = true;
bool canSleep = false;
bool isFixedBase = (mass==0);//todo: figure out when base is fixed
mb = new btMultiBody(totalNumJoints,mass, localInertiaDiagonal, isFixedBase, canSleep, multiDof);
}
btAssert(mb);
(*link).m_link_index = linkIndex;
//compute this links center of mass transform, aligned with the principal axis of inertia
{
//btTransform rigidBodyFrameInWorldSpace =linkTransformInWorldSpace*inertialFrame;
mappings.m_linkMasses.push_back(mass);
mappings.m_linkLocalDiagonalInertiaTensors.push_back(localInertiaDiagonal);
mappings.m_linkLocalInertiaTransforms.push_back(localInertialTransform);
if ((*link).parent_joint)
{
btTransform offsetInA,offsetInB;
offsetInA.setIdentity();
//offsetInA = mappings.m_linkLocalInertiaTransforms[parentIndex].inverse()*parent2joint;
offsetInA = parent2joint;
offsetInB.setIdentity();
//offsetInB = localInertialTransform.inverse();
const Joint* pj = (*link).parent_joint.get();
//btVector3 jointAxis(0,0,1);//pj->axis.x,pj->axis.y,pj->axis.z);
btVector3 jointAxis(pj->axis.x,pj->axis.y,pj->axis.z);
mappings.m_jointAxisArray.push_back(jointAxis);
mappings.m_jointOffsetInParent.push_back(offsetInA);
mappings.m_jointOffsetInChild.push_back(offsetInB);
mappings.m_jointTypeArray.push_back(pj->type);
switch (pj->type)
{
case Joint::FIXED:
{
printf("Fixed joint\n");
mb->setupFixed(linkIndex-1,mass,localInertiaDiagonal,parentIndex-1,offsetInA.getRotation(),offsetInA.getOrigin(),offsetInB.getOrigin());
break;
}
case Joint::CONTINUOUS:
case Joint::REVOLUTE:
{
printf("Revolute joint\n");
mb->setupRevolute(linkIndex-1,mass,localInertiaDiagonal,parentIndex-1,offsetInA.getRotation(),jointAxis,offsetInA.getOrigin(),offsetInB.getOrigin(),true);
mb->finalizeMultiDof();
//mb->setJointVel(linkIndex-1,1);
break;
}
case Joint::PRISMATIC:
{
mb->setupPrismatic(linkIndex-1,mass,localInertiaDiagonal,parentIndex-1,offsetInA.getRotation(),jointAxis,offsetInB.getOrigin(),true);
printf("Prismatic joint\n");
break;
}
default:
{
printf("Unknown joint\n");
btAssert(0);
}
};
} else
{
mappings.m_jointAxisArray.push_back(btVector3(0,0,0));
btTransform ident;
ident.setIdentity();
mappings.m_jointOffsetInParent.push_back(ident);
mappings.m_jointOffsetInChild.push_back(ident);
mappings.m_jointTypeArray.push_back(-1);
}
}
//btCompoundShape* compoundShape = new btCompoundShape();
btCollisionShape* shape = 0;
for (int v=0;v<(int)link->visual_array.size();v++)
{
const Visual* visual = link->visual_array[v].get();
shape = convertVisualToCollisionShape(visual,pathPrefix);
if (shape)//childShape)
{
gfxBridge.createCollisionShapeGraphicsObject(shape);//childShape);
btVector3 color(0,0,1);
if (visual->material.get())
{
color.setValue(visual->material->color.r,visual->material->color.g,visual->material->color.b);//,visual->material->color.a);
}
btVector3 localInertia(0,0,0);
if (mass)
{
shape->calculateLocalInertia(mass,localInertia);
}
//btRigidBody::btRigidBodyConstructionInfo rbci(mass,0,shape,localInertia);
btVector3 visual_pos(visual->origin.position.x,visual->origin.position.y,visual->origin.position.z);
btQuaternion visual_orn(visual->origin.rotation.x,visual->origin.rotation.y,visual->origin.rotation.z,visual->origin.rotation.w);
btTransform visual_frame;
visual_frame.setOrigin(visual_pos);
visual_frame.setRotation(visual_orn);
btTransform childTransform;
childTransform.setIdentity();//TODO(erwincoumans): compute relative visual/inertial transform
// compoundShape->addChildShape(childTransform,childShape);
}
}
if (shape)//compoundShape->getNumChildShapes()>0)
{
btMultiBodyLinkCollider* col= new btMultiBodyLinkCollider(mb, linkIndex-1);
col->setCollisionShape(shape);
btTransform tr;
tr.setIdentity();
tr = linkTransformInWorldSpace;
//if we don't set the initial pose of the btCollisionObject, the simulator will do this
//when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
//tr.setOrigin(local_origin[0]);
//tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
bool isDynamic = true;
short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
world->addCollisionObject(col,collisionFilterGroup,collisionFilterMask);
btVector3 color(0.0,0.0,0.5);
gfxBridge.createCollisionObjectGraphicsObject(col,color);
btScalar friction = 0.5f;
col->setFriction(friction);
if (parentIndex>=0)
{
mb->getLink(linkIndex-1).m_collider=col;
} else
{
mb->setBaseCollider(col);
}
}
for (std::vector<my_shared_ptr<Link> >::const_iterator child = link->child_links.begin(); child != link->child_links.end(); child++)
{
if (*child)
{
URDF2BulletMultiBody(*child,gfxBridge, linkTransformInWorldSpace, world,mappings,pathPrefix,mb,totalNumJoints);
}
else
{
std::cout << "root link: " << link->name << " has a null child!" << *child << std::endl;
}
}
return mb;
}
void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhysicsBridge& gfxBridge, const btTransform& parentTransformInWorldSpace, btDiscreteDynamicsWorld* world, URDF2BulletMappings& mappings, const char* pathPrefix)
{
btCollisionShape* shape = 0;
@ -112,11 +496,13 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
inertialFrame.setRotation(btQuaternion((*link).inertial->origin.rotation.x,(*link).inertial->origin.rotation.y,(*link).inertial->origin.rotation.z,(*link).inertial->origin.rotation.w));
}
btTransform parent2joint;
btTransform parent2joint;
parent2joint.setIdentity();
if ((*link).parent_joint)
{
btTransform p2j;
const urdf::Vector3 pos = (*link).parent_joint->parent_to_joint_origin_transform.position;
const urdf::Rotation orn = (*link).parent_joint->parent_to_joint_origin_transform.rotation;
@ -130,72 +516,13 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
{
printf("converting link %s",link->name.c_str());
for (int v=0;v<link->visual_array.size();v++)
printf("converting visuals of link %s",link->name.c_str());
for (int v=0;v<(int)link->visual_array.size();v++)
{
const Visual* visual = link->visual_array[v].get();
switch (visual->geometry->type)
{
case Geometry::CYLINDER:
{
printf("processing a cylinder\n");
urdf::Cylinder* cyl = (urdf::Cylinder*)visual->geometry.get();
btAlignedObjectArray<btVector3> vertices;
//int numVerts = sizeof(barrel_vertices)/(9*sizeof(float));
int numSteps = 32;
for (int i=0;i<numSteps;i++)
{
btVector3 vert(cyl->radius*btSin(SIMD_2_PI*(float(i)/numSteps)),cyl->radius*btCos(SIMD_2_PI*(float(i)/numSteps)),cyl->length/2.);
vertices.push_back(vert);
vert[2] = -cyl->length/2.;
vertices.push_back(vert);
}
btConvexHullShape* cylZShape = new btConvexHullShape(&vertices[0].x(), vertices.size(), sizeof(btVector3));
cylZShape->initializePolyhedralFeatures();
//btVector3 halfExtents(cyl->radius,cyl->radius,cyl->length/2.);
//btCylinderShapeZ* cylZShape = new btCylinderShapeZ(halfExtents);
cylZShape->setMargin(0.001);
shape = cylZShape;
break;
}
case Geometry::BOX:
{
printf("processing a box\n");
urdf::Box* box = (urdf::Box*)visual->geometry.get();
btVector3 extents(box->dim.x,box->dim.y,box->dim.z);
btBoxShape* boxShape = new btBoxShape(extents*0.5f);
shape = boxShape;
break;
}
case Geometry::SPHERE:
{
printf("processing a sphere\n");
urdf::Sphere* sphere = (urdf::Sphere*)visual->geometry.get();
btScalar radius = sphere->radius*0.8;
btSphereShape* sphereShape = new btSphereShape(radius);
shape = sphereShape;
break;
break;
}
case Geometry::MESH:
{
break;
}
default:
{
printf("Error: unknown visual geometry type\n");
}
}
shape = convertVisualToCollisionShape(visual,pathPrefix);
if (shape)
{
gfxBridge.createCollisionShapeGraphicsObject(shape);
@ -225,7 +552,7 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
btRigidBody* body = new btRigidBody(rbci);
world->addRigidBody(body,bodyCollisionFilterGroup,bodyCollisionFilterMask);
// body->setFriction(0);
@ -241,25 +568,16 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
//create a joint if necessary
if ((*link).parent_joint)
{
btAssert(pp);
btRigidBody* parentBody =pp->m_bulletRigidBody;
const Joint* pj = (*link).parent_joint.get();
btTransform offsetInA,offsetInB;
btTransform p2j; p2j.setIdentity();
btVector3 p2jPos; p2jPos.setValue(pj->parent_to_joint_origin_transform.position.x,
pj->parent_to_joint_origin_transform.position.y,
pj->parent_to_joint_origin_transform.position.z);
btQuaternion p2jOrn;p2jOrn.setValue(pj->parent_to_joint_origin_transform.rotation.x,
pj->parent_to_joint_origin_transform.rotation.y,
pj->parent_to_joint_origin_transform.rotation.z,
pj->parent_to_joint_origin_transform.rotation.w);
p2j.setOrigin(p2jPos);
p2j.setRotation(p2jOrn);
offsetInA.setIdentity();
offsetInA = pp->m_localVisualFrame.inverse()*p2j;
offsetInA = pp->m_localVisualFrame.inverse()*parent2joint;
offsetInB.setIdentity();
offsetInB = visual_frame.inverse();
@ -331,7 +649,7 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
{
if (*child)
{
URDFvisual2BulletCollisionShape(*child,gfxBridge, linkTransformInWorldSpace, world,mappings);
URDFvisual2BulletCollisionShape(*child,gfxBridge, linkTransformInWorldSpace, world,mappings,pathPrefix);
}
else
@ -353,32 +671,42 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
this->createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(
//btIDebugDraw::DBG_DrawConstraints
btIDebugDraw::DBG_DrawConstraints
+btIDebugDraw::DBG_DrawContactPoints
//+btIDebugDraw::DBG_DrawAabb
+btIDebugDraw::DBG_DrawAabb
);//+btIDebugDraw::DBG_DrawConstraintLimits);
btVector3 gravity(0,0,0);
gravity[upAxis]=-9.8;
m_dynamicsWorld->setGravity(gravity);
int argc=0;
char* filename="somefile.urdf";
//int argc=0;
char relativeFileName[1024];
b3FileUtils fu;
printf("m_fileName=%s\n", m_fileName);
bool fileFound = fu.findFile(m_fileName, relativeFileName, 1024);
std::string xml_string;
if (argc < 2){
std::cerr << "No URDF file name provided, using a dummy test URDF" << std::endl;
std::string xml_string;
char pathPrefix[1024];
pathPrefix[0] = 0;
if (!fileFound){
std::cerr << "URDF file not found, using a dummy test URDF" << std::endl;
xml_string = std::string(urdf_char);
} else
{
int maxPathLen = 1024;
fu.extractPath(relativeFileName,pathPrefix,maxPathLen);
std::fstream xml_file(filename, std::fstream::in);
std::fstream xml_file(relativeFileName, std::fstream::in);
while ( xml_file.good() )
{
std::string line;
@ -407,10 +735,46 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
printTree(root_link);
btTransform worldTrans;
worldTrans.setIdentity();
int numJoints = (*robot).m_numJoints;
if (1)
{
URDF2BulletMappings mappings;
URDFvisual2BulletCollisionShape(root_link, gfxBridge, worldTrans,m_dynamicsWorld,mappings);
URDFvisual2BulletCollisionShape(root_link, gfxBridge, worldTrans,m_dynamicsWorld,mappings,pathPrefix);
}
//the btMultiBody support is work-in-progress :-)
if (0)
{
URDF2BulletMappings mappings;
btMultiBody* mb = URDF2BulletMultiBody(root_link, gfxBridge, worldTrans,m_dynamicsWorld,mappings,pathPrefix, 0,numJoints);
mb->setHasSelfCollision(false);
mb->finalizeMultiDof();
m_dynamicsWorld->addMultiBody(mb);
//m_dynamicsWorld->integrateTransforms(0.f);
}
printf("numJoints/DOFS = %d\n", numJoints);
if (0)
{
btVector3 halfExtents(1,1,1);
btBoxShape* box = new btBoxShape(halfExtents);
box->initializePolyhedralFeatures();
gfxBridge.createCollisionShapeGraphicsObject(box);
btTransform start; start.setIdentity();
btVector3 origin(0,0,0);
origin[upAxis]=5;
start.setOrigin(origin);
btRigidBody* body = createRigidBody(1,start,box);
btVector3 color(0.5,0.5,0.5);
gfxBridge.createRigidBodyGraphicsObject(body,color);
}
{
@ -418,16 +782,27 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
groundHalfExtents[upAxis]=1.f;
btBoxShape* box = new btBoxShape(groundHalfExtents);
box->initializePolyhedralFeatures();
gfxBridge.createCollisionShapeGraphicsObject(box);
btTransform start; start.setIdentity();
btVector3 groundOrigin(0,0,0);
groundOrigin[upAxis]=-1.5;
groundOrigin[upAxis]=-2.5;
start.setOrigin(groundOrigin);
btRigidBody* body = createRigidBody(0,start,box);
//m_dynamicsWorld->removeRigidBody(body);
// m_dynamicsWorld->addRigidBody(body,2,1);
btVector3 color(0.5,0.5,0.5);
gfxBridge.createRigidBodyGraphicsObject(body,color);
}
}
void ImportUrdfDemo::stepSimulation(float deltaTime)
{
if (m_dynamicsWorld)
{
//the maximal coordinates/iterative MLCP solver requires a smallish timestep to converge
m_dynamicsWorld->stepSimulation(deltaTime,10,1./240.);
}
}

View File

@ -2,15 +2,20 @@
#define IMPORT_URDF_SETUP_H
#include "../../Demos/CommonRigidBodySetup.h"
#include "../../Demos/CommonMultiBodySetup.h"
class ImportUrdfDemo : public CommonRigidBodySetup
class ImportUrdfDemo : public CommonMultiBodySetup
{
char m_fileName[1024];
public:
ImportUrdfDemo();
virtual ~ImportUrdfDemo();
virtual void initPhysics(GraphicsPhysicsBridge& gfxBridge);
virtual void stepSimulation(float deltaTime);
void setFileName(const char* urdfFileName);
};
#endif //IMPORT_URDF_SETUP_H

View File

@ -27,7 +27,15 @@ ELSE(WIN32)
MESSAGE(${COCOA})
link_libraries(${COCOA})
ELSE(APPLE)
LINK_LIBRARIES( GLEW X11 pthread dl Xext)
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( X11 pthread dl Xext)
ENDIF(APPLE)
ENDIF(WIN32)

View File

@ -11,15 +11,13 @@ int main(int argc, char* argv[])
{
b3CommandLineArgs myArgs(argc,argv);
float dt = 1./120.f;
SimpleOpenGL3App* app = new SimpleOpenGL3App("SimpleOpenGL3App",1024,768);
app->m_instancingRenderer->setCameraDistance(13);
app->m_instancingRenderer->setCameraPitch(0);
app->m_instancingRenderer->setCameraTargetPosition(b3MakeVector3(0,0,0));
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
myArgs.GetCmdLineArgument("mp4_file",gVideoFileName);
if (gVideoFileName)
@ -40,8 +38,7 @@ int main(int argc, char* argv[])
app->dumpNextFrameToPng(fileName);
}
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
app->m_instancingRenderer->init();
app->m_instancingRenderer->updateCamera();

View File

@ -21,6 +21,10 @@ struct MyGraphicsPhysicsBridge : public GraphicsPhysicsBridge
{
}
virtual void createRigidBodyGraphicsObject(btRigidBody* body, const btVector3& color)
{
createCollisionObjectGraphicsObject(body,color);
}
virtual void createCollisionObjectGraphicsObject(btCollisionObject* body, const btVector3& color)
{
btCollisionShape* shape = body->getCollisionShape();
btTransform startTransform = body->getWorldTransform();
@ -32,6 +36,10 @@ struct MyGraphicsPhysicsBridge : public GraphicsPhysicsBridge
}
virtual void createCollisionShapeGraphicsObject(btCollisionShape* collisionShape)
{
//already has a graphics object?
if (collisionShape->getUserIndex()>=0)
return;
//todo: support all collision shape types
switch (collisionShape->getShapeType())
{
@ -45,7 +53,7 @@ struct MyGraphicsPhysicsBridge : public GraphicsPhysicsBridge
}
case TRIANGLE_MESH_SHAPE_PROXYTYPE:
{
break;
}
default:
@ -149,7 +157,7 @@ struct MyGraphicsPhysicsBridge : public GraphicsPhysicsBridge
{
return m_glApp->m_parameterInterface;
}
virtual void setUpAxis(int axis)
{
m_glApp->setUpAxis(axis);
@ -233,7 +241,7 @@ btVector3 Bullet2RigidBodyDemo::getRayTo(int x,int y)
btVector3 rightOffset;
btVector3 cameraUp=btVector3(0,0,0);
cameraUp[m_glApp->getUpAxis()]=1;
btVector3 vertical = cameraUp;
btVector3 hor;
@ -291,7 +299,7 @@ bool Bullet2RigidBodyDemo::mouseButtonCallback(int button, int state, float x, f
btVector3 rayFrom = camPos;
btVector3 rayTo = getRayTo(x,y);
m_physicsSetup->pickBody(rayFrom, rayTo);

View File

@ -1,7 +1,7 @@
#ifndef CONSTAINT_PHYSICS_SETUP_H
#define CONSTAINT_PHYSICS_SETUP_H
#include "../CommonRigidBodySetup.h"
#include "../../../Demos/CommonRigidBodySetup.h"
struct ConstraintPhysicsSetup : public CommonRigidBodySetup
{

View File

@ -169,7 +169,7 @@ bool Bullet2MultiBodyDemo::mouseMoveCallback(float x,float y)
//keep it at the same picking distance
btVector3 newRayTo = getRayTo(x,y);
btVector3 rayFrom;
btVector3 oldPivotInB = pickCon->getPivotInB();
// btVector3 oldPivotInB = pickCon->getPivotInB();
btVector3 newPivotB;
m_glApp->m_instancingRenderer->getCameraPosition(rayFrom);
btVector3 dir = newRayTo-rayFrom;
@ -186,7 +186,7 @@ bool Bullet2MultiBodyDemo::mouseMoveCallback(float x,float y)
btVector3 newRayTo = getRayTo(x,y);
btVector3 rayFrom;
btVector3 oldPivotInB = m_pickingMultiBodyPoint2Point->getPivotInB();
// btVector3 oldPivotInB = m_pickingMultiBodyPoint2Point->getPivotInB();
btVector3 newPivotB;
btVector3 camPos;
m_glApp->m_instancingRenderer->getCameraPosition(camPos);
@ -438,7 +438,7 @@ btMultiBody* FeatherstoneDemo1::createFeatherstoneMultiBody(class btMultiBodyDyn
btVector4 halfExtents(7.5,0.45,4.5,1);
{
float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
@ -484,7 +484,7 @@ btMultiBody* FeatherstoneDemo1::createFeatherstoneMultiBody(class btMultiBodyDyn
{
btVector3 posr = local_origin[i+1];
float pos[4]={posr.x(),posr.y(),posr.z(),1};
//float pos[4]={posr.x(),posr.y(),posr.z(),1};
float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};
@ -531,8 +531,8 @@ void FeatherstoneDemo1::createGround()
{
//create ground
int cubeShapeId = m_glApp->registerCubeShape();
float pos[]={0,0,0};
float orn[]={0,0,0,1};
//float pos[]={0,0,0};
//float orn[]={0,0,0,1};
{
@ -575,7 +575,8 @@ void FeatherstoneDemo1::initPhysics()
settings.m_isFixedBase = false;
settings.m_basePosition.setValue(0,10,0);
settings.m_numLinks = 10;
btMultiBody* mb = createFeatherstoneMultiBody(m_dynamicsWorld,settings);
//btMultiBody* mb =
createFeatherstoneMultiBody(m_dynamicsWorld,settings);
m_glApp->m_instancingRenderer->writeTransforms();
@ -727,7 +728,7 @@ class RagDoll2
hull->buildHull(0.01);
{
int strideInBytes = 9*sizeof(float);
// int strideInBytes = 9*sizeof(float);
int numVertices = hull->numVertices();
int numIndices =hull->numIndices();
@ -988,7 +989,7 @@ public:
virtual ~RagDoll2 ()
{
int i;
//int i;
/*
// Remove all constraints
for ( i = 0; i < JOINT_COUNT; ++i)
@ -1027,8 +1028,8 @@ void FeatherstoneDemo2::initPhysics()
settings.m_usePrismatic = true;
btMultiBody* mb = createFeatherstoneMultiBody(m_dynamicsWorld,settings);
*/
btVector3 offset(0,2,0);
RagDoll2* doll = new RagDoll2(m_dynamicsWorld,offset,m_glApp);
// btVector3 offset(0,2,0);
//RagDoll2* doll = new RagDoll2(m_dynamicsWorld,offset,m_glApp);
m_glApp->m_instancingRenderer->writeTransforms();

View File

@ -307,7 +307,7 @@ void MultiDofDemo::addColliders_testMultiDof(btMultiBody *pMultiBody, btMultiBod
{
float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
@ -348,7 +348,7 @@ void MultiDofDemo::addColliders_testMultiDof(btMultiBody *pMultiBody, btMultiBod
{
btVector3 posr = local_origin[i+1];
float pos[4]={posr.x(),posr.y(),posr.z(),1};
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};

View File

@ -14,7 +14,7 @@ extern "C" {
}
char* sLuaFileName = "init_physics.lua";
const char* sLuaFileName = "init_physics.lua";
static const float scaling=0.35f;
static LuaPhysicsSetup* sLuaDemo = 0;

View File

@ -0,0 +1,251 @@
//test addJointTorque
#include "TestJointTorqueSetup.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
TestJointTorqueSetup::TestJointTorqueSetup()
{
}
TestJointTorqueSetup::~TestJointTorqueSetup()
{
}
void TestJointTorqueSetup::initPhysics(GraphicsPhysicsBridge& gfxBridge)
{
int upAxis = 2;
btVector4 colors[4] =
{
btVector4(1,0,0,1),
btVector4(0,1,0,1),
btVector4(0,1,1,1),
btVector4(1,1,0,1),
};
int curColor = 0;
gfxBridge.setUpAxis(upAxis);
this->createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(
//btIDebugDraw::DBG_DrawConstraints
+btIDebugDraw::DBG_DrawWireframe
+btIDebugDraw::DBG_DrawContactPoints
+btIDebugDraw::DBG_DrawAabb
);//+btIDebugDraw::DBG_DrawConstraintLimits);
//create a static ground object
if (0)
{
btVector3 groundHalfExtents(20,20,20);
groundHalfExtents[upAxis]=1.f;
btBoxShape* box = new btBoxShape(groundHalfExtents);
box->initializePolyhedralFeatures();
gfxBridge.createCollisionShapeGraphicsObject(box);
btTransform start; start.setIdentity();
btVector3 groundOrigin(0,0,0);
groundOrigin[upAxis]=-1.5;
start.setOrigin(groundOrigin);
btRigidBody* body = createRigidBody(0,start,box);
btVector4 color = colors[curColor];
curColor++;
curColor&=3;
gfxBridge.createRigidBodyGraphicsObject(body,color);
}
{
bool floating = false;
bool damping = true;
bool gyro = true;
int numLinks = 5;
bool spherical = false; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals
bool canSleep = false;
bool selfCollide = false;
btVector3 linkHalfExtents(0.05, 0.37, 0.1);
btVector3 baseHalfExtents(0.05, 0.37, 0.1);
btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
//mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm
//init the base
btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
float baseMass = 1.f;
if(baseMass)
{
btCollisionShape *pTempBox = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
pTempBox->calculateLocalInertia(baseMass, baseInertiaDiag);
delete pTempBox;
}
bool isMultiDof = false;
btMultiBody *pMultiBody = new btMultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep, isMultiDof);
m_multiBody = pMultiBody;
btQuaternion baseOriQuat(0.f, 0.f, 0.f, 1.f);
pMultiBody->setBasePos(basePosition);
pMultiBody->setWorldToBaseRot(baseOriQuat);
btVector3 vel(0, 0, 0);
// pMultiBody->setBaseVel(vel);
//init the links
btVector3 hingeJointAxis(1, 0, 0);
float linkMass = 1.f;
btVector3 linkInertiaDiag(0.f, 0.f, 0.f);
btCollisionShape *pTempBox = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));
pTempBox->calculateLocalInertia(linkMass, linkInertiaDiag);
delete pTempBox;
//y-axis assumed up
btVector3 parentComToCurrentCom(0, -linkHalfExtents[1] * 2.f, 0); //par body's COM to cur body's COM offset
btVector3 currentPivotToCurrentCom(0, -linkHalfExtents[1], 0); //cur body's COM to cur body's PIV offset
btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
//////
btScalar q0 = 0.f * SIMD_PI/ 180.f;
btQuaternion quat0(btVector3(0, 1, 0).normalized(), q0);
quat0.normalize();
/////
for(int i = 0; i < numLinks; ++i)
{
if(!spherical)
pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
else
//pMultiBody->setupPlanar(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, btVector3(1, 0, 0), parentComToCurrentPivot*2, false);
pMultiBody->setupSpherical(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), parentComToCurrentPivot, currentPivotToCurrentCom, false);
}
//pMultiBody->finalizeMultiDof();
btMultiBodyDynamicsWorld* world = m_dynamicsWorld;
///
world->addMultiBody(pMultiBody);
btMultiBody* mbC = pMultiBody;
mbC->setCanSleep(canSleep);
mbC->setHasSelfCollision(selfCollide);
mbC->setUseGyroTerm(gyro);
//
if(!damping)
{
mbC->setLinearDamping(0.f);
mbC->setAngularDamping(0.f);
}else
{ mbC->setLinearDamping(0.1f);
mbC->setAngularDamping(0.9f);
}
//
btVector3 gravity(0,0,0);
//gravity[upAxis] = -9.81;
m_dynamicsWorld->setGravity(gravity);
//////////////////////////////////////////////
if(numLinks > 0)
{
btScalar q0 = 45.f * SIMD_PI/ 180.f;
if(!spherical)
if(mbC->isMultiDof())
mbC->setJointPosMultiDof(0, &q0);
else
mbC->setJointPos(0, q0);
else
{
btQuaternion quat0(btVector3(1, 1, 0).normalized(), q0);
quat0.normalize();
mbC->setJointPosMultiDof(0, quat0);
}
}
///
btAlignedObjectArray<btQuaternion> world_to_local;
world_to_local.resize(pMultiBody->getNumLinks() + 1);
btAlignedObjectArray<btVector3> local_origin;
local_origin.resize(pMultiBody->getNumLinks() + 1);
world_to_local[0] = pMultiBody->getWorldToBaseRot();
local_origin[0] = pMultiBody->getBasePos();
double friction = 1;
{
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
if (1)
{
btCollisionShape* box = new btBoxShape(baseHalfExtents);
gfxBridge.createCollisionShapeGraphicsObject(box);
btMultiBodyLinkCollider* col= new btMultiBodyLinkCollider(pMultiBody, -1);
col->setCollisionShape(box);
btTransform tr;
tr.setIdentity();
//if we don't set the initial pose of the btCollisionObject, the simulator will do this
//when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
tr.setOrigin(local_origin[0]);
tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
world->addCollisionObject(col, 2,1+2);
btVector3 color(0.0,0.0,0.5);
gfxBridge.createCollisionObjectGraphicsObject(col,color);
col->setFriction(friction);
pMultiBody->setBaseCollider(col);
}
}
for (int i=0; i < pMultiBody->getNumLinks(); ++i)
{
const int parent = pMultiBody->getParent(i);
world_to_local[i+1] = pMultiBody->getParentToLocalRot(i) * world_to_local[parent+1];
local_origin[i+1] = local_origin[parent+1] + (quatRotate(world_to_local[i+1].inverse() , pMultiBody->getRVector(i)));
}
for (int i=0; i < pMultiBody->getNumLinks(); ++i)
{
btVector3 posr = local_origin[i+1];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};
btCollisionShape* box = new btBoxShape(linkHalfExtents);
gfxBridge.createCollisionShapeGraphicsObject(box);
btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, i);
col->setCollisionShape(box);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
col->setFriction(friction);
world->addCollisionObject(col,2,1+2);
btVector4 color = colors[curColor];
curColor++;
curColor&=3;
gfxBridge.createCollisionObjectGraphicsObject(col,color);
pMultiBody->getLink(i).m_collider=col;
}
}
}
void TestJointTorqueSetup::stepSimulation(float deltaTime)
{
m_multiBody->addJointTorque(0, 10.0);
m_dynamicsWorld->stepSimulation(deltaTime);
}

View File

@ -0,0 +1,21 @@
#ifndef TEST_JOINT_TORQUE_SETUP_H
#define TEST_JOINT_TORQUE_SETUP_H
#include "../../../Demos/CommonMultiBodySetup.h"
struct TestJointTorqueSetup : public CommonMultiBodySetup
{
btMultiBody* m_multiBody;
public:
TestJointTorqueSetup();
virtual ~TestJointTorqueSetup();
virtual void initPhysics(GraphicsPhysicsBridge& gfxBridge);
virtual void stepSimulation(float deltaTime);
};
#endif //TEST_JOINT_TORQUE_SETUP_H

View File

@ -197,10 +197,46 @@ btCollisionShape* btWorldImporter::convertCollisionShape( btCollisionShapeData*
}
break;
}
//The btCapsuleShape* API has issue passing the margin/scaling/halfextents unmodified through the API
//so deal with this
case CAPSULE_SHAPE_PROXYTYPE:
{
btCapsuleShapeData* capData = (btCapsuleShapeData*)shapeData;
switch (capData->m_upAxis)
{
case 0:
{
shape = createCapsuleShapeX(1,1);
break;
}
case 1:
{
shape = createCapsuleShapeY(1,1);
break;
}
case 2:
{
shape = createCapsuleShapeZ(1,1);
break;
}
default:
{
printf("error: wrong up axis for btCapsuleShape\n");
}
};
if (shape)
{
btCapsuleShape* cap = (btCapsuleShape*) shape;
cap->deSerializeFloat(capData);
}
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
case CONE_SHAPE_PROXYTYPE:
case CAPSULE_SHAPE_PROXYTYPE:
case BOX_SHAPE_PROXYTYPE:
case SPHERE_SHAPE_PROXYTYPE:
case MULTI_SPHERE_SHAPE_PROXYTYPE:
@ -227,36 +263,7 @@ btCollisionShape* btWorldImporter::convertCollisionShape( btCollisionShapeData*
shape = createSphereShape(implicitShapeDimensions.getX());
break;
}
case CAPSULE_SHAPE_PROXYTYPE:
{
btCapsuleShapeData* capData = (btCapsuleShapeData*)shapeData;
switch (capData->m_upAxis)
{
case 0:
{
shape = createCapsuleShapeX(implicitShapeDimensions.getY()+bsd->m_collisionMargin*2,2*implicitShapeDimensions.getX());
break;
}
case 1:
{
shape = createCapsuleShapeY(implicitShapeDimensions.getX()+bsd->m_collisionMargin*2,2*implicitShapeDimensions.getY());
break;
}
case 2:
{
shape = createCapsuleShapeZ(implicitShapeDimensions.getX()+bsd->m_collisionMargin*2,2*implicitShapeDimensions.getZ());
break;
}
default:
{
printf("error: wrong up axis for btCapsuleShape\n");
}
bsd->m_collisionMargin = 0.f;
};
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
{
btCylinderShapeData* cylData = (btCylinderShapeData*) shapeData;

View File

@ -1,3 +1,5 @@
[![Travis Build Status](https://api.travis-ci.org/bulletphysics/bullet3.png?branch=master)](https://travis-ci.org/bulletphysics/bullet3)
[![Appveyor Build status](https://ci.appveyor.com/api/projects/status/6sly9uxajr6xsstq)](https://ci.appveyor.com/project/erwincoumans/bullet3)
Bullet 3.x GPU rigid body pipeline using OpenCL.

9
appveyor.yml Normal file
View File

@ -0,0 +1,9 @@
build:
project: build3/vs2010/0_Bullet3Solution.sln
before_build:
- echo %CD%
- ps: cd build3
- echo %CD%
- premake4 vs2010
- ps: cd ..

View File

@ -112,7 +112,7 @@ void CrossSplitter::Layout( Skin::Base* /*skin*/ )
else
{
//This should probably use Fill docking instead
m_Sections[m_iZoomedSection]->SetBounds( 0, 0, Width(), Height() );
m_Sections[(int)m_iZoomedSection]->SetBounds( 0, 0, Width(), Height() );
}
}

View File

@ -23,7 +23,7 @@ void Resizer::OnMouseMoved( int x, int y, int /*deltaX*/, int /*deltaY*/ )
if ( !m_pTarget ) return;
if ( !m_bDepressed ) return;
Gwen::Rect oldBounds = m_pTarget->GetBounds();
// Gwen::Rect oldBounds = m_pTarget->GetBounds();
Gwen::Rect pBounds = m_pTarget->GetBounds();
Gwen::Point pntMin = m_pTarget->GetMinimumSize();

View File

@ -134,8 +134,14 @@ void ScrollControl::UpdateScrollBars()
m_InnerPanel->SetSize( Utility::Max(Width(), childrenWidth), Utility::Max(Height(), childrenHeight));
float wPercent = (float)Width() / (float)(childrenWidth + (m_VerticalScrollBar->Hidden() ? 0 : m_VerticalScrollBar->Width()));
float hPercent = (float)Height() / (float)(childrenHeight + (m_HorizontalScrollBar->Hidden() ? 0 : m_HorizontalScrollBar->Height()));
float hg = (float)(childrenWidth + (m_VerticalScrollBar->Hidden() ? 0 : m_VerticalScrollBar->Width()));
if (hg==0.f)
hg = 0.00001f;
float wPercent = (float)Width() / hg;
hg = (float)(childrenHeight + (m_HorizontalScrollBar->Hidden() ? 0 : m_HorizontalScrollBar->Height()));
if (hg==0.f)
hg = 0.00001f;
float hPercent = (float)Height() / hg;
if ( m_bCanScrollV )
SetVScrollRequired( hPercent >= 1 );

View File

@ -101,12 +101,12 @@ bool TreeControl::OnKeyUp( bool bDown )
if (bDown)
{
ForceUpdateScrollBars();
int maxIndex = 0;
// int maxIndex = 0;
int newIndex = 0;
int maxItem=0;
int curItem=-1;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItem,&curItem);
maxIndex = maxItem;
// maxIndex = maxItem;
int targetItem = curItem;
if (curItem>0)
{
@ -121,29 +121,32 @@ bool TreeControl::OnKeyUp( bool bDown )
iterate(ITERATE_ACTION_DESELECT_INDEX,&maxItem,&deselectIndex);
}
curItem = newIndex;
float amount = float(newIndex)/float(maxIndex);
// float amount = float(newIndex)/float(maxIndex);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
//float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
{
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
}
@ -157,12 +160,12 @@ bool TreeControl::OnKeyDown( bool bDown )
if (bDown)
{
ForceUpdateScrollBars();
int maxIndex = 0;
// int maxIndex = 0;
int newIndex = 0;
int maxItem=0;
int curItem=-1;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItem,&curItem);
maxIndex = maxItem;
// maxIndex = maxItem;
int targetItem = curItem;
if (curItem>=0)
{
@ -177,29 +180,32 @@ bool TreeControl::OnKeyDown( bool bDown )
iterate(ITERATE_ACTION_DESELECT_INDEX,&maxItem,&deselectIndex);
}
curItem= newIndex;
float amount = (int)float(newIndex)/float(maxIndex);
// float amount = (int)float(newIndex)/float(maxIndex);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
//float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
//float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
{
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
}
@ -219,29 +225,32 @@ bool TreeControl::OnKeyRight( bool bDown )
int maxItem=0;
int curItem=0;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItem,&curItem);
float amount = float(curItem)/float(maxItem);
// float amount = float(curItem)/float(maxItem);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
// float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
{
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
Invalidate();
@ -262,34 +271,36 @@ bool TreeControl::OnKeyLeft( bool bDown )
int maxItems=0;
int curItem=0;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItems,&curItem);
float amount = float(curItem)/float(maxItems);
// float amount = float(curItem)/float(maxItems);
// m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(amount,true);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
// float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
{
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
{
int numItems = (viewSize)/16-1;
float newAmount = float((curItem-numItems)*16)/(contSize-viewSize);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
if (newAmount>curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
Invalidate();
}
Invalidate();
}
//viewSize/contSize

View File

@ -73,7 +73,7 @@ void TreeNode::Render( Skin::Base* skin )
TreeNode* TreeNode::AddNode( const UnicodeString& strLabel )
{
int sz = sizeof(TreeNode);
// int sz = sizeof(TreeNode);
TreeNode* node = new TreeNode( this );
node->SetText( strLabel );
node->Dock( Pos::Top );
@ -231,7 +231,7 @@ void TreeNode::iterate(int action, int* curIndex, int* targetIndex)
Gwen::String name = Gwen::Utility::UnicodeToString(m_Title->GetText());
int actualIndex = curIndex? *curIndex : -1;
// int actualIndex = curIndex? *curIndex : -1;
//printf("iterated over item %d with name = %s\n", actualIndex, name.c_str());
if (action==ITERATE_ACTION_SELECT)

View File

@ -164,7 +164,7 @@ namespace Gwen
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GLenum format = GL_RGB;
//GLenum format = GL_RGB;
unsigned char* texdata = new unsigned char[256*256*4];
for (int i=0;i<256*256;i++)
{
@ -316,11 +316,11 @@ namespace Gwen
Gwen::String converted_string = Gwen::Utility::UnicodeToString( text );
float yOffset=0.0f;
for ( int i=0; i<text.length(); i++ )
for ( int i=0; i<(int)text.length(); i++ )
{
wchar_t chr = text[i];
// wchar_t chr = text[i];
char ch = converted_string[i];
float curSpacing = sGwenDebugFontSpacing[ch] * m_fLetterSpacing * fSize * m_fFontScale[0];
float curSpacing = sGwenDebugFontSpacing[(int)ch] * m_fLetterSpacing * fSize * m_fFontScale[0];
Gwen::Rect r( pos.x + yOffset, pos.y-fSize*0.2f, (fSize * m_fFontScale[0]), fSize * m_fFontScale[1] );
if ( m_pFontTexture )
@ -390,10 +390,10 @@ namespace Gwen
Gwen::String converted_string = Gwen::Utility::UnicodeToString( text );
float spacing = 0.0f;
for ( int i=0; i<text.length(); i++ )
for ( int i=0; i<(int)text.length(); i++ )
{
char ch = converted_string[i];
spacing += sGwenDebugFontSpacing[ch];
spacing += sGwenDebugFontSpacing[(int)ch];
}
p.x = spacing*m_fLetterSpacing*fSize * m_fFontScale[0];

View File

@ -78,7 +78,7 @@ namespace Gwen
m_Render->DrawLinedRect( control->GetRenderBounds() );
}
Gwen::Rect rect = control->GetRenderBounds();
// Gwen::Rect rect = control->GetRenderBounds();
if ( bChecked )
{
m_Render->SetDrawColor( Color( 0, 0, 0, 255) );
@ -490,7 +490,7 @@ namespace Gwen
virtual void DrawSlider( Gwen::Controls::Base* control, bool bIsHorizontal, int numNotches, int barSize)
{
Gwen::Rect rect = control->GetRenderBounds();
Gwen::Rect notchRect = rect;
// Gwen::Rect notchRect = rect;
if ( bIsHorizontal )
{

View File

@ -145,7 +145,7 @@ struct sth_stash* sth_create(int cachew, int cacheh, RenderCallbacks* renderCall
memset(stash,0,sizeof(struct sth_stash));
stash->m_renderCallbacks = renderCallbacks;
// Allocate memory for the first texture
texture = (struct sth_texture*)malloc(sizeof(struct sth_texture));
if (texture == NULL)
@ -161,11 +161,11 @@ struct sth_stash* sth_create(int cachew, int cacheh, RenderCallbacks* renderCall
stash->itw = 1.0f/cachew;
stash->ith = 1.0f/cacheh;
stash->textures = texture;
stash->m_renderCallbacks->updateTexture(texture, 0, stash->tw, stash->th);
stash->m_renderCallbacks->updateTexture(texture, 0, stash->tw, stash->th);
return stash;
}
int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
@ -177,7 +177,7 @@ int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
if (fnt == NULL) goto error;
memset(fnt,0,sizeof(struct sth_font));
// Init hash lookup.
for (i = 0; i < HASH_LUT_SIZE; ++i)
fnt->lut[i] = -1;
@ -187,8 +187,8 @@ int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
// Init stb_truetype
if (!stbtt_InitFont(&fnt->font, fnt->data, 0))
goto error;
// Store normalized line height. The real line height is got
// by multiplying the lineh by font size.
stbtt_GetFontVMetrics(&fnt->font, &ascent, &descent, &lineGap);
@ -203,7 +203,7 @@ int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
fnt->next = stash->fonts;
stash->fonts = fnt;
return idx++;
error:
@ -219,8 +219,8 @@ int sth_add_font(struct sth_stash* stash, const char* path)
FILE* fp = 0;
int datasize;
unsigned char* data = NULL;
int idx;
int idx=0;
// Read in the font data.
fp = fopen(path, "rb");
if (!fp) goto error;
@ -229,11 +229,16 @@ int sth_add_font(struct sth_stash* stash, const char* path)
fseek(fp,0,SEEK_SET);
data = (unsigned char*)malloc(datasize);
if (data == NULL) goto error;
fread(data, 1, datasize, fp);
int bytesRead;
bytesRead = fread(data, 1, datasize, fp);
if (bytesRead)
{
idx = sth_add_font_from_memory(stash, data);
}
fclose(fp);
fp = 0;
idx = sth_add_font_from_memory(stash, data);
// Modify type of the loaded font.
if (idx)
stash->fonts->type = TTFONT_FILE;
@ -241,7 +246,7 @@ int sth_add_font(struct sth_stash* stash, const char* path)
free(data);
return idx;
error:
if (data) free(data);
if (fp) fclose(fp);
@ -271,7 +276,7 @@ int sth_add_bitmap_font(struct sth_stash* stash, int ascent, int descent, int li
fnt->type = BMFONT;
fnt->next = stash->fonts;
stash->fonts = fnt;
return idx++;
error:
@ -295,7 +300,7 @@ error:
if (stash == NULL) return;
texture = stash->textures;
while (texture != NULL && texture->id != id)
while (texture != NULL && texture->id != id)
texture = texture->next;
if (texture == NULL)
@ -313,7 +318,7 @@ error:
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT) return;
for (; *s; ++s)
{
if (!decutf8(&state, &codepoint, *(unsigned char*)s)) break;
@ -338,7 +343,7 @@ error:
glyph->xoff = xoffset;
glyph->yoff = yoffset - base;
glyph->xadv = xadvance;
// Find code point and size.
h = hashint(codepoint) & (HASH_LUT_SIZE-1);
// Insert char to hash lookup.
@ -353,7 +358,7 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
float scale;
struct sth_texture* texture = NULL;
struct sth_glyph* glyph = NULL;
unsigned int h;
float size = isize/10.0f;
int rh;
@ -369,10 +374,10 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
i = fnt->glyphs[i].next;
}
// Could not find glyph.
// For bitmap fonts: ignore this glyph.
if (fnt->type == BMFONT) return 0;
// For truetype fonts: create this glyph.
scale = stbtt_ScaleForPixelHeight(&fnt->font, size);
g = stbtt_FindGlyphIndex(&fnt->font, codepoint);
@ -380,7 +385,7 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
stbtt_GetGlyphBitmapBox(&fnt->font, g, scale,scale, &x0,&y0,&x1,&y1);
gw = x1-x0;
gh = y1-y0;
// Check if glyph is larger than maximum texture size
if (gw >= stash->tw || gh >= stash->th)
return 0;
@ -396,7 +401,7 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
if (texture->rows[i].h >= rh && texture->rows[i].x+gw+1 <= stash->tw)
br = &texture->rows[i];
}
// If no row is found, there are 3 possibilities:
// - add new row
// - try next texture
@ -421,10 +426,10 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
texture = texture->next;
if (texture == NULL) goto error;
memset(texture,0,sizeof(struct sth_texture));
stash->m_renderCallbacks->updateTexture(texture,0,stash->tw,stash->th);
}
continue;
}
@ -434,10 +439,10 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
br->x = BORDER_X_LEFT;
br->y = py+BORDER_Y_BOTTOM;
br->h = rh+ADDITIONAL_HEIGHT;
texture->nrows++;
texture->nrows++;
}
}
// Alloc space for new glyph.
fnt->nglyphs++;
fnt->glyphs = (sth_glyph*)realloc(fnt->glyphs, fnt->nglyphs*sizeof(struct sth_glyph));
@ -473,7 +478,7 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
stash->m_renderCallbacks->updateTexture(texture,glyph, stash->tw, stash->th);
}
return glyph;
error:
@ -486,26 +491,26 @@ static int get_quad(struct sth_stash* stash, struct sth_font* fnt, struct sth_gl
{
float rx,ry;
float scale = 1.f/s_retinaScale;//1.0f;
if (fnt->type == BMFONT)
scale = isize/(glyph->size*10.0f);
rx = (*x + scale * float(glyph->xoff));
ry = (*y + scale * float(glyph->yoff));
q->x0 = rx;
q->y0 = ry + 1.5f*0.5f*float(isize)/10.f;
q->x1 = rx + scale * float(glyph->x1 - glyph->x0_);
q->y1 = ry + scale * float(glyph->y1 - glyph->y0)+ 1.5f*0.5f*float(isize)/10.f;
q->s0 = float(glyph->x0_) * stash->itw;
q->t0 = float(glyph->y0) * stash->ith;
q->s1 = float(glyph->x1) * stash->itw;
q->t1 = float(glyph->y1) * stash->ith;
*x += scale * glyph->xadv;
return 1;
}
@ -523,7 +528,7 @@ static Vertex* setv(Vertex* v, float x, float y, float s, float t, float width,
}
v->position.p[2] = 0.f;
v->position.p[3] = 1.f;
v->uv.p[0] = s;
v->uv.p[1] = t;
@ -531,7 +536,7 @@ static Vertex* setv(Vertex* v, float x, float y, float s, float t, float width,
v->colour.p[1] = 0.1f;
v->colour.p[2] = 0.1f;
v->colour.p[3] = 1.f;
return v+1;
}
@ -545,7 +550,7 @@ static void flush_draw(struct sth_stash* stash)
{
if (texture->nverts > 0)
{
stash->m_renderCallbacks->render(texture);
stash->m_renderCallbacks->render(texture);
texture->nverts = 0;
}
texture = texture->next;
@ -584,7 +589,7 @@ void sth_end_draw(struct sth_stash* stash)
stash->nverts += 6;
}
*/
flush_draw(stash);
stash->drawing = 0;
}
@ -606,7 +611,7 @@ void sth_draw_texture(struct sth_stash* stash,
short isize = (short)(size*10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
if (stash == NULL) return;
if (!stash->textures) return;
@ -614,23 +619,23 @@ void sth_draw_texture(struct sth_stash* stash,
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
int once = true;
for (; once; ++s)
{
once=false;
if (decutf8(&state, &codepoint, *(unsigned char*)s))
if (decutf8(&state, &codepoint, *(unsigned char*)s))
continue;
glyph = get_glyph(stash, fnt, codepoint, isize);
if (!glyph)
if (!glyph)
continue;
texture = glyph->texture;
if (texture->nverts+6 >= VERT_COUNT)
flush_draw(stash);
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q))
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q))
continue;
v = &texture->newverts[texture->nverts];
q.x0 = 0;
q.y0 = 0;
@ -646,11 +651,11 @@ void sth_draw_texture(struct sth_stash* stash,
v = setv(v, q.x0, q.y1, 0,1,(float)screenwidth,(float)screenheight);
texture->nverts += 6;
}
flush_draw(stash);
if (dx) *dx = x;
}
@ -664,7 +669,7 @@ void sth_draw_text(struct sth_stash* stash,
float x, float y,
const char* s, float* dx, int screenwidth, int screenheight, int measureOnly, float retinaScale)
{
unsigned int codepoint;
struct sth_glyph* glyph = NULL;
struct sth_texture* texture = NULL;
@ -673,7 +678,7 @@ void sth_draw_text(struct sth_stash* stash,
short isize = (short)(size*10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
s_retinaScale = retinaScale;
if (stash == NULL) return;
@ -682,23 +687,23 @@ void sth_draw_text(struct sth_stash* stash,
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
for (; *s; ++s)
{
if (decutf8(&state, &codepoint, *(unsigned char*)s))
if (decutf8(&state, &codepoint, *(unsigned char*)s))
continue;
glyph = get_glyph(stash, fnt, codepoint, isize);
if (!glyph) continue;
texture = glyph->texture;
if (!measureOnly)
{
if (texture->nverts+6 >= VERT_COUNT)
flush_draw(stash);
}
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q)) continue;
if (!measureOnly)
{
v = &texture->newverts[texture->nverts];
@ -714,7 +719,7 @@ void sth_draw_text(struct sth_stash* stash,
texture->nverts += 6;
}
}
if (dx) *dx = x;
}
@ -730,16 +735,16 @@ void sth_dim_text(struct sth_stash* stash,
short isize = (short)(size*10.0f);
struct sth_font* fnt = NULL;
float x = 0, y = 0;
if (stash == NULL)
if (stash == NULL)
return;
if (!stash->textures)
if (!stash->textures)
return;
fnt = stash->fonts;
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
*minx = *maxx = x;
*miny = *maxy = y;

View File

@ -37,8 +37,7 @@ InternalOpenGL2RenderCallbacks::~InternalOpenGL2RenderCallbacks()
void InternalOpenGL2RenderCallbacks::display2()
{
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// glViewport(0,0,10,10);
//const float timeScale = 0.008f;
@ -48,39 +47,31 @@ void InternalOpenGL2RenderCallbacks::display2()
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBindVertexArray(s_vertexArrayObject);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// glBindTexture(GL_TEXTURE_2D,m_texturehandle);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
vec2 p( 0.f,0.f);//?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
glUniform2fv(data->m_positionUniform, 1, (const GLfloat *)&p);
err = glGetError();
assert(err==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(data->m_positionAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(data->m_colourAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(data->m_textureAttribute);
glVertexAttribPointer(data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
glVertexAttribPointer(data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4));
glVertexAttribPointer(data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4)));
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
/*
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
@ -101,10 +92,7 @@ void InternalOpenGL2RenderCallbacks::display2()
void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight)
{
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
if (glyph)
@ -114,13 +102,11 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glBindTexture(GL_TEXTURE_2D, *gltexture);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels);
GLenum err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
} else
{
@ -132,8 +118,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
//create new texture
glGenTextures(1, texId);
GLenum err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
@ -143,8 +128,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
////////////////////////////
//create the other data
@ -155,8 +139,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glGenBuffers(1, &s_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, VERT_COUNT * sizeof(Vertex), texture->newverts, GL_DYNAMIC_DRAW);
GLuint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
for (int i=0;i<INDEX_COUNT;i++)
{
@ -167,9 +150,8 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,INDEX_COUNT*sizeof(int), s_indexData,GL_STATIC_DRAW);
err = glGetError();
assert(err==GL_NO_ERROR);
}
assert(glGetError()==GL_NO_ERROR);
}
} else
{
//delete texture
@ -196,13 +178,10 @@ void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
GLuint* texId = (GLuint*) texture->m_userData;
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, *texId);
bool useFiltering = false;
@ -215,25 +194,21 @@ void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBindVertexArray(s_vertexArrayObject);
glBufferData(GL_ARRAY_BUFFER, texture->nverts * sizeof(Vertex), &texture->newverts[0].position.p[0], GL_DYNAMIC_DRAW);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = texture->nverts;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindVertexArray(0);

View File

@ -32,7 +32,14 @@ ENDIF(APPLE)
#no Linux detection?
IF(NOT WIN32 AND NOT APPLE)
SET(OpenGLWindow_SRCS ${OpenGLWindowLinux_CPP} ${OpenGLWindowCommon_CPP} )
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
ADD_DEFINITIONS(-DGLEW_STATIC)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
SET(OpenGLWindow_SRCS ${OpenGLWindowLinux_CPP} ${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows/glew.c ${OpenGLWindowCommon_CPP} )
ENDIF()

View File

@ -16,8 +16,8 @@ subject to the following restrictions:
///todo: make this configurable in the gui
bool useShadowMap=true;//false;//true;
float shadowMapWidth=8192;
float shadowMapHeight=8192;
int shadowMapWidth=8192;
int shadowMapHeight=8192;
float shadowMapWorldSize=100;
float WHEEL_MULTIPLIER=0.01f;
float MOUSE_MOVE_MULTIPLIER = 0.4f;

View File

@ -131,8 +131,8 @@ void GLPrimitiveRenderer::loadBufferData()
glGenBuffers(1, &m_data->m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(Vertex), vertexData, GL_DYNAMIC_DRAW);
GLuint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
@ -142,16 +142,14 @@ void GLPrimitiveRenderer::loadBufferData()
glEnableVertexAttribArray(m_data->m_positionAttribute);
glEnableVertexAttribArray(m_data->m_colourAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4));
glVertexAttribPointer(m_data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4)));
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
@ -191,8 +189,7 @@ void GLPrimitiveRenderer::loadBufferData()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256,256,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glGenerateMipmap(GL_TEXTURE_2D);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
delete[] image;
@ -217,36 +214,25 @@ void GLPrimitiveRenderer::drawLine()
void GLPrimitiveRenderer::drawRect(float x0, float y0, float x1, float y1, float color[4])
{
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D,m_data->m_texturehandle);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
drawTexturedRect(x0,y0,x1,y1,color,0,0,1,1);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}
void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0,float v0, float u1, float v1, int useRGBA)
{
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glUseProgram(m_data->m_shaderProg);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBindVertexArray(m_data->m_vertexArrayObject);
@ -263,10 +249,10 @@ void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y
}
Vertex vertexData[4] = {
{ vec4(-1.+2.*x0/float(m_screenWidth), 1.-2.*y0/float(m_screenHeight), 0, 0 ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v0)},
{ vec4(-1.+2.*x0/float(m_screenWidth), 1.-2.*y1/float(m_screenHeight), 0, 1 ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v1)},
{ vec4( -1.+2.*x1/float(m_screenWidth), 1.-2.*y1/float(m_screenHeight), 1, 1 ), vec4(color[0], color[1], color[2], color[3]) ,vec2(u1,v1)},
{ vec4( -1.+2.*x1/float(m_screenWidth), 1.-2.*y0/float(m_screenHeight), 1, 0 ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u1,v0)}
{ vec4(-1.f+2.f*x0/float(m_screenWidth), 1.f-2.f*y0/float(m_screenHeight), 0.f, 0.f ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v0)},
{ vec4(-1.f+2.f*x0/float(m_screenWidth), 1.f-2.f*y1/float(m_screenHeight), 0.f, 1.f ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v1)},
{ vec4( -1.f+2.f*x1/float(m_screenWidth), 1.f-2.f*y1/float(m_screenHeight), 1.f, 1.f ), vec4(color[0], color[1], color[2], color[3]) ,vec2(u1,v1)},
{ vec4( -1.f+2.f*x1/float(m_screenWidth), 1.f-2.f*y0/float(m_screenHeight), 1.f, 0.f ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u1,v0)}
};
glBufferSubData(GL_ARRAY_BUFFER, 0,4 * sizeof(Vertex), vertexData);
@ -276,8 +262,7 @@ void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
vec2 p( 0.f,0.f);//?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
if (useRGBA)
@ -290,60 +275,47 @@ void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_positionAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_colourAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4));
glVertexAttribPointer(m_data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4)));
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = 6;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindVertexArray(0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
//glDisableVertexAttribArray(m_data->m_textureAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glUseProgram(0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}

View File

@ -119,55 +119,37 @@ public:
{
m_yOffset=0;
glEnable(GL_BLEND);
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glDisable(GL_DEPTH_TEST);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
//glColor4ub(255,0,0,255);
err = glGetError();
assert(err==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
// saveOpenGLState(width,height);//m_glutScreenWidth,m_glutScreenHeight);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glEnable(GL_BLEND);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}
virtual void End()
{
@ -375,10 +357,7 @@ public:
glBindTexture(GL_TEXTURE_2D,texHandle);
// glDisable(GL_DEPTH_TEST);
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
/* bool useFiltering = true;
@ -406,8 +385,8 @@ public:
m_primitiveRenderer->drawTexturedRect(rect.x, rect.y+m_yOffset, rect.x+rect.w, rect.y+rect.h+m_yOffset, color,0+add,0,1+add,1,true);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}

View File

@ -18,8 +18,7 @@ void gltLoadShaderSrc(const char *szShaderSrc, GLuint shader)
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
{
GLuint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// Temporary Shader objects
GLuint hVertexShader;
@ -36,7 +35,7 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
// Compile them
glCompileShader(hVertexShader);
err = glGetError();
assert(glGetError()==GL_NO_ERROR);
glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
@ -51,10 +50,10 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
return (GLuint)NULL;
}
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glCompileShader(hFragmentShader);
err = glGetError();
assert(glGetError()==GL_NO_ERROR);
glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
@ -69,7 +68,7 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
return (GLuint)NULL;
}
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// Check for errors

View File

@ -81,7 +81,7 @@ public:
virtual void setWindowTitle(const char* title);
int fileOpenDialog(char* filename, int maxNameLength);
};

View File

@ -989,8 +989,48 @@ void MacOpenGLWindow::setRequestExit()
m_internalData->m_exitRequested = true;
}
#include <string.h>
int MacOpenGLWindow::fileOpenDialog(char* filename, int maxNameLength)
{
//save/restore the OpenGL context, NSOpenPanel can mess it up
//http://stackoverflow.com/questions/13987148/nsopenpanel-breaks-my-sdl-opengl-app
NSOpenGLContext *foo = [NSOpenGLContext currentContext];
// get the url of a .txt file
NSOpenPanel * zOpenPanel = [NSOpenPanel openPanel];
NSArray * zAryOfExtensions = [NSArray arrayWithObject:@"urdf"];
[zOpenPanel setAllowedFileTypes:zAryOfExtensions];
NSInteger zIntResult = [zOpenPanel runModal];
[foo makeCurrentContext];
if (zIntResult == NSFileHandlingPanelCancelButton) {
NSLog(@"readUsingOpenPanel cancelled");
return 0;
}
NSURL *zUrl = [zOpenPanel URL];
if (zUrl)
{
//without the file://
NSString *myString = [zUrl absoluteString];
int slen = [myString length];
if (slen < maxNameLength)
{
const char *cfilename=[myString UTF8String];
//expect file:// at start of URL
const char* p = strstr(cfilename, "file://");
if (p==cfilename)
{
int actualLen = strlen(cfilename)-7;
memcpy(filename, cfilename+7,actualLen);
filename[actualLen]=0;
return actualLen;
}
}
}
return 0;
}

View File

@ -430,19 +430,17 @@ static void writeTextureToFile(int textureWidth, int textureHeight, const char*
{
int numComponents = 4;
//glPixelStorei(GL_PACK_ALIGNMENT,1);
GLuint err=glGetError();
assert(err==GL_NO_ERROR);
b3Assert(glGetError()==GL_NO_ERROR);
//glReadBuffer(GL_BACK);//COLOR_ATTACHMENT0);
err=glGetError();
assert(err==GL_NO_ERROR);
float* orgPixels = (float*)malloc(textureWidth*textureHeight*numComponents*4);
glReadPixels(0,0,textureWidth, textureHeight, GL_RGBA, GL_FLOAT, orgPixels);
//it is useful to have the actual float values for debugging purposes
//convert float->char
char* pixels = (char*)malloc(textureWidth*textureHeight*numComponents);
err=glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
for (int j=0;j<textureHeight;j++)
{

View File

@ -137,6 +137,40 @@ void Win32OpenGLWindow::endRendering()
}
int Win32OpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
{
//wchar_t wideChars[1024];
OPENFILENAME ofn ;
ZeroMemory( &ofn , sizeof( ofn));
ofn.lStructSize = sizeof ( ofn );
ofn.hwndOwner = NULL ;
#ifdef UNICODE
WCHAR bla[1024];
ofn.lpstrFile = bla;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 1023;
ofn.lpstrFilter = L"URDF\0*.urdf\0";
#else
ofn.lpstrFile = fileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 1023;
//ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.lpstrFilter = "URDF\0*.urdf\0";
#endif
ofn.nFilterIndex =1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0 ;
ofn.lpstrInitialDir=NULL ;
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ;
GetOpenFileName( &ofn );
return strlen(fileName);
//return 0;
}

View File

@ -51,6 +51,8 @@ public:
virtual void endRendering();
virtual float getRetinaScale() const {return 1.f;}
virtual int fileOpenDialog(char* fileName, int maxFileNameLength);
};

View File

@ -29,7 +29,34 @@
#include <pthread.h>
GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
GLint att[] = { GLX_RGBA,
GLX_DEPTH_SIZE, 24,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER,
None };
/*
static int att[] =
{
GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None
GLX_X_RENDERABLE , True,
GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , True,
None
};
*/
static bool forceOpenGL3 = true;
@ -37,6 +64,7 @@ static bool forceOpenGL3 = true;
#ifdef DYNAMIC_LOAD_X11_FUNCTIONS
///our X11 function typedefs
typedef int (*PFNXFREE)(void*);
typedef XErrorHandler (* PFNXSETERRORHANDLER) (XErrorHandler);
typedef int (* PFNXSYNC) (Display* a,Bool b);
@ -47,10 +75,14 @@ typedef int (*PFNXMAPWINDOW) (Display*, Window);
typedef int (*PFNXSTORENAME) (Display* a,Window b,_Xconst char* c);
typedef int (*PFNXCLOSEDISPLAY) (Display* a);
typedef int (*PFNXDESTROYWINDOW) (Display* a,Window b);
typedef int (*PFNXRAISEWINDOW) (Display* a, Window b);
#if NeedWidePrototypes
typedef KeySym (*PFNXKEYCODETOKEYSYM) (Display* a,unsigned int b,int c);
typedef KeySym* (*PFNXGETKEYBOARDMAPPING) (Display*,unsigned int,int,int*);
typedef KeySym (*PFNXKEYCODETOKEYSYM) (Display* a,unsigned int b,int c);
#else
typedef KeySym (*PFNXKEYCODETOKEYSYM) (Display* a,KeyCode b,int c);
typedef KeySym* (*PFNXGETKEYBOARDMAPPING) (Display*,KeyCode,int,int*);
typedef KeySym (*PFNXKEYCODETOKEYSYM) (Display* a,KeyCode b,int c);
#endif
typedef void (*PFNXCONVERTCASE) (KeySym /* sym */,KeySym * /* lower */,KeySym * /* upper */);
typedef int (*PFNXPENDING) (Display* a);
@ -63,6 +95,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#define X11_LIBRARY "libX11.so.6"
#define MyXSync m_data->m_x11_XSync
#define MyXGetKeyboardMapping m_data->m_x11_XGetKeyboardMapping
#define MyXSetErrorHandler m_data->m_x11_XSetErrorHandler
#define MyXOpenDisplay m_data->m_x11_XOpenDisplay
#define MyXCreateColormap m_data->m_x11_XCreateColormap
@ -70,6 +103,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#define MyXMapWindow m_data->m_x11_XMapWindow
#define MyXStoreName m_data->m_x11_XStoreName
#define MyXDestroyWindow m_data->m_x11_XDestroyWindow
#define MyXRaiseWindow m_data->m_x11_XRaiseWindow
#define MyXCloseDisplay m_data->m_x11_XCloseDisplay
#define MyXKeycodeToKeysym m_data->m_x11_XKeycodeToKeysym
#define MyXConvertCase m_data->m_x11_XConvertCase
@ -87,6 +121,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#else
#define MyXSync XSync
#define MyXGetKeyboardMapping XGetKeyboardMapping
#define MyXSetErrorHandler XSetErrorHandler
#define MyXOpenDisplay XOpenDisplay
#define MyXCreateColormap XCreateColormap
@ -94,6 +129,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#define MyXMapWindow XMapWindow
#define MyXStoreName XStoreName
#define MyXDestroyWindow XDestroyWindow
#define MyXRaiseWindow XRaiseWindow
#define MyXCloseDisplay XCloseDisplay
#define MyXKeycodeToKeysym XKeycodeToKeysym
#define MyXConvertCase XConvertCase
@ -136,7 +172,9 @@ struct InternalData2
PFNXSTORENAME m_x11_XStoreName;
PFNXCLOSEDISPLAY m_x11_XCloseDisplay;
PFNXDESTROYWINDOW m_x11_XDestroyWindow;
PFNXRAISEWINDOW m_x11_XRaiseWindow;
PFNXKEYCODETOKEYSYM m_x11_XKeycodeToKeysym;
PFNXGETKEYBOARDMAPPING m_x11_XGetKeyboardMapping;
PFNXCONVERTCASE m_x11_XConvertCase;
PFNXPENDING m_x11_XPending;
PFNXNEXTEVENT m_x11_XNextEvent;
@ -190,13 +228,15 @@ struct InternalData2
if (missingFunc) { printf("Error: missing func XMapWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XStoreName = (PFNXSTORENAME) dlsym(m_x11_library,"XStoreName"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XStoreName in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XCloseDisplay = (PFNXCLOSEDISPLAY) dlsym(m_x11_library,"XCloseDisplay"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XCloseDisplay in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XDestroyWindow = (PFNXDESTROYWINDOW) dlsym(m_x11_library,"XDestroyWindow"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XMapWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
if (missingFunc) { printf("Error: missing func XDestroyWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XRaiseWindow = (PFNXRAISEWINDOW) dlsym(m_x11_library,"XRaiseWindow"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XRaiseWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XGetKeyboardMapping = (PFNXGETKEYBOARDMAPPING) dlsym(m_x11_library,"XGetKeyboardMapping"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XGetKeyboardMapping in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XKeycodeToKeysym = (PFNXKEYCODETOKEYSYM) dlsym(m_x11_library,"XKeycodeToKeysym"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XKeycodeToKeysym in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XConvertCase = (PFNXCONVERTCASE) dlsym(m_x11_library,"XConvertCase"))==NULL) | missingFunc;
@ -612,9 +652,21 @@ void X11OpenGLWindow::closeWindow()
int X11OpenGLWindow::getAsciiCodeFromVirtualKeycode(int keycode)
{
int result = 0;
KeySym key, key_lc, key_uc;
key = MyXKeycodeToKeysym( m_data->m_dpy, keycode, 0 );
int keysyms_per_keycode_return;
KeySym *keysym = MyXGetKeyboardMapping(m_data->m_dpy,
keycode,
1,
&keysyms_per_keycode_return);
key = keysym[0];
//key = MyXKeycodeToKeysym( m_data->m_dpy, keycode, 0 );
switch( key )
{
case XK_Escape: return B3G_ESCAPE;
@ -660,9 +712,12 @@ int X11OpenGLWindow::getAsciiCodeFromVirtualKeycode(int keycode)
{
return (int) key;
}
return -1;
result = -1;
}
return 0;
MyXFree(keysym);
return result;
}
void X11OpenGLWindow::pumpMessage()
@ -913,4 +968,29 @@ b3KeyboardCallback X11OpenGLWindow::getKeyboardCallback()
{
return m_data->m_keyboardCallback;
}
#include <stdio.h>
int X11OpenGLWindow::fileOpenDialog(char* filename, int maxNameLength)
{
int len = 0;
FILE * output = popen("zenity --file-selection --file-filter=\"*.urdf\" --file-filter=\"*.*\"","r");
if (output)
{
while( fgets(filename, maxNameLength-1, output) != NULL )
{
len=strlen(filename);
if (len>0)
{
filename[len-1]=0;
printf("file open (length=%d) = %s\n", len,filename);
}
}
pclose(output);
} else
{
printf("Error: fileOpenDialog no popen output, perhaps install zenity?\n");
}
MyXRaiseWindow(m_data->m_dpy, m_data->m_win);
return len;
}

View File

@ -59,6 +59,7 @@ public:
virtual void setWindowTitle(const char* title);
int fileOpenDialog(char* filename, int maxNameLength);
};

View File

@ -110,6 +110,8 @@ class b3gWindowInterface
virtual float getRetinaScale() const =0;
virtual int fileOpenDialog(char* fileName, int maxFileNameLength) = 0;
};
#endif //B3G_WINDOW_INTERFACE_H

View File

@ -5,8 +5,14 @@
--flags {}
defines { "LUA_COMPAT_ALL"}
if os.is("Linux") then
defines {"LUA_USE_LINUX"}
end
if os.is("MacOSX") then
defines {"LUA_USE_MACOSX"}
end
targetdir "../../lib"
includedirs {
@ -18,4 +24,4 @@
}
include "lua_compiler"
include "lua_standalone"
include "lua_standalone"

View File

@ -115,6 +115,7 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
#if defined(LUA_USE_DLOPEN)
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.

View File

@ -42,8 +42,8 @@
#if defined(LUA_USE_LINUX)
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
#define LUA_USE_READLINE /* needs some extra libraries */
//#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
//#define LUA_USE_READLINE /* needs some extra libraries */
#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#define LUA_USE_LONGLONG /* assume support for long long */
@ -51,8 +51,8 @@
#if defined(LUA_USE_MACOSX)
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* does not need -ldl */
#define LUA_USE_READLINE /* needs an extra library: -lreadline */
//#define LUA_USE_DLOPEN /* does not need -ldl */
//#define LUA_USE_READLINE /* needs an extra library: -lreadline */
#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#define LUA_USE_LONGLONG /* assume support for long long */

View File

@ -26,6 +26,8 @@
http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
Encryption is not supported.
*/
#define NOCRYPT
#define NOUNCRYPT
#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))

View File

@ -116,6 +116,7 @@ my_shared_ptr<ModelInterface> parseURDF(const std::string &xml_string)
{
my_shared_ptr<Link> link;
link.reset(new Link);
model->m_numLinks++;
try {
parseLink(*link, link_xml);
@ -176,6 +177,7 @@ my_shared_ptr<ModelInterface> parseURDF(const std::string &xml_string)
{
my_shared_ptr<Joint> joint;
joint.reset(new Joint);
model->m_numJoints++;
if (parseJoint(*joint, joint_xml))
{

View File

@ -223,6 +223,8 @@ public:
std::vector<my_shared_ptr<Joint> > child_joints;
std::vector<my_shared_ptr<Link> > child_links;
mutable int m_link_index;
const Link* getParent() const
{return parent_link_;}
@ -242,6 +244,8 @@ public:
this->child_links.clear();
this->collision_array.clear();
this->visual_array.clear();
this->m_link_index=-1;
this->parent_link_ = NULL;
};
private:

View File

@ -41,7 +41,7 @@
#include <map>
//#include <boost/function.hpp>
#include <urdf/urdfdom_headers/urdf_model/include/urdf_model/link.h>
#include <stdio.h> //printf
#include <urdf/urdfdom_headers/urdf_exception/include/urdf_exception/exception.h>
namespace urdf {
@ -82,6 +82,8 @@ public:
void clear()
{
m_numLinks=0;
m_numJoints = 0;
name_.clear();
this->links_.clear();
this->joints_.clear();
@ -132,6 +134,7 @@ public:
this->getLink(child_link_name, child_link);
if (!child_link)
{
printf("Error: child link [%s] of joint [%s] not found\n", child_link_name.c_str(),joint->first.c_str() );
assert(0);
// throw ParseError("child link [" + child_link_name + "] of joint [" + joint->first + "] not found");
}
@ -206,6 +209,8 @@ public:
/// \brief The root is always a link (the parent of the tree describing the robot)
my_shared_ptr<Link> root_link_;
int m_numLinks;//includes parent
int m_numJoints;
};

View File

@ -1,3 +1,4 @@
function findOpenGL()
configuration{}
if os.is("Linux") then
@ -7,6 +8,22 @@
return true
end
function findOpenGL3()
configuration{}
if os.is("MacOSX") then
local osversion = os.getversion()
--Mac OSX 10.9 and above supports OpenGL 3, below doesn't, so ...
if osversion.majorversion > 10 or (osversion.majorversion == 10 and osversion.minorversion >=9) then
return findOpenGL()
else
return false
end
else
return findOpenGL()
end
end
function initOpenGL()
configuration {}
configuration {"Windows"}

View File

@ -1,6 +1,12 @@
solution "0_Bullet3Solution"
local osversion = os.getversion()
print(string.format(" %d.%d.%d (%s)",
osversion.majorversion, osversion.minorversion, osversion.revision,
osversion.description))
-- Multithreaded compiling
if _ACTION == "vs2010" or _ACTION=="vs2008" then
buildoptions { "/MP" }
@ -35,8 +41,8 @@
newoption
{
trigger = "bullet2gpu",
description = "Enable Bullet 2.x GPU using b3GpuDynamicsWorld bridge to Bullet 3.x"
trigger = "bullet2demos",
description = "Compile the Bullet 2 demos (Demo/Extra folder)"
}
newoption
@ -113,13 +119,12 @@
include "../test/TestBullet3OpenCL"
end
if findOpenGL() then
if findOpenGL3() then
include "../Demos3/AllBullet2Demos"
include "../Demos3/GpuDemos"
include"../Demos3/BasicDemoConsole"
include"../Demos3/BasicDemoCustomOpenGL2"
include "../btgui/OpenGLTrueTypeFont"
-- include "../Demos3/CpuDemos"
-- include "../Demos3/Wavefront"
@ -137,6 +142,7 @@ if findOpenGL() then
include "../btgui/GwenOpenGLTest"
end
-- include "../demo/gpudemo"
if _OPTIONS["midi"] then
include "../btgui/MidiTest"
@ -169,7 +175,7 @@ end
-- include "../demo/gpu_initialize"
-- include "../opencl/lds_bank_conflict"
-- include "../opencl/reduce"
include "../btgui/OpenGLTrueTypeFont"
-- include "../btgui/OpenGLTrueTypeFont"
-- include "../btgui/OpenGLWindow"
-- include "../demo/ObjLoader"
-- include "../test/b3DynamicBvhBroadphase"
@ -180,7 +186,10 @@ end
include "../test/enet/client"
end
if _OPTIONS["bullet2gpu"] then
if _OPTIONS["bullet2demos"] then
include "../Extras"
if findOpenGL() then
include "../Demos"
end
end

414
data/r2d2.urdf Normal file
View File

@ -0,0 +1,414 @@
<?xml version="1.0"?>
<robot name="physics">
<link name="base_link">
<visual>
<geometry>
<cylinder length="0.6" radius="0.2"/>
</geometry>
<material name="blue">
<color rgba="0 0 .8 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.6" radius="0.2"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<link name="right_leg">
<visual>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
<material name="white">
<color rgba="1 1 1 1"/>
</material>
</visual>
<collision>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="base_to_right_leg" type="fixed">
<parent link="base_link"/>
<child link="right_leg"/>
<origin xyz="0.22 0 .25"/>
</joint>
<link name="right_base">
<visual>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
<material name="white"/>
</visual>
<collision>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_base_joint" type="fixed">
<parent link="right_leg"/>
<child link="right_base"/>
<origin xyz="0 0 -0.6"/>
</joint>
<link name="right_front_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black">
<color rgba="0 0 0 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_front_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="right_base"/>
<child link="right_front_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<link name="right_back_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black"/>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_back_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="right_base"/>
<child link="right_back_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 -0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<link name="left_leg">
<visual>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
<material name="white"/>
</visual>
<collision>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="base_to_left_leg" type="fixed">
<parent link="base_link"/>
<child link="left_leg"/>
<origin xyz="-0.22 0 .25"/>
</joint>
<link name="left_base">
<visual>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
<material name="white"/>
</visual>
<collision>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_base_joint" type="fixed">
<parent link="left_leg"/>
<child link="left_base"/>
<origin xyz="0 0 -0.6"/>
</joint>
<link name="left_front_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black"/>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_front_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="left_base"/>
<child link="left_front_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<link name="left_back_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black"/>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_back_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="left_base"/>
<child link="left_back_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 -0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<joint name="gripper_extension" type="prismatic">
<parent link="base_link"/>
<child link="gripper_pole"/>
<limit effort="1000.0" lower="-0.38" upper="0" velocity="0.5"/>
<origin rpy="0 0 1.57075" xyz="0 0.19 .2"/>
</joint>
<link name="gripper_pole">
<visual>
<geometry>
<cylinder length="0.2" radius=".01"/>
</geometry>
<origin rpy="0 1.57075 0 " xyz="0.1 0 0"/>
<material name="Gray">
<color rgba=".7 .7 .7 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.2" radius=".01"/>
</geometry>
<origin rpy="0 1.57075 0 " xyz="0.1 0 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_gripper_joint" type="revolute">
<axis xyz="0 0 1"/>
<limit effort="1000.0" lower="0.0" upper="0.548" velocity="0.5"/>
<origin rpy="0 0 0" xyz="0.2 0.01 0"/>
<parent link="gripper_pole"/>
<child link="left_gripper"/>
</joint>
<link name="left_gripper">
<visual>
<origin rpy="0.0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
<origin rpy="0.0 0 0" xyz="0 0 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_tip_joint" type="fixed">
<parent link="left_gripper"/>
<child link="left_tip"/>
</joint>
<link name="left_tip">
<visual>
<origin rpy="0.0 0 0" xyz="0.09137 0.00495 0"/>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
<origin rpy="0.0 0 0" xyz="0.09137 0.00495 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_gripper_joint" type="revolute">
<axis xyz="0 0 -1"/>
<limit effort="1000.0" lower="0.0" upper="0.548" velocity="0.5"/>
<origin rpy="0 0 0" xyz="0.2 -0.01 0"/>
<parent link="gripper_pole"/>
<child link="right_gripper"/>
</joint>
<link name="right_gripper">
<visual>
<origin rpy="-3.1415 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
<origin rpy="-3.1415 0 0" xyz="0 0 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_tip_joint" type="fixed">
<parent link="right_gripper"/>
<child link="right_tip"/>
</joint>
<link name="right_tip">
<visual>
<origin rpy="-3.1415 0 0" xyz="0.09137 0.00495 0"/>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
<origin rpy="-3.1415 0 0" xyz="0.09137 0.00495 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<link name="head">
<visual>
<geometry>
<sphere radius="0.2"/>
</geometry>
<material name="white"/>
</visual>
<collision>
<geometry>
<sphere radius="0.2"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="head_swivel" type="continuous">
<parent link="base_link"/>
<child link="head"/>
<axis xyz="0 0 1"/>
<origin xyz="0 0 0.3"/>
</joint>
<link name="box">
<visual>
<geometry>
<box size=".08 .08 .08"/>
</geometry>
<material name="blue"/>
</visual>
<collision>
<geometry>
<box size=".08 .08 .08"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="tobox" type="fixed">
<parent link="head"/>
<child link="box"/>
<origin xyz="0 0.1414 0.1414"/>
</joint>
</robot>

BIN
data/spider.bullet Normal file

Binary file not shown.

View File

@ -0,0 +1,116 @@
#ifndef B3_FILE_UTILS_H
#define B3_FILE_UTILS_H
#include <stdio.h>
#include "b3Scalar.h"
#include <stddef.h>//ptrdiff_h
struct b3FileUtils
{
b3FileUtils()
{
}
virtual ~b3FileUtils()
{
}
bool findFile(const char* orgFileName, char* relativeFileName, int maxRelativeFileNameMaxLen)
{
FILE* f=0;
f = fopen(orgFileName,"rb");
if (f)
{
//printf("original file found: [%s]\n", orgFileName);
sprintf(relativeFileName,"%s", orgFileName);
fclose(f);
return true;
}
//printf("Trying various directories, relative to current working directory\n");
const char* prefix[]={"./","./data/","../data/","../../data/","../../../data/","../../../../data/"};
int numPrefixes = sizeof(prefix)/sizeof(const char*);
f=0;
bool fileFound = false;
int result = 0;
for (int i=0;!f && i<numPrefixes;i++)
{
#ifdef _WIN32
sprintf_s(relativeFileName,maxRelativeFileNameMaxLen,"%s%s",prefix[i],orgFileName);
#else
sprintf(relativeFileName,"%s%s",prefix[i],orgFileName);
#endif
f = fopen(relativeFileName,"rb");
if (f)
{
fileFound = true;
break;
}
}
if (f)
{
fclose(f);
}
return fileFound;
}
static const char* strip2(const char* name, const char* pattern)
{
size_t const patlen = strlen(pattern);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = name; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
return oriptr;
}
void extractPath(const char* fileName, char* path, int maxPathLength)
{
const char* stripped = strip2(fileName, "/");
stripped = strip2(stripped, "\\");
ptrdiff_t len = stripped-fileName;
b3Assert((len+1)<maxPathLength);
if (len && ((len+1)<maxPathLength))
{
for (int i=0;i<len;i++)
{
path[i] = fileName[i];
}
path[len]=0;
} else
{
b3Assert(maxPathLength>0);
if (maxPathLength>0)
{
path[0] = 0;
}
}
}
/*static const char* strip2(const char* name, const char* pattern)
{
size_t const patlen = strlen(pattern);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = name; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
return oriptr;
}
*/
};
#endif //B3_FILE_UTILS_H

View File

@ -276,8 +276,9 @@ void b3GpuGridBroadphase::calculateOverlappingPairs(int maxPairs)
{
b3AlignedObjectArray<b3Int4> pairsCpu;
m_gpuPairs.copyToHost(pairsCpu);
printf("m_gpuPairs.size()=%d\n",m_gpuPairs.size());
int sz = m_gpuPairs.size();
printf("m_gpuPairs.size()=%d\n",sz);
for (int i=0;i<m_gpuPairs.size();i++)
{
printf("pair %d = %d,%d\n",i,pairsCpu[i].x,pairsCpu[i].y);

View File

@ -782,7 +782,8 @@ cl_program b3OpenCLUtils_compileCLProgramFromString(cl_context clContext, cl_dev
binarySize = ftell( file );
rewind( file );
binary = (char*)malloc(sizeof(char)*binarySize);
fread( binary, sizeof(char), binarySize, file );
int bytesRead;
bytesRead = fread( binary, sizeof(char), binarySize, file );
fclose( file );
m_cpProgram = clCreateProgramWithBinary( clContext, 1,&device, &binarySize, (const unsigned char**)&binary, 0, &status );

View File

@ -74,13 +74,14 @@ bFile::bFile(const char *filename, const char headerString[7])
fseek(fp, 0L, SEEK_SET);
mFileBuffer = (char*)malloc(mFileLen+1);
fread(mFileBuffer, mFileLen, 1, fp);
int bytesRead;
bytesRead = fread(mFileBuffer, mFileLen, 1, fp);
fclose(fp);
//
parseHeader();
}
}
@ -101,9 +102,9 @@ bFile::bFile( char *memoryBuffer, int len, const char headerString[7])
}
mFileBuffer = memoryBuffer;
mFileLen = len;
parseHeader();
}
@ -210,12 +211,12 @@ void bFile::parseInternal(int verboseMode, char* memDna,int memDnaLength)
// read the DNA1 block and extract SDNA
if (getNextBlock(&dna, tempBuffer, mFlags) > 0)
{
if (strncmp((tempBuffer + ChunkUtils::getOffset(mFlags)), "SDNANAME", 8) ==0)
if (strncmp((tempBuffer + ChunkUtils::getOffset(mFlags)), "SDNANAME", 8) ==0)
dna.oldPtr = (tempBuffer + ChunkUtils::getOffset(mFlags));
else dna.oldPtr = 0;
}
else dna.oldPtr = 0;
}
}
// Some Bullet files are missing the DNA1 block
// In Blender it's DNA1 + ChunkUtils::getOffset() + SDNA + NAME
// In Bullet tests its SDNA + NAME
@ -224,7 +225,7 @@ void bFile::parseInternal(int verboseMode, char* memDna,int memDnaLength)
dna.oldPtr = blenderData + i;
dna.len = mFileLen-i;
// Also no REND block, so exit now.
// Also no REND block, so exit now.
if (mVersion==276) break;
}
@ -240,11 +241,11 @@ void bFile::parseInternal(int verboseMode, char* memDna,int memDnaLength)
mFileDNA = new bDNA();
///mFileDNA->init will convert part of DNA file endianness to current CPU endianness if necessary
mFileDNA->init((char*)dna.oldPtr, dna.len, (mFlags & FD_ENDIAN_SWAP)!=0);
if (mVersion==276)
{
@ -270,10 +271,10 @@ void bFile::parseInternal(int verboseMode, char* memDna,int memDnaLength)
mMemoryDNA = new bDNA();
int littleEndian= 1;
littleEndian= ((char*)&littleEndian)[0];
mMemoryDNA->init(memDna,memDnaLength,littleEndian==0);
///@todo we need a better version check, add version/sub version info from FileGlobal into memory DNA/header files
@ -289,16 +290,16 @@ void bFile::parseInternal(int verboseMode, char* memDna,int memDnaLength)
//printf ("Warning, file DNA is newer than built in.");
}
mFileDNA->initCmpFlags(mMemoryDNA);
parseData();
resolvePointers(verboseMode);
updateOldPointers();
}
@ -309,8 +310,8 @@ void bFile::swap(char *head, bChunkInd& dataChunk, bool ignoreEndianFlag)
char *data = head;
short *strc = mFileDNA->getStruct(dataChunk.dna_nr);
const char s[] = "SoftBodyMaterialData";
int szs = sizeof(s);
if (strncmp((char*)&dataChunk.code,"ARAY",4)==0)
@ -322,7 +323,7 @@ void bFile::swap(char *head, bChunkInd& dataChunk, bool ignoreEndianFlag)
return;
}
}
int len = mFileDNA->getLength(strc[0]);
@ -410,11 +411,11 @@ void bFile::swapDNA(char* ptr)
// Parse names
if (swap)
if (swap)
dataLen = ChunkUtils::swapInt(*intPtr);
else
else
dataLen = *intPtr;
*intPtr = ChunkUtils::swapInt(*intPtr);
intPtr++;
@ -426,7 +427,7 @@ void bFile::swapDNA(char* ptr)
cp++;
}
{
nr= (long)cp;
//long mask=3;
@ -448,9 +449,9 @@ void bFile::swapDNA(char* ptr)
intPtr = (int*)cp;
assert(strncmp(cp, "TYPE", 4)==0); intPtr++;
if (swap)
if (swap)
dataLen = ChunkUtils::swapInt(*intPtr);
else
else
dataLen = *intPtr;
*intPtr = ChunkUtils::swapInt(*intPtr);
@ -485,7 +486,7 @@ void bFile::swapDNA(char* ptr)
intPtr = (int*)cp;
assert(strncmp(cp, "TLEN", 4)==0); intPtr++;
shtPtr = (short*)intPtr;
for ( i=0; i<dataLen; i++, shtPtr++)
{
@ -493,7 +494,7 @@ void bFile::swapDNA(char* ptr)
shtPtr[0] = ChunkUtils::swapShort(shtPtr[0]);
}
if (dataLen & 1)
if (dataLen & 1)
shtPtr++;
/*
@ -509,12 +510,12 @@ void bFile::swapDNA(char* ptr)
intPtr = (int*)shtPtr;
cp = (char*)intPtr;
assert(strncmp(cp, "STRC", 4)==0);
assert(strncmp(cp, "STRC", 4)==0);
intPtr++;
if (swap)
if (swap)
dataLen = ChunkUtils::swapInt(*intPtr);
else
else
dataLen = *intPtr;
*intPtr = ChunkUtils::swapInt(*intPtr);
@ -525,7 +526,7 @@ void bFile::swapDNA(char* ptr)
shtPtr = (short*)intPtr;
for ( i=0; i<dataLen; i++)
{
//if (swap)
{
int len = shtPtr[1];
@ -573,11 +574,11 @@ void bFile::preSwap()
mFileBuffer[8]='V';
}
mDataStart = 12;
char *dataPtr = mFileBuffer+mDataStart;
@ -595,7 +596,7 @@ void bFile::preSwap()
while (1)
{
// one behind
if (dataChunk.code == B3_SDNA || dataChunk.code==B3_DNA1 || dataChunk.code == B3_TYPE || dataChunk.code == B3_TLEN || dataChunk.code==B3_STRC)
if (dataChunk.code == B3_SDNA || dataChunk.code==B3_DNA1 || dataChunk.code == B3_TYPE || dataChunk.code == B3_TLEN || dataChunk.code==B3_STRC)
{
swapDNA(dataPtr);
@ -604,7 +605,7 @@ void bFile::preSwap()
{
//if (dataChunk.code == DNA1) break;
dataPtrHead = dataPtr+ChunkUtils::getOffset(mFlags);
swapLen(dataPtr);
if (dataChunk.dna_nr>=0)
{
@ -632,7 +633,7 @@ void bFile::preSwap()
}
}
@ -644,7 +645,7 @@ char* bFile::readStruct(char *head, bChunkInd& dataChunk)
if (mFlags & FD_ENDIAN_SWAP)
swap(head, dataChunk, ignoreEndianFlag);
if (!mFileDNA->flagEqual(dataChunk.dna_nr))
{
@ -656,7 +657,7 @@ char* bFile::readStruct(char *head, bChunkInd& dataChunk)
oldStruct = mFileDNA->getStruct(dataChunk.dna_nr);
oldType = mFileDNA->getType(oldStruct[0]);
oldLen = mFileDNA->getLength(oldStruct[0]);
if ((mFlags&FD_BROKEN_DNA)!=0)
@ -951,7 +952,7 @@ void bFile::safeSwapPtr(char *dst, const char *src)
B3_SWITCH_LONGINT(longValue);
*((int*)dst) = (int)(longValue>>3);
}
}
else if (ptrMem==8 && ptrFile==4)
{
@ -991,7 +992,7 @@ void bFile::getMatchingFileDNA(short* dna_addr, const char* lookupName, const c
const char* type = mFileDNA->getType(dna_addr[0]);
const char* name = mFileDNA->getName(dna_addr[1]);
int eleLen = mFileDNA->getElementSize(dna_addr[0], dna_addr[1]);
@ -1008,7 +1009,7 @@ void bFile::getMatchingFileDNA(short* dna_addr, const char* lookupName, const c
//int arrayLenold = mFileDNA->getArraySize((char*)name.c_str());
int arrayLen = mFileDNA->getArraySizeNew(dna_addr[1]);
//assert(arrayLenold == arrayLen);
if (name[0] == '*')
{
// cast pointers
@ -1022,11 +1023,11 @@ void bFile::getMatchingFileDNA(short* dna_addr, const char* lookupName, const c
{
//void **sarray = (void**)strcData;
//void **darray = (void**)data;
char *cpc, *cpo;
cpc = (char*)strcData;
cpo = (char*)data;
for (int a=0; a<arrayLen; a++)
{
safeSwapPtr(cpc, cpo);
@ -1162,7 +1163,7 @@ void bFile::resolvePointersMismatch()
}
}
for (i=0; i<m_pointerPtrFixupArray.size(); i++)
{
char* cur= m_pointerPtrFixupArray.at(i);
@ -1227,7 +1228,7 @@ void bFile::resolvePointersChunk(const bChunkInd& dataChunk, int verboseMode)
int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verboseMode,int recursion)
{
bParse::bDNA* fileDna = mFileDNA ? mFileDNA : mMemoryDNA;
char* memType;
@ -1238,7 +1239,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
char* elemPtr= strcPtr;
short int* oldStruct = fileDna->getStruct(dna_nr);
int elementLength = oldStruct[1];
oldStruct+=2;
@ -1249,8 +1250,8 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
memType = fileDna->getType(oldStruct[0]);
memName = fileDna->getName(oldStruct[1]);
int arrayLen = fileDna->getArraySizeNew(oldStruct[1]);
if (memName[0] == '*')
@ -1268,7 +1269,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
}
//skip the *
printf("<%s type=\"pointer\"> ",&memName[1]);
printf("%d ", array[a]);
printf("%p ", array[a]);
printf("</%s>\n",&memName[1]);
}
@ -1286,7 +1287,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
printf(" ");
}
printf("<%s type=\"pointer\"> ",&memName[1]);
printf("%d ", ptr);
printf("%p ", ptr);
printf("</%s>\n",&memName[1]);
}
ptr = findLibPointer(ptr);
@ -1316,7 +1317,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
} else
{
int revType = fileDna->getReverseType(oldStruct[0]);
if (oldStruct[0]>=firstStructType) //revType != -1 &&
if (oldStruct[0]>=firstStructType) //revType != -1 &&
{
char cleanName[MAX_STRLEN];
getCleanName(memName,cleanName);
@ -1421,7 +1422,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
}
}
}
}
}
}
@ -1429,7 +1430,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
int size = fileDna->getElementSize(oldStruct[0], oldStruct[1]);
totalSize += size;
elemPtr+=size;
}
return totalSize;
@ -1445,9 +1446,9 @@ void bFile::resolvePointers(int verboseMode)
if (1) //mFlags & (FD_BITS_VARIES | FD_VERSION_VARIES))
{
resolvePointersMismatch();
resolvePointersMismatch();
}
{
if (verboseMode & FD_VERBOSE_EXPORT_XML)
@ -1465,9 +1466,9 @@ void bFile::resolvePointers(int verboseMode)
//dataChunk.len
short int* oldStruct = fileDna->getStruct(dataChunk.dna_nr);
char* oldType = fileDna->getType(oldStruct[0]);
if (verboseMode & FD_VERBOSE_EXPORT_XML)
printf(" <%s pointer=%d>\n",oldType,dataChunk.oldPtr);
printf(" <%s pointer=%p>\n",oldType,dataChunk.oldPtr);
resolvePointersChunk(dataChunk, verboseMode);
@ -1483,8 +1484,8 @@ void bFile::resolvePointers(int verboseMode)
printf("</bullet_physics>\n");
}
}
}
@ -1518,13 +1519,13 @@ void bFile::dumpChunks(bParse::bDNA* dna)
bChunkInd& dataChunk = m_chunks[i];
char* codeptr = (char*)&dataChunk.code;
char codestr[5] = {codeptr[0],codeptr[1],codeptr[2],codeptr[3],0};
short* newStruct = dna->getStruct(dataChunk.dna_nr);
char* typeName = dna->getType(newStruct[0]);
printf("%3d: %s ",i,typeName);
printf("code=%s ",codestr);
printf("ptr=%p ",dataChunk.oldPtr);
printf("len=%d ",dataChunk.len);
printf("nr=%d ",dataChunk.nr);
@ -1534,8 +1535,8 @@ void bFile::dumpChunks(bParse::bDNA* dna)
}
printf("\n");
}
@ -1544,7 +1545,7 @@ void bFile::dumpChunks(bParse::bDNA* dna)
ifd.success = 0;
ifd.IDname = NULL;
ifd.just_print_it = 1;
for (i=0; i<bf->m_blocks.size(); ++i)
for (i=0; i<bf->m_blocks.size(); ++i)
{
BlendBlock* bb = bf->m_blocks[i];
printf("tag='%s'\tptr=%p\ttype=%s\t[%4d]", bb->tag, bb,bf->types[bb->type_index].name,bb->m_array_entries_.size());
@ -1563,7 +1564,7 @@ void bFile::writeChunks(FILE* fp, bool fixupPointers)
for (int i=0;i<m_chunks.size();i++)
{
bChunkInd& dataChunk = m_chunks.at(i);
// Ouch! need to rebuild the struct
short *oldStruct,*curStruct;
char *oldType, *newType;
@ -1574,7 +1575,7 @@ void bFile::writeChunks(FILE* fp, bool fixupPointers)
oldLen = fileDna->getLength(oldStruct[0]);
///don't try to convert Link block data, just memcpy it. Other data can be converted.
reverseOld = mMemoryDNA->getReverseType(oldType);
if ((reverseOld!=-1))
{
@ -1586,7 +1587,7 @@ void bFile::writeChunks(FILE* fp, bool fixupPointers)
// make sure it's the same
assert((strcmp(oldType, newType)==0) && "internal error, struct mismatch!");
curLen = mMemoryDNA->getLength(curStruct[0]);
dataChunk.dna_nr = reverseOld;
if (strcmp("Link",oldType)!=0)
@ -1596,10 +1597,10 @@ void bFile::writeChunks(FILE* fp, bool fixupPointers)
{
// printf("keep length of link = %d\n",dataChunk.len);
}
//write the structure header
fwrite(&dataChunk,sizeof(bChunkInd),1,fp);
short int* curStruct1;
@ -1615,7 +1616,7 @@ void bFile::writeChunks(FILE* fp, bool fixupPointers)
printf("serious error, struct mismatch: don't write\n");
}
}
}
@ -1625,9 +1626,9 @@ int bFile::getNextBlock(bChunkInd *dataChunk, const char *dataPtr, const int fl
bool swap = false;
bool varies = false;
if (flags &FD_ENDIAN_SWAP)
if (flags &FD_ENDIAN_SWAP)
swap = true;
if (flags &FD_BITS_VARIES)
if (flags &FD_BITS_VARIES)
varies = true;
if (VOID_IS_8)
@ -1697,11 +1698,11 @@ int bFile::getNextBlock(bChunkInd *dataChunk, const char *dataPtr, const int fl
{
b3Long64 oldPtr =0;
memcpy(&oldPtr, &head.m_uniqueInts[0], 8);
if (swap)
if (swap)
B3_SWITCH_LONGINT(oldPtr);
chunk.m_uniqueInt = (int)(oldPtr >> 3);
}
chunk.dna_nr = head.dna_nr;
chunk.nr = head.nr;

View File

@ -38,8 +38,9 @@ static DBVT_INLINE btDbvtVolume merge( const btDbvtVolume& a,
const btDbvtVolume& b)
{
#if (DBVT_MERGE_IMPL==DBVT_IMPL_SSE)
ATTRIBUTE_ALIGNED16(char locals[sizeof(btDbvtAabbMm)]);
btDbvtVolume& res=*(btDbvtVolume*)locals;
ATTRIBUTE_ALIGNED16( char locals[sizeof(btDbvtAabbMm)]);
btDbvtVolume* ptr = (btDbvtVolume*) locals;
btDbvtVolume& res=*ptr;
#else
btDbvtVolume res;
#endif
@ -250,7 +251,8 @@ static btDbvtVolume bounds( const tNodeArray& leaves)
{
#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
ATTRIBUTE_ALIGNED16(char locals[sizeof(btDbvtVolume)]);
btDbvtVolume& volume=*(btDbvtVolume*)locals;
btDbvtVolume* ptr = (btDbvtVolume*) locals;
btDbvtVolume& volume=*ptr;
volume=leaves[0]->volume;
#else
btDbvtVolume volume=leaves[0]->volume;

View File

@ -4,8 +4,8 @@ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
@ -31,11 +31,11 @@ btCollisionObject::btCollisionObject()
m_activationState1(1),
m_deactivationTime(btScalar(0.)),
m_friction(btScalar(0.5)),
m_rollingFriction(0.0f),
m_restitution(btScalar(0.)),
m_rollingFriction(0.0f),
m_internalType(CO_COLLISION_OBJECT),
m_userObjectPointer(0),
m_userIndex(-1),
m_userIndex(-1),
m_hitFraction(btScalar(1.)),
m_ccdSweptSphereRadius(btScalar(0.)),
m_ccdMotionThreshold(btScalar(0.)),

View File

@ -1,43 +1,43 @@
#ifndef BT_COLLISION_OBJECT_WRAPPER_H
#define BT_COLLISION_OBJECT_WRAPPER_H
///btCollisionObjectWrapperis an internal data structure.
///Most users can ignore this and use btCollisionObject and btCollisionShape instead
class btCollisionShape;
class btCollisionObject;
class btTransform;
#include "LinearMath/btScalar.h" // for SIMD_FORCE_INLINE definition
#define BT_DECLARE_STACK_ONLY_OBJECT \
private: \
void* operator new(size_t size); \
void operator delete(void*);
struct btCollisionObjectWrapper;
struct btCollisionObjectWrapper
{
BT_DECLARE_STACK_ONLY_OBJECT
private:
btCollisionObjectWrapper(const btCollisionObjectWrapper&); // not implemented. Not allowed.
btCollisionObjectWrapper* operator=(const btCollisionObjectWrapper&);
public:
const btCollisionObjectWrapper* m_parent;
const btCollisionShape* m_shape;
const btCollisionObject* m_collisionObject;
const btTransform& m_worldTransform;
int m_partId;
int m_index;
btCollisionObjectWrapper(const btCollisionObjectWrapper* parent, const btCollisionShape* shape, const btCollisionObject* collisionObject, const btTransform& worldTransform, int partId, int index)
: m_parent(parent), m_shape(shape), m_collisionObject(collisionObject), m_worldTransform(worldTransform),
m_partId(partId), m_index(index)
{}
SIMD_FORCE_INLINE const btTransform& getWorldTransform() const { return m_worldTransform; }
SIMD_FORCE_INLINE const btCollisionObject* getCollisionObject() const { return m_collisionObject; }
SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const { return m_shape; }
};
#endif //BT_COLLISION_OBJECT_WRAPPER_H
#ifndef BT_COLLISION_OBJECT_WRAPPER_H
#define BT_COLLISION_OBJECT_WRAPPER_H
///btCollisionObjectWrapperis an internal data structure.
///Most users can ignore this and use btCollisionObject and btCollisionShape instead
class btCollisionShape;
class btCollisionObject;
class btTransform;
#include "LinearMath/btScalar.h" // for SIMD_FORCE_INLINE definition
#define BT_DECLARE_STACK_ONLY_OBJECT \
private: \
void* operator new(size_t size); \
void operator delete(void*);
struct btCollisionObjectWrapper;
struct btCollisionObjectWrapper
{
BT_DECLARE_STACK_ONLY_OBJECT
private:
btCollisionObjectWrapper(const btCollisionObjectWrapper&); // not implemented. Not allowed.
btCollisionObjectWrapper* operator=(const btCollisionObjectWrapper&);
public:
const btCollisionObjectWrapper* m_parent;
const btCollisionShape* m_shape;
const btCollisionObject* m_collisionObject;
const btTransform& m_worldTransform;
int m_partId;
int m_index;
btCollisionObjectWrapper(const btCollisionObjectWrapper* parent, const btCollisionShape* shape, const btCollisionObject* collisionObject, const btTransform& worldTransform, int partId, int index)
: m_parent(parent), m_shape(shape), m_collisionObject(collisionObject), m_worldTransform(worldTransform),
m_partId(partId), m_index(index)
{}
SIMD_FORCE_INLINE const btTransform& getWorldTransform() const { return m_worldTransform; }
SIMD_FORCE_INLINE const btCollisionObject* getCollisionObject() const { return m_collisionObject; }
SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const { return m_shape; }
};
#endif //BT_COLLISION_OBJECT_WRAPPER_H

View File

@ -292,7 +292,7 @@ void btCollisionWorld::rayTestSingleInternal(const btTransform& rayFromTrans,con
btGjkConvexCast gjkConvexCaster(castShape,convexShape,&simplexSolver);
//btContinuousConvexCollision convexCaster(castShape,convexShape,&simplexSolver,0);
bool condition = true;
btConvexCast* convexCasterPtr = 0;
//use kF_UseSubSimplexConvexCastRaytest by default
if (resultCallback.m_flags & btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest)
@ -1245,7 +1245,10 @@ public:
void btCollisionWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color)
{
// Draw a small simplex at the center of the object
getDebugDrawer()->drawTransform(worldTransform,1);
if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawFrames)
{
getDebugDrawer()->drawTransform(worldTransform,1);
}
if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
{

View File

@ -123,7 +123,7 @@ public:
//backup
btTransform orgTrans = m_compoundColObjWrap->getWorldTransform();
btTransform orgInterpolationTrans = m_compoundColObjWrap->getWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(index);
btTransform newChildWorldTrans = orgTrans*childTrans ;
@ -294,7 +294,7 @@ void btCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrap
btManifoldArray manifoldArray;
const btCollisionShape* childShape = 0;
btTransform orgTrans;
btTransform orgInterpolationTrans;
btTransform newChildWorldTrans;
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
@ -304,8 +304,8 @@ void btCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrap
{
childShape = compoundShape->getChildShape(i);
//if not longer overlapping, remove the algorithm
orgTrans = colObjWrap->getWorldTransform();
orgInterpolationTrans = colObjWrap->getWorldTransform();
orgTrans = colObjWrap->getWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(i);
newChildWorldTrans = orgTrans*childTrans ;

View File

@ -1,427 +1,426 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btCompoundCompoundCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btCompoundShape.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btAabbUtil2.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
btShapePairCallback gCompoundCompoundChildShapePairCallback = 0;
btCompoundCompoundCollisionAlgorithm::btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped)
:btCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,isSwapped)
{
void* ptr = btAlignedAlloc(sizeof(btHashedSimplePairCache),16);
m_childCollisionAlgorithmCache= new(ptr) btHashedSimplePairCache();
const btCollisionObjectWrapper* col0ObjWrap = body0Wrap;
btAssert (col0ObjWrap->getCollisionShape()->isCompound());
const btCollisionObjectWrapper* col1ObjWrap = body1Wrap;
btAssert (col1ObjWrap->getCollisionShape()->isCompound());
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape());
m_compoundShapeRevision0 = compoundShape0->getUpdateRevision();
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape());
m_compoundShapeRevision1 = compoundShape1->getUpdateRevision();
}
btCompoundCompoundCollisionAlgorithm::~btCompoundCompoundCollisionAlgorithm()
{
removeChildAlgorithms();
m_childCollisionAlgorithmCache->~btHashedSimplePairCache();
btAlignedFree(m_childCollisionAlgorithmCache);
}
void btCompoundCompoundCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray)
{
int i;
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
((btCollisionAlgorithm*)pairs[i].m_userPointer)->getAllContactManifolds(manifoldArray);
}
}
}
void btCompoundCompoundCollisionAlgorithm::removeChildAlgorithms()
{
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
int numChildren = pairs.size();
int i;
for (i=0;i<numChildren;i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer;
algo->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(algo);
}
}
m_childCollisionAlgorithmCache->removeAllPairs();
}
struct btCompoundCompoundLeafCallback : btDbvt::ICollide
{
int m_numOverlapPairs;
const btCollisionObjectWrapper* m_compound0ColObjWrap;
const btCollisionObjectWrapper* m_compound1ColObjWrap;
btDispatcher* m_dispatcher;
const btDispatcherInfo& m_dispatchInfo;
btManifoldResult* m_resultOut;
class btHashedSimplePairCache* m_childCollisionAlgorithmCache;
btPersistentManifold* m_sharedManifold;
btCompoundCompoundLeafCallback (const btCollisionObjectWrapper* compound1ObjWrap,
const btCollisionObjectWrapper* compound0ObjWrap,
btDispatcher* dispatcher,
const btDispatcherInfo& dispatchInfo,
btManifoldResult* resultOut,
btHashedSimplePairCache* childAlgorithmsCache,
btPersistentManifold* sharedManifold)
:m_compound0ColObjWrap(compound1ObjWrap),m_compound1ColObjWrap(compound0ObjWrap),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut),
m_childCollisionAlgorithmCache(childAlgorithmsCache),
m_sharedManifold(sharedManifold),
m_numOverlapPairs(0)
{
}
void Process(const btDbvtNode* leaf0,const btDbvtNode* leaf1)
{
m_numOverlapPairs++;
int childIndex0 = leaf0->dataAsInt;
int childIndex1 = leaf1->dataAsInt;
btAssert(childIndex0>=0);
btAssert(childIndex1>=0);
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(m_compound0ColObjWrap->getCollisionShape());
btAssert(childIndex0<compoundShape0->getNumChildShapes());
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(m_compound1ColObjWrap->getCollisionShape());
btAssert(childIndex1<compoundShape1->getNumChildShapes());
const btCollisionShape* childShape0 = compoundShape0->getChildShape(childIndex0);
const btCollisionShape* childShape1 = compoundShape1->getChildShape(childIndex1);
//backup
btTransform orgTrans0 = m_compound0ColObjWrap->getWorldTransform();
const btTransform& childTrans0 = compoundShape0->getChildTransform(childIndex0);
btTransform newChildWorldTrans0 = orgTrans0*childTrans0 ;
btTransform orgTrans1 = m_compound1ColObjWrap->getWorldTransform();
const btTransform& childTrans1 = compoundShape1->getChildTransform(childIndex1);
btTransform newChildWorldTrans1 = orgTrans1*childTrans1 ;
//perform an AABB check first
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0);
childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1);
if (gCompoundCompoundChildShapePairCallback)
{
if (!gCompoundCompoundChildShapePairCallback(childShape0,childShape1))
return;
}
if (TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
btCollisionObjectWrapper compoundWrap0(this->m_compound0ColObjWrap,childShape0, m_compound0ColObjWrap->getCollisionObject(),newChildWorldTrans0,-1,childIndex0);
btCollisionObjectWrapper compoundWrap1(this->m_compound1ColObjWrap,childShape1,m_compound1ColObjWrap->getCollisionObject(),newChildWorldTrans1,-1,childIndex1);
btSimplePair* pair = m_childCollisionAlgorithmCache->findPair(childIndex0,childIndex1);
btCollisionAlgorithm* colAlgo = 0;
if (pair)
{
colAlgo = (btCollisionAlgorithm*)pair->m_userPointer;
} else
{
colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0,&compoundWrap1,m_sharedManifold);
pair = m_childCollisionAlgorithmCache->addOverlappingPair(childIndex0,childIndex1);
btAssert(pair);
pair->m_userPointer = colAlgo;
}
btAssert(colAlgo);
const btCollisionObjectWrapper* tmpWrap0 = 0;
const btCollisionObjectWrapper* tmpWrap1 = 0;
tmpWrap0 = m_resultOut->getBody0Wrap();
tmpWrap1 = m_resultOut->getBody1Wrap();
m_resultOut->setBody0Wrap(&compoundWrap0);
m_resultOut->setBody1Wrap(&compoundWrap1);
m_resultOut->setShapeIdentifiersA(-1,childIndex0);
m_resultOut->setShapeIdentifiersB(-1,childIndex1);
colAlgo->processCollision(&compoundWrap0,&compoundWrap1,m_dispatchInfo,m_resultOut);
m_resultOut->setBody0Wrap(tmpWrap0);
m_resultOut->setBody1Wrap(tmpWrap1);
}
}
};
static DBVT_INLINE bool MyIntersect( const btDbvtAabbMm& a,
const btDbvtAabbMm& b, const btTransform& xform)
{
btVector3 newmin,newmax;
btTransformAabb(b.Mins(),b.Maxs(),0.f,xform,newmin,newmax);
btDbvtAabbMm newb = btDbvtAabbMm::FromMM(newmin,newmax);
return Intersect(a,newb);
}
static inline void MycollideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
const btTransform& xform,
btCompoundCompoundLeafCallback* callback)
{
if(root0&&root1)
{
int depth=1;
int treshold=btDbvt::DOUBLE_STACKSIZE-4;
btAlignedObjectArray<btDbvt::sStkNN> stkStack;
stkStack.resize(btDbvt::DOUBLE_STACKSIZE);
stkStack[0]=btDbvt::sStkNN(root0,root1);
do {
btDbvt::sStkNN p=stkStack[--depth];
if(MyIntersect(p.a->volume,p.b->volume,xform))
{
if(depth>treshold)
{
stkStack.resize(stkStack.size()*2);
treshold=stkStack.size()-4;
}
if(p.a->isinternal())
{
if(p.b->isinternal())
{
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[1]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[1]);
}
else
{
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b);
}
}
else
{
if(p.b->isinternal())
{
stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[1]);
}
else
{
callback->Process(p.a,p.b);
}
}
}
} while(depth);
}
}
void btCompoundCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
const btCollisionObjectWrapper* col0ObjWrap = body0Wrap;
const btCollisionObjectWrapper* col1ObjWrap= body1Wrap;
btAssert (col0ObjWrap->getCollisionShape()->isCompound());
btAssert (col1ObjWrap->getCollisionShape()->isCompound());
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape());
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape());
const btDbvt* tree0 = compoundShape0->getDynamicAabbTree();
const btDbvt* tree1 = compoundShape1->getDynamicAabbTree();
if (!tree0 || !tree1)
{
return btCompoundCollisionAlgorithm::processCollision(body0Wrap,body1Wrap,dispatchInfo,resultOut);
}
///btCompoundShape might have changed:
////make sure the internal child collision algorithm caches are still valid
if ((compoundShape0->getUpdateRevision() != m_compoundShapeRevision0) || (compoundShape1->getUpdateRevision() != m_compoundShapeRevision1))
{
///clear all
removeChildAlgorithms();
m_compoundShapeRevision0 = compoundShape0->getUpdateRevision();
m_compoundShapeRevision1 = compoundShape1->getUpdateRevision();
}
///we need to refresh all contact manifolds
///note that we should actually recursively traverse all children, btCompoundShape can nested more then 1 level deep
///so we should add a 'refreshManifolds' in the btCollisionAlgorithm
{
int i;
btManifoldArray manifoldArray;
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer;
algo->getAllContactManifolds(manifoldArray);
for (int m=0;m<manifoldArray.size();m++)
{
if (manifoldArray[m]->getNumContacts())
{
resultOut->setPersistentManifold(manifoldArray[m]);
resultOut->refreshContactPoints();
resultOut->setPersistentManifold(0);
}
}
manifoldArray.resize(0);
}
}
}
btCompoundCompoundLeafCallback callback(col0ObjWrap,col1ObjWrap,this->m_dispatcher,dispatchInfo,resultOut,this->m_childCollisionAlgorithmCache,m_sharedManifold);
const btTransform xform=col0ObjWrap->getWorldTransform().inverse()*col1ObjWrap->getWorldTransform();
MycollideTT(tree0->m_root,tree1->m_root,xform,&callback);
//printf("#compound-compound child/leaf overlap =%d \r",callback.m_numOverlapPairs);
//remove non-overlapping child pairs
{
btAssert(m_removePairs.size()==0);
//iterate over all children, perform an AABB check inside ProcessChildShape
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
int i;
btManifoldArray manifoldArray;
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer;
{
btTransform orgTrans0;
const btCollisionShape* childShape0 = 0;
btTransform newChildWorldTrans0;
btTransform orgInterpolationTrans0;
childShape0 = compoundShape0->getChildShape(pairs[i].m_indexA);
orgTrans0 = col0ObjWrap->getWorldTransform();
orgInterpolationTrans0 = col0ObjWrap->getWorldTransform();
const btTransform& childTrans0 = compoundShape0->getChildTransform(pairs[i].m_indexA);
newChildWorldTrans0 = orgTrans0*childTrans0 ;
childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0);
}
{
btTransform orgInterpolationTrans1;
const btCollisionShape* childShape1 = 0;
btTransform orgTrans1;
btTransform newChildWorldTrans1;
childShape1 = compoundShape1->getChildShape(pairs[i].m_indexB);
orgTrans1 = col1ObjWrap->getWorldTransform();
orgInterpolationTrans1 = col1ObjWrap->getWorldTransform();
const btTransform& childTrans1 = compoundShape1->getChildTransform(pairs[i].m_indexB);
newChildWorldTrans1 = orgTrans1*childTrans1 ;
childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1);
}
if (!TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
algo->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(algo);
m_removePairs.push_back(btSimplePair(pairs[i].m_indexA,pairs[i].m_indexB));
}
}
}
for (int i=0;i<m_removePairs.size();i++)
{
m_childCollisionAlgorithmCache->removeOverlappingPair(m_removePairs[i].m_indexA,m_removePairs[i].m_indexB);
}
m_removePairs.clear();
}
}
btScalar btCompoundCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
btAssert(0);
return 0.f;
}
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btCompoundCompoundCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btCompoundShape.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btAabbUtil2.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
btShapePairCallback gCompoundCompoundChildShapePairCallback = 0;
btCompoundCompoundCollisionAlgorithm::btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped)
:btCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,isSwapped)
{
void* ptr = btAlignedAlloc(sizeof(btHashedSimplePairCache),16);
m_childCollisionAlgorithmCache= new(ptr) btHashedSimplePairCache();
const btCollisionObjectWrapper* col0ObjWrap = body0Wrap;
btAssert (col0ObjWrap->getCollisionShape()->isCompound());
const btCollisionObjectWrapper* col1ObjWrap = body1Wrap;
btAssert (col1ObjWrap->getCollisionShape()->isCompound());
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape());
m_compoundShapeRevision0 = compoundShape0->getUpdateRevision();
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape());
m_compoundShapeRevision1 = compoundShape1->getUpdateRevision();
}
btCompoundCompoundCollisionAlgorithm::~btCompoundCompoundCollisionAlgorithm()
{
removeChildAlgorithms();
m_childCollisionAlgorithmCache->~btHashedSimplePairCache();
btAlignedFree(m_childCollisionAlgorithmCache);
}
void btCompoundCompoundCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray)
{
int i;
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
((btCollisionAlgorithm*)pairs[i].m_userPointer)->getAllContactManifolds(manifoldArray);
}
}
}
void btCompoundCompoundCollisionAlgorithm::removeChildAlgorithms()
{
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
int numChildren = pairs.size();
int i;
for (i=0;i<numChildren;i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer;
algo->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(algo);
}
}
m_childCollisionAlgorithmCache->removeAllPairs();
}
struct btCompoundCompoundLeafCallback : btDbvt::ICollide
{
int m_numOverlapPairs;
const btCollisionObjectWrapper* m_compound0ColObjWrap;
const btCollisionObjectWrapper* m_compound1ColObjWrap;
btDispatcher* m_dispatcher;
const btDispatcherInfo& m_dispatchInfo;
btManifoldResult* m_resultOut;
class btHashedSimplePairCache* m_childCollisionAlgorithmCache;
btPersistentManifold* m_sharedManifold;
btCompoundCompoundLeafCallback (const btCollisionObjectWrapper* compound1ObjWrap,
const btCollisionObjectWrapper* compound0ObjWrap,
btDispatcher* dispatcher,
const btDispatcherInfo& dispatchInfo,
btManifoldResult* resultOut,
btHashedSimplePairCache* childAlgorithmsCache,
btPersistentManifold* sharedManifold)
:m_numOverlapPairs(0),m_compound0ColObjWrap(compound1ObjWrap),m_compound1ColObjWrap(compound0ObjWrap),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut),
m_childCollisionAlgorithmCache(childAlgorithmsCache),
m_sharedManifold(sharedManifold)
{
}
void Process(const btDbvtNode* leaf0,const btDbvtNode* leaf1)
{
m_numOverlapPairs++;
int childIndex0 = leaf0->dataAsInt;
int childIndex1 = leaf1->dataAsInt;
btAssert(childIndex0>=0);
btAssert(childIndex1>=0);
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(m_compound0ColObjWrap->getCollisionShape());
btAssert(childIndex0<compoundShape0->getNumChildShapes());
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(m_compound1ColObjWrap->getCollisionShape());
btAssert(childIndex1<compoundShape1->getNumChildShapes());
const btCollisionShape* childShape0 = compoundShape0->getChildShape(childIndex0);
const btCollisionShape* childShape1 = compoundShape1->getChildShape(childIndex1);
//backup
btTransform orgTrans0 = m_compound0ColObjWrap->getWorldTransform();
const btTransform& childTrans0 = compoundShape0->getChildTransform(childIndex0);
btTransform newChildWorldTrans0 = orgTrans0*childTrans0 ;
btTransform orgTrans1 = m_compound1ColObjWrap->getWorldTransform();
const btTransform& childTrans1 = compoundShape1->getChildTransform(childIndex1);
btTransform newChildWorldTrans1 = orgTrans1*childTrans1 ;
//perform an AABB check first
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0);
childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1);
if (gCompoundCompoundChildShapePairCallback)
{
if (!gCompoundCompoundChildShapePairCallback(childShape0,childShape1))
return;
}
if (TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
btCollisionObjectWrapper compoundWrap0(this->m_compound0ColObjWrap,childShape0, m_compound0ColObjWrap->getCollisionObject(),newChildWorldTrans0,-1,childIndex0);
btCollisionObjectWrapper compoundWrap1(this->m_compound1ColObjWrap,childShape1,m_compound1ColObjWrap->getCollisionObject(),newChildWorldTrans1,-1,childIndex1);
btSimplePair* pair = m_childCollisionAlgorithmCache->findPair(childIndex0,childIndex1);
btCollisionAlgorithm* colAlgo = 0;
if (pair)
{
colAlgo = (btCollisionAlgorithm*)pair->m_userPointer;
} else
{
colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0,&compoundWrap1,m_sharedManifold);
pair = m_childCollisionAlgorithmCache->addOverlappingPair(childIndex0,childIndex1);
btAssert(pair);
pair->m_userPointer = colAlgo;
}
btAssert(colAlgo);
const btCollisionObjectWrapper* tmpWrap0 = 0;
const btCollisionObjectWrapper* tmpWrap1 = 0;
tmpWrap0 = m_resultOut->getBody0Wrap();
tmpWrap1 = m_resultOut->getBody1Wrap();
m_resultOut->setBody0Wrap(&compoundWrap0);
m_resultOut->setBody1Wrap(&compoundWrap1);
m_resultOut->setShapeIdentifiersA(-1,childIndex0);
m_resultOut->setShapeIdentifiersB(-1,childIndex1);
colAlgo->processCollision(&compoundWrap0,&compoundWrap1,m_dispatchInfo,m_resultOut);
m_resultOut->setBody0Wrap(tmpWrap0);
m_resultOut->setBody1Wrap(tmpWrap1);
}
}
};
static DBVT_INLINE bool MyIntersect( const btDbvtAabbMm& a,
const btDbvtAabbMm& b, const btTransform& xform)
{
btVector3 newmin,newmax;
btTransformAabb(b.Mins(),b.Maxs(),0.f,xform,newmin,newmax);
btDbvtAabbMm newb = btDbvtAabbMm::FromMM(newmin,newmax);
return Intersect(a,newb);
}
static inline void MycollideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
const btTransform& xform,
btCompoundCompoundLeafCallback* callback)
{
if(root0&&root1)
{
int depth=1;
int treshold=btDbvt::DOUBLE_STACKSIZE-4;
btAlignedObjectArray<btDbvt::sStkNN> stkStack;
stkStack.resize(btDbvt::DOUBLE_STACKSIZE);
stkStack[0]=btDbvt::sStkNN(root0,root1);
do {
btDbvt::sStkNN p=stkStack[--depth];
if(MyIntersect(p.a->volume,p.b->volume,xform))
{
if(depth>treshold)
{
stkStack.resize(stkStack.size()*2);
treshold=stkStack.size()-4;
}
if(p.a->isinternal())
{
if(p.b->isinternal())
{
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[1]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[1]);
}
else
{
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b);
}
}
else
{
if(p.b->isinternal())
{
stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[1]);
}
else
{
callback->Process(p.a,p.b);
}
}
}
} while(depth);
}
}
void btCompoundCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
const btCollisionObjectWrapper* col0ObjWrap = body0Wrap;
const btCollisionObjectWrapper* col1ObjWrap= body1Wrap;
btAssert (col0ObjWrap->getCollisionShape()->isCompound());
btAssert (col1ObjWrap->getCollisionShape()->isCompound());
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape());
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape());
const btDbvt* tree0 = compoundShape0->getDynamicAabbTree();
const btDbvt* tree1 = compoundShape1->getDynamicAabbTree();
if (!tree0 || !tree1)
{
return btCompoundCollisionAlgorithm::processCollision(body0Wrap,body1Wrap,dispatchInfo,resultOut);
}
///btCompoundShape might have changed:
////make sure the internal child collision algorithm caches are still valid
if ((compoundShape0->getUpdateRevision() != m_compoundShapeRevision0) || (compoundShape1->getUpdateRevision() != m_compoundShapeRevision1))
{
///clear all
removeChildAlgorithms();
m_compoundShapeRevision0 = compoundShape0->getUpdateRevision();
m_compoundShapeRevision1 = compoundShape1->getUpdateRevision();
}
///we need to refresh all contact manifolds
///note that we should actually recursively traverse all children, btCompoundShape can nested more then 1 level deep
///so we should add a 'refreshManifolds' in the btCollisionAlgorithm
{
int i;
btManifoldArray manifoldArray;
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer;
algo->getAllContactManifolds(manifoldArray);
for (int m=0;m<manifoldArray.size();m++)
{
if (manifoldArray[m]->getNumContacts())
{
resultOut->setPersistentManifold(manifoldArray[m]);
resultOut->refreshContactPoints();
resultOut->setPersistentManifold(0);
}
}
manifoldArray.resize(0);
}
}
}
btCompoundCompoundLeafCallback callback(col0ObjWrap,col1ObjWrap,this->m_dispatcher,dispatchInfo,resultOut,this->m_childCollisionAlgorithmCache,m_sharedManifold);
const btTransform xform=col0ObjWrap->getWorldTransform().inverse()*col1ObjWrap->getWorldTransform();
MycollideTT(tree0->m_root,tree1->m_root,xform,&callback);
//printf("#compound-compound child/leaf overlap =%d \r",callback.m_numOverlapPairs);
//remove non-overlapping child pairs
{
btAssert(m_removePairs.size()==0);
//iterate over all children, perform an AABB check inside ProcessChildShape
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
int i;
btManifoldArray manifoldArray;
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer;
{
btTransform orgTrans0;
const btCollisionShape* childShape0 = 0;
btTransform newChildWorldTrans0;
btTransform orgInterpolationTrans0;
childShape0 = compoundShape0->getChildShape(pairs[i].m_indexA);
orgTrans0 = col0ObjWrap->getWorldTransform();
orgInterpolationTrans0 = col0ObjWrap->getWorldTransform();
const btTransform& childTrans0 = compoundShape0->getChildTransform(pairs[i].m_indexA);
newChildWorldTrans0 = orgTrans0*childTrans0 ;
childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0);
}
{
btTransform orgInterpolationTrans1;
const btCollisionShape* childShape1 = 0;
btTransform orgTrans1;
btTransform newChildWorldTrans1;
childShape1 = compoundShape1->getChildShape(pairs[i].m_indexB);
orgTrans1 = col1ObjWrap->getWorldTransform();
orgInterpolationTrans1 = col1ObjWrap->getWorldTransform();
const btTransform& childTrans1 = compoundShape1->getChildTransform(pairs[i].m_indexB);
newChildWorldTrans1 = orgTrans1*childTrans1 ;
childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1);
}
if (!TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
algo->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(algo);
m_removePairs.push_back(btSimplePair(pairs[i].m_indexA,pairs[i].m_indexB));
}
}
}
for (int i=0;i<m_removePairs.size();i++)
{
m_childCollisionAlgorithmCache->removeOverlappingPair(m_removePairs[i].m_indexA,m_removePairs[i].m_indexB);
}
m_removePairs.clear();
}
}
btScalar btCompoundCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
btAssert(0);
return 0.f;
}

View File

@ -1,89 +1,89 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H
#define BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H
#include "btCompoundCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "BulletCollision/CollisionDispatch/btHashedSimplePairCache.h"
class btDispatcher;
class btCollisionObject;
class btCollisionShape;
typedef bool (*btShapePairCallback)(const btCollisionShape* pShape0, const btCollisionShape* pShape1);
extern btShapePairCallback gCompoundCompoundChildShapePairCallback;
/// btCompoundCompoundCollisionAlgorithm supports collision between two btCompoundCollisionShape shapes
class btCompoundCompoundCollisionAlgorithm : public btCompoundCollisionAlgorithm
{
class btHashedSimplePairCache* m_childCollisionAlgorithmCache;
btSimplePairArray m_removePairs;
int m_compoundShapeRevision0;//to keep track of changes, so that childAlgorithm array can be updated
int m_compoundShapeRevision1;
void removeChildAlgorithms();
// void preallocateChildAlgorithms(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);
public:
btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped);
virtual ~btCompoundCompoundCollisionAlgorithm();
virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
virtual void getAllContactManifolds(btManifoldArray& manifoldArray);
struct CreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCompoundCollisionAlgorithm));
return new(mem) btCompoundCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,false);
}
};
struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCompoundCollisionAlgorithm));
return new(mem) btCompoundCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,true);
}
};
};
#endif //BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H
#define BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H
#include "btCompoundCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "BulletCollision/CollisionDispatch/btHashedSimplePairCache.h"
class btDispatcher;
class btCollisionObject;
class btCollisionShape;
typedef bool (*btShapePairCallback)(const btCollisionShape* pShape0, const btCollisionShape* pShape1);
extern btShapePairCallback gCompoundCompoundChildShapePairCallback;
/// btCompoundCompoundCollisionAlgorithm supports collision between two btCompoundCollisionShape shapes
class btCompoundCompoundCollisionAlgorithm : public btCompoundCollisionAlgorithm
{
class btHashedSimplePairCache* m_childCollisionAlgorithmCache;
btSimplePairArray m_removePairs;
int m_compoundShapeRevision0;//to keep track of changes, so that childAlgorithm array can be updated
int m_compoundShapeRevision1;
void removeChildAlgorithms();
// void preallocateChildAlgorithms(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);
public:
btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped);
virtual ~btCompoundCompoundCollisionAlgorithm();
virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
virtual void getAllContactManifolds(btManifoldArray& manifoldArray);
struct CreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCompoundCollisionAlgorithm));
return new(mem) btCompoundCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,false);
}
};
struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCompoundCollisionAlgorithm));
return new(mem) btCompoundCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,true);
}
};
};
#endif //BT_COMPOUND_COMPOUND_COLLISION_ALGORITHM_H

View File

@ -88,20 +88,19 @@ partId, int triangleIndex)
//just for debugging purposes
//printf("triangle %d",m_triangleCount++);
const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
btCollisionAlgorithmConstructionInfo ci;
ci.m_dispatcher1 = m_dispatcher;
//const btCollisionObject* ob = static_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
#if 0
///debug drawing of the overlapping triangles
if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && (m_dispatchInfoPtr->m_debugDraw->getDebugMode() &btIDebugDraw::DBG_DrawWireframe ))
{
const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
btVector3 color(1,1,0);
btTransform& tr = ob->getWorldTransform();
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color);

View File

@ -105,8 +105,7 @@ btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(const btDefault
int maxSize = sizeof(btConvexConvexAlgorithm);
int maxSize2 = sizeof(btConvexConcaveCollisionAlgorithm);
int maxSize3 = sizeof(btCompoundCollisionAlgorithm);
int sl = sizeof(btConvexSeparatingDistanceUtil);
sl = sizeof(btGjkPairDetector);
int collisionAlgorithmMaxElementSize = btMax(maxSize,constructionInfo.m_customCollisionAlgorithmMaxElementSize);
collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize2);
collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize3);

View File

@ -1,278 +1,278 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btHashedSimplePairCache.h"
#include <stdio.h>
int gOverlappingSimplePairs = 0;
int gRemoveSimplePairs =0;
int gAddedSimplePairs =0;
int gFindSimplePairs =0;
btHashedSimplePairCache::btHashedSimplePairCache():
m_blockedForChanges(false)
{
int initialAllocatedSize= 2;
m_overlappingPairArray.reserve(initialAllocatedSize);
growTables();
}
btHashedSimplePairCache::~btHashedSimplePairCache()
{
}
void btHashedSimplePairCache::removeAllPairs()
{
m_overlappingPairArray.clear();
m_hashTable.clear();
m_next.clear();
int initialAllocatedSize= 2;
m_overlappingPairArray.reserve(initialAllocatedSize);
growTables();
}
btSimplePair* btHashedSimplePairCache::findPair(int indexA, int indexB)
{
gFindSimplePairs++;
/*if (indexA > indexB)
btSwap(indexA, indexB);*/
int hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA), static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1));
if (hash >= m_hashTable.size())
{
return NULL;
}
int index = m_hashTable[hash];
while (index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], indexA, indexB) == false)
{
index = m_next[index];
}
if (index == BT_SIMPLE_NULL_PAIR)
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
//#include <stdio.h>
void btHashedSimplePairCache::growTables()
{
int newCapacity = m_overlappingPairArray.capacity();
if (m_hashTable.size() < newCapacity)
{
//grow hashtable and next table
int curHashtableSize = m_hashTable.size();
m_hashTable.resize(newCapacity);
m_next.resize(newCapacity);
int i;
for (i= 0; i < newCapacity; ++i)
{
m_hashTable[i] = BT_SIMPLE_NULL_PAIR;
}
for (i = 0; i < newCapacity; ++i)
{
m_next[i] = BT_SIMPLE_NULL_PAIR;
}
for(i=0;i<curHashtableSize;i++)
{
const btSimplePair& pair = m_overlappingPairArray[i];
int indexA = pair.m_indexA;
int indexB = pair.m_indexB;
int hashValue = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1)); // New hash value with new mask
m_next[i] = m_hashTable[hashValue];
m_hashTable[hashValue] = i;
}
}
}
btSimplePair* btHashedSimplePairCache::internalAddPair(int indexA, int indexB)
{
int hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1)); // New hash value with new mask
btSimplePair* pair = internalFindPair(indexA, indexB, hash);
if (pair != NULL)
{
return pair;
}
int count = m_overlappingPairArray.size();
int oldCapacity = m_overlappingPairArray.capacity();
void* mem = &m_overlappingPairArray.expandNonInitializing();
int newCapacity = m_overlappingPairArray.capacity();
if (oldCapacity < newCapacity)
{
growTables();
//hash with new capacity
hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1));
}
pair = new (mem) btSimplePair(indexA,indexB);
pair->m_userPointer = 0;
m_next[count] = m_hashTable[hash];
m_hashTable[hash] = count;
return pair;
}
void* btHashedSimplePairCache::removeOverlappingPair(int indexA, int indexB)
{
gRemoveSimplePairs++;
/*if (indexA > indexB)
btSwap(indexA, indexB);*/
int hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1));
btSimplePair* pair = internalFindPair(indexA, indexB, hash);
if (pair == NULL)
{
return 0;
}
void* userData = pair->m_userPointer;
int pairIndex = int(pair - &m_overlappingPairArray[0]);
btAssert(pairIndex < m_overlappingPairArray.size());
// Remove the pair from the hash table.
int index = m_hashTable[hash];
btAssert(index != BT_SIMPLE_NULL_PAIR);
int previous = BT_SIMPLE_NULL_PAIR;
while (index != pairIndex)
{
previous = index;
index = m_next[index];
}
if (previous != BT_SIMPLE_NULL_PAIR)
{
btAssert(m_next[previous] == pairIndex);
m_next[previous] = m_next[pairIndex];
}
else
{
m_hashTable[hash] = m_next[pairIndex];
}
// We now move the last pair into spot of the
// pair being removed. We need to fix the hash
// table indices to support the move.
int lastPairIndex = m_overlappingPairArray.size() - 1;
// If the removed pair is the last pair, we are done.
if (lastPairIndex == pairIndex)
{
m_overlappingPairArray.pop_back();
return userData;
}
// Remove the last pair from the hash table.
const btSimplePair* last = &m_overlappingPairArray[lastPairIndex];
/* missing swap here too, Nat. */
int lastHash = static_cast<int>(getHash(static_cast<unsigned int>(last->m_indexA), static_cast<unsigned int>(last->m_indexB)) & (m_overlappingPairArray.capacity()-1));
index = m_hashTable[lastHash];
btAssert(index != BT_SIMPLE_NULL_PAIR);
previous = BT_SIMPLE_NULL_PAIR;
while (index != lastPairIndex)
{
previous = index;
index = m_next[index];
}
if (previous != BT_SIMPLE_NULL_PAIR)
{
btAssert(m_next[previous] == lastPairIndex);
m_next[previous] = m_next[lastPairIndex];
}
else
{
m_hashTable[lastHash] = m_next[lastPairIndex];
}
// Copy the last pair into the remove pair's spot.
m_overlappingPairArray[pairIndex] = m_overlappingPairArray[lastPairIndex];
// Insert the last pair into the hash table
m_next[pairIndex] = m_hashTable[lastHash];
m_hashTable[lastHash] = pairIndex;
m_overlappingPairArray.pop_back();
return userData;
}
//#include <stdio.h>
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btHashedSimplePairCache.h"
#include <stdio.h>
int gOverlappingSimplePairs = 0;
int gRemoveSimplePairs =0;
int gAddedSimplePairs =0;
int gFindSimplePairs =0;
btHashedSimplePairCache::btHashedSimplePairCache():
m_blockedForChanges(false)
{
int initialAllocatedSize= 2;
m_overlappingPairArray.reserve(initialAllocatedSize);
growTables();
}
btHashedSimplePairCache::~btHashedSimplePairCache()
{
}
void btHashedSimplePairCache::removeAllPairs()
{
m_overlappingPairArray.clear();
m_hashTable.clear();
m_next.clear();
int initialAllocatedSize= 2;
m_overlappingPairArray.reserve(initialAllocatedSize);
growTables();
}
btSimplePair* btHashedSimplePairCache::findPair(int indexA, int indexB)
{
gFindSimplePairs++;
/*if (indexA > indexB)
btSwap(indexA, indexB);*/
int hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA), static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1));
if (hash >= m_hashTable.size())
{
return NULL;
}
int index = m_hashTable[hash];
while (index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], indexA, indexB) == false)
{
index = m_next[index];
}
if (index == BT_SIMPLE_NULL_PAIR)
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
//#include <stdio.h>
void btHashedSimplePairCache::growTables()
{
int newCapacity = m_overlappingPairArray.capacity();
if (m_hashTable.size() < newCapacity)
{
//grow hashtable and next table
int curHashtableSize = m_hashTable.size();
m_hashTable.resize(newCapacity);
m_next.resize(newCapacity);
int i;
for (i= 0; i < newCapacity; ++i)
{
m_hashTable[i] = BT_SIMPLE_NULL_PAIR;
}
for (i = 0; i < newCapacity; ++i)
{
m_next[i] = BT_SIMPLE_NULL_PAIR;
}
for(i=0;i<curHashtableSize;i++)
{
const btSimplePair& pair = m_overlappingPairArray[i];
int indexA = pair.m_indexA;
int indexB = pair.m_indexB;
int hashValue = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1)); // New hash value with new mask
m_next[i] = m_hashTable[hashValue];
m_hashTable[hashValue] = i;
}
}
}
btSimplePair* btHashedSimplePairCache::internalAddPair(int indexA, int indexB)
{
int hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1)); // New hash value with new mask
btSimplePair* pair = internalFindPair(indexA, indexB, hash);
if (pair != NULL)
{
return pair;
}
int count = m_overlappingPairArray.size();
int oldCapacity = m_overlappingPairArray.capacity();
void* mem = &m_overlappingPairArray.expandNonInitializing();
int newCapacity = m_overlappingPairArray.capacity();
if (oldCapacity < newCapacity)
{
growTables();
//hash with new capacity
hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1));
}
pair = new (mem) btSimplePair(indexA,indexB);
pair->m_userPointer = 0;
m_next[count] = m_hashTable[hash];
m_hashTable[hash] = count;
return pair;
}
void* btHashedSimplePairCache::removeOverlappingPair(int indexA, int indexB)
{
gRemoveSimplePairs++;
/*if (indexA > indexB)
btSwap(indexA, indexB);*/
int hash = static_cast<int>(getHash(static_cast<unsigned int>(indexA),static_cast<unsigned int>(indexB)) & (m_overlappingPairArray.capacity()-1));
btSimplePair* pair = internalFindPair(indexA, indexB, hash);
if (pair == NULL)
{
return 0;
}
void* userData = pair->m_userPointer;
int pairIndex = int(pair - &m_overlappingPairArray[0]);
btAssert(pairIndex < m_overlappingPairArray.size());
// Remove the pair from the hash table.
int index = m_hashTable[hash];
btAssert(index != BT_SIMPLE_NULL_PAIR);
int previous = BT_SIMPLE_NULL_PAIR;
while (index != pairIndex)
{
previous = index;
index = m_next[index];
}
if (previous != BT_SIMPLE_NULL_PAIR)
{
btAssert(m_next[previous] == pairIndex);
m_next[previous] = m_next[pairIndex];
}
else
{
m_hashTable[hash] = m_next[pairIndex];
}
// We now move the last pair into spot of the
// pair being removed. We need to fix the hash
// table indices to support the move.
int lastPairIndex = m_overlappingPairArray.size() - 1;
// If the removed pair is the last pair, we are done.
if (lastPairIndex == pairIndex)
{
m_overlappingPairArray.pop_back();
return userData;
}
// Remove the last pair from the hash table.
const btSimplePair* last = &m_overlappingPairArray[lastPairIndex];
/* missing swap here too, Nat. */
int lastHash = static_cast<int>(getHash(static_cast<unsigned int>(last->m_indexA), static_cast<unsigned int>(last->m_indexB)) & (m_overlappingPairArray.capacity()-1));
index = m_hashTable[lastHash];
btAssert(index != BT_SIMPLE_NULL_PAIR);
previous = BT_SIMPLE_NULL_PAIR;
while (index != lastPairIndex)
{
previous = index;
index = m_next[index];
}
if (previous != BT_SIMPLE_NULL_PAIR)
{
btAssert(m_next[previous] == lastPairIndex);
m_next[previous] = m_next[lastPairIndex];
}
else
{
m_hashTable[lastHash] = m_next[lastPairIndex];
}
// Copy the last pair into the remove pair's spot.
m_overlappingPairArray[pairIndex] = m_overlappingPairArray[lastPairIndex];
// Insert the last pair into the hash table
m_next[pairIndex] = m_hashTable[lastHash];
m_hashTable[lastHash] = pairIndex;
m_overlappingPairArray.pop_back();
return userData;
}
//#include <stdio.h>

View File

@ -1,174 +1,174 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_HASHED_SIMPLE_PAIR_CACHE_H
#define BT_HASHED_SIMPLE_PAIR_CACHE_H
#include "LinearMath/btAlignedObjectArray.h"
const int BT_SIMPLE_NULL_PAIR=0xffffffff;
struct btSimplePair
{
btSimplePair(int indexA,int indexB)
:m_indexA(indexA),
m_indexB(indexB),
m_userPointer(0)
{
}
int m_indexA;
int m_indexB;
union
{
void* m_userPointer;
int m_userValue;
};
};
typedef btAlignedObjectArray<btSimplePair> btSimplePairArray;
extern int gOverlappingSimplePairs;
extern int gRemoveSimplePairs;
extern int gAddedSimplePairs;
extern int gFindSimplePairs;
class btHashedSimplePairCache
{
btSimplePairArray m_overlappingPairArray;
bool m_blockedForChanges;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
public:
btHashedSimplePairCache();
virtual ~btHashedSimplePairCache();
void removeAllPairs();
virtual void* removeOverlappingPair(int indexA,int indexB);
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btSimplePair* addOverlappingPair(int indexA,int indexB)
{
gAddedSimplePairs++;
return internalAddPair(indexA,indexB);
}
virtual btSimplePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btSimplePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btSimplePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btSimplePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btSimplePair* findPair(int indexA,int indexB);
int GetCount() const { return m_overlappingPairArray.size(); }
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btSimplePair* internalAddPair(int indexA, int indexB);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btSimplePair& pair, int indexA, int indexB)
{
return pair.m_indexA == indexA && pair.m_indexB == indexB;
}
SIMD_FORCE_INLINE unsigned int getHash(unsigned int indexA, unsigned int indexB)
{
int key = static_cast<int>(((unsigned int)indexA) | (((unsigned int)indexB) <<16));
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return static_cast<unsigned int>(key);
}
SIMD_FORCE_INLINE btSimplePair* internalFindPair(int proxyIdA , int proxyIdB, int hash)
{
int index = m_hashTable[hash];
while( index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyIdA, proxyIdB) == false)
{
index = m_next[index];
}
if ( index == BT_SIMPLE_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
};
#endif //BT_HASHED_SIMPLE_PAIR_CACHE_H
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_HASHED_SIMPLE_PAIR_CACHE_H
#define BT_HASHED_SIMPLE_PAIR_CACHE_H
#include "LinearMath/btAlignedObjectArray.h"
const int BT_SIMPLE_NULL_PAIR=0xffffffff;
struct btSimplePair
{
btSimplePair(int indexA,int indexB)
:m_indexA(indexA),
m_indexB(indexB),
m_userPointer(0)
{
}
int m_indexA;
int m_indexB;
union
{
void* m_userPointer;
int m_userValue;
};
};
typedef btAlignedObjectArray<btSimplePair> btSimplePairArray;
extern int gOverlappingSimplePairs;
extern int gRemoveSimplePairs;
extern int gAddedSimplePairs;
extern int gFindSimplePairs;
class btHashedSimplePairCache
{
btSimplePairArray m_overlappingPairArray;
bool m_blockedForChanges;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
public:
btHashedSimplePairCache();
virtual ~btHashedSimplePairCache();
void removeAllPairs();
virtual void* removeOverlappingPair(int indexA,int indexB);
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btSimplePair* addOverlappingPair(int indexA,int indexB)
{
gAddedSimplePairs++;
return internalAddPair(indexA,indexB);
}
virtual btSimplePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btSimplePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btSimplePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btSimplePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btSimplePair* findPair(int indexA,int indexB);
int GetCount() const { return m_overlappingPairArray.size(); }
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btSimplePair* internalAddPair(int indexA, int indexB);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btSimplePair& pair, int indexA, int indexB)
{
return pair.m_indexA == indexA && pair.m_indexB == indexB;
}
SIMD_FORCE_INLINE unsigned int getHash(unsigned int indexA, unsigned int indexB)
{
int key = static_cast<int>(((unsigned int)indexA) | (((unsigned int)indexB) <<16));
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return static_cast<unsigned int>(key);
}
SIMD_FORCE_INLINE btSimplePair* internalFindPair(int proxyIdA , int proxyIdB, int hash)
{
int index = m_hashTable[hash];
while( index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyIdA, proxyIdB) == false)
{
index = m_next[index];
}
if ( index == BT_SIMPLE_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
};
#endif //BT_HASHED_SIMPLE_PAIR_CACHE_H

View File

@ -114,7 +114,6 @@ struct btConnectivityProcessor : public btTriangleCallback
if(numshared >= 3)
return;
}
switch (numshared)
{
case 0:
@ -203,6 +202,7 @@ struct btConnectivityProcessor : public btTriangleCallback
ang4 = 0.f;
} else
{
calculatedEdge.normalize();
btVector3 calculatedNormalA = calculatedEdge.cross(edgeCrossA);
calculatedNormalA.normalize();
@ -213,7 +213,7 @@ struct btConnectivityProcessor : public btTriangleCallback
isConvex = (dotA<0.);
correctedAngle = isConvex ? ang4 : -ang4;
btQuaternion orn2 = btQuaternion(btVector3(calculatedEdge.x(), calculatedEdge.y(), calculatedEdge.z()),-correctedAngle);
btQuaternion orn2(calculatedEdge,-correctedAngle);
calculatedNormalB = btMatrix3x3(orn2)*normalA;
@ -301,6 +301,11 @@ struct btConnectivityProcessor : public btTriangleCallback
break;
}
default:
{
// printf("warning: duplicate triangle\n");
}
}
}
};

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