Merge remote-tracking branch 'bp/master' into pullRequest

This commit is contained in:
Jie Tan 2017-04-28 14:36:56 -07:00
commit 93fc04c6c3
98 changed files with 37426 additions and 462 deletions

View File

@ -254,7 +254,7 @@ ENDIF()
OPTION(BUILD_BULLET3 "Set when you want to build Bullet 3" ON) OPTION(BUILD_BULLET3 "Set when you want to build Bullet 3" ON)
OPTION(BUILD_PYBULLET "Set when you want to build pybullet (experimental Python bindings for Bullet)" OFF) OPTION(BUILD_PYBULLET "Set when you want to build pybullet (Python bindings for Bullet)" OFF)
OPTION(BUILD_ENET "Set when you want to build apps with enet UDP networking support" ON) OPTION(BUILD_ENET "Set when you want to build apps with enet UDP networking support" ON)
OPTION(BUILD_CLSOCKET "Set when you want to build apps with enet TCP networking support" ON) OPTION(BUILD_CLSOCKET "Set when you want to build apps with enet TCP networking support" ON)
@ -268,6 +268,8 @@ IF(BUILD_PYBULLET)
OPTION(BUILD_PYBULLET_ENET "Set when you want to build pybullet with enet UDP networking support" ON) OPTION(BUILD_PYBULLET_ENET "Set when you want to build pybullet with enet UDP networking support" ON)
OPTION(BUILD_PYBULLET_CLSOCKET "Set when you want to build pybullet with enet TCP networking support" ON) OPTION(BUILD_PYBULLET_CLSOCKET "Set when you want to build pybullet with enet TCP networking support" ON)
OPTION(BUILD_PYBULLET_MAC_USE_PYTHON_FRAMEWORK "Set when you want to use the Python Framework on Mac" ON)
IF(BUILD_PYBULLET_NUMPY) IF(BUILD_PYBULLET_NUMPY)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_LIST_DIR}/build3/cmake) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_LIST_DIR}/build3/cmake)
#include(FindNumPy) #include(FindNumPy)
@ -286,6 +288,19 @@ IF(BUILD_PYBULLET)
ELSE(WIN32) ELSE(WIN32)
SET(BUILD_SHARED_LIBS ON CACHE BOOL "Shared Libs" FORCE) SET(BUILD_SHARED_LIBS ON CACHE BOOL "Shared Libs" FORCE)
ENDIF(WIN32) ENDIF(WIN32)
IF(APPLE)
OPTION(BUILD_PYBULLET_MAC_USE_PYTHON_FRAMEWORK "Set when you want to use the Python Framework on Mac" ON)
IF(NOT BUILD_PYBULLET_MAC_USE_PYTHON_FRAMEWORK)
add_definitions(-DB3_NO_PYTHON_FRAMEWORK)
ENDIF(NOT BUILD_PYBULLET_MAC_USE_PYTHON_FRAMEWORK)
OPTION(BUILD_PYBULLET_SHOW_PY_VERSION "Set when you want to show the PY_MAJOR_VERSION and PY_MAJOR_VERSION using #pragme message." OFF)
IF(BUILD_PYBULLET_SHOW_PY_VERSION)
add_definitions(-DB3_DUMP_PYTHON_VERSION)
ENDIF()
ENDIF(APPLE)
ENDIF(BUILD_PYBULLET) ENDIF(BUILD_PYBULLET)
IF(BUILD_BULLET3) IF(BUILD_BULLET3)

View File

@ -158,11 +158,15 @@ end
description = "Double precision version of Bullet" description = "Double precision version of Bullet"
} }
newoption
{
trigger = "audio",
description = "Enable audio"
}
if _OPTIONS["double"] then if _OPTIONS["double"] then
defines {"BT_USE_DOUBLE_PRECISION"} defines {"BT_USE_DOUBLE_PRECISION"}
end end
configurations {"Release", "Debug"} configurations {"Release", "Debug"}
configuration "Release" configuration "Release"
flags { "Optimize", "EnableSSE2","StaticRuntime", "NoMinimalRebuild", "FloatFast"} flags { "Optimize", "EnableSSE2","StaticRuntime", "NoMinimalRebuild", "FloatFast"}
@ -251,6 +255,10 @@ end
language "C++" language "C++"
if _OPTIONS["audio"] then
include "../examples/TinyAudio"
end
if not _OPTIONS["no-demos"] then if not _OPTIONS["no-demos"] then
include "../examples/ExampleBrowser" include "../examples/ExampleBrowser"
include "../examples/RobotSimulator" include "../examples/RobotSimulator"
@ -266,9 +274,10 @@ end
if _OPTIONS["enable_pybullet"] then if _OPTIONS["enable_pybullet"] then
include "../examples/pybullet" include "../examples/pybullet"
end end
include "../examples/SimpleOpenGL3"
if _OPTIONS["standalone-examples"] then if _OPTIONS["standalone-examples"] then
include "../examples/SimpleOpenGL3"
include "../examples/TinyRenderer" include "../examples/TinyRenderer"
include "../examples/BasicDemo" include "../examples/BasicDemo"
include "../examples/InverseDynamics" include "../examples/InverseDynamics"

View File

@ -7,7 +7,7 @@
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/> <geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1"> <body pos="0 0 1">
<joint type="free"/> <joint type="free"/>
<geom fromto="0.0 0.0 0.0 0. 0.2 0.0" name="aux_1_geom" size="0.05" type="capsule"/> <geom name="aux_1_geom" size="0.05 0.1" type="capsule"/>
</body> </body>
</worldbody> </worldbody>
</mujoco> </mujoco>

View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom fromto="-0.1 0.0 0.0 0.1 0.0 0.0" name="aux_1_geom" size="0.05" type="capsule"/>
</body>
</worldbody>
</mujoco>

View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom fromto="0.0 -0.1 0.0 0.0 0.1 0.0" name="aux_1_geom" size="0.05" type="capsule"/>
</body>
</worldbody>
</mujoco>

View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom fromto="0.0 0.0 -0.1 0.0 0.0 0.1" name="aux_1_geom" size="0.05" type="capsule"/>
</body>
</worldbody>
</mujoco>

13
data/mjcf/cylinder.xml Normal file
View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom name="aux_1_geom" size="0.05 0.1" type="cylinder"/>
</body>
</worldbody>
</mujoco>

View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom fromto="-0.1 0.0 0.0 0.1 0.0 0.0" name="aux_1_geom" size="0.05" type="cylinder"/>
</body>
</worldbody>
</mujoco>

View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom fromto="0.0 -0.1 0.0 0.0 0.1 0.0" name="aux_1_geom" size="0.05" type="cylinder"/>
</body>
</worldbody>
</mujoco>

View File

@ -0,0 +1,13 @@
<!--
MuJoCo MJCF test file. See http://mujoco.org/book/index.html
-->
<mujoco>
<worldbody>
<light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body pos="0 0 1">
<joint type="free"/>
<geom fromto="0.0 0.0 -0.1 0.0 0.0 0.1" name="aux_1_geom" size="0.05" type="cylinder"/>
</body>
</worldbody>
</mujoco>

View File

@ -84,7 +84,7 @@ ELSE(WIN32)
ADD_DEFINITIONS("-DGLEW_STATIC") ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1") ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( pthread dl ) LINK_LIBRARIES( pthread ${DL} )
ENDIF(APPLE) ENDIF(APPLE)
ENDIF(WIN32) ENDIF(WIN32)

View File

@ -1,5 +1,16 @@
SUBDIRS( HelloWorld BasicDemo ) SUBDIRS( HelloWorld BasicDemo )
IF(BUILD_BULLET3) IF(BUILD_BULLET3)
SET(DL dl)
IF(CMAKE_SYSTEM_NAME MATCHES "Linux")
SET(OSDEF -D_LINUX)
ELSE(CMAKE_SYSTEM_NAME MATCHES "Linux")
IF(APPLE)
SET(OSDEF -D_DARWIN)
ELSE(APPLE)
SET(OSDEF -D_BSD)
SET(DL "")
ENDIF(APPLE)
ENDIF(CMAKE_SYSTEM_NAME MATCHES "Linux")
SUBDIRS( ExampleBrowser RobotSimulator SharedMemory ThirdPartyLibs/Gwen ThirdPartyLibs/BussIK ThirdPartyLibs/clsocket OpenGLWindow ) SUBDIRS( ExampleBrowser RobotSimulator SharedMemory ThirdPartyLibs/Gwen ThirdPartyLibs/BussIK ThirdPartyLibs/clsocket OpenGLWindow )
ENDIF() ENDIF()
IF(BUILD_PYBULLET) IF(BUILD_PYBULLET)

View File

@ -24,6 +24,8 @@ struct CommonCameraInterface
virtual void setCameraUpVector(float x,float y, float z) = 0; virtual void setCameraUpVector(float x,float y, float z) = 0;
virtual void getCameraUpVector(float up[3]) const = 0; virtual void getCameraUpVector(float up[3]) const = 0;
virtual void getCameraForwardVector(float fwd[3]) const = 0;
///the setCameraUpAxis will call the 'setCameraUpVector' and 'setCameraForwardVector' ///the setCameraUpAxis will call the 'setCameraUpVector' and 'setCameraForwardVector'
virtual void setCameraUpAxis(int axis) = 0; virtual void setCameraUpAxis(int axis) = 0;
virtual int getCameraUpAxis() const = 0; virtual int getCameraUpAxis() const = 0;

View File

@ -49,6 +49,8 @@ public:
virtual void vrControllerMoveCallback(int controllerId, float pos[4], float orientation[4], float analogAxis) {} virtual void vrControllerMoveCallback(int controllerId, float pos[4], float orientation[4], float analogAxis) {}
virtual void vrControllerButtonCallback(int controllerId, int button, int state, float pos[4], float orientation[4]){} virtual void vrControllerButtonCallback(int controllerId, int button, int state, float pos[4], float orientation[4]){}
virtual void vrHMDMoveCallback(int controllerId, float pos[4], float orientation[4]){}
virtual void vrGenericTrackerMoveCallback(int controllerId, float pos[4], float orientation[4]){}
virtual void processCommandLineArgs(int argc, char* argv[]){}; virtual void processCommandLineArgs(int argc, char* argv[]){};
}; };

View File

@ -44,12 +44,22 @@ struct GUIHelperInterface
virtual CommonRenderInterface* getRenderInterface()=0; virtual CommonRenderInterface* getRenderInterface()=0;
virtual const CommonRenderInterface* getRenderInterface() const
{
return 0;
}
virtual CommonGraphicsApp* getAppInterface()=0; virtual CommonGraphicsApp* getAppInterface()=0;
virtual void setUpAxis(int axis)=0; virtual void setUpAxis(int axis)=0;
virtual void resetCamera(float camDist, float pitch, float yaw, float camPosX,float camPosY, float camPosZ)=0; virtual void resetCamera(float camDist, float pitch, float yaw, float camPosX,float camPosY, float camPosZ)=0;
virtual bool getCameraInfo(int* width, int* height, float viewMatrix[16], float projectionMatrix[16], float camUp[3], float camForward[3],float hor[3], float vert[3] ) const
{
return false;
}
virtual void setVisualizerFlag(int flag, int enable){}; virtual void setVisualizerFlag(int flag, int enable){};
virtual void copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16], virtual void copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16],

View File

@ -26,7 +26,7 @@ struct SliderParams
m_callback(0), m_callback(0),
m_paramValuePointer(targetValuePointer), m_paramValuePointer(targetValuePointer),
m_userPointer(0), m_userPointer(0),
m_clampToNotches(true), m_clampToNotches(false),
m_clampToIntegers(false), m_clampToIntegers(false),
m_showValues(true) m_showValues(true)
{ {

View File

@ -28,6 +28,8 @@ struct CommonRenderInterface
virtual CommonCameraInterface* getActiveCamera()=0; virtual CommonCameraInterface* getActiveCamera()=0;
virtual void setActiveCamera(CommonCameraInterface* cam)=0; virtual void setActiveCamera(CommonCameraInterface* cam)=0;
virtual void setLightPosition(const float lightPos[3]) = 0;
virtual void setLightPosition(const double lightPos[3]) = 0;
virtual void renderScene()=0; virtual void renderScene()=0;
virtual void renderSceneInternal(int renderMode=B3_DEFAULT_RENDERMODE){}; virtual void renderSceneInternal(int renderMode=B3_DEFAULT_RENDERMODE){};

View File

@ -65,7 +65,7 @@ IF (BUILD_SHARED_LIBS)
TARGET_LINK_LIBRARIES( TARGET_LINK_LIBRARIES(
BulletExampleBrowserLib Bullet3Common BulletSoftBody BulletDynamics BulletCollision BulletInverseDynamicsUtils BulletExampleBrowserLib Bullet3Common BulletSoftBody BulletDynamics BulletCollision BulletInverseDynamicsUtils
BulletInverseDynamics LinearMath OpenGLWindow gwen BussIK BulletInverseDynamics LinearMath OpenGLWindow gwen BussIK
pthread dl pthread ${DL}
) )
ENDIF(APPLE) ENDIF(APPLE)
ENDIF(WIN32) ENDIF(WIN32)
@ -106,7 +106,7 @@ ELSE(WIN32)
ADD_DEFINITIONS("-DGLEW_STATIC") ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1") ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
INCLUDE_DIRECTORIES( ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/Glew ) INCLUDE_DIRECTORIES( ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/Glew )
LINK_LIBRARIES( pthread dl) LINK_LIBRARIES( pthread ${DL})
ENDIF(APPLE) ENDIF(APPLE)
ENDIF(WIN32) ENDIF(WIN32)

View File

@ -201,96 +201,99 @@ void MyKeyboardCallback(int key, int state)
//if (handled) //if (handled)
// return; // return;
if (key=='a' && state) //if (s_window && s_window->isModifierKeyPressed(B3G_CONTROL))
{ {
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawAabb; if (key=='a' && state)
}
if (key=='c' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawContactPoints;
}
if (key == 'd' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_NoDeactivation;
gDisableDeactivation = ((gDebugDrawFlags & btIDebugDraw::DBG_NoDeactivation) != 0);
}
if (key == 'k' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawConstraints;
}
if (key=='l' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawConstraintLimits;
}
if (key=='w' && state)
{
visualWireframe=!visualWireframe;
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawWireframe;
}
if (key=='v' && state)
{
renderVisualGeometry = !renderVisualGeometry;
}
if (key=='g' && state)
{
renderGrid = !renderGrid;
renderGui = !renderGui;
}
if (key=='i' && state)
{
pauseSimulation = !pauseSimulation;
}
if (key == 'o' && state)
{
singleStepSimulation = true;
}
if (key=='p')
{
#ifndef BT_NO_PROFILE
if (state)
{ {
b3ChromeUtilsStartTimings(); gDebugDrawFlags ^= btIDebugDraw::DBG_DrawAabb;
} else
{
b3ChromeUtilsStopTimingsAndWriteJsonFile();
} }
#endif //BT_NO_PROFILE if (key=='c' && state)
}
#ifndef NO_OPENGL3
if (key=='s' && state)
{
useShadowMap=!useShadowMap;
}
#endif
if (key==B3G_F1)
{
static int count=0;
if (state)
{ {
b3Printf("F1 pressed %d", count++); gDebugDrawFlags ^= btIDebugDraw::DBG_DrawContactPoints;
}
if (key == 'd' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_NoDeactivation;
gDisableDeactivation = ((gDebugDrawFlags & btIDebugDraw::DBG_NoDeactivation) != 0);
}
if (key == 'k' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawConstraints;
}
if (gPngFileName) if (key=='l' && state)
{
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawConstraintLimits;
}
if (key=='w' && state)
{
visualWireframe=!visualWireframe;
gDebugDrawFlags ^= btIDebugDraw::DBG_DrawWireframe;
}
if (key=='v' && state)
{
renderVisualGeometry = !renderVisualGeometry;
}
if (key=='g' && state)
{
renderGrid = !renderGrid;
renderGui = !renderGui;
}
if (key=='i' && state)
{
pauseSimulation = !pauseSimulation;
}
if (key == 'o' && state)
{
singleStepSimulation = true;
}
if (key=='p')
{
#ifndef BT_NO_PROFILE
if (state)
{ {
b3Printf("disable image dump"); b3ChromeUtilsStartTimings();
gPngFileName=0;
} else } else
{ {
gPngFileName = gAllExamples->getExampleName(sCurrentDemoIndex); b3ChromeUtilsStopTimingsAndWriteJsonFile();
b3Printf("enable image dump %s",gPngFileName);
} }
} else #endif //BT_NO_PROFILE
}
#ifndef NO_OPENGL3
if (key=='s' && state)
{ {
b3Printf("F1 released %d",count++); useShadowMap=!useShadowMap;
}
#endif
if (key==B3G_F1)
{
static int count=0;
if (state)
{
b3Printf("F1 pressed %d", count++);
if (gPngFileName)
{
b3Printf("disable image dump");
gPngFileName=0;
} else
{
gPngFileName = gAllExamples->getExampleName(sCurrentDemoIndex);
b3Printf("enable image dump %s",gPngFileName);
}
} else
{
b3Printf("F1 released %d",count++);
}
} }
} }
if (key==B3G_ESCAPE && s_window) if (key==B3G_ESCAPE && s_window)

View File

@ -190,6 +190,11 @@ struct CommonRenderInterface* OpenGLGuiHelper::getRenderInterface()
return m_data->m_glApp->m_renderer; return m_data->m_glApp->m_renderer;
} }
const struct CommonRenderInterface* OpenGLGuiHelper::getRenderInterface() const
{
return m_data->m_glApp->m_renderer;
}
void OpenGLGuiHelper::createRigidBodyGraphicsObject(btRigidBody* body, const btVector3& color) void OpenGLGuiHelper::createRigidBodyGraphicsObject(btRigidBody* body, const btVector3& color)
{ {
createCollisionObjectGraphicsObject(body,color); createCollisionObjectGraphicsObject(body,color);
@ -333,6 +338,12 @@ void OpenGLGuiHelper::render(const btDiscreteDynamicsWorld* rbWorld)
void OpenGLGuiHelper::createPhysicsDebugDrawer(btDiscreteDynamicsWorld* rbWorld) void OpenGLGuiHelper::createPhysicsDebugDrawer(btDiscreteDynamicsWorld* rbWorld)
{ {
btAssert(rbWorld); btAssert(rbWorld);
if (m_data->m_debugDraw)
{
delete m_data->m_debugDraw;
m_data->m_debugDraw = 0;
}
m_data->m_debugDraw = new MyDebugDrawer(m_data->m_glApp); m_data->m_debugDraw = new MyDebugDrawer(m_data->m_glApp);
rbWorld->setDebugDrawer(m_data->m_debugDraw ); rbWorld->setDebugDrawer(m_data->m_debugDraw );
@ -386,6 +397,57 @@ void OpenGLGuiHelper::resetCamera(float camDist, float pitch, float yaw, float c
} }
} }
bool OpenGLGuiHelper::getCameraInfo(int* width, int* height, float viewMatrix[16], float projectionMatrix[16], float camUp[3], float camForward[3],float hor[3], float vert[3] ) const
{
if (getRenderInterface() && getRenderInterface()->getActiveCamera())
{
*width = m_data->m_glApp->m_window->getWidth()*m_data->m_glApp->m_window->getRetinaScale();
*height = m_data->m_glApp->m_window->getHeight()*m_data->m_glApp->m_window->getRetinaScale();
getRenderInterface()->getActiveCamera()->getCameraViewMatrix(viewMatrix);
getRenderInterface()->getActiveCamera()->getCameraProjectionMatrix(projectionMatrix);
getRenderInterface()->getActiveCamera()->getCameraUpVector(camUp);
getRenderInterface()->getActiveCamera()->getCameraForwardVector(camForward);
float frustumNearPlane = getRenderInterface()->getActiveCamera()->getCameraFrustumNear();
float frustumFarPlane = getRenderInterface()->getActiveCamera()->getCameraFrustumFar();
float top = 1.f;
float bottom = -1.f;
float tanFov = (top-bottom)*0.5f / frustumNearPlane;
float fov = btScalar(2.0) * btAtan(tanFov);
btVector3 camPos,camTarget;
getRenderInterface()->getActiveCamera()->getCameraPosition(camPos);
getRenderInterface()->getActiveCamera()->getCameraTargetPosition(camTarget);
btVector3 rayFrom = camPos;
btVector3 rayForward = (camTarget-camPos);
rayForward.normalize();
float farPlane = 10000.f;
rayForward*= farPlane;
btVector3 rightOffset;
btVector3 cameraUp=btVector3(camUp[0],camUp[1],camUp[2]);
btVector3 vertical = cameraUp;
btVector3 hori;
hori = rayForward.cross(vertical);
hori.normalize();
vertical = hori.cross(rayForward);
vertical.normalize();
float tanfov = tanf(0.5f*fov);
hori *= 2.f * farPlane * tanfov;
vertical *= 2.f * farPlane * tanfov;
btScalar aspect = *width / *height;
hori*=aspect;
//compute 'hor' and 'vert' vectors, useful to generate raytracer rays
hor[0] = hori[0];
hor[1] = hori[1];
hor[2] = hori[2];
vert[0] = vertical[0];
vert[1] = vertical[1];
vert[2] = vertical[2];
return true;
}
return false;
}
void OpenGLGuiHelper::copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16], void OpenGLGuiHelper::copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16],
unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels, unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels,

View File

@ -15,6 +15,7 @@ struct OpenGLGuiHelper : public GUIHelperInterface
virtual ~OpenGLGuiHelper(); virtual ~OpenGLGuiHelper();
virtual struct CommonRenderInterface* getRenderInterface(); virtual struct CommonRenderInterface* getRenderInterface();
virtual const struct CommonRenderInterface* getRenderInterface() const;
virtual void createRigidBodyGraphicsObject(btRigidBody* body, const btVector3& color); virtual void createRigidBodyGraphicsObject(btRigidBody* body, const btVector3& color);
@ -44,6 +45,7 @@ struct OpenGLGuiHelper : public GUIHelperInterface
virtual void resetCamera(float camDist, float pitch, float yaw, float camPosX,float camPosY, float camPosZ); virtual void resetCamera(float camDist, float pitch, float yaw, float camPosX,float camPosY, float camPosZ);
virtual bool getCameraInfo(int* width, int* height, float viewMatrix[16], float projectionMatrix[16], float camUp[3], float camForward[3],float hor[3], float vert[3] ) const;
virtual void copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16], virtual void copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16],
unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels, unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels,

View File

@ -814,7 +814,17 @@ struct BulletMJCFImporterInternalData
case URDF_GEOM_CYLINDER: case URDF_GEOM_CYLINDER:
{ {
//todo double r = col->m_geometry.m_capsuleRadius;
btScalar h(0);
//and one cylinder of 'height'
if (col->m_geometry.m_hasFromTo)
{
h = (col->m_geometry.m_capsuleFrom-col->m_geometry.m_capsuleTo).length();
} else
{
h = col->m_geometry.m_capsuleHeight;
}
totalVolume += SIMD_PI*r*r*h;
break; break;
} }
case URDF_GEOM_MESH: case URDF_GEOM_MESH:
@ -832,10 +842,16 @@ struct BulletMJCFImporterInternalData
//one sphere //one sphere
double r = col->m_geometry.m_capsuleRadius; double r = col->m_geometry.m_capsuleRadius;
totalVolume += 4./3.*SIMD_PI*r*r*r; totalVolume += 4./3.*SIMD_PI*r*r*r;
//and one cylinder of 'height' btScalar h(0);
btScalar h = (col->m_geometry.m_capsuleFrom-col->m_geometry.m_capsuleTo).length(); if (col->m_geometry.m_hasFromTo)
{
//and one cylinder of 'height'
h = (col->m_geometry.m_capsuleFrom-col->m_geometry.m_capsuleTo).length();
} else
{
h = col->m_geometry.m_capsuleHeight;
}
totalVolume += SIMD_PI*r*r*h; totalVolume += SIMD_PI*r*r*h;
break; break;
} }
default: default:
@ -935,6 +951,7 @@ struct BulletMJCFImporterInternalData
} }
} }
const char* o = xml->Attribute("quat"); const char* o = xml->Attribute("quat");
if (o)
{ {
std::string ornStr = o; std::string ornStr = o;
btQuaternion orn(0,0,0,1); btQuaternion orn(0,0,0,1);
@ -1585,7 +1602,40 @@ class btCompoundShape* BulletMJCFImporter::convertLinkCollisionShapes(int linkIn
} }
case URDF_GEOM_CYLINDER: case URDF_GEOM_CYLINDER:
{ {
// childShape = new btCylinderShape(col->m_geometry...); if (col->m_geometry.m_hasFromTo)
{
btVector3 f = col->m_geometry.m_capsuleFrom;
btVector3 t = col->m_geometry.m_capsuleTo;
//compute the local 'fromto' transform
btVector3 localPosition = btScalar(0.5)*(t+f);
btQuaternion localOrn;
localOrn = btQuaternion::getIdentity();
btVector3 diff = t-f;
btScalar lenSqr = diff.length2();
btScalar height = 0.f;
if (lenSqr > SIMD_EPSILON)
{
height = btSqrt(lenSqr);
btVector3 ax = diff / height;
btVector3 zAxis(0,0,1);
localOrn = shortestArcQuat(zAxis,ax);
}
btCylinderShapeZ* cyl = new btCylinderShapeZ(btVector3(col->m_geometry.m_capsuleRadius,col->m_geometry.m_capsuleRadius,btScalar(0.5)*height));
btCompoundShape* compound = new btCompoundShape();
btTransform localTransform(localOrn,localPosition);
compound->addChildShape(localTransform,cyl);
childShape = compound;
} else
{
btCylinderShapeZ* cap = new btCylinderShapeZ(btVector3(col->m_geometry.m_capsuleRadius,
col->m_geometry.m_capsuleRadius,btScalar(0.5)*col->m_geometry.m_capsuleHeight));
childShape = cap;
}
break; break;
} }
case URDF_GEOM_MESH: case URDF_GEOM_MESH:
@ -1673,15 +1723,10 @@ class btCompoundShape* BulletMJCFImporter::convertLinkCollisionShapes(int linkIn
} }
case URDF_GEOM_CAPSULE: case URDF_GEOM_CAPSULE:
{ {
//todo: convert fromto to btCapsuleShape + local btTransform
if (col->m_geometry.m_hasFromTo) if (col->m_geometry.m_hasFromTo)
{ {
btVector3 f = col->m_geometry.m_capsuleFrom; btVector3 f = col->m_geometry.m_capsuleFrom;
btVector3 t = col->m_geometry.m_capsuleTo; btVector3 t = col->m_geometry.m_capsuleTo;
//MuJoCo seems to take the average of the spheres as center?
//btVector3 c = (f+t)*0.5;
//f-=c;
//t-=c;
btVector3 fromto[2] = {f,t}; btVector3 fromto[2] = {f,t};
btScalar radii[2] = {btScalar(col->m_geometry.m_capsuleRadius) btScalar radii[2] = {btScalar(col->m_geometry.m_capsuleRadius)
,btScalar(col->m_geometry.m_capsuleRadius)}; ,btScalar(col->m_geometry.m_capsuleRadius)};
@ -1696,6 +1741,11 @@ class btCompoundShape* BulletMJCFImporter::convertLinkCollisionShapes(int linkIn
} }
break; break;
} }
case URDF_GEOM_UNKNOWN:
{
break;
}
} // switch geom } // switch geom
if (childShape) if (childShape)

View File

@ -120,14 +120,25 @@ ImportMJCFSetup::ImportMJCFSetup(struct GUIHelperInterface* helper, int option,
if (gMCFJFileNameArray.size()==0) if (gMCFJFileNameArray.size()==0)
{ {
gMCFJFileNameArray.push_back("MPL/MPL.xml"); gMCFJFileNameArray.push_back("MPL/MPL.xml");
gMCFJFileNameArray.push_back("mjcf/humanoid.xml"); gMCFJFileNameArray.push_back("mjcf/humanoid.xml");
gMCFJFileNameArray.push_back("mjcf/inverted_pendulum.xml"); gMCFJFileNameArray.push_back("mjcf/inverted_pendulum.xml");
gMCFJFileNameArray.push_back("mjcf/ant.xml"); gMCFJFileNameArray.push_back("mjcf/ant.xml");
gMCFJFileNameArray.push_back("mjcf/hello_mjcf.xml"); gMCFJFileNameArray.push_back("mjcf/hello_mjcf.xml");
gMCFJFileNameArray.push_back("mjcf/cylinder.xml");
gMCFJFileNameArray.push_back("mjcf/cylinder_fromtoX.xml");
gMCFJFileNameArray.push_back("mjcf/cylinder_fromtoY.xml");
gMCFJFileNameArray.push_back("mjcf/cylinder_fromtoZ.xml");
gMCFJFileNameArray.push_back("mjcf/capsule.xml"); gMCFJFileNameArray.push_back("mjcf/capsule.xml");
// gMCFJFileNameArray.push_back("mjcf/hopper.xml"); gMCFJFileNameArray.push_back("mjcf/capsule_fromtoX.xml");
// gMCFJFileNameArray.push_back("mjcf/swimmer.xml"); gMCFJFileNameArray.push_back("mjcf/capsule_fromtoY.xml");
// gMCFJFileNameArray.push_back("mjcf/reacher.xml"); gMCFJFileNameArray.push_back("mjcf/capsule_fromtoZ.xml");
gMCFJFileNameArray.push_back("mjcf/hopper.xml");
gMCFJFileNameArray.push_back("mjcf/swimmer.xml");
gMCFJFileNameArray.push_back("mjcf/reacher.xml");
} }
int numFileNames = gMCFJFileNameArray.size(); int numFileNames = gMCFJFileNameArray.size();

View File

@ -10,7 +10,7 @@
bool b3ImportMeshUtility::loadAndRegisterMeshFromFileInternal(const std::string& fileName, b3ImportMeshData& meshData) bool b3ImportMeshUtility::loadAndRegisterMeshFromFileInternal(const std::string& fileName, b3ImportMeshData& meshData)
{ {
B3_PROFILE("loadAndRegisterMeshFromFileInternal");
meshData.m_gfxShape = 0; meshData.m_gfxShape = 0;
meshData.m_textureImage = 0; meshData.m_textureImage = 0;
meshData.m_textureHeight = 0; meshData.m_textureHeight = 0;
@ -26,7 +26,10 @@ bool b3ImportMeshUtility::loadAndRegisterMeshFromFileInternal(const std::string&
btVector3 shift(0,0,0); btVector3 shift(0,0,0);
std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::shape_t> shapes;
std::string err = tinyobj::LoadObj(shapes, relativeFileName, pathPrefix); {
B3_PROFILE("tinyobj::LoadObj");
std::string err = tinyobj::LoadObj(shapes, relativeFileName, pathPrefix);
}
GLInstanceGraphicsShape* gfxShape = btgCreateGraphicsShapeFromWavefrontObj(shapes); GLInstanceGraphicsShape* gfxShape = btgCreateGraphicsShapeFromWavefrontObj(shapes);

View File

@ -9,9 +9,16 @@
GLInstanceGraphicsShape* LoadMeshFromObj(const char* relativeFileName, const char* materialPrefixPath) GLInstanceGraphicsShape* LoadMeshFromObj(const char* relativeFileName, const char* materialPrefixPath)
{ {
B3_PROFILE("LoadMeshFromObj");
std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::shape_t> shapes;
std::string err = tinyobj::LoadObj(shapes, relativeFileName, materialPrefixPath); {
B3_PROFILE("tinyobj::LoadObj2");
std::string err = tinyobj::LoadObj(shapes, relativeFileName, materialPrefixPath);
}
GLInstanceGraphicsShape* gfxShape = btgCreateGraphicsShapeFromWavefrontObj(shapes); {
return gfxShape; B3_PROFILE("btgCreateGraphicsShapeFromWavefrontObj");
GLInstanceGraphicsShape* gfxShape = btgCreateGraphicsShapeFromWavefrontObj(shapes);
return gfxShape;
}
} }

View File

@ -46,6 +46,7 @@ static GLInstanceGraphicsShape* LoadMeshFromSTL(const char* relativeFileName)
int expectedBinaryFileSize = numTriangles* 50 + 84; int expectedBinaryFileSize = numTriangles* 50 + 84;
if (expectedBinaryFileSize != size) if (expectedBinaryFileSize != size)
{ {
delete[] memoryBuffer;
return 0; return 0;
} }

View File

@ -421,6 +421,7 @@ bool BulletURDFImporter::getRootTransformInWorld(btTransform& rootTransformInWor
static btCollisionShape* createConvexHullFromShapes(std::vector<tinyobj::shape_t>& shapes, const btVector3& geomScale) static btCollisionShape* createConvexHullFromShapes(std::vector<tinyobj::shape_t>& shapes, const btVector3& geomScale)
{ {
B3_PROFILE("createConvexHullFromShapes");
btCompoundShape* compound = new btCompoundShape(); btCompoundShape* compound = new btCompoundShape();
compound->setMargin(gUrdfDefaultCollisionMargin); compound->setMargin(gUrdfDefaultCollisionMargin);
@ -633,6 +634,7 @@ btCollisionShape* convertURDFToCollisionShape(const UrdfCollision* collision, co
case UrdfGeometry::FILE_OBJ: case UrdfGeometry::FILE_OBJ:
if (collision->m_flags & URDF_FORCE_CONCAVE_TRIMESH) if (collision->m_flags & URDF_FORCE_CONCAVE_TRIMESH)
{ {
glmesh = LoadMeshFromObj(collision->m_geometry.m_meshFileName.c_str(), 0); glmesh = LoadMeshFromObj(collision->m_geometry.m_meshFileName.c_str(), 0);
} }
else else
@ -744,19 +746,23 @@ upAxisMat.setIdentity();
{ {
BT_PROFILE("convert trimesh"); BT_PROFILE("convert trimesh");
btTriangleMesh* meshInterface = new btTriangleMesh(); btTriangleMesh* meshInterface = new btTriangleMesh();
for (int i=0; i<glmesh->m_numIndices/3; i++)
{ {
float* v0 = glmesh->m_vertices->at(glmesh->m_indices->at(i*3)).xyzw; BT_PROFILE("convert vertices");
float* v1 = glmesh->m_vertices->at(glmesh->m_indices->at(i*3+1)).xyzw;
float* v2 = glmesh->m_vertices->at(glmesh->m_indices->at(i*3+2)).xyzw; for (int i=0; i<glmesh->m_numIndices/3; i++)
meshInterface->addTriangle( {
btVector3(v0[0],v0[1],v0[2]), const btVector3& v0 = convertedVerts[glmesh->m_indices->at(i*3)];
btVector3(v1[0],v1[1],v1[2]), const btVector3& v1 = convertedVerts[glmesh->m_indices->at(i*3+1)];
btVector3(v2[0],v2[1],v2[2])); const btVector3& v2 = convertedVerts[glmesh->m_indices->at(i*3+2)];
meshInterface->addTriangle(v0,v1,v2);
}
}
{
BT_PROFILE("create btBvhTriangleMeshShape");
btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(meshInterface,true,true);
//trimesh->setLocalScaling(collision->m_geometry.m_meshScale);
shape = trimesh;
} }
btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(meshInterface,true,true);
trimesh->setLocalScaling(collision->m_geometry.m_meshScale);
shape = trimesh;
} else } else
{ {
@ -765,7 +771,7 @@ upAxisMat.setIdentity();
convexHull->optimizeConvexHull(); convexHull->optimizeConvexHull();
//convexHull->initializePolyhedralFeatures(); //convexHull->initializePolyhedralFeatures();
convexHull->setMargin(gUrdfDefaultCollisionMargin); convexHull->setMargin(gUrdfDefaultCollisionMargin);
convexHull->setLocalScaling(collision->m_geometry.m_meshScale); //convexHull->setLocalScaling(collision->m_geometry.m_meshScale);
shape = convexHull; shape = convexHull;
} }

View File

@ -50,9 +50,9 @@ enum UrdfGeomTypes
URDF_GEOM_BOX, URDF_GEOM_BOX,
URDF_GEOM_CYLINDER, URDF_GEOM_CYLINDER,
URDF_GEOM_MESH, URDF_GEOM_MESH,
URDF_GEOM_PLANE, URDF_GEOM_PLANE,
URDF_GEOM_CAPSULE//non-standard URDF? URDF_GEOM_CAPSULE, //non-standard URDF?
URDF_GEOM_UNKNOWN,
}; };
@ -83,6 +83,14 @@ struct UrdfGeometry
UrdfMaterial m_localMaterial; UrdfMaterial m_localMaterial;
bool m_hasLocalMaterial; bool m_hasLocalMaterial;
UrdfGeometry()
:m_type(URDF_GEOM_UNKNOWN),
m_hasFromTo(false),
m_hasLocalMaterial(false)
{
}
}; };
bool findExistingMeshFile(const std::string& urdf_path, std::string fn, bool findExistingMeshFile(const std::string& urdf_path, std::string fn,

View File

@ -61,7 +61,7 @@ if (BUILD_SHARED_LIBS)
else() else()
set (CMAKE_THREAD_PREFER_PTHREAD TRUE) set (CMAKE_THREAD_PREFER_PTHREAD TRUE)
FIND_PACKAGE(Threads) FIND_PACKAGE(Threads)
target_link_libraries(OpenGLWindow dl ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(OpenGLWindow ${DL} ${CMAKE_THREAD_LIBS_INIT})
endif() endif()
endif() endif()

View File

@ -79,7 +79,6 @@ float shadowMapWorldSize=10;
static InternalDataRenderer* sData2; static InternalDataRenderer* sData2;
GLint lineWidthRange[2]={1,1}; GLint lineWidthRange[2]={1,1};
static b3Vector3 gLightPos=b3MakeVector3(-5,12,-4);
struct b3GraphicsInstance struct b3GraphicsInstance
{ {
@ -156,6 +155,7 @@ struct InternalDataRenderer : public GLInstanceRendererInternalData
GLfloat m_projectionMatrix[16]; GLfloat m_projectionMatrix[16];
GLfloat m_viewMatrix[16]; GLfloat m_viewMatrix[16];
b3Vector3 m_lightPos;
GLuint m_defaultTexturehandle; GLuint m_defaultTexturehandle;
b3AlignedObjectArray<InternalTextureHandle> m_textureHandles; b3AlignedObjectArray<InternalTextureHandle> m_textureHandles;
@ -172,6 +172,8 @@ struct InternalDataRenderer : public GLInstanceRendererInternalData
m_shadowTexture(0), m_shadowTexture(0),
m_renderFrameBuffer(0) m_renderFrameBuffer(0)
{ {
m_lightPos=b3MakeVector3(-50,30,100);
//clear to zero to make it obvious if the matrix is used uninitialized //clear to zero to make it obvious if the matrix is used uninitialized
for (int i=0;i<16;i++) for (int i=0;i<16;i++)
{ {
@ -996,23 +998,26 @@ void GLInstancingRenderer::setActiveCamera(CommonCameraInterface* cam)
m_data->m_activeCamera = cam; m_data->m_activeCamera = cam;
} }
void GLInstancingRenderer::setLightPosition(const float lightPos[3])
{
m_data->m_lightPos[0] = lightPos[0];
m_data->m_lightPos[1] = lightPos[1];
m_data->m_lightPos[2] = lightPos[2];
}
void GLInstancingRenderer::setLightPosition(const double lightPos[3])
{
m_data->m_lightPos[0] = lightPos[0];
m_data->m_lightPos[1] = lightPos[1];
m_data->m_lightPos[2] = lightPos[2];
}
void GLInstancingRenderer::updateCamera(int upAxis) void GLInstancingRenderer::updateCamera(int upAxis)
{ {
b3Assert(glGetError() ==GL_NO_ERROR); b3Assert(glGetError() ==GL_NO_ERROR);
m_upAxis = upAxis; m_upAxis = upAxis;
switch (upAxis)
{
case 1:
gLightPos = b3MakeVector3(-50.f,100,30);
break;
case 2:
gLightPos = b3MakeVector3(-50.f,30,100);
break;
default:
b3Assert(0);
};
m_data->m_activeCamera->setCameraUpAxis(upAxis); m_data->m_activeCamera->setCameraUpAxis(upAxis);
m_data->m_activeCamera->setAspectRatio((float)m_screenWidth/(float)m_screenHeight); m_data->m_activeCamera->setAspectRatio((float)m_screenWidth/(float)m_screenHeight);
@ -1551,10 +1556,13 @@ void GLInstancingRenderer::renderSceneInternal(int renderMode)
b3CreateOrtho(-shadowMapWorldSize,shadowMapWorldSize,-shadowMapWorldSize,shadowMapWorldSize,1,300,depthProjectionMatrix);//-14,14,-14,14,1,200, depthProjectionMatrix); b3CreateOrtho(-shadowMapWorldSize,shadowMapWorldSize,-shadowMapWorldSize,shadowMapWorldSize,1,300,depthProjectionMatrix);//-14,14,-14,14,1,200, depthProjectionMatrix);
float depthViewMatrix[4][4]; float depthViewMatrix[4][4];
b3Vector3 center = b3MakeVector3(0,0,0); b3Vector3 center = b3MakeVector3(0,0,0);
float upf[3]; //float upf[3];
m_data->m_activeCamera->getCameraUpVector(upf); //m_data->m_activeCamera->getCameraUpVector(upf);
b3Vector3 up = b3MakeVector3(upf[0],upf[1],upf[2]); b3Vector3 up, fwd;
b3CreateLookAt(gLightPos,center,up,&depthViewMatrix[0][0]); b3Vector3 lightDir = m_data->m_lightPos.normalized();
b3PlaneSpace1(lightDir,up,fwd);
// b3Vector3 up = b3MakeVector3(upf[0],upf[1],upf[2]);
b3CreateLookAt(m_data->m_lightPos,center,up,&depthViewMatrix[0][0]);
//b3CreateLookAt(lightPos,m_data->m_cameraTargetPosition,b3Vector3(0,1,0),(float*)depthModelViewMatrix2); //b3CreateLookAt(lightPos,m_data->m_cameraTargetPosition,b3Vector3(0,1,0),(float*)depthModelViewMatrix2);
GLfloat depthModelMatrix[4][4]; GLfloat depthModelMatrix[4][4];
@ -1724,7 +1732,7 @@ b3Assert(glGetError() ==GL_NO_ERROR);
glUniformMatrix4fv(ProjectionMatrix, 1, false, &m_data->m_projectionMatrix[0]); glUniformMatrix4fv(ProjectionMatrix, 1, false, &m_data->m_projectionMatrix[0]);
glUniformMatrix4fv(ModelViewMatrix, 1, false, &m_data->m_viewMatrix[0]); glUniformMatrix4fv(ModelViewMatrix, 1, false, &m_data->m_viewMatrix[0]);
b3Vector3 gLightDir = gLightPos; b3Vector3 gLightDir = m_data->m_lightPos;
gLightDir.normalize(); gLightDir.normalize();
glUniform3f(regularLightDirIn,gLightDir[0],gLightDir[1],gLightDir[2]); glUniform3f(regularLightDirIn,gLightDir[0],gLightDir[1],gLightDir[2]);
@ -1761,7 +1769,7 @@ b3Assert(glGetError() ==GL_NO_ERROR);
float MVP[16]; float MVP[16];
b3Matrix4x4Mul16(m_data->m_projectionMatrix,m_data->m_viewMatrix,MVP); b3Matrix4x4Mul16(m_data->m_projectionMatrix,m_data->m_viewMatrix,MVP);
glUniformMatrix4fv(useShadow_MVP, 1, false, &MVP[0]); glUniformMatrix4fv(useShadow_MVP, 1, false, &MVP[0]);
b3Vector3 gLightDir = gLightPos; b3Vector3 gLightDir = m_data->m_lightPos;
gLightDir.normalize(); gLightDir.normalize();
glUniform3f(useShadow_lightDirIn,gLightDir[0],gLightDir[1],gLightDir[2]); glUniform3f(useShadow_lightDirIn,gLightDir[0],gLightDir[1],gLightDir[2]);
glUniformMatrix4fv(useShadow_DepthBiasModelViewMatrix, 1, false, &depthBiasMVP[0][0]); glUniformMatrix4fv(useShadow_DepthBiasModelViewMatrix, 1, false, &depthBiasMVP[0][0]);

View File

@ -117,6 +117,8 @@ public:
virtual CommonCameraInterface* getActiveCamera(); virtual CommonCameraInterface* getActiveCamera();
virtual void setActiveCamera(CommonCameraInterface* cam); virtual void setActiveCamera(CommonCameraInterface* cam);
virtual void setLightPosition(const float lightPos[3]);
virtual void setLightPosition(const double lightPos[3]);
virtual void resize(int width, int height); virtual void resize(int width, int height);
virtual int getScreenWidth() virtual int getScreenWidth()

View File

@ -1,3 +1,5 @@
#ifdef __APPLE__
#include "MacOpenGLWindow.h" #include "MacOpenGLWindow.h"
#include "OpenGLInclude.h" #include "OpenGLInclude.h"
@ -187,6 +189,7 @@ void MacOpenGLWindow::setAllowRetina(bool allow)
} }
#endif //__APPLE__

View File

@ -39,6 +39,8 @@ void main(void)
float visibility = texture(shadowMap, vec3(ShadowCoord.xy,(ShadowCoord.z)/ShadowCoord.w)); float visibility = texture(shadowMap, vec3(ShadowCoord.xy,(ShadowCoord.z)/ShadowCoord.w));
if (intensity<0.5)
visibility = 0;
intensity = 0.7*intensity + 0.3*intensity*visibility; intensity = 0.7*intensity + 0.3*intensity*visibility;

View File

@ -32,7 +32,8 @@ static const char* useShadowMapInstancingFragmentShader= \
" \n" " \n"
" \n" " \n"
" float visibility = texture(shadowMap, vec3(ShadowCoord.xy,(ShadowCoord.z)/ShadowCoord.w));\n" " float visibility = texture(shadowMap, vec3(ShadowCoord.xy,(ShadowCoord.z)/ShadowCoord.w));\n"
" \n" " if (intensity<0.5)\n"
" visibility = 0;\n"
" intensity = 0.7*intensity + 0.3*intensity*visibility;\n" " intensity = 0.7*intensity + 0.3*intensity*visibility;\n"
" \n" " \n"
" cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient;\n" " cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient;\n"

View File

@ -68,6 +68,8 @@ void SimpleCamera::setVRCamera(const float viewMat[16], const float projectionMa
{ {
m_data->m_viewMatrixVR[i] = viewMat[i]; m_data->m_viewMatrixVR[i] = viewMat[i];
m_data->m_projectionMatrixVR[i] = projectionMatrix[i]; m_data->m_projectionMatrixVR[i] = projectionMatrix[i];
m_data->m_frustumZNear = m_data->m_projectionMatrixVR[14]/(m_data->m_projectionMatrixVR[10]-1);
m_data->m_frustumZFar = m_data->m_projectionMatrixVR[14]/(m_data->m_projectionMatrixVR[10]+1);
} }
} }
@ -346,11 +348,37 @@ void SimpleCamera::setCameraUpVector(float x,float y ,float z)
void SimpleCamera::getCameraUpVector(float up[3]) const void SimpleCamera::getCameraUpVector(float up[3]) const
{ {
up[0] = float(m_data->m_cameraUp[0]); if (m_data->m_enableVR)
up[1] = float(m_data->m_cameraUp[1]); {
up[2] = float(m_data->m_cameraUp[2]); float viewMatTotal[16];
getCameraViewMatrix(viewMatTotal);
up[0] = viewMatTotal[0];
up[1] = viewMatTotal[4];
up[2] = viewMatTotal[8];
} else
{
up[0] = float(m_data->m_cameraUp[0]);
up[1] = float(m_data->m_cameraUp[1]);
up[2] = float(m_data->m_cameraUp[2]);
}
} }
void SimpleCamera::getCameraForwardVector(float fwd[3]) const
{
if (m_data->m_enableVR)
{
float viewMatTotal[16];
getCameraViewMatrix(viewMatTotal);
fwd[0] = viewMatTotal[2];
fwd[1] = viewMatTotal[6];
fwd[2] = viewMatTotal[10];
} else
{
fwd[0] = float(m_data->m_cameraForward[0]);
fwd[1] = float(m_data->m_cameraForward[1]);
fwd[2] = float(m_data->m_cameraForward[2]);
}
}
void SimpleCamera::setCameraYaw(float yaw) void SimpleCamera::setCameraYaw(float yaw)
{ {

View File

@ -35,6 +35,10 @@ struct SimpleCamera : public CommonCameraInterface
virtual void setCameraUpVector(float x,float y, float z); virtual void setCameraUpVector(float x,float y, float z);
void getCameraUpVector(float up[3]) const; void getCameraUpVector(float up[3]) const;
void getCameraForwardVector(float fwd[3]) const;
///the setCameraUpAxis will call the 'setCameraUpVector' and 'setCameraForwardVector' ///the setCameraUpAxis will call the 'setCameraUpVector' and 'setCameraForwardVector'
virtual void setCameraUpAxis(int axis); virtual void setCameraUpAxis(int axis);
virtual int getCameraUpAxis() const; virtual int getCameraUpAxis() const;

View File

@ -12,6 +12,7 @@
#include "GLInstanceGraphicsShape.h" #include "GLInstanceGraphicsShape.h"
#include "stdlib.h" #include "stdlib.h"
#include "TwFonts.h" #include "TwFonts.h"
#include "SimpleOpenGL2Renderer.h"
#ifdef __APPLE__ #ifdef __APPLE__
#include "MacOpenGLWindow.h" #include "MacOpenGLWindow.h"
#else #else
@ -177,6 +178,8 @@ SimpleOpenGL2App::SimpleOpenGL2App(const char* title, int width, int height)
m_window->setWheelCallback(Simple2WheelCallback); m_window->setWheelCallback(Simple2WheelCallback);
m_window->setResizeCallback(Simple2ResizeCallback); m_window->setResizeCallback(Simple2ResizeCallback);
m_renderer = new SimpleOpenGL2Renderer(width,height);
} }
SimpleOpenGL2App::~SimpleOpenGL2App() SimpleOpenGL2App::~SimpleOpenGL2App()

View File

@ -78,6 +78,14 @@ void SimpleOpenGL2Renderer::setActiveCamera(CommonCameraInterface* cam)
b3Assert(0);//not supported yet b3Assert(0);//not supported yet
} }
void SimpleOpenGL2Renderer::setLightPosition(const float lightPos[3])
{
}
void SimpleOpenGL2Renderer::setLightPosition(const double lightPos[3])
{
}
void SimpleOpenGL2Renderer::updateCamera(int upAxis) void SimpleOpenGL2Renderer::updateCamera(int upAxis)
{ {
float projection[16]; float projection[16];

View File

@ -25,6 +25,10 @@ public:
virtual CommonCameraInterface* getActiveCamera(); virtual CommonCameraInterface* getActiveCamera();
virtual void setActiveCamera(CommonCameraInterface* cam); virtual void setActiveCamera(CommonCameraInterface* cam);
virtual void setLightPosition(const float lightPos[3]);
virtual void setLightPosition(const double lightPos[3]);
virtual void resize(int width, int height); virtual void resize(int width, int height);
virtual void removeAllInstances(); virtual void removeAllInstances();

View File

@ -16,7 +16,7 @@ struct SimpleOpenGL3App : public CommonGraphicsApp
class GLInstancingRenderer* m_instancingRenderer; class GLInstancingRenderer* m_instancingRenderer;
virtual void setBackgroundColor(float red, float green, float blue); virtual void setBackgroundColor(float red, float green, float blue);
SimpleOpenGL3App(const char* title, int width,int height, bool allowRetina); SimpleOpenGL3App(const char* title, int width,int height, bool allowRetina=true);
virtual ~SimpleOpenGL3App(); virtual ~SimpleOpenGL3App();
virtual int registerCubeShape(float halfExtentsX=1.f,float halfExtentsY=1.f, float halfExtentsZ = 1.f, int textureIndex = -1, float textureScaling = 1); virtual int registerCubeShape(float halfExtentsX=1.f,float halfExtentsY=1.f, float halfExtentsZ = 1.f, int textureIndex = -1, float textureScaling = 1);

View File

@ -18,6 +18,8 @@
#include "../CommonInterfaces/CommonParameterInterface.h" #include "../CommonInterfaces/CommonParameterInterface.h"
struct TinyRendererSetupInternalData struct TinyRendererSetupInternalData
{ {
@ -42,6 +44,8 @@ struct TinyRendererSetupInternalData
int m_textureHandle; int m_textureHandle;
int m_animateRenderer; int m_animateRenderer;
btVector3 m_lightPos;
TinyRendererSetupInternalData(int width, int height) TinyRendererSetupInternalData(int width, int height)
: :
m_rgbColorBuffer(width,height,TGAImage::RGB), m_rgbColorBuffer(width,height,TGAImage::RGB),
@ -53,6 +57,8 @@ struct TinyRendererSetupInternalData
m_textureHandle(0), m_textureHandle(0),
m_animateRenderer(0) m_animateRenderer(0)
{ {
m_lightPos.setValue(-3,15,15);
m_depthBuffer.resize(m_width*m_height); m_depthBuffer.resize(m_width*m_height);
m_shadowBuffer.resize(m_width*m_height); m_shadowBuffer.resize(m_width*m_height);
// m_segmentationMaskBuffer.resize(m_width*m_height); // m_segmentationMaskBuffer.resize(m_width*m_height);
@ -115,9 +121,7 @@ struct TinyRendererSetup : public CommonExampleInterface
virtual bool keyboardCallback(int key, int state); virtual bool keyboardCallback(int key, int state);
virtual void renderScene() virtual void renderScene();
{
}
void animateRenderer(int animateRendererIndex) void animateRenderer(int animateRendererIndex)
{ {
@ -295,6 +299,28 @@ void TinyRendererSetup::initPhysics()
m_guiHelper->getParameterInterface()->registerComboBox( comboParams); m_guiHelper->getParameterInterface()->registerComboBox( comboParams);
} }
{
SliderParams slider("LightPosX",&m_internalData->m_lightPos[0]);
slider.m_minVal=-10;
slider.m_maxVal=10;
if (m_guiHelper->getParameterInterface())
m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
}
{
SliderParams slider("LightPosY",&m_internalData->m_lightPos[1]);
slider.m_minVal=-10;
slider.m_maxVal=10;
if (m_guiHelper->getParameterInterface())
m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
}
{
SliderParams slider("LightPosZ",&m_internalData->m_lightPos[2]);
slider.m_minVal=-10;
slider.m_maxVal=10;
if (m_guiHelper->getParameterInterface())
m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
}
} }
@ -303,14 +329,33 @@ void TinyRendererSetup::exitPhysics()
} }
void TinyRendererSetup::stepSimulation(float deltaTime) void TinyRendererSetup::stepSimulation(float deltaTime)
{ {
m_internalData->updateTransforms(); m_internalData->updateTransforms();
}
void TinyRendererSetup::renderScene()
{
m_internalData->updateTransforms();
btVector4 from(m_internalData->m_lightPos[0],m_internalData->m_lightPos[1],m_internalData->m_lightPos[2],1);
btVector4 toX(m_internalData->m_lightPos[0]+0.1,m_internalData->m_lightPos[1],m_internalData->m_lightPos[2],1);
btVector4 toY(m_internalData->m_lightPos[0],m_internalData->m_lightPos[1]+0.1,m_internalData->m_lightPos[2],1);
btVector4 toZ(m_internalData->m_lightPos[0],m_internalData->m_lightPos[1],m_internalData->m_lightPos[2]+0.1,1);
btVector4 colorX(1,0,0,1);
btVector4 colorY(0,1,0,1);
btVector4 colorZ(0,0,1,1);
int width=2;
m_guiHelper->getRenderInterface()->drawLine( from,toX,colorX,width);
m_guiHelper->getRenderInterface()->drawLine( from,toY,colorY,width);
m_guiHelper->getRenderInterface()->drawLine( from,toZ,colorZ,width);
if (!m_useSoftware) if (!m_useSoftware)
{ {
btVector3 lightPos(m_internalData->m_lightPos[0],m_internalData->m_lightPos[1],m_internalData->m_lightPos[2]);
m_guiHelper->getRenderInterface()->setLightPosition(lightPos);
for (int i=0;i<m_internalData->m_transforms.size();i++) for (int i=0;i<m_internalData->m_transforms.size();i++)
{ {
m_guiHelper->getRenderInterface()->writeSingleInstanceTransformToCPU(m_internalData->m_transforms[i].getOrigin(),m_internalData->m_transforms[i].getRotation(),i); m_guiHelper->getRenderInterface()->writeSingleInstanceTransformToCPU(m_internalData->m_transforms[i].getOrigin(),m_internalData->m_transforms[i].getRotation(),i);
@ -358,17 +403,7 @@ void TinyRendererSetup::stepSimulation(float deltaTime)
m_internalData->m_renderObjects[o]->m_viewMatrix[i][j] = viewMat[i+4*j]; m_internalData->m_renderObjects[o]->m_viewMatrix[i][j] = viewMat[i+4*j];
m_internalData->m_renderObjects[o]->m_projectionMatrix[i][j] = projMat[i+4*j]; m_internalData->m_renderObjects[o]->m_projectionMatrix[i][j] = projMat[i+4*j];
btVector3 lightDirWorld; btVector3 lightDirWorld = btVector3(m_internalData->m_lightPos[0],m_internalData->m_lightPos[1],m_internalData->m_lightPos[2]);
switch (m_app->getUpAxis())
{
case 1:
lightDirWorld = btVector3(-50.f,100,30);
break;
case 2:
lightDirWorld = btVector3(-50.f,30,100);
break;
default:{}
};
m_internalData->m_renderObjects[o]->m_lightDirWorld = lightDirWorld.normalized(); m_internalData->m_renderObjects[o]->m_lightDirWorld = lightDirWorld.normalized();
@ -399,17 +434,7 @@ void TinyRendererSetup::stepSimulation(float deltaTime)
m_internalData->m_renderObjects[o]->m_viewMatrix[i][j] = viewMat[i+4*j]; m_internalData->m_renderObjects[o]->m_viewMatrix[i][j] = viewMat[i+4*j];
m_internalData->m_renderObjects[o]->m_projectionMatrix[i][j] = projMat[i+4*j]; m_internalData->m_renderObjects[o]->m_projectionMatrix[i][j] = projMat[i+4*j];
btVector3 lightDirWorld; btVector3 lightDirWorld = btVector3(m_internalData->m_lightPos[0],m_internalData->m_lightPos[1],m_internalData->m_lightPos[2]);
switch (m_app->getUpAxis())
{
case 1:
lightDirWorld = btVector3(-50.f,100,30);
break;
case 2:
lightDirWorld = btVector3(-50.f,30,100);
break;
default:{}
};
m_internalData->m_renderObjects[o]->m_lightDirWorld = lightDirWorld.normalized(); m_internalData->m_renderObjects[o]->m_lightDirWorld = lightDirWorld.normalized();

View File

@ -99,11 +99,7 @@ ELSE(WIN32)
ENDIF(BUILD_ENET) ENDIF(BUILD_ENET)
IF(BUILD_CLSOCKET) IF(BUILD_CLSOCKET)
IF(APPLE) ADD_DEFINITIONS(${OSDEF})
ADD_DEFINITIONS(-D_DARWIN)
ELSE()
ADD_DEFINITIONS(-D_LINUX)
ENDIF()
ENDIF(BUILD_CLSOCKET) ENDIF(BUILD_CLSOCKET)
ENDIF(WIN32) ENDIF(WIN32)
@ -160,7 +156,7 @@ ELSE(WIN32)
ADD_DEFINITIONS("-DGLEW_STATIC") ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1") ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( pthread dl ) LINK_LIBRARIES( pthread ${DL} )
ENDIF(APPLE) ENDIF(APPLE)
ENDIF(WIN32) ENDIF(WIN32)

View File

@ -114,7 +114,7 @@ ELSE(WIN32)
) )
ELSE(APPLE) ELSE(APPLE)
LINK_LIBRARIES( pthread dl ) LINK_LIBRARIES( pthread ${DL} )
ADD_EXECUTABLE(App_PhysicsServer_SharedMemory ADD_EXECUTABLE(App_PhysicsServer_SharedMemory
${SharedMemory_SRCS} ${SharedMemory_SRCS}
../MultiThreading/b3PosixThreadSupport.cpp ../MultiThreading/b3PosixThreadSupport.cpp
@ -181,7 +181,7 @@ ELSE(WIN32)
) )
ELSE(APPLE) ELSE(APPLE)
LINK_LIBRARIES( pthread dl ) LINK_LIBRARIES( pthread ${DL} )
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1") ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC") ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1") ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")

View File

@ -1383,17 +1383,52 @@ b3SharedMemoryCommandHandle b3CreateRaycastCommandInit(b3PhysicsClientHandle phy
struct SharedMemoryCommand *command = cl->getAvailableSharedMemoryCommand(); struct SharedMemoryCommand *command = cl->getAvailableSharedMemoryCommand();
b3Assert(command); b3Assert(command);
command->m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS; command->m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS;
command->m_requestRaycastIntersections.m_rayFromPosition[0] = rayFromWorldX; command->m_requestRaycastIntersections.m_numRays = 1;
command->m_requestRaycastIntersections.m_rayFromPosition[1] = rayFromWorldY; command->m_requestRaycastIntersections.m_rayFromPositions[0][0] = rayFromWorldX;
command->m_requestRaycastIntersections.m_rayFromPosition[2] = rayFromWorldZ; command->m_requestRaycastIntersections.m_rayFromPositions[0][1] = rayFromWorldY;
command->m_requestRaycastIntersections.m_rayToPosition[0] = rayToWorldX; command->m_requestRaycastIntersections.m_rayFromPositions[0][2] = rayFromWorldZ;
command->m_requestRaycastIntersections.m_rayToPosition[1] = rayToWorldY; command->m_requestRaycastIntersections.m_rayToPositions[0][0] = rayToWorldX;
command->m_requestRaycastIntersections.m_rayToPosition[2] = rayToWorldZ; command->m_requestRaycastIntersections.m_rayToPositions[0][1] = rayToWorldY;
command->m_requestRaycastIntersections.m_rayToPositions[0][2] = rayToWorldZ;
return (b3SharedMemoryCommandHandle)command; return (b3SharedMemoryCommandHandle)command;
} }
b3SharedMemoryCommandHandle b3CreateRaycastBatchCommandInit(b3PhysicsClientHandle physClient)
{
PhysicsClient *cl = (PhysicsClient *)physClient;
b3Assert(cl);
b3Assert(cl->canSubmitCommand());
struct SharedMemoryCommand *command = cl->getAvailableSharedMemoryCommand();
b3Assert(command);
command->m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS;
command->m_updateFlags = 0;
command->m_requestRaycastIntersections.m_numRays = 0;
return (b3SharedMemoryCommandHandle)command;
}
void b3RaycastBatchAddRay(b3SharedMemoryCommandHandle commandHandle, const double rayFromWorld[3], const double rayToWorld[3])
{
struct SharedMemoryCommand* command = (struct SharedMemoryCommand*) commandHandle;
b3Assert(command);
b3Assert(command->m_type == CMD_REQUEST_RAY_CAST_INTERSECTIONS);
if (command->m_type == CMD_REQUEST_RAY_CAST_INTERSECTIONS)
{
int numRays = command->m_requestRaycastIntersections.m_numRays;
if (numRays<MAX_RAY_INTERSECTION_BATCH_SIZE)
{
command->m_requestRaycastIntersections.m_rayFromPositions[numRays][0] = rayFromWorld[0];
command->m_requestRaycastIntersections.m_rayFromPositions[numRays][1] = rayFromWorld[1];
command->m_requestRaycastIntersections.m_rayFromPositions[numRays][2] = rayFromWorld[2];
command->m_requestRaycastIntersections.m_rayToPositions[numRays][0] = rayToWorld[0];
command->m_requestRaycastIntersections.m_rayToPositions[numRays][1] = rayToWorld[1];
command->m_requestRaycastIntersections.m_rayToPositions[numRays][2] = rayToWorld[2];
command->m_requestRaycastIntersections.m_numRays++;
}
}
}
void b3GetRaycastInformation(b3PhysicsClientHandle physClient, struct b3RaycastInformation* raycastInfo) void b3GetRaycastInformation(b3PhysicsClientHandle physClient, struct b3RaycastInformation* raycastInfo)
{ {
PhysicsClient* cl = (PhysicsClient* ) physClient; PhysicsClient* cl = (PhysicsClient* ) physClient;
@ -2502,11 +2537,20 @@ b3SharedMemoryCommandHandle b3RequestVREventsCommandInit(b3PhysicsClientHandle p
b3Assert(command); b3Assert(command);
command->m_type = CMD_REQUEST_VR_EVENTS_DATA; command->m_type = CMD_REQUEST_VR_EVENTS_DATA;
command->m_updateFlags = 0; command->m_updateFlags = VR_DEVICE_CONTROLLER;
return (b3SharedMemoryCommandHandle)command; return (b3SharedMemoryCommandHandle)command;
} }
void b3VREventsSetDeviceTypeFilter(b3SharedMemoryCommandHandle commandHandle, int deviceTypeFilter)
{
struct SharedMemoryCommand* command = (struct SharedMemoryCommand*) commandHandle;
b3Assert(command);
if (command->m_type == CMD_REQUEST_VR_EVENTS_DATA)
{
command->m_updateFlags = deviceTypeFilter;
}
}
void b3GetVREventsData(b3PhysicsClientHandle physClient, struct b3VREventsData* vrEventsData) void b3GetVREventsData(b3PhysicsClientHandle physClient, struct b3VREventsData* vrEventsData)
{ {
PhysicsClient* cl = (PhysicsClient* ) physClient; PhysicsClient* cl = (PhysicsClient* ) physClient;
@ -2604,6 +2648,7 @@ b3SharedMemoryCommandHandle b3StateLoggingCommandInit(b3PhysicsClientHandle phys
command->m_type = CMD_STATE_LOGGING; command->m_type = CMD_STATE_LOGGING;
command->m_updateFlags = 0; command->m_updateFlags = 0;
command->m_stateLoggingArguments.m_numBodyUniqueIds = 0; command->m_stateLoggingArguments.m_numBodyUniqueIds = 0;
command->m_stateLoggingArguments.m_deviceFilterType = VR_DEVICE_CONTROLLER;
return (b3SharedMemoryCommandHandle)command; return (b3SharedMemoryCommandHandle)command;
@ -2724,6 +2769,20 @@ int b3StateLoggingSetMaxLogDof(b3SharedMemoryCommandHandle commandHandle, int ma
return 0; return 0;
} }
int b3StateLoggingSetDeviceTypeFilter(b3SharedMemoryCommandHandle commandHandle, int deviceTypeFilter)
{
struct SharedMemoryCommand* command = (struct SharedMemoryCommand*) commandHandle;
b3Assert(command);
b3Assert(command->m_type == CMD_STATE_LOGGING);
if (command->m_type == CMD_STATE_LOGGING)
{
command->m_updateFlags |= STATE_LOGGING_FILTER_DEVICE_TYPE;
command->m_stateLoggingArguments.m_deviceFilterType = deviceTypeFilter;
}
return 0;
}
int b3StateLoggingStop(b3SharedMemoryCommandHandle commandHandle, int loggingUid) int b3StateLoggingStop(b3SharedMemoryCommandHandle commandHandle, int loggingUid)
{ {
struct SharedMemoryCommand* command = (struct SharedMemoryCommand*) commandHandle; struct SharedMemoryCommand* command = (struct SharedMemoryCommand*) commandHandle;
@ -2784,6 +2843,33 @@ void b3ConfigureOpenGLVisualizerSetViewMatrix(b3SharedMemoryCommandHandle comman
} }
} }
b3SharedMemoryCommandHandle b3InitRequestOpenGLVisualizerCameraCommand(b3PhysicsClientHandle physClient)
{
PhysicsClient* cl = (PhysicsClient*)physClient;
b3Assert(cl);
b3Assert(cl->canSubmitCommand());
struct SharedMemoryCommand* command = cl->getAvailableSharedMemoryCommand();
b3Assert(command);
command->m_type = CMD_REQUEST_OPENGL_VISUALIZER_CAMERA;
command->m_updateFlags = 0;
return (b3SharedMemoryCommandHandle)command;
}
int b3GetStatusOpenGLVisualizerCamera(b3SharedMemoryStatusHandle statusHandle, b3OpenGLVisualizerCameraInfo* camera)
{
const SharedMemoryStatus* status = (const SharedMemoryStatus* ) statusHandle;
//b3Assert(status);
if (status && status->m_type == CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED)
{
*camera = status->m_visualizerCameraResultArgs;
return 1;
}
return 0;
}
void b3SetTimeOut(b3PhysicsClientHandle physClient, double timeOutInSeconds) void b3SetTimeOut(b3PhysicsClientHandle physClient, double timeOutInSeconds)
{ {
PhysicsClient* cl = (PhysicsClient*)physClient; PhysicsClient* cl = (PhysicsClient*)physClient;

View File

@ -104,6 +104,9 @@ b3SharedMemoryCommandHandle b3InitConfigureOpenGLVisualizer(b3PhysicsClientHandl
void b3ConfigureOpenGLVisualizerSetVisualizationFlags(b3SharedMemoryCommandHandle commandHandle, int flag, int enabled); void b3ConfigureOpenGLVisualizerSetVisualizationFlags(b3SharedMemoryCommandHandle commandHandle, int flag, int enabled);
void b3ConfigureOpenGLVisualizerSetViewMatrix(b3SharedMemoryCommandHandle commandHandle, float cameraDistance, float cameraPitch, float cameraYaw, const float cameraTargetPosition[3]); void b3ConfigureOpenGLVisualizerSetViewMatrix(b3SharedMemoryCommandHandle commandHandle, float cameraDistance, float cameraPitch, float cameraYaw, const float cameraTargetPosition[3]);
b3SharedMemoryCommandHandle b3InitRequestOpenGLVisualizerCameraCommand(b3PhysicsClientHandle physClient);
int b3GetStatusOpenGLVisualizerCamera(b3SharedMemoryStatusHandle statusHandle, struct b3OpenGLVisualizerCameraInfo* camera);
/// Add/remove user-specific debug lines and debug text messages /// Add/remove user-specific debug lines and debug text messages
b3SharedMemoryCommandHandle b3InitUserDebugDrawAddLine3D(b3PhysicsClientHandle physClient, double fromXYZ[3], double toXYZ[3], double colorRGB[3], double lineWidth, double lifeTime); b3SharedMemoryCommandHandle b3InitUserDebugDrawAddLine3D(b3PhysicsClientHandle physClient, double fromXYZ[3], double toXYZ[3], double colorRGB[3], double lineWidth, double lifeTime);
@ -332,6 +335,9 @@ b3SharedMemoryCommandHandle b3CreateRaycastCommandInit(b3PhysicsClientHandle phy
double rayFromWorldY, double rayFromWorldZ, double rayFromWorldY, double rayFromWorldZ,
double rayToWorldX, double rayToWorldY, double rayToWorldZ); double rayToWorldX, double rayToWorldY, double rayToWorldZ);
b3SharedMemoryCommandHandle b3CreateRaycastBatchCommandInit(b3PhysicsClientHandle physClient);
void b3RaycastBatchAddRay(b3SharedMemoryCommandHandle commandHandle, const double rayFromWorld[3], const double rayToWorld[3]);
void b3GetRaycastInformation(b3PhysicsClientHandle physClient, struct b3RaycastInformation* raycastInfo); void b3GetRaycastInformation(b3PhysicsClientHandle physClient, struct b3RaycastInformation* raycastInfo);
@ -349,6 +355,8 @@ int b3LoadBunnySetCollisionMargin(b3SharedMemoryCommandHandle commandHandle, dou
b3SharedMemoryCommandHandle b3RequestVREventsCommandInit(b3PhysicsClientHandle physClient); b3SharedMemoryCommandHandle b3RequestVREventsCommandInit(b3PhysicsClientHandle physClient);
void b3VREventsSetDeviceTypeFilter(b3SharedMemoryCommandHandle commandHandle, int deviceTypeFilter);
void b3GetVREventsData(b3PhysicsClientHandle physClient, struct b3VREventsData* vrEventsData); void b3GetVREventsData(b3PhysicsClientHandle physClient, struct b3VREventsData* vrEventsData);
b3SharedMemoryCommandHandle b3SetVRCameraStateCommandInit(b3PhysicsClientHandle physClient); b3SharedMemoryCommandHandle b3SetVRCameraStateCommandInit(b3PhysicsClientHandle physClient);
@ -367,6 +375,7 @@ int b3StateLoggingSetLinkIndexA(b3SharedMemoryCommandHandle commandHandle, int l
int b3StateLoggingSetLinkIndexB(b3SharedMemoryCommandHandle commandHandle, int linkIndexB); int b3StateLoggingSetLinkIndexB(b3SharedMemoryCommandHandle commandHandle, int linkIndexB);
int b3StateLoggingSetBodyAUniqueId(b3SharedMemoryCommandHandle commandHandle, int bodyAUniqueId); int b3StateLoggingSetBodyAUniqueId(b3SharedMemoryCommandHandle commandHandle, int bodyAUniqueId);
int b3StateLoggingSetBodyBUniqueId(b3SharedMemoryCommandHandle commandHandle, int bodyBUniqueId); int b3StateLoggingSetBodyBUniqueId(b3SharedMemoryCommandHandle commandHandle, int bodyBUniqueId);
int b3StateLoggingSetDeviceTypeFilter(b3SharedMemoryCommandHandle commandHandle, int deviceTypeFilter);
int b3GetStatusLoggingUniqueId(b3SharedMemoryStatusHandle statusHandle); int b3GetStatusLoggingUniqueId(b3SharedMemoryStatusHandle statusHandle);
int b3StateLoggingStop(b3SharedMemoryCommandHandle commandHandle, int loggingUniqueId); int b3StateLoggingStop(b3SharedMemoryCommandHandle commandHandle, int loggingUniqueId);

View File

@ -89,10 +89,10 @@ protected:
virtual void resetCamera() virtual void resetCamera()
{ {
float dist = 4; float dist = 3.45;
float pitch = 193; float pitch = 287;
float yaw = 25; float yaw = 16.2;
float targetPos[3]={0,0,0.5};//-3,2.8,-2.5}; float targetPos[3]={2.05,0.02,0.53};//-3,2.8,-2.5};
m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]); m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]);
} }
@ -256,7 +256,11 @@ void PhysicsClientExample::prepareAndSubmitCommand(int commandId)
case CMD_LOAD_SDF: case CMD_LOAD_SDF:
{ {
b3SharedMemoryCommandHandle commandHandle = b3LoadSdfCommandInit(m_physicsClientHandle, "two_cubes.sdf");//kuka_iiwa/model.sdf"); #ifdef BT_DEBUG
b3SharedMemoryCommandHandle commandHandle = b3LoadSdfCommandInit(m_physicsClientHandle, "two_cubes.sdf");
#else
b3SharedMemoryCommandHandle commandHandle = b3LoadSdfCommandInit(m_physicsClientHandle, "kitchens/1.sdf");//two_cubes.sdf");//kitchens/1.sdf");//kuka_iiwa/model.sdf");
#endif
b3SubmitClientCommand(m_physicsClientHandle, commandHandle); b3SubmitClientCommand(m_physicsClientHandle, commandHandle);
break; break;
} }
@ -834,13 +838,16 @@ void PhysicsClientExample::stepSimulation(float deltaTime)
//todo: rescale the depthValue to [0..255] //todo: rescale the depthValue to [0..255]
if (depthValue>-1e20) if (depthValue>-1e20)
{ {
int rgb = (depthValue-minDepthValue)*(255. / (btFabs(maxDepthValue-minDepthValue))); int rgb = 0;
if (rgb<0 || rgb>255)
{
printf("rgb=%d\n",rgb);
}
if (maxDepthValue!=minDepthValue)
{
rgb = (depthValue-minDepthValue)*(255. / (btFabs(maxDepthValue-minDepthValue)));
if (rgb<0 || rgb>255)
{
//printf("rgb=%d\n",rgb);
}
}
m_canvas->setPixel(m_canvasDepthIndex,i,j, m_canvas->setPixel(m_canvasDepthIndex,i,j,
rgb, rgb,
rgb, rgb,

View File

@ -990,6 +990,16 @@ const SharedMemoryStatus* PhysicsClientSharedMemory::processServerStatus() {
b3Warning("State Logging failed"); b3Warning("State Logging failed");
break; break;
} }
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_FAILED:
{
b3Warning("Request visualizer camera failed");
break;
}
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED:
{
break;
}
default: { default: {
b3Error("Unknown server status %d\n", serverCmd.m_type); b3Error("Unknown server status %d\n", serverCmd.m_type);
btAssert(0); btAssert(0);

View File

@ -834,6 +834,16 @@ void PhysicsDirect::postProcessStatus(const struct SharedMemoryStatus& serverCmd
break; break;
} }
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED:
{
break;
}
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_FAILED:
{
b3Warning("requestOpenGLVisualizeCamera failed");
break;
}
case CMD_REMOVE_USER_CONSTRAINT_FAILED: case CMD_REMOVE_USER_CONSTRAINT_FAILED:
{ {
b3Warning("removeConstraint failed"); b3Warning("removeConstraint failed");

View File

@ -376,7 +376,8 @@ struct MyBroadphaseCallback : public btBroadphaseAabbCallback
if (bodyUniqueId >= 0) if (bodyUniqueId >= 0)
{ {
m_bodyUniqueIds.push_back(bodyUniqueId); m_bodyUniqueIds.push_back(bodyUniqueId);
m_links.push_back(mbl->m_link); //it is not a multibody, so use -1 otherwise
m_links.push_back(-1);
} }
return true; return true;
} }
@ -605,6 +606,7 @@ struct b3VRControllerEvents
{ {
for (int i=0;i<MAX_VR_CONTROLLERS;i++) for (int i=0;i<MAX_VR_CONTROLLERS;i++)
{ {
m_vrEvents[i].m_deviceType = 0;
m_vrEvents[i].m_numButtonEvents = 0; m_vrEvents[i].m_numButtonEvents = 0;
m_vrEvents[i].m_numMoveEvents = 0; m_vrEvents[i].m_numMoveEvents = 0;
for (int b=0;b<MAX_VR_BUTTONS;b++) for (int b=0;b<MAX_VR_BUTTONS;b++)
@ -628,6 +630,7 @@ struct b3VRControllerEvents
if (vrEvents[i].m_numMoveEvents+vrEvents[i].m_numButtonEvents) if (vrEvents[i].m_numMoveEvents+vrEvents[i].m_numButtonEvents)
{ {
m_vrEvents[controlledId].m_controllerId = vrEvents[i].m_controllerId; m_vrEvents[controlledId].m_controllerId = vrEvents[i].m_controllerId;
m_vrEvents[controlledId].m_deviceType = vrEvents[i].m_deviceType;
m_vrEvents[controlledId].m_pos[0] = vrEvents[i].m_pos[0]; m_vrEvents[controlledId].m_pos[0] = vrEvents[i].m_pos[0];
m_vrEvents[controlledId].m_pos[1] = vrEvents[i].m_pos[1]; m_vrEvents[controlledId].m_pos[1] = vrEvents[i].m_pos[1];
@ -659,13 +662,14 @@ struct VRControllerStateLogger : public InternalStateLogger
{ {
b3VRControllerEvents m_vrEvents; b3VRControllerEvents m_vrEvents;
int m_loggingTimeStamp; int m_loggingTimeStamp;
int m_deviceTypeFilter;
std::string m_fileName; std::string m_fileName;
FILE* m_logFileHandle; FILE* m_logFileHandle;
std::string m_structTypes; std::string m_structTypes;
VRControllerStateLogger(int loggingUniqueId, const std::string& fileName) VRControllerStateLogger(int loggingUniqueId, int deviceTypeFilter, const std::string& fileName)
:m_loggingTimeStamp(0), :m_loggingTimeStamp(0),
m_deviceTypeFilter(deviceTypeFilter),
m_fileName(fileName), m_fileName(fileName),
m_logFileHandle(0) m_logFileHandle(0)
{ {
@ -693,7 +697,8 @@ struct VRControllerStateLogger : public InternalStateLogger
structNames.push_back("buttons4"); structNames.push_back("buttons4");
structNames.push_back("buttons5"); structNames.push_back("buttons5");
structNames.push_back("buttons6"); structNames.push_back("buttons6");
m_structTypes = "IfIIIffffffffIIIIIII"; structNames.push_back("deviceType");
m_structTypes = "IfIIIffffffffIIIIIIII";
const char* fileNameC = fileName.c_str(); const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes); m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
@ -718,62 +723,64 @@ struct VRControllerStateLogger : public InternalStateLogger
for (int i=0;i<MAX_VR_CONTROLLERS;i++) for (int i=0;i<MAX_VR_CONTROLLERS;i++)
{ {
b3VRControllerEvent& event = m_vrEvents.m_vrEvents[i]; b3VRControllerEvent& event = m_vrEvents.m_vrEvents[i];
if (m_deviceTypeFilter & event.m_deviceType)
if (event.m_numButtonEvents + event.m_numMoveEvents)
{ {
MinitaurLogRecord logData; if (event.m_numButtonEvents + event.m_numMoveEvents)
//serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
//log the event
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
logData.m_values.push_back(event.m_controllerId);
logData.m_values.push_back(event.m_numMoveEvents);
logData.m_values.push_back(event.m_numButtonEvents);
logData.m_values.push_back(event.m_pos[0]);
logData.m_values.push_back(event.m_pos[1]);
logData.m_values.push_back(event.m_pos[2]);
logData.m_values.push_back(event.m_orn[0]);
logData.m_values.push_back(event.m_orn[1]);
logData.m_values.push_back(event.m_orn[2]);
logData.m_values.push_back(event.m_orn[3]);
logData.m_values.push_back(event.m_analogAxis);
int packedButtons[7]={0,0,0,0,0,0,0};
int packedButtonIndex = 0;
int packedButtonShift = 0;
//encode the 64 buttons into 7 int (3 bits each), each int stores 10 buttons
for (int b=0;b<MAX_VR_BUTTONS;b++)
{ {
int buttonMask = event.m_buttons[b]; MinitaurLogRecord logData;
buttonMask = buttonMask << (packedButtonShift*3);
packedButtons[packedButtonIndex] |= buttonMask;
packedButtonShift++;
if (packedButtonShift>=10) //serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
//log the event
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
logData.m_values.push_back(event.m_controllerId);
logData.m_values.push_back(event.m_numMoveEvents);
logData.m_values.push_back(event.m_numButtonEvents);
logData.m_values.push_back(event.m_pos[0]);
logData.m_values.push_back(event.m_pos[1]);
logData.m_values.push_back(event.m_pos[2]);
logData.m_values.push_back(event.m_orn[0]);
logData.m_values.push_back(event.m_orn[1]);
logData.m_values.push_back(event.m_orn[2]);
logData.m_values.push_back(event.m_orn[3]);
logData.m_values.push_back(event.m_analogAxis);
int packedButtons[7]={0,0,0,0,0,0,0};
int packedButtonIndex = 0;
int packedButtonShift = 0;
//encode the 64 buttons into 7 int (3 bits each), each int stores 10 buttons
for (int b=0;b<MAX_VR_BUTTONS;b++)
{ {
packedButtonShift=0; int buttonMask = event.m_buttons[b];
packedButtonIndex++; buttonMask = buttonMask << (packedButtonShift*3);
if (packedButtonIndex>=7) packedButtons[packedButtonIndex] |= buttonMask;
packedButtonShift++;
if (packedButtonShift>=10)
{ {
btAssert(0); packedButtonShift=0;
break; packedButtonIndex++;
if (packedButtonIndex>=7)
{
btAssert(0);
break;
}
} }
} }
}
for (int b=0;b<7;b++) for (int b=0;b<7;b++)
{ {
logData.m_values.push_back(packedButtons[b]); logData.m_values.push_back(packedButtons[b]);
} }
logData.m_values.push_back(event.m_deviceType);
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData); event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
event.m_numButtonEvents = 0; for (int b=0;b<MAX_VR_BUTTONS;b++)
event.m_numMoveEvents = 0; {
for (int b=0;b<MAX_VR_BUTTONS;b++) event.m_buttons[b] = 0;
{ }
event.m_buttons[b] = 0;
} }
} }
} }
@ -824,7 +831,7 @@ struct GenericRobotStateLogger : public InternalStateLogger
structNames.push_back("omegaZ"); structNames.push_back("omegaZ");
structNames.push_back("qNum"); structNames.push_back("qNum");
m_structTypes = "IfIfffffffffffffI"; m_structTypes = "IfifffffffffffffI";
for (int i=0;i<m_maxLogDof;i++) for (int i=0;i<m_maxLogDof;i++)
{ {
@ -999,7 +1006,7 @@ struct ContactPointsStateLogger : public InternalStateLogger
structNames.push_back("contactNormalOnBZ"); structNames.push_back("contactNormalOnBZ");
structNames.push_back("contactDistance"); structNames.push_back("contactDistance");
structNames.push_back("normalForce"); structNames.push_back("normalForce");
m_structTypes = "IfIIIIIfffffffffff"; m_structTypes = "IfIiiiifffffffffff";
const char* fileNameC = fileName.c_str(); const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes); m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
@ -1209,7 +1216,9 @@ struct PhysicsServerCommandProcessorInternalData
bool m_allowRealTimeSimulation; bool m_allowRealTimeSimulation;
bool m_hasGround; bool m_hasGround;
b3VRControllerEvents m_vrEvents1; b3VRControllerEvents m_vrControllerEvents;
btAlignedObjectArray<b3KeyboardEvent> m_keyboardEvents; btAlignedObjectArray<b3KeyboardEvent> m_keyboardEvents;
btMultiBodyFixedConstraint* m_gripperRigidbodyFixed; btMultiBodyFixedConstraint* m_gripperRigidbodyFixed;
@ -1324,7 +1333,7 @@ struct PhysicsServerCommandProcessorInternalData
m_pickedConstraint(0), m_pickedConstraint(0),
m_pickingMultiBodyPoint2Point(0) m_pickingMultiBodyPoint2Point(0)
{ {
m_vrEvents1.init(); m_vrControllerEvents.init();
initHandles(); initHandles();
#if 0 #if 0
@ -1508,7 +1517,10 @@ void PhysicsServerCommandProcessor::createEmptyDynamicsWorld()
// m_data->m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 2; // m_data->m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 2;
//todo: islands/constraints are buggy in btMultiBodyDynamicsWorld! (performance + see slipping grasp) //todo: islands/constraints are buggy in btMultiBodyDynamicsWorld! (performance + see slipping grasp)
if (m_data->m_guiHelper)
{
m_data->m_guiHelper->createPhysicsDebugDrawer(m_data->m_dynamicsWorld);
}
m_data->m_dynamicsWorld->setInternalTickCallback(logCallback,this); m_data->m_dynamicsWorld->setInternalTickCallback(logCallback,this);
} }
@ -2310,7 +2322,12 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
{ {
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName; std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++; int loggerUid = m_data->m_stateLoggersUniqueId++;
VRControllerStateLogger* logger = new VRControllerStateLogger(loggerUid,fileName); int deviceFilterType = VR_DEVICE_CONTROLLER;
if (clientCmd.m_updateFlags & STATE_LOGGING_FILTER_DEVICE_TYPE)
{
deviceFilterType = clientCmd.m_stateLoggingArguments.m_deviceFilterType;
}
VRControllerStateLogger* logger = new VRControllerStateLogger(loggerUid,deviceFilterType, fileName);
m_data->m_stateLoggers.push_back(logger); m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED; serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid; serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
@ -2362,20 +2379,23 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
case CMD_REQUEST_VR_EVENTS_DATA: case CMD_REQUEST_VR_EVENTS_DATA:
{ {
BT_PROFILE("CMD_REQUEST_VR_EVENTS_DATA"); BT_PROFILE("CMD_REQUEST_VR_EVENTS_DATA");
serverStatusOut.m_sendVREvents.m_numVRControllerEvents = 0; serverStatusOut.m_sendVREvents.m_numVRControllerEvents = 0;
for (int i=0;i<MAX_VR_CONTROLLERS;i++) for (int i=0;i<MAX_VR_CONTROLLERS;i++)
{ {
b3VRControllerEvent& event = m_data->m_vrEvents1.m_vrEvents[i]; b3VRControllerEvent& event = m_data->m_vrControllerEvents.m_vrEvents[i];
if (event.m_numButtonEvents + event.m_numMoveEvents) if (clientCmd.m_updateFlags&event.m_deviceType)
{ {
serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event; if (event.m_numButtonEvents + event.m_numMoveEvents)
event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
for (int b=0;b<MAX_VR_BUTTONS;b++)
{ {
event.m_buttons[b] = 0; serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
for (int b=0;b<MAX_VR_BUTTONS;b++)
{
event.m_buttons[b] = 0;
}
} }
} }
} }
@ -2424,58 +2444,74 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
case CMD_REQUEST_RAY_CAST_INTERSECTIONS: case CMD_REQUEST_RAY_CAST_INTERSECTIONS:
{ {
BT_PROFILE("CMD_REQUEST_RAY_CAST_INTERSECTIONS"); BT_PROFILE("CMD_REQUEST_RAY_CAST_INTERSECTIONS");
btVector3 rayFromWorld(clientCmd.m_requestRaycastIntersections.m_rayFromPosition[0],
clientCmd.m_requestRaycastIntersections.m_rayFromPosition[1],
clientCmd.m_requestRaycastIntersections.m_rayFromPosition[2]);
btVector3 rayToWorld(clientCmd.m_requestRaycastIntersections.m_rayToPosition[0],
clientCmd.m_requestRaycastIntersections.m_rayToPosition[1],
clientCmd.m_requestRaycastIntersections.m_rayToPosition[2]);
btCollisionWorld::ClosestRayResultCallback rayResultCallback(rayFromWorld,rayToWorld);
m_data->m_dynamicsWorld->rayTest(rayFromWorld,rayToWorld,rayResultCallback);
serverStatusOut.m_raycastHits.m_numRaycastHits = 0; serverStatusOut.m_raycastHits.m_numRaycastHits = 0;
if (rayResultCallback.hasHit()) for (int ray=0;ray<clientCmd.m_requestRaycastIntersections.m_numRays;ray++)
{ {
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitFraction btVector3 rayFromWorld(clientCmd.m_requestRaycastIntersections.m_rayFromPositions[ray][0],
= rayResultCallback.m_closestHitFraction; clientCmd.m_requestRaycastIntersections.m_rayFromPositions[ray][1],
clientCmd.m_requestRaycastIntersections.m_rayFromPositions[ray][2]);
btVector3 rayToWorld(clientCmd.m_requestRaycastIntersections.m_rayToPositions[ray][0],
clientCmd.m_requestRaycastIntersections.m_rayToPositions[ray][1],
clientCmd.m_requestRaycastIntersections.m_rayToPositions[ray][2]);
int objectUniqueId = -1; btCollisionWorld::ClosestRayResultCallback rayResultCallback(rayFromWorld,rayToWorld);
int linkIndex = -1; m_data->m_dynamicsWorld->rayTest(rayFromWorld,rayToWorld,rayResultCallback);
int rayHits = serverStatusOut.m_raycastHits.m_numRaycastHits;
const btRigidBody* body = btRigidBody::upcast(rayResultCallback.m_collisionObject); if (rayResultCallback.hasHit())
if (body)
{ {
objectUniqueId = rayResultCallback.m_collisionObject->getUserIndex2(); serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitFraction
= rayResultCallback.m_closestHitFraction;
int objectUniqueId = -1;
int linkIndex = -1;
const btRigidBody* body = btRigidBody::upcast(rayResultCallback.m_collisionObject);
if (body)
{
objectUniqueId = rayResultCallback.m_collisionObject->getUserIndex2();
} else
{
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(rayResultCallback.m_collisionObject);
if (mblB && mblB->m_multiBody)
{
linkIndex = mblB->m_link;
objectUniqueId = mblB->m_multiBody->getUserIndex2();
}
}
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitObjectUniqueId
= objectUniqueId;
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitObjectLinkIndex
= linkIndex;
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitPositionWorld[0]
= rayResultCallback.m_hitPointWorld[0];
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitPositionWorld[1]
= rayResultCallback.m_hitPointWorld[1];
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitPositionWorld[2]
= rayResultCallback.m_hitPointWorld[2];
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitNormalWorld[0]
= rayResultCallback.m_hitNormalWorld[0];
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitNormalWorld[1]
= rayResultCallback.m_hitNormalWorld[1];
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitNormalWorld[2]
= rayResultCallback.m_hitNormalWorld[2];
} else } else
{ {
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(rayResultCallback.m_collisionObject); serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitFraction = 1;
if (mblB && mblB->m_multiBody) serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitObjectUniqueId = -1;
{ serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitObjectLinkIndex = -1;
linkIndex = mblB->m_link; serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitPositionWorld[0] = 0;
objectUniqueId = mblB->m_multiBody->getUserIndex2(); serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitPositionWorld[1] = 0;
} serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitPositionWorld[2] = 0;
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitNormalWorld[0] = 0;
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitNormalWorld[1] = 0;
serverStatusOut.m_raycastHits.m_rayHits[rayHits].m_hitNormalWorld[2] = 0;
} }
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitObjectUniqueId
= objectUniqueId;
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitObjectLinkIndex
= linkIndex;
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitPositionWorld[0]
= rayResultCallback.m_hitPointWorld[0];
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitPositionWorld[1]
= rayResultCallback.m_hitPointWorld[1];
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitPositionWorld[2]
= rayResultCallback.m_hitPointWorld[2];
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitNormalWorld[0]
= rayResultCallback.m_hitNormalWorld[0];
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitNormalWorld[1]
= rayResultCallback.m_hitNormalWorld[1];
serverStatusOut.m_raycastHits.m_rayHits[serverStatusOut.m_raycastHits.m_numRaycastHits].m_hitNormalWorld[2]
= rayResultCallback.m_hitNormalWorld[2];
serverStatusOut.m_raycastHits.m_numRaycastHits++; serverStatusOut.m_raycastHits.m_numRaycastHits++;
} }
serverStatusOut.m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS_COMPLETED; serverStatusOut.m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS_COMPLETED;
@ -2756,10 +2792,21 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
fwrite(line,len,1,f); fwrite(line,len,1,f);
} }
{ {
sprintf(line,"p.connect(p.SHARED_MEMORY)\n"); sprintf(line,"cin = p.connect(p.SHARED_MEMORY)\n");
int len = strlen(line); int len = strlen(line);
fwrite(line,len,1,f); fwrite(line,len,1,f);
} }
{
sprintf(line,"if (cin < 0):\n");
int len = strlen(line);
fwrite(line,len,1,f);
}
{
sprintf(line," cin = p.connect(p.GUI)\n");
int len = strlen(line);
fwrite(line,len,1,f);
}
//for each objects ... //for each objects ...
for (int i=0;i<m_data->m_saveWorldBodyData.size();i++) for (int i=0;i<m_data->m_saveWorldBodyData.size();i++)
{ {
@ -2794,15 +2841,21 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
int len = strlen(line); int len = strlen(line);
fwrite(line,len,1,f); fwrite(line,len,1,f);
} }
if (strstr(sd.m_fileName.c_str(),".xml") && i==0)
{
sprintf(line,"objects = p.loadMJCF(\"%s\")\n",sd.m_fileName.c_str());
int len = strlen(line);
fwrite(line,len,1,f);
}
if (strstr(sd.m_fileName.c_str(),".sdf") || ((strstr(sd.m_fileName.c_str(),".urdf")) && mb->getNumLinks()) ) if (strstr(sd.m_fileName.c_str(),".sdf") || strstr(sd.m_fileName.c_str(),".xml") || ((strstr(sd.m_fileName.c_str(),".urdf")) && mb->getNumLinks()) )
{ {
sprintf(line,"ob = objects[%d]\n",i); sprintf(line,"ob = objects[%d]\n",i);
int len = strlen(line); int len = strlen(line);
fwrite(line,len,1,f); fwrite(line,len,1,f);
} }
if (strstr(sd.m_fileName.c_str(),".sdf")) if (strstr(sd.m_fileName.c_str(),".sdf")||strstr(sd.m_fileName.c_str(),".xml"))
{ {
sprintf(line,"p.resetBasePositionAndOrientation(ob,[%f,%f,%f],[%f,%f,%f,%f])\n", sprintf(line,"p.resetBasePositionAndOrientation(ob,[%f,%f,%f],[%f,%f,%f,%f])\n",
comTr.getOrigin()[0],comTr.getOrigin()[1],comTr.getOrigin()[2], comTr.getOrigin()[0],comTr.getOrigin()[1],comTr.getOrigin()[2],
@ -4155,6 +4208,24 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
break; break;
} }
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA:
{
BT_PROFILE("CMD_REQUEST_OPENGL_VISUALIZER_CAMERA");
SharedMemoryStatus& serverCmd = serverStatusOut;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&serverCmd.m_visualizerCameraResultArgs.m_width,
&serverCmd.m_visualizerCameraResultArgs.m_height,
serverCmd.m_visualizerCameraResultArgs.m_viewMatrix,
serverCmd.m_visualizerCameraResultArgs.m_projectionMatrix,
serverCmd.m_visualizerCameraResultArgs.m_camUp,
serverCmd.m_visualizerCameraResultArgs.m_camForward,
serverCmd.m_visualizerCameraResultArgs.m_horizontal,
serverCmd.m_visualizerCameraResultArgs.m_vertical);
serverCmd.m_type = result ? CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED: CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_FAILED;
hasStatus = true;
break;
}
case CMD_CONFIGURE_OPENGL_VISUALIZER: case CMD_CONFIGURE_OPENGL_VISUALIZER:
{ {
BT_PROFILE("CMD_CONFIGURE_OPENGL_VISUALIZER"); BT_PROFILE("CMD_CONFIGURE_OPENGL_VISUALIZER");
@ -4585,7 +4656,7 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
// Set jacobian value // Set jacobian value
tree->calculateJacobians(q); tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, num_dofs); btInverseDynamics::mat3x jac_t(3, num_dofs);
tree->getBodyJacobianTrans(clientCmd.m_calculateJacobianArguments.m_linkIndex, &jac_t); tree->getBodyJacobianTrans(clientCmd.m_calculateJacobianArguments.m_linkIndex+1, &jac_t);
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
for (int j = 0; j < num_dofs; ++j) for (int j = 0; j < num_dofs; ++j)
@ -5011,8 +5082,9 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
tree->calculateJacobians(q); tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs); btInverseDynamics::mat3x jac_t(3, numDofs);
btInverseDynamics::mat3x jac_r(3,numDofs); btInverseDynamics::mat3x jac_r(3,numDofs);
tree->getBodyJacobianTrans(endEffectorLinkIndex, &jac_t); // Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianRot(endEffectorLinkIndex, &jac_r); tree->getBodyJacobianTrans(endEffectorLinkIndex+1, &jac_t);
tree->getBodyJacobianRot(endEffectorLinkIndex+1, &jac_r);
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
for (int j = 0; j < numDofs; ++j) for (int j = 0; j < numDofs; ++j)
@ -5652,15 +5724,15 @@ void PhysicsServerCommandProcessor::enableRealTimeSimulation(bool enableRealTime
m_data->m_allowRealTimeSimulation = enableRealTimeSim; m_data->m_allowRealTimeSimulation = enableRealTimeSim;
} }
void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec, const struct b3VRControllerEvent* vrEvents, int numVREvents,const struct b3KeyboardEvent* keyEvents, int numKeyEvents) void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec, const struct b3VRControllerEvent* vrControllerEvents, int numVRControllerEvents,const struct b3KeyboardEvent* keyEvents, int numKeyEvents)
{ {
m_data->m_vrEvents1.addNewVREvents(vrEvents,numVREvents); m_data->m_vrControllerEvents.addNewVREvents(vrControllerEvents,numVRControllerEvents);
for (int i=0;i<m_data->m_stateLoggers.size();i++) for (int i=0;i<m_data->m_stateLoggers.size();i++)
{ {
if (m_data->m_stateLoggers[i]->m_loggingType==STATE_LOGGING_VR_CONTROLLERS) if (m_data->m_stateLoggers[i]->m_loggingType==STATE_LOGGING_VR_CONTROLLERS)
{ {
VRControllerStateLogger* vrLogger = (VRControllerStateLogger*) m_data->m_stateLoggers[i]; VRControllerStateLogger* vrLogger = (VRControllerStateLogger*) m_data->m_stateLoggers[i];
vrLogger->m_vrEvents.addNewVREvents(vrEvents,numVREvents); vrLogger->m_vrEvents.addNewVREvents(vrControllerEvents,numVRControllerEvents);
} }
} }
@ -5759,6 +5831,7 @@ void PhysicsServerCommandProcessor::resetSimulation()
if (m_data && m_data->m_guiHelper) if (m_data && m_data->m_guiHelper)
{ {
m_data->m_guiHelper->removeAllGraphicsInstances(); m_data->m_guiHelper->removeAllGraphicsInstances();
m_data->m_guiHelper->removeAllUserDebugItems();
} }
if (m_data) if (m_data)
{ {
@ -6180,8 +6253,8 @@ void PhysicsServerCommandProcessor::createDefaultRobotAssets()
tree->calculateJacobians(q); tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3,numDofs); btInverseDynamics::mat3x jac_t(3,numDofs);
btInverseDynamics::mat3x jac_r(3,numDofs); btInverseDynamics::mat3x jac_r(3,numDofs);
tree->getBodyJacobianTrans(endEffectorLinkIndex, &jac_t); tree->getBodyJacobianTrans(endEffectorLinkIndex+1, &jac_t);
tree->getBodyJacobianRot(endEffectorLinkIndex, &jac_r); tree->getBodyJacobianRot(endEffectorLinkIndex+1, &jac_r);
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
for (int j = 0; j < numDofs; ++j) for (int j = 0; j < numDofs; ++j)

View File

@ -808,6 +808,12 @@ public:
m_childGuiHelper->resetCamera(camDist,pitch,yaw,camPosX,camPosY,camPosZ); m_childGuiHelper->resetCamera(camDist,pitch,yaw,camPosX,camPosY,camPosZ);
} }
virtual bool getCameraInfo(int* width, int* height, float viewMatrix[16], float projectionMatrix[16], float camUp[3], float camForward[3],float hor[3], float vert[3] ) const
{
return m_childGuiHelper->getCameraInfo(width,height,viewMatrix,projectionMatrix,camUp,camForward,hor,vert);
}
float m_viewMatrix[16]; float m_viewMatrix[16];
float m_projectionMatrix[16]; float m_projectionMatrix[16];
unsigned char* m_pixelsRGBA; unsigned char* m_pixelsRGBA;
@ -1046,6 +1052,8 @@ public:
virtual void vrControllerButtonCallback(int controllerId, int button, int state, float pos[4], float orientation[4]); virtual void vrControllerButtonCallback(int controllerId, int button, int state, float pos[4], float orientation[4]);
virtual void vrControllerMoveCallback(int controllerId, float pos[4], float orientation[4], float analogAxis); virtual void vrControllerMoveCallback(int controllerId, float pos[4], float orientation[4], float analogAxis);
virtual void vrHMDMoveCallback(int controllerId, float pos[4], float orientation[4]);
virtual void vrGenericTrackerMoveCallback(int controllerId, float pos[4], float orientation[4]);
virtual bool mouseMoveCallback(float x,float y) virtual bool mouseMoveCallback(float x,float y)
@ -2229,6 +2237,7 @@ void PhysicsServerExample::vrControllerButtonCallback(int controllerId, int butt
m_args[0].m_csGUI->lock(); m_args[0].m_csGUI->lock();
m_args[0].m_vrControllerEvents[controllerId].m_controllerId = controllerId; m_args[0].m_vrControllerEvents[controllerId].m_controllerId = controllerId;
m_args[0].m_vrControllerEvents[controllerId].m_deviceType = VR_DEVICE_CONTROLLER;
m_args[0].m_vrControllerEvents[controllerId].m_pos[0] = trTotal.getOrigin()[0]; m_args[0].m_vrControllerEvents[controllerId].m_pos[0] = trTotal.getOrigin()[0];
m_args[0].m_vrControllerEvents[controllerId].m_pos[1] = trTotal.getOrigin()[1]; m_args[0].m_vrControllerEvents[controllerId].m_pos[1] = trTotal.getOrigin()[1];
m_args[0].m_vrControllerEvents[controllerId].m_pos[2] = trTotal.getOrigin()[2]; m_args[0].m_vrControllerEvents[controllerId].m_pos[2] = trTotal.getOrigin()[2];
@ -2252,7 +2261,7 @@ void PhysicsServerExample::vrControllerButtonCallback(int controllerId, int butt
void PhysicsServerExample::vrControllerMoveCallback(int controllerId, float pos[4], float orn[4], float analogAxis) void PhysicsServerExample::vrControllerMoveCallback(int controllerId, float pos[4], float orn[4], float analogAxis)
{ {
if (controllerId <= 0 || controllerId >= MAX_VR_CONTROLLERS) if (controllerId < 0 || controllerId >= MAX_VR_CONTROLLERS)
{ {
printf("Controller Id exceeds max: %d > %d", controllerId, MAX_VR_CONTROLLERS); printf("Controller Id exceeds max: %d > %d", controllerId, MAX_VR_CONTROLLERS);
return; return;
@ -2299,6 +2308,7 @@ void PhysicsServerExample::vrControllerMoveCallback(int controllerId, float pos[
m_args[0].m_csGUI->lock(); m_args[0].m_csGUI->lock();
m_args[0].m_vrControllerEvents[controllerId].m_controllerId = controllerId; m_args[0].m_vrControllerEvents[controllerId].m_controllerId = controllerId;
m_args[0].m_vrControllerEvents[controllerId].m_deviceType = VR_DEVICE_CONTROLLER;
m_args[0].m_vrControllerEvents[controllerId].m_pos[0] = trTotal.getOrigin()[0]; m_args[0].m_vrControllerEvents[controllerId].m_pos[0] = trTotal.getOrigin()[0];
m_args[0].m_vrControllerEvents[controllerId].m_pos[1] = trTotal.getOrigin()[1]; m_args[0].m_vrControllerEvents[controllerId].m_pos[1] = trTotal.getOrigin()[1];
m_args[0].m_vrControllerEvents[controllerId].m_pos[2] = trTotal.getOrigin()[2]; m_args[0].m_vrControllerEvents[controllerId].m_pos[2] = trTotal.getOrigin()[2];
@ -2311,4 +2321,87 @@ void PhysicsServerExample::vrControllerMoveCallback(int controllerId, float pos[
m_args[0].m_csGUI->unlock(); m_args[0].m_csGUI->unlock();
} }
void PhysicsServerExample::vrHMDMoveCallback(int controllerId, float pos[4], float orn[4])
{
if (controllerId < 0 || controllerId >= MAX_VR_CONTROLLERS)
{
printf("Controller Id exceeds max: %d > %d", controllerId, MAX_VR_CONTROLLERS);
return;
}
//we may need to add some trLocal transform, to align the camera to our preferences
btTransform trLocal;
trLocal.setIdentity();
// trLocal.setRotation(btQuaternion(btVector3(0, 0, 1), SIMD_HALF_PI)*btQuaternion(btVector3(0, 1, 0), SIMD_HALF_PI));
btTransform trOrg;
trOrg.setIdentity();
trOrg.setOrigin(btVector3(pos[0], pos[1], pos[2]));
trOrg.setRotation(btQuaternion(orn[0], orn[1], orn[2], orn[3]));
btTransform tr2a;
tr2a.setIdentity();
btTransform tr2;
tr2.setIdentity();
tr2.setOrigin(gVRTeleportPos1);
tr2a.setRotation(gVRTeleportOrn);
btTransform trTotal = tr2*tr2a*trOrg*trLocal;
m_args[0].m_csGUI->lock();
m_args[0].m_vrControllerEvents[controllerId].m_controllerId = controllerId;
m_args[0].m_vrControllerEvents[controllerId].m_deviceType = VR_DEVICE_HMD;
m_args[0].m_vrControllerEvents[controllerId].m_pos[0] = trTotal.getOrigin()[0];
m_args[0].m_vrControllerEvents[controllerId].m_pos[1] = trTotal.getOrigin()[1];
m_args[0].m_vrControllerEvents[controllerId].m_pos[2] = trTotal.getOrigin()[2];
m_args[0].m_vrControllerEvents[controllerId].m_orn[0] = trTotal.getRotation()[0];
m_args[0].m_vrControllerEvents[controllerId].m_orn[1] = trTotal.getRotation()[1];
m_args[0].m_vrControllerEvents[controllerId].m_orn[2] = trTotal.getRotation()[2];
m_args[0].m_vrControllerEvents[controllerId].m_orn[3] = trTotal.getRotation()[3];
m_args[0].m_vrControllerEvents[controllerId].m_numMoveEvents++;
m_args[0].m_csGUI->unlock();
}
void PhysicsServerExample::vrGenericTrackerMoveCallback(int controllerId, float pos[4], float orn[4])
{
if (controllerId < 0 || controllerId >= MAX_VR_CONTROLLERS)
{
printf("Controller Id exceeds max: %d > %d", controllerId, MAX_VR_CONTROLLERS);
return;
}
//we may need to add some trLocal transform, to align the camera to our preferences
btTransform trLocal;
trLocal.setIdentity();
trLocal.setRotation(btQuaternion(btVector3(0, 0, 1), SIMD_HALF_PI)*btQuaternion(btVector3(0, 1, 0), SIMD_HALF_PI));
btTransform trOrg;
trOrg.setIdentity();
trOrg.setOrigin(btVector3(pos[0], pos[1], pos[2]));
trOrg.setRotation(btQuaternion(orn[0], orn[1], orn[2], orn[3]));
btTransform tr2a;
tr2a.setIdentity();
btTransform tr2;
tr2.setIdentity();
tr2.setOrigin(gVRTeleportPos1);
tr2a.setRotation(gVRTeleportOrn);
btTransform trTotal = tr2*tr2a*trOrg*trLocal;
m_args[0].m_csGUI->lock();
m_args[0].m_vrControllerEvents[controllerId].m_controllerId = controllerId;
m_args[0].m_vrControllerEvents[controllerId].m_deviceType = VR_DEVICE_GENERIC_TRACKER;
m_args[0].m_vrControllerEvents[controllerId].m_pos[0] = trTotal.getOrigin()[0];
m_args[0].m_vrControllerEvents[controllerId].m_pos[1] = trTotal.getOrigin()[1];
m_args[0].m_vrControllerEvents[controllerId].m_pos[2] = trTotal.getOrigin()[2];
m_args[0].m_vrControllerEvents[controllerId].m_orn[0] = trTotal.getRotation()[0];
m_args[0].m_vrControllerEvents[controllerId].m_orn[1] = trTotal.getRotation()[1];
m_args[0].m_vrControllerEvents[controllerId].m_orn[2] = trTotal.getRotation()[2];
m_args[0].m_vrControllerEvents[controllerId].m_orn[3] = trTotal.getRotation()[3];
m_args[0].m_vrControllerEvents[controllerId].m_numMoveEvents++;
m_args[0].m_csGUI->unlock();
}
B3_STANDALONE_EXAMPLE(PhysicsServerCreateFunc) B3_STANDALONE_EXAMPLE(PhysicsServerCreateFunc)

View File

@ -185,14 +185,15 @@ enum EnumRequestContactDataUpdateFlags
struct RequestRaycastIntersections struct RequestRaycastIntersections
{ {
double m_rayFromPosition[3]; int m_numRays;
double m_rayToPosition[3]; double m_rayFromPositions[MAX_RAY_INTERSECTION_BATCH_SIZE][3];
double m_rayToPositions[MAX_RAY_INTERSECTION_BATCH_SIZE][3];
}; };
struct SendRaycastHits struct SendRaycastHits
{ {
int m_numRaycastHits; int m_numRaycastHits;
b3RayHitInfo m_rayHits[MAX_RAY_HITS]; b3RayHitInfo m_rayHits[MAX_RAY_INTERSECTION_BATCH_SIZE];
}; };
struct RequestContactDataArgs struct RequestContactDataArgs
@ -604,6 +605,7 @@ struct UserDebugDrawResultArgs
double m_parameterValue; double m_parameterValue;
}; };
struct SendVREvents struct SendVREvents
{ {
int m_numVRControllerEvents; int m_numVRControllerEvents;
@ -616,6 +618,7 @@ struct SendKeyboardEvents
b3KeyboardEvent m_keyboardEvents[MAX_KEYBOARD_EVENTS]; b3KeyboardEvent m_keyboardEvents[MAX_KEYBOARD_EVENTS];
}; };
enum eVRCameraEnums enum eVRCameraEnums
{ {
VR_CAMERA_ROOT_POSITION=1, VR_CAMERA_ROOT_POSITION=1,
@ -633,6 +636,7 @@ enum eStateLoggingEnums
STATE_LOGGING_FILTER_LINK_INDEX_B=32, STATE_LOGGING_FILTER_LINK_INDEX_B=32,
STATE_LOGGING_FILTER_BODY_UNIQUE_ID_A=64, STATE_LOGGING_FILTER_BODY_UNIQUE_ID_A=64,
STATE_LOGGING_FILTER_BODY_UNIQUE_ID_B=128, STATE_LOGGING_FILTER_BODY_UNIQUE_ID_B=128,
STATE_LOGGING_FILTER_DEVICE_TYPE=256
}; };
struct VRCameraState struct VRCameraState
@ -656,6 +660,7 @@ struct StateLoggingRequest
int m_linkIndexB; // only if STATE_LOGGING_FILTER_LINK_INDEX_B flag is set int m_linkIndexB; // only if STATE_LOGGING_FILTER_LINK_INDEX_B flag is set
int m_bodyUniqueIdA; // only if STATE_LOGGING_FILTER_BODY_UNIQUE_ID_A flag is set int m_bodyUniqueIdA; // only if STATE_LOGGING_FILTER_BODY_UNIQUE_ID_A flag is set
int m_bodyUniqueIdB; // only if STATE_LOGGING_FILTER_BODY_UNIQUE_ID_B flag is set int m_bodyUniqueIdB; // only if STATE_LOGGING_FILTER_BODY_UNIQUE_ID_B flag is set
int m_deviceFilterType; //user to select (filter) which VR devices to log
}; };
struct StateLoggingResultArgs struct StateLoggingResultArgs
@ -785,7 +790,7 @@ struct SharedMemoryStatus
struct SendKeyboardEvents m_sendKeyboardEvents; struct SendKeyboardEvents m_sendKeyboardEvents;
struct SendRaycastHits m_raycastHits; struct SendRaycastHits m_raycastHits;
struct StateLoggingResultArgs m_stateLoggingResultArgs; struct StateLoggingResultArgs m_stateLoggingResultArgs;
struct b3OpenGLVisualizerCameraInfo m_visualizerCameraResultArgs;
}; };
}; };

View File

@ -54,6 +54,7 @@ enum EnumSharedMemoryClientCommand
CMD_STATE_LOGGING, CMD_STATE_LOGGING,
CMD_CONFIGURE_OPENGL_VISUALIZER, CMD_CONFIGURE_OPENGL_VISUALIZER,
CMD_REQUEST_KEYBOARD_EVENTS_DATA, CMD_REQUEST_KEYBOARD_EVENTS_DATA,
CMD_REQUEST_OPENGL_VISUALIZER_CAMERA,
//don't go beyond this command! //don't go beyond this command!
CMD_MAX_CLIENT_COMMANDS, CMD_MAX_CLIENT_COMMANDS,
@ -133,6 +134,8 @@ enum EnumSharedMemoryServerStatus
CMD_STATE_LOGGING_FAILED, CMD_STATE_LOGGING_FAILED,
CMD_REQUEST_KEYBOARD_EVENTS_DATA_COMPLETED, CMD_REQUEST_KEYBOARD_EVENTS_DATA_COMPLETED,
CMD_REQUEST_KEYBOARD_EVENTS_DATA_FAILED, CMD_REQUEST_KEYBOARD_EVENTS_DATA_FAILED,
CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_FAILED,
CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED,
//don't go beyond 'CMD_MAX_SERVER_COMMANDS! //don't go beyond 'CMD_MAX_SERVER_COMMANDS!
CMD_MAX_SERVER_COMMANDS CMD_MAX_SERVER_COMMANDS
}; };
@ -248,18 +251,37 @@ struct b3CameraImageData
const int* m_segmentationMaskValues;//m_pixelWidth*m_pixelHeight ints const int* m_segmentationMaskValues;//m_pixelWidth*m_pixelHeight ints
}; };
struct b3OpenGLVisualizerCameraInfo
{
int m_width;
int m_height;
float m_viewMatrix[16];
float m_projectionMatrix[16];
float m_camUp[3];
float m_camForward[3];
float m_horizontal[3];
float m_vertical[3];
};
enum b3VREventType enum b3VREventType
{ {
VR_CONTROLLER_MOVE_EVENT=1, VR_CONTROLLER_MOVE_EVENT=1,
VR_CONTROLLER_BUTTON_EVENT VR_CONTROLLER_BUTTON_EVENT=2,
VR_HMD_MOVE_EVENT=4,
VR_GENERIC_TRACKER_MOVE_EVENT=8,
}; };
#define MAX_VR_BUTTONS 64 #define MAX_VR_BUTTONS 64
#define MAX_VR_CONTROLLERS 8 #define MAX_VR_CONTROLLERS 8
#define MAX_RAY_HITS 128
#define MAX_RAY_INTERSECTION_BATCH_SIZE 256
#define MAX_RAY_HITS MAX_RAY_INTERSECTION_BATCH_SIZE
#define MAX_KEYBOARD_EVENTS 256 #define MAX_KEYBOARD_EVENTS 256
enum b3VRButtonInfo enum b3VRButtonInfo
{ {
eButtonIsDown = 1, eButtonIsDown = 1,
@ -267,9 +289,19 @@ enum b3VRButtonInfo
eButtonReleased = 4, eButtonReleased = 4,
}; };
enum eVRDeviceTypeEnums
{
VR_DEVICE_CONTROLLER=1,
VR_DEVICE_HMD=2,
VR_DEVICE_GENERIC_TRACKER=4,
};
struct b3VRControllerEvent struct b3VRControllerEvent
{ {
int m_controllerId;//valid for VR_CONTROLLER_MOVE_EVENT and VR_CONTROLLER_BUTTON_EVENT int m_controllerId;//valid for VR_CONTROLLER_MOVE_EVENT and VR_CONTROLLER_BUTTON_EVENT
int m_deviceType;
int m_numMoveEvents; int m_numMoveEvents;
int m_numButtonEvents; int m_numButtonEvents;
@ -285,6 +317,11 @@ struct b3VREventsData
{ {
int m_numControllerEvents; int m_numControllerEvents;
struct b3VRControllerEvent* m_controllerEvents; struct b3VRControllerEvent* m_controllerEvents;
int m_numHmdEvents;
struct b3VRMoveEvent* m_hmdEvents;
int m_numGenericTrackerEvents;
struct b3VRMoveEvent* m_genericTrackerEvents;
}; };

View File

@ -37,7 +37,7 @@ ELSE(WIN32)
ADD_DEFINITIONS("-DGLEW_STATIC") ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1") ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( X11 pthread dl Xext) LINK_LIBRARIES( X11 pthread ${DL} Xext)
ENDIF(APPLE) ENDIF(APPLE)
ENDIF(WIN32) ENDIF(WIN32)

View File

@ -1,12 +1,23 @@
//#define USE_OPENGL2
#ifdef USE_OPENGL2
#include "OpenGLWindow/SimpleOpenGL2App.h"
typedef SimpleOpenGL2App SimpleOpenGLApp ;
#else
#include "OpenGLWindow/SimpleOpenGL3App.h" #include "OpenGLWindow/SimpleOpenGL3App.h"
typedef SimpleOpenGL3App SimpleOpenGLApp ;
#endif //USE_OPENGL2
#include "Bullet3Common/b3Quaternion.h" #include "Bullet3Common/b3Quaternion.h"
#include "Bullet3Common/b3CommandLineArgs.h" #include "Bullet3Common/b3CommandLineArgs.h"
#include "assert.h" #include "assert.h"
#include <stdio.h> #include <stdio.h>
char* gVideoFileName = 0; char* gVideoFileName = 0;
char* gPngFileName = 0; char* gPngFileName = 0;
@ -19,9 +30,131 @@ static b3KeyboardCallback sOldKeyboardCB = 0;
float gWidth = 1024; float gWidth = 1024;
float gHeight = 768; float gHeight = 768;
SimpleOpenGLApp* app = 0;
float gMouseX = 0;
float gMouseY = 0;
float g_MouseWheel = 0.0f;
int g_MousePressed[3] = {0};
int g_MousePressed2[3] = {0};
//#define B3_USE_IMGUI
#ifdef B3_USE_IMGUI
#include "OpenGLWindow/OpenGLInclude.h"
#include "ThirdPartyLibs/imgui/imgui.h"
static GLuint g_FontTexture = 0;
void ImGui_ImplBullet_CreateDeviceObjects()
{
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
}
void ImGui_ImplBullet_RenderDrawLists(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_TEXTURE_2D);
//glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Render command lists
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, pos)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
#undef OFFSETOF
// Restore modified state
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
#endif //B3_USE_IMGUI
void MyWheelCallback(float deltax, float deltay) void MyWheelCallback(float deltax, float deltay)
{ {
g_MouseWheel += deltax+deltay;
if (sOldWheelCB) if (sOldWheelCB)
sOldWheelCB(deltax,deltay); sOldWheelCB(deltax,deltay);
} }
@ -36,12 +169,29 @@ void MyResizeCallback( float width, float height)
void MyMouseMoveCallback( float x, float y) void MyMouseMoveCallback( float x, float y)
{ {
printf("Mouse Move: %f, %f\n", x,y); printf("Mouse Move: %f, %f\n", x,y);
gMouseX = x;
gMouseY = y;
if (sOldMouseMoveCB) if (sOldMouseMoveCB)
sOldMouseMoveCB(x,y); sOldMouseMoveCB(x,y);
} }
void MyMouseButtonCallback(int button, int state, float x, float y) void MyMouseButtonCallback(int button, int state, float x, float y)
{ {
gMouseX = x;
gMouseY = y;
{
if (button>=0 && button<3)
{
if (state)
{
g_MousePressed[button] = state;
}
g_MousePressed2[button] = state;
}
}
if (sOldMouseButtonCB) if (sOldMouseButtonCB)
sOldMouseButtonCB(button,state,x,y); sOldMouseButtonCB(button,state,x,y);
} }
@ -59,17 +209,56 @@ void MyKeyboardCallback(int keycode, int state)
} }
bool ImGui_ImplGlfw_Init()
{
#if 0
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.RenderDrawListsFn = ImGui_ImplGlfw_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
io.ClipboardUserData = g_Window;
#ifdef _WIN32
io.ImeWindowHandle = glfwGetWin32Window(g_Window);
#endif
#endif
return true;
}
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
{ {
b3CommandLineArgs myArgs(argc, argv); b3CommandLineArgs myArgs(argc, argv);
SimpleOpenGL3App* app = new SimpleOpenGL3App("SimpleOpenGL3App", gWidth, gHeight, true); app = new SimpleOpenGLApp("SimpleOpenGLApp", gWidth, gHeight);
app->m_renderer->getActiveCamera()->setCameraDistance(13);
app->m_renderer->getActiveCamera()->setCameraPitch(0);
app->m_renderer->getActiveCamera()->setCameraTargetPosition(0, 0, 0);
app->m_instancingRenderer->getActiveCamera()->setCameraDistance(13);
app->m_instancingRenderer->getActiveCamera()->setCameraPitch(0);
app->m_instancingRenderer->getActiveCamera()->setCameraTargetPosition(0, 0, 0);
sOldKeyboardCB = app->m_window->getKeyboardCallback(); sOldKeyboardCB = app->m_window->getKeyboardCallback();
app->m_window->setKeyboardCallback(MyKeyboardCallback); app->m_window->setKeyboardCallback(MyKeyboardCallback);
sOldMouseMoveCB = app->m_window->getMouseMoveCallback(); sOldMouseMoveCB = app->m_window->getMouseMoveCallback();
@ -120,6 +309,8 @@ int main(int argc, char* argv[])
//update the texels of the texture using a simple pattern, animated using frame index //update the texels of the texture using a simple pattern, animated using frame index
for (int y = 0; y < textureHeight; ++y) for (int y = 0; y < textureHeight; ++y)
{ {
@ -137,19 +328,62 @@ int main(int argc, char* argv[])
app->m_renderer->activateTexture(textureHandle); app->m_renderer->activateTexture(textureHandle);
app->m_renderer->updateTexture(textureHandle, image); app->m_renderer->updateTexture(textureHandle, image);
float color[4] = { 255, 1, 1, 1 }; //float color[4] = { 255, 1, 1, 1 };
app->m_primRenderer->drawTexturedRect(100, 200, gWidth / 2 - 50, gHeight / 2 - 50, color, 0, 0, 1, 1, true); //app->m_primRenderer->drawTexturedRect(100, 200, gWidth / 2 - 50, gHeight / 2 - 50, color, 0, 0, 1, 1, true);
app->m_instancingRenderer->init(); app->m_renderer->init();
app->m_instancingRenderer->updateCamera(); app->m_renderer->updateCamera(1);
app->m_renderer->renderScene(); app->m_renderer->renderScene();
app->drawGrid(); app->drawGrid();
char bla[1024]; char bla[1024];
sprintf(bla, "Simple test frame %d", frameCount); sprintf(bla, "Simple test frame %d", frameCount);
app->drawText(bla, 10, 10); //app->drawText(bla, 10, 10);
#ifdef B3_USE_IMGUI
{
bool show_test_window = true;
bool show_another_window = false;
ImVec4 clear_color = ImColor(114, 144, 154);
// Start the frame
ImGuiIO& io = ImGui::GetIO();
if (!g_FontTexture)
ImGui_ImplBullet_CreateDeviceObjects();
io.DisplaySize = ImVec2((float)gWidth, (float)gHeight);
io.DisplayFramebufferScale = ImVec2(gWidth > 0 ? ((float)1.) : 0, gHeight > 0 ? ((float)1.) : 0);
io.DeltaTime = (float)(1.0f/60.0f);
io.MousePos = ImVec2((float)gMouseX, (float)gMouseY);
io.RenderDrawListsFn = ImGui_ImplBullet_RenderDrawLists;
for (int i=0;i<3;i++)
{
io.MouseDown[i] = g_MousePressed[i]|g_MousePressed2[i];
g_MousePressed[i] = false;
}
io.MouseWheel = g_MouseWheel;
ImGui::NewFrame();
ImGui::ShowTestWindow();
ImGui::ShowMetricsWindow();
#if 0
static float f = 0.0f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
ImGui::ColorEdit3("clear color", (float*)&clear_color);
if (ImGui::Button("Test Window")) show_test_window ^= 1;
if (ImGui::Button("Another Window")) show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
#endif
ImGui::Render();
}
#endif //B3_USE_IMGUI
app->swapBuffer(); app->swapBuffer();
} while (!app->m_window->requestedExit()); } while (!app->m_window->requestedExit());

View File

@ -709,8 +709,50 @@ bool CMainApplication::HandleInput()
vr::VRControllerState_t state; vr::VRControllerState_t state;
if( m_pHMD->GetControllerState( unDevice, &state ,sizeof(vr::VRControllerState_t)) ) if( m_pHMD->GetControllerState( unDevice, &state ,sizeof(vr::VRControllerState_t)) )
{ {
b3Transform tr;
getControllerTransform(unDevice, tr);
float pos[3] = { tr.getOrigin()[0], tr.getOrigin()[1], tr.getOrigin()[2] };
b3Quaternion born = tr.getRotation();
float orn[4] = { born[0], born[1], born[2], born[3] };
//we need to have the 'move' events, so no early out here //we need to have the 'move' events, so no early out here
//if (sPrevStates[unDevice].unPacketNum != state.unPacketNum) //if (sPrevStates[unDevice].unPacketNum != state.unPacketNum)
if( m_pHMD->GetTrackedDeviceClass( unDevice) == vr::TrackedDeviceClass_HMD )
{
Matrix4 rotYtoZ = rotYtoZ.identity();
//some Bullet apps (especially robotics related) require Z as up-axis)
if (m_app->getUpAxis()==2)
{
rotYtoZ.rotateX(-90);
}
Matrix4 viewMatCenter = m_mat4HMDPose * rotYtoZ;
const float* mat = viewMatCenter.invertAffine().get();
pos[0] = mat[12];
pos[1] = mat[13];
pos[2] = mat[14];
b3Matrix3x3 bmat;
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
bmat[i][j] = mat[i+4*j];
}
}
b3Quaternion orn2;
bmat.getRotation(orn2);
orn[0] = orn2[0];
orn[1] = orn2[1];
orn[2] = orn2[2];
orn[3] = orn2[3];
sExample->vrHMDMoveCallback(unDevice, pos,orn);
}
if( m_pHMD->GetTrackedDeviceClass( unDevice) == vr::TrackedDeviceClass_GenericTracker )
{
sExample->vrGenericTrackerMoveCallback(unDevice, pos,orn);
}
if( m_pHMD->GetTrackedDeviceClass( unDevice) == vr::TrackedDeviceClass_Controller ) if( m_pHMD->GetTrackedDeviceClass( unDevice) == vr::TrackedDeviceClass_Controller )
{ {
sPrevStates[unDevice].unPacketNum = state.unPacketNum; sPrevStates[unDevice].unPacketNum = state.unPacketNum;
@ -723,11 +765,6 @@ bool CMainApplication::HandleInput()
if (isTrigger) if (isTrigger)
{ {
b3Transform tr;
getControllerTransform(unDevice, tr);
float pos[3] = { tr.getOrigin()[0], tr.getOrigin()[1], tr.getOrigin()[2] };
b3Quaternion born = tr.getRotation();
float orn[4] = { born[0], born[1], born[2], born[3] };
//pressed now, not pressed before -> raise a button down event //pressed now, not pressed before -> raise a button down event
if ((sPrevStates[unDevice].ulButtonPressed&trigger)==0) if ((sPrevStates[unDevice].ulButtonPressed&trigger)==0)
@ -765,11 +802,6 @@ bool CMainApplication::HandleInput()
{ {
b3Transform tr;
getControllerTransform(unDevice, tr);
float pos[3] = { tr.getOrigin()[0], tr.getOrigin()[1], tr.getOrigin()[2] };
b3Quaternion born = tr.getRotation();
float orn[4] = { born[0], born[1], born[2], born[3] };
// printf("Device RELEASED: %d, button %d\n", unDevice,button); // printf("Device RELEASED: %d, button %d\n", unDevice,button);
//not pressed now, but pressed before -> raise a button up event //not pressed now, but pressed before -> raise a button up event

View File

@ -35,7 +35,7 @@ int main(int argc, char* argv[])
CommonExampleInterface* example = StandaloneExampleCreateFunc(options); CommonExampleInterface* example = StandaloneExampleCreateFunc(options);
example->initPhysics(); example->initPhysics();
for (int i = 0; i < 1000; i++) for (int i = 0; i < 100000; i++)
{ {
printf("Simulating step %d\n", i); printf("Simulating step %d\n", i);
example->stepSimulation(1.f / 60.f); example->stepSimulation(1.f / 60.f);

View File

@ -4,7 +4,7 @@
#define GWEN_MACROS_H #define GWEN_MACROS_H
#include <stdlib.h> #include <stdlib.h>
#include <stdarg.h> #include <stdarg.h>
#ifndef __APPLE__ #if !defined(__APPLE__) && !defined(__OpenBSD__)
#include <malloc.h> #include <malloc.h>
#endif //__APPLE__ #endif //__APPLE__
#include <memory.h> #include <memory.h>
@ -38,7 +38,7 @@
#define GwenUtil_OutputDebugWideString( lpOutputString ) //wprintf( lpOutputString ) #define GwenUtil_OutputDebugWideString( lpOutputString ) //wprintf( lpOutputString )
#define GwenUtil_WideStringToFloat( _Str ) wcstof(_Str, NULL) #define GwenUtil_WideStringToFloat( _Str ) wcstof(_Str, NULL)
#elif defined(__linux__) #elif defined(__linux__) || defined(__OpenBSD__)
#define GwenUtil_VSNPrintFSafe( _DstBuf, _DstSize, _MaxCount, _Format, _ArgList ) vsnprintf( _DstBuf, _DstSize, _Format, _ArgList ) #define GwenUtil_VSNPrintFSafe( _DstBuf, _DstSize, _MaxCount, _Format, _ArgList ) vsnprintf( _DstBuf, _DstSize, _Format, _ArgList )
#define GwenUtil_VSWPrintFSafe( _DstBuf, _SizeInWords, _Format, _ArgList ) vswprintf( _DstBuf, _SizeInWords, _Format, _ArgList ) #define GwenUtil_VSWPrintFSafe( _DstBuf, _SizeInWords, _Format, _ArgList ) vswprintf( _DstBuf, _SizeInWords, _Format, _ArgList )

View File

@ -30,14 +30,7 @@ LIST(APPEND CLSOCKET_SOURCES ${CLSOCKET_HEADERS})
# OS and compiler checks. # OS and compiler checks.
if(UNIX) if(UNIX)
# linux / normal unix # linux / normal unix
add_definitions(-D_LINUX) add_definitions(${OSDEF})
if(CYGWIN)
# Special Cygwin stuff here
elseif(APPLE)
# Special Apple stuff here
remove_definitions(-D_LINUX)
add_definitions(-D_DARWIN)
endif()
elseif(WIN32) elseif(WIN32)
add_definitions(-DWIN32) add_definitions(-DWIN32)
SET(PROJECT_LIBS Ws2_32.lib) SET(PROJECT_LIBS Ws2_32.lib)

View File

@ -61,7 +61,7 @@ extern "C"
#define __WORDSIZE 32 #define __WORDSIZE 32
#endif #endif
#if defined(_LINUX) || defined(_DARWIN) #if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
typedef unsigned char uint8; typedef unsigned char uint8;
typedef char int8; typedef char int8;
typedef unsigned short uint16; typedef unsigned short uint16;
@ -176,7 +176,7 @@ extern "C"
#define GETHOSTBYNAME(a) gethostbyname(a) #define GETHOSTBYNAME(a) gethostbyname(a)
#endif #endif
#if defined(_LINUX) || defined(_DARWIN) #if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#define ACCEPT(a,b,c) accept(a,b,c) #define ACCEPT(a,b,c) accept(a,b,c)
#define CONNECT(a,b,c) connect(a,b,c) #define CONNECT(a,b,c) connect(a,b,c)
#define CLOSE(a) close(a) #define CLOSE(a) close(a)

View File

@ -49,7 +49,7 @@
#include <stdarg.h> #include <stdarg.h>
#include <errno.h> #include <errno.h>
#if defined(_LINUX) || defined (_DARWIN) #if defined(_LINUX) || defined (_DARWIN) || defined(_BSD)
#include <sys/socket.h> #include <sys/socket.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <arpa/inet.h> #include <arpa/inet.h>
@ -66,7 +66,7 @@
#ifdef _DARWIN #ifdef _DARWIN
#include <net/if.h> #include <net/if.h>
#endif #endif
#if defined(_LINUX) || defined (_DARWIN) #if defined(_LINUX) || defined (_DARWIN) || defined(_BSD)
#include <sys/time.h> #include <sys/time.h>
#include <sys/uio.h> #include <sys/uio.h>
#include <unistd.h> #include <unistd.h>

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2015 Omar Cornut and ImGui contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,226 @@
dear imgui,
=====
[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui)
[![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720)
(This library is free and will stay free, but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you work for a company using ImGui or have the means to do so, please consider financial support. I can invoice for private support, custom development etc.)
[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
dear imgui (AKA ImGui), is a bloat-free graphical user interface library for C++. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies).
ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/ debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries.
ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard.
ImGui is self-contained within a few files that you can easily copy and compile into your application/engine:
- imgui.cpp
- imgui.h
- imgui_demo.cpp
- imgui_draw.cpp
- imgui_internal.h
- imconfig.h (empty by default, user-editable)
- stb_rect_pack.h
- stb_textedit.h
- stb_truetype.h
No specific build process is required. You can add the .cpp files to your project or #include them from an existing file.
Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example:
![screenshot of sample code alongside its output with ImGui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png)
ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase.
_A common misunderstanding is to think that immediate mode gui == immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes, as the gui functions as called by the user. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._
ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc.
Binaries/Demo
-------------
You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at the features of ImGui, you can download Windows binaries of the demo app here.
- [imgui-demo-binaries-20161113.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20161113.zip) (Windows binaries, ImGui 1.49+ 2016/11/13, 5 executables, 588 KB)
Bindings
--------
_NB: those third-party bindings may be more or less maintained, more or less close to the spirit of original API and therefore I cannot give much guarantee about them. People who create language bindings sometimes haven't used the C++ API themselves (for the good reason that they aren't C++ users). ImGui was designed with C++ in mind and some of the subtleties may be lost in translation with other languages. If your language supports it, I would suggest replicating the function overloading and default parameters used in the original, else the API may be harder to use. In doubt, please check the original C++ version first!_
_Integrating Dear ImGui within your custom engine is a matter of wiring mouse/keyboard inputs and providing a render function that can bind a texture and render simple textured triangles. The examples/ folder is populated with applications doing just that. If you are an experienced programmer it should take you less than an hour to integrate Dear ImGui in your custom engine, but make sure to spend time reading the FAQ, the comments and other documentation!_
Languages:
- cimgui: thin c-api wrapper for ImGui https://github.com/Extrawurst/cimgui
- ImGui.NET: An ImGui wrapper for .NET Core https://github.com/mellinoe/ImGui.NET
- imgui-rs: Rust bindings for dear imgui https://github.com/Gekkio/imgui-rs
- DerelictImgui: Dynamic bindings for the D programming language: https://github.com/Extrawurst/DerelictImgui
- CyImGui: Python bindings for dear imgui using Cython: https://github.com/chromy/cyimgui
- pyimgui: Another Python bindings for dear imgui: https://github.com/swistakm/pyimgui
- LUA: https://github.com/patrickriordan/imgui_lua_bindings
Frameworks:
- Main ImGui repository include examples for DirectX9, DirectX10, DirectX11, OpenGL2/3, Vulkan, Allegro 5, SDL+GL2/3, iOS and Marmalade: https://github.com/ocornut/imgui/tree/master/examples
- Unmerged PR: DirectX12 example (with issues) https://github.com/ocornut/imgui/pull/301
- Unmerged PR: SDL2 + OpenGLES + Emscripten example https://github.com/ocornut/imgui/pull/336
- Unmerged PR: FreeGlut + OpenGL2 example https://github.com/ocornut/imgui/pull/801
- Unmerged PR: Native Win32 and OSX example https://github.com/ocornut/imgui/pull/281
- Unmerged PR: Android Example https://github.com/ocornut/imgui/pull/421
- Cinder backend for dear imgui https://github.com/simongeilfus/Cinder-ImGui
- FlexGUI: Flexium/SFML backend for dear imgui https://github.com/DXsmiley/FlexGUI
- IrrIMGUI: Irrlicht backend for dear imgui https://github.com/ZahlGraf/IrrIMGUI
- LÖVE backend for dear imgui https://github.com/slages/love-imgui
- Ogre backend for dear imgui https://bitbucket.org/LMCrashy/ogreimgui/src
- ofxImGui: openFrameworks backend for dear imgui https://github.com/jvcleave/ofxImGui
- SFML backend for dear imgui https://github.com/EliasD/imgui-sfml
- SFML backend for dear imgui https://github.com/Mischa-Alff/imgui-backends
- cocos2d-x with imgui https://github.com/c0i/imguix https://github.com/ocornut/imgui/issues/551
- NanoRT: software raytraced version https://github.com/syoyo/imgui/tree/nanort/examples/raytrace_example
For other bindings: see [this page](https://github.com/ocornut/imgui/wiki/Links/).
Please contact me with the Issues tracker or Twitter to fix/update this list.
Gallery
-------
See the [Screenshots Thread](https://github.com/ocornut/imgui/issues/123) for some user creations.
![screenshot 1](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_01.png)
[![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png)
![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_02.png)
[![screenshot profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler-880.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler.png)
![screenshot 3](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_01.png)
![screenshot 4](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_03.png)
![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v140/test_window_05_menus.png)
![screenshot 6](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/skinning_sample_02.png)
![screenshot 7](https://cloud.githubusercontent.com/assets/8225057/7903336/96f0fb7c-07d0-11e5-95d6-41c6a1595e5a.png)
ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with:
```
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
// For Microsoft IME, pass your HWND to enable IME positioning:
io.ImeWindowHandle = my_hwnd;
```
![Japanese screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01_jp.png)
References
----------
The Immediate Mode GUI paradigm may at first appear unusual to some users. This is mainly because "Retained Mode" GUIs have been so widespread and predominant. The following links can give you a better understanding about how Immediate Mode GUIs works.
- [Johannes 'johno' Norneby's article](http://www.johno.se/book/imgui.html).
- [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf).
- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/).
- [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861).
See the [Links page](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to different languages and frameworks.
Frequently Asked Question (FAQ)
-------------------------------
<b>Where is the documentation?</b>
- The documentation is at the top of imgui.cpp + effectively imgui.h.
- Example code is in imgui_demo.cpp and particularly the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output.
- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder.
- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort.
<b>Why the odd dual naming, "dear imgui" vs "ImGui"?</b>
The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations.
<b>How do I update to a newer version of ImGui?</b>
<br><b>What is ImTextureID and how do I display an image?</b>
<br><b>I integrated ImGui in my engine and the text or lines are blurry..</b>
<br><b>I integrated ImGui in my engine and some elements are disappearing when I move windows around..</b>
<br><b>How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs.</b>
<br><b>How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?</b>
<br><b>How can I load a different font than the default?</b>
<br><b>How can I easily use icons in my application?</b>
<br><b>How can I load multiple fonts?</b>
<br><b>How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?</b>
<br><b>How can I use the drawing facilities without an ImGui window? (using ImDrawList API)</b>
See the FAQ in imgui.cpp for answers.
<b>How do you use ImGui on a platform that may not have a mouse or keyboard?</b>
I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/symless/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate.
<b>Can you create elaborate/serious tools with ImGui?</b>
Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools).
ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Many programmers have unfortunately been taught by their environment to make unnecessarily complicated things. ImGui is about making things that are simple, efficient and powerful.
<b>Is ImGui fast?</b>
Probably fast enough for most uses. Down to the foundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it.
Mileage may vary but the following screenshot can give you a rough idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup are likely to be the bottleneck. Testing performance as part of a real application is recommended).
![performance screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v138/performance_01.png)
This is showing framerate for the full application loop on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M with an optimized executable. In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint.
If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem.
<b>Can you reskin the look of ImGui?</b>
You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface.
This is [LumixEngine](https://github.com/nem0/LumixEngine) with a minor skinning hack + a docking/tabs extension (both of which you can find in the Issues section and will eventually be merged).
[![Skinning in LumixEngine](https://cloud.githubusercontent.com/assets/8225057/13198792/92808c5c-d812-11e5-9507-16b63918b05b.jpg)](https://cloud.githubusercontent.com/assets/8225057/13044612/59f07aec-d3cf-11e5-8ccb-39adf2e13e69.png)
<b>Why using C++ (as opposed to C)?</b>
ImGui takes advantage of a few C++ features for convenience but nothing anywhere Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed.
There is an unofficial but reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly. I would suggest using your target language functionality to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. It was really designed with C++ in mind and may not make the same amount of sense with another language. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages.
Donate
------
<b>How can I help financing further development of Dear ImGui?</b>
[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
Your contributions are keeping the library alive. For end-users, I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated. I can invoice for private support, custom development or whatever makes more sense in a given context. I am available for hire to work on or with ImGui. Please e-mail for details. Thanks!
Credits
-------
Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com).
I first discovered imgui principles at [Q-Games](http://www.q-games.com) where Atman had dropped his own simple imgui implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating on it.
Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license).
Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain).
Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub.
Ongoing ImGui development is financially supported on [**Patreon**](http://www.patreon.com/imgui).
Double-chocolate sponsors:
- Media Molecule
- Mobigame
- Insomniac Games (sponsored the gamepad/keyboard navigation branch)
- Aras Pranckevičius
Salty caramel supporters:
- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Recognition Robotics, Chris Genova, ikrima, Glenn Fiedler, Geoffrey Evans, Dakko Dakko.
Caramel supporters:
- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm, Farhan Wali, Jeff Roberts, Matt Reyer, Colin Riley, Victor Martins, Josh Simmons, Garrett Hoofman, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, [Kit framework](http://svkonsult.se/kit), Josh Faust, Martin Donlon, Quinton, Felix.
And other supporters; thanks!
License
-------
Dear ImGui is licensed under the MIT License, see LICENSE for more information.

View File

@ -0,0 +1,54 @@
//-----------------------------------------------------------------------------
// USER IMPLEMENTATION
// This file contains compile-time options for ImGui.
// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO().
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Include imgui_user.h at the end of imgui.h
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions)
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS
//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty)
//#define IMGUI_DISABLE_TEST_WINDOWS
//---- Don't define obsolete functions names
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Pack colors to BGRA instead of RGBA (remove need to post process vertex buffer in back ends)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Implement STB libraries in a namespace to avoid conflicts
//#define IMGUI_STB_NAMESPACE ImGuiStb
//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
/*
#define IM_VEC2_CLASS_EXTRA \
ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers.
/*
namespace ImGui
{
void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL);
}
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,776 @@
// dear imgui, v1.50 WIP
// (internals)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
// #define IMGUI_DEFINE_MATH_OPERATORS
#pragma once
#ifndef IMGUI_VERSION
#error Must include imgui.h before imgui_internal.h
#endif
#include <stdio.h> // FILE*
#include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport)
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wold-style-cast"
#endif
//-----------------------------------------------------------------------------
// Forward Declarations
//-----------------------------------------------------------------------------
struct ImRect;
struct ImGuiColMod;
struct ImGuiStyleMod;
struct ImGuiGroupData;
struct ImGuiSimpleColumns;
struct ImGuiDrawContext;
struct ImGuiTextEditState;
struct ImGuiIniData;
struct ImGuiMouseCursorData;
struct ImGuiPopupRef;
struct ImGuiWindow;
typedef int ImGuiLayoutType; // enum ImGuiLayoutType_
typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_
typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_
typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_
//-------------------------------------------------------------------------
// STB libraries
//-------------------------------------------------------------------------
namespace ImGuiStb
{
#undef STB_TEXTEDIT_STRING
#undef STB_TEXTEDIT_CHARTYPE
#define STB_TEXTEDIT_STRING ImGuiTextEditState
#define STB_TEXTEDIT_CHARTYPE ImWchar
#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f
#include "stb_textedit.h"
} // namespace ImGuiStb
//-----------------------------------------------------------------------------
// Context
//-----------------------------------------------------------------------------
#ifndef GImGui
extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointer
#endif
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
#define IM_PI 3.14159265358979323846f
#define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM))
// Helpers: UTF-8 <> wchar
IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count
IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count
IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count)
IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points
// Helpers: Misc
IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings
IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0);
IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode);
IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c);
static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; }
static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
// Helpers: String
IMGUI_API int ImStricmp(const char* str1, const char* str2);
IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count);
IMGUI_API char* ImStrdup(const char* str);
IMGUI_API int ImStrlenW(const ImWchar* str);
IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3);
IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args);
// Helpers: Math
// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined)
#ifdef IMGUI_DEFINE_MATH_OPERATORS
static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); }
static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); }
static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); }
static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); }
static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); }
static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); }
static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); }
#endif
static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; }
static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; }
static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; }
static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; }
static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); }
static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); }
static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; }
static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; }
static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; }
static inline float ImFloor(float f) { return (float)(int)f; }
static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
// Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.
#ifdef IMGUI_DEFINE_PLACEMENT_NEW
struct ImPlacementNewDummy {};
inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; }
inline void operator delete(void*, ImPlacementNewDummy, void*) {}
#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR)
#endif
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
enum ImGuiButtonFlags_
{
ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set)
ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release)
ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release)
ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release)
ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping
ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press
ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction
ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only
ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held
ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable
};
enum ImGuiSliderFlags_
{
ImGuiSliderFlags_Vertical = 1 << 0
};
enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
ImGuiSelectableFlags_Menu = 1 << 3,
ImGuiSelectableFlags_MenuItem = 1 << 4,
ImGuiSelectableFlags_Disabled = 1 << 5,
ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6
};
// FIXME: this is in development, not exposed/functional as a generic feature yet.
enum ImGuiLayoutType_
{
ImGuiLayoutType_Vertical,
ImGuiLayoutType_Horizontal
};
enum ImGuiPlotType
{
ImGuiPlotType_Lines,
ImGuiPlotType_Histogram
};
enum ImGuiDataType
{
ImGuiDataType_Int,
ImGuiDataType_Float,
ImGuiDataType_Float2,
};
enum ImGuiCorner
{
ImGuiCorner_TopLeft = 1 << 0, // 1
ImGuiCorner_TopRight = 1 << 1, // 2
ImGuiCorner_BottomRight = 1 << 2, // 4
ImGuiCorner_BottomLeft = 1 << 3, // 8
ImGuiCorner_All = 0x0F
};
// 2D axis aligned bounding-box
// NB: we can't rely on ImVec2 math operators being available here
struct IMGUI_API ImRect
{
ImVec2 Min; // Upper-left
ImVec2 Max; // Lower-right
ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {}
ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {}
ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {}
ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {}
ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); }
ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); }
float GetWidth() const { return Max.x-Min.x; }
float GetHeight() const { return Max.y-Min.y; }
ImVec2 GetTL() const { return Min; } // Top-left
ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right
ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left
ImVec2 GetBR() const { return Max; } // Bottom-right
bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; }
bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; }
bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; }
void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; }
void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; }
void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; }
void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }
void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; }
void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; }
void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const
{
if (!on_edge && Contains(p))
return p;
if (p.x > Max.x) p.x = Max.x;
else if (p.x < Min.x) p.x = Min.x;
if (p.y > Max.y) p.y = Max.y;
else if (p.y < Min.y) p.y = Min.y;
return p;
}
};
// Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColMod
{
ImGuiCol Col;
ImVec4 BackupValue;
};
// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable.
struct ImGuiStyleMod
{
ImGuiStyleVar VarIdx;
union { int BackupInt[2]; float BackupFloat[2]; };
ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; }
ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; }
ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; }
};
// Stacked data for BeginGroup()/EndGroup()
struct ImGuiGroupData
{
ImVec2 BackupCursorPos;
ImVec2 BackupCursorMaxPos;
float BackupIndentX;
float BackupGroupOffsetX;
float BackupCurrentLineHeight;
float BackupCurrentLineTextBaseOffset;
float BackupLogLinePosY;
bool BackupActiveIdIsAlive;
bool AdvanceCursor;
};
// Per column data for Columns()
struct ImGuiColumnData
{
float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
//float IndentX;
};
// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper.
struct IMGUI_API ImGuiSimpleColumns
{
int Count;
float Spacing;
float Width, NextWidth;
float Pos[8], NextWidths[8];
ImGuiSimpleColumns();
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
float CalcExtraSpace(float avail_w);
};
// Internal state of the currently focused/edited text input box
struct IMGUI_API ImGuiTextEditState
{
ImGuiID Id; // widget id owning the text state
ImVector<ImWchar> Text; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.
ImVector<char> InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered)
ImVector<char> TempTextBuffer;
int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format.
int BufSizeA; // end-user buffer size
float ScrollX;
ImGuiStb::STB_TexteditState StbState;
float CursorAnim;
bool CursorFollow;
bool SelectedAllMouseLock;
ImGuiTextEditState() { memset(this, 0, sizeof(*this)); }
void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); }
bool HasSelection() const { return StbState.select_start != StbState.select_end; }
void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; }
void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; }
void OnKeyPressed(int key);
};
// Data saved in imgui.ini file
struct ImGuiIniData
{
char* Name;
ImGuiID Id;
ImVec2 Pos;
ImVec2 Size;
bool Collapsed;
};
// Mouse cursor data (used when io.MouseDrawCursor is set)
struct ImGuiMouseCursorData
{
ImGuiMouseCursor Type;
ImVec2 HotOffset;
ImVec2 Size;
ImVec2 TexUvMin[2];
ImVec2 TexUvMax[2];
};
// Storage for current popup stack
struct ImGuiPopupRef
{
ImGuiID PopupId; // Set on OpenPopup()
ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
ImGuiWindow* ParentWindow; // Set on OpenPopup()
ImGuiID ParentMenuSet; // Set on OpenPopup()
ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup
ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; }
};
// Main state for ImGui
struct ImGuiContext
{
bool Initialized;
ImGuiIO IO;
ImGuiStyle Style;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize()
float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters.
ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel
float Time;
int FrameCount;
int FrameCountEnded;
int FrameCountRendered;
ImVector<ImGuiWindow*> Windows;
ImVector<ImGuiWindow*> WindowsSortBuffer;
ImGuiWindow* CurrentWindow; // Being drawn into
ImVector<ImGuiWindow*> CurrentWindowStack;
ImGuiWindow* FocusedWindow; // Will catch keyboard inputs
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
ImGuiID HoveredId; // Hovered widget
bool HoveredIdAllowOverlap;
ImGuiID HoveredIdPreviousFrame;
ImGuiID ActiveId; // Active widget
ImGuiID ActiveIdPreviousFrame;
bool ActiveIdIsAlive;
bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
bool ActiveIdAllowOverlap; // Set only by active widget
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window.
ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId
ImVector<ImGuiIniData> Settings; // .ini Settings
float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero
ImVector<ImGuiColMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont()
ImVector<ImGuiPopupRef> OpenPopupStack; // Which popups are open (persistent)
ImVector<ImGuiPopupRef> CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame)
// Storage for SetNexWindow** and SetNextTreeNode*** functions
ImVec2 SetNextWindowPosVal;
ImVec2 SetNextWindowSizeVal;
ImVec2 SetNextWindowContentSizeVal;
bool SetNextWindowCollapsedVal;
ImGuiSetCond SetNextWindowPosCond;
ImGuiSetCond SetNextWindowSizeCond;
ImGuiSetCond SetNextWindowContentSizeCond;
ImGuiSetCond SetNextWindowCollapsedCond;
ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true
ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback;
void* SetNextWindowSizeConstraintCallbackUserData;
bool SetNextWindowSizeConstraint;
bool SetNextWindowFocus;
bool SetNextTreeNodeOpenVal;
ImGuiSetCond SetNextTreeNodeOpenCond;
// Render
ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user
ImVector<ImDrawList*> RenderDrawLists[3];
float ModalWindowDarkeningRatio;
ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays
ImGuiMouseCursor MouseCursor;
ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_];
// Widget state
ImGuiTextEditState InputTextState;
ImFont InputTextPasswordFont;
ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc.
ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode
float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings
ImVec2 DragLastMouseDelta;
float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
float DragSpeedScaleSlow;
float DragSpeedScaleFast;
ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
char Tooltip[1024];
char* PrivateClipboard; // If no custom clipboard handler is defined
ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor
// Logging
bool LogEnabled;
FILE* LogFile; // If != NULL log to stdout/ file
ImGuiTextBuffer* LogClipboard; // Else log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
int LogStartDepth;
int LogAutoExpandMaxDepth;
// Misc
float FramerateSecPerFrame[120]; // calculate estimate of framerate for user
int FramerateSecPerFrameIdx;
float FramerateSecPerFrameAccum;
int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags
int CaptureKeyboardNextFrame;
char TempBuffer[1024*3+1]; // temporary text buffer
ImGuiContext()
{
Initialized = false;
Font = NULL;
FontSize = FontBaseSize = 0.0f;
FontTexUvWhitePixel = ImVec2(0.0f, 0.0f);
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountRendered = -1;
CurrentWindow = NULL;
FocusedWindow = NULL;
HoveredWindow = NULL;
HoveredRootWindow = NULL;
HoveredId = 0;
HoveredIdAllowOverlap = false;
HoveredIdPreviousFrame = 0;
ActiveId = 0;
ActiveIdPreviousFrame = 0;
ActiveIdIsAlive = false;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
ActiveIdClickOffset = ImVec2(-1,-1);
ActiveIdWindow = NULL;
MovedWindow = NULL;
MovedWindowMoveId = 0;
SettingsDirtyTimer = 0.0f;
SetNextWindowPosVal = ImVec2(0.0f, 0.0f);
SetNextWindowSizeVal = ImVec2(0.0f, 0.0f);
SetNextWindowCollapsedVal = false;
SetNextWindowPosCond = 0;
SetNextWindowSizeCond = 0;
SetNextWindowContentSizeCond = 0;
SetNextWindowCollapsedCond = 0;
SetNextWindowSizeConstraintRect = ImRect();
SetNextWindowSizeConstraintCallback = NULL;
SetNextWindowSizeConstraintCallbackUserData = NULL;
SetNextWindowSizeConstraint = false;
SetNextWindowFocus = false;
SetNextTreeNodeOpenVal = false;
SetNextTreeNodeOpenCond = 0;
ScalarAsInputTextId = 0;
DragCurrentValue = 0.0f;
DragLastMouseDelta = ImVec2(0.0f, 0.0f);
DragSpeedDefaultRatio = 1.0f / 100.0f;
DragSpeedScaleSlow = 0.01f;
DragSpeedScaleFast = 10.0f;
ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f);
memset(Tooltip, 0, sizeof(Tooltip));
PrivateClipboard = NULL;
OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f);
ModalWindowDarkeningRatio = 0.0f;
OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
MouseCursor = ImGuiMouseCursor_Arrow;
memset(MouseCursorData, 0, sizeof(MouseCursorData));
LogEnabled = false;
LogFile = NULL;
LogClipboard = NULL;
LogStartDepth = 0;
LogAutoExpandMaxDepth = 2;
memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
FramerateSecPerFrameIdx = 0;
FramerateSecPerFrameAccum = 0.0f;
CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1;
memset(TempBuffer, 0, sizeof(TempBuffer));
}
};
// Transient per-window data, reset at the beginning of the frame
// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered.
struct IMGUI_API ImGuiDrawContext
{
ImVec2 CursorPos;
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos;
ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame
float CurrentLineHeight;
float CurrentLineTextBaseOffset;
float PrevLineHeight;
float PrevLineTextBaseOffset;
float LogLinePosY;
int TreeDepth;
ImGuiID LastItemId;
ImRect LastItemRect;
bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window)
bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window)
bool MenuBarAppending;
float MenuBarOffsetX;
ImVector<ImGuiWindow*> ChildWindows;
ImGuiStorage* StateStorage;
ImGuiLayoutType LayoutType;
// We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.
float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window
float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f]
bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true]
bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false]
ImVector<float> ItemWidthStack;
ImVector<float> TextWrapPosStack;
ImVector<bool> AllowKeyboardFocusStack;
ImVector<bool> ButtonRepeatStack;
ImVector<ImGuiGroupData>GroupStack;
ImGuiColorEditMode ColorEditMode;
int StackSizesBackup[6]; // Store size of various stacks for asserting
float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
float GroupOffsetX;
float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
int ColumnsCurrent;
int ColumnsCount;
float ColumnsMinX;
float ColumnsMaxX;
float ColumnsStartPosY;
float ColumnsCellMinY;
float ColumnsCellMaxY;
bool ColumnsShowBorders;
ImGuiID ColumnsSetId;
ImVector<ImGuiColumnData> ColumnsData;
ImGuiDrawContext()
{
CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f);
CurrentLineHeight = PrevLineHeight = 0.0f;
CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
LogLinePosY = -1.0f;
TreeDepth = 0;
LastItemId = 0;
LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f);
LastItemHoveredAndUsable = LastItemHoveredRect = false;
MenuBarAppending = false;
MenuBarOffsetX = 0.0f;
StateStorage = NULL;
LayoutType = ImGuiLayoutType_Vertical;
ItemWidth = 0.0f;
ButtonRepeat = false;
AllowKeyboardFocus = true;
TextWrapPos = -1.0f;
ColorEditMode = ImGuiColorEditMode_RGB;
memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
IndentX = 0.0f;
GroupOffsetX = 0.0f;
ColumnsOffsetX = 0.0f;
ColumnsCurrent = 0;
ColumnsCount = 1;
ColumnsMinX = ColumnsMaxX = 0.0f;
ColumnsStartPosY = 0.0f;
ColumnsCellMinY = ColumnsCellMaxY = 0.0f;
ColumnsShowBorders = true;
ColumnsSetId = 0;
}
};
// Windows data
struct IMGUI_API ImGuiWindow
{
char* Name;
ImGuiID ID; // == ImHash(Name)
ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_
int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0.
ImVec2 PosFloat;
ImVec2 Pos; // Position rounded-up to nearest pixel
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame
ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize()
ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis
ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect
ImGuiID MoveId; // == window->GetID("#MOVE")
ImVec2 Scroll;
ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)
ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered
bool ScrollbarX, ScrollbarY;
ImVec2 ScrollbarSizes;
float BorderSize;
bool Active; // Set to true on Begin()
bool WasActive;
bool Accessed; // Set to true when any widget access the current window
bool Collapsed; // Set when collapsing window to become only title-bar
bool SkipItems; // == Visible && !Collapsed
int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling)
int AutoFitFramesX, AutoFitFramesY;
bool AutoFitOnlyGrows;
int AutoPosLastDirection;
int HiddenFrames;
int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag.
int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag.
int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag.
bool SetWindowPosCenterWanted;
ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame
ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack
ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2.
ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window.
int LastFrameActive;
float ItemWidthDefault;
ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items
ImGuiStorage StateStorage;
float FontWindowScale; // Scale multiplier per-window
ImDrawList* DrawList;
ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself.
ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself.
ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL.
// Navigation / Focus
int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister()
int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through)
int FocusIdxAllRequestCurrent; // Item being requested for focus
int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus
int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame)
int FocusIdxTabRequestNext; // "
public:
ImGuiWindow(const char* name);
~ImGuiWindow();
ImGuiID GetID(const char* str, const char* str_end = NULL);
ImGuiID GetID(const void* ptr);
ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL);
ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); }
float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; }
float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; }
ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }
float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; }
ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }
};
//-----------------------------------------------------------------------------
// Internal API
// No guarantee of forward compatibility here.
//-----------------------------------------------------------------------------
namespace ImGui
{
// We should always have a CurrentWindow in the stack (there is an implicit "Debug" window)
// If this ever crash because g.CurrentWindow is NULL it means that either
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; }
inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* GetParentWindow();
IMGUI_API ImGuiWindow* FindWindowByName(const char* name);
IMGUI_API void FocusWindow(ImGuiWindow* window);
IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead!
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void ClearActiveID();
IMGUI_API void SetHoveredID(ImGuiID id);
IMGUI_API void KeepAliveID(ImGuiID id);
IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f);
IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f);
IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id);
IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged);
IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false);
IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested
IMGUI_API void FocusableItemUnregister(ImGuiWindow* window);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y);
IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);
IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing);
// NB: All position are in absolute pixels coordinates (not window coordinates)
// FIXME: All those functions are a mess and needs to be refactored into something decent. AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION.
// We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers.
IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true);
IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width);
IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f);
IMGUI_API void RenderBullet(ImVec2 pos);
IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col);
IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);
IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0);
IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius);
IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0);
IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power);
IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format);
IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power);
IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power);
IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format);
IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision);
IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL);
IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging
IMGUI_API void TreePushRawID(ImGuiID id);
IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size);
IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value);
IMGUI_API float RoundScalar(float value, int decimal_precision);
} // namespace ImGui
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef _MSC_VER
#pragma warning (pop)
#endif

View File

@ -0,0 +1,583 @@
// stb_rect_pack.h - v0.10 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// Bugfixes / warning fixes
// Jeremy Jaussaud
//
// Version history:
//
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// This software is dual-licensed to the public domain and under the following
// license: you are granted a perpetual, irrevocable license to copy, modify,
// publish, and distribute this file as you see fit.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
#ifdef STBRP_LARGE_RECTS
typedef int stbrp_coord;
#else
typedef unsigned short stbrp_coord;
#endif
STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
#endif
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
#ifdef STBRP_LARGE_RECTS
context->extra[1].y = (1<<30);
#else
context->extra[1].y = 65535;
#endif
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height < c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
STBRP_ASSERT(y <= best_y);
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
stbrp_node *L1 = NULL, *L2 = NULL;
int count=0;
cur = context->active_head;
while (cur) {
L1 = cur;
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
L2 = cur;
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int rect_width_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->w > q->w)
return -1;
if (p->w < q->w)
return 1;
return (p->h > q->h) ? -1 : (p->h < q->h);
}
static int rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
#ifdef STBRP_LARGE_RECTS
#define STBRP__MAXVAL 0xffffffff
#else
#define STBRP__MAXVAL 0xffff
#endif
STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
#endif
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags
for (i=0; i < num_rects; ++i)
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
}
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

10228
examples/TinyAudio/RtAudio.cpp Normal file

File diff suppressed because it is too large Load Diff

1163
examples/TinyAudio/RtAudio.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,102 @@
#include "TinyAudioExample.h"
#include "../CommonInterfaces/CommonExampleInterface.h"
#include "../CommonInterfaces/CommonGUIHelperInterface.h"
#include "RtAudio.h"
#include "b3AudioListener.h"
#include "b3SoundSource.h"
class TinyAudioExample : public CommonExampleInterface
{
b3AudioListener m_listener;
b3SoundSource m_soundA;
RtAudio m_dac;
GUIHelperInterface* m_guiHelper;
int m_soundIndexA;
public:
TinyAudioExample(struct GUIHelperInterface* helper)
:m_guiHelper(helper)
{
}
virtual ~TinyAudioExample()
{
}
virtual void initPhysics()
{
m_soundIndexA = m_listener.addSoundSource(&m_soundA);
RtAudioFormat format = ( sizeof(double) == 8 ) ? RTAUDIO_FLOAT64 : RTAUDIO_FLOAT32;
RtAudio::StreamParameters parameters;
parameters.deviceId = 1;// dac.getDefaultOutputDevice();
parameters.nChannels = 2;
// The default real-time audio input and output buffer size. If
// clicks are occuring in the input and/or output sound stream, a
// larger buffer size may help. Larger buffer sizes, however, produce
// more latency.
const unsigned int RT_BUFFER_SIZE = 512;
unsigned int bufferFrames = RT_BUFFER_SIZE;
int sampleRate = m_listener.getSampleRate();
m_dac.openStream( &parameters, NULL, format, (unsigned int)sampleRate, &bufferFrames, &b3AudioListener::tick,
(void *)m_listener.getTickData());
// Install an interrupt handler function.
// (void) signal( SIGINT, finish );
m_dac.startStream();
}
virtual void exitPhysics()
{
m_dac.closeStream();
m_listener.removeSoundSource(m_soundIndexA);
}
virtual void renderScene()
{
}
virtual void stepSimulation(float deltaTime)
{
}
virtual void physicsDebugDraw(int debugFlags)
{
}
virtual bool mouseMoveCallback(float x,float y)
{
return false;
}
virtual bool mouseButtonCallback(int button, int state, float x, float y)
{
return false;
}
virtual bool keyboardCallback(int key, int state)
{
return false;
}
void resetCamera()
{
float dist = 4;
float pitch = 52;
float yaw = 35;
float targetPos[3]={0,0,0};
m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]);
}
};
CommonExampleInterface* TinyAudioExampleCreateFunc(CommonExampleOptions& options)
{
return new TinyAudioExample(options.m_guiHelper);
}
B3_STANDALONE_EXAMPLE(TinyAudioExampleCreateFunc)

View File

@ -0,0 +1,7 @@
#ifndef TINY_AUDIO_EXAMPLE_H
#define TINY_AUDIO_EXAMPLE_H
class CommonExampleInterface* TinyAudioExampleCreateFunc(struct CommonExampleOptions& options);
#endif //TINY_AUDIO_EXAMPLE_H

View File

@ -0,0 +1,132 @@
#include "b3AudioListener.h"
#include "b3SoundSource.h"
template <class T>
inline const T& MyMin(const T& a, const T& b)
{
return a < b ? a : b ;
}
#define MAX_SOUND_SOURCES 128
struct b3AudioListenerInternalData
{
int m_numControlTicks;
double m_sampleRate;
b3SoundSource* m_soundSources[MAX_SOUND_SOURCES];
b3AudioListenerInternalData()
:m_numControlTicks(64),
m_sampleRate(48000)
{
for (int i=0;i<MAX_SOUND_SOURCES;i++)
{
m_soundSources[i] = 0;
}
}
};
b3AudioListener::b3AudioListener()
{
m_data = new b3AudioListenerInternalData();
}
b3AudioListener::~b3AudioListener()
{
delete m_data;
}
int b3AudioListener::addSoundSource(b3SoundSource* source)
{
int soundIndex = -1;
for (int i=0;i<MAX_SOUND_SOURCES;i++)
{
if (m_data->m_soundSources[i]==0)
{
m_data->m_soundSources[i] = source;
soundIndex = i;
break;
}
}
return soundIndex;
}
void b3AudioListener::removeSoundSource(int soundSourceIndex)
{
if (soundSourceIndex >=0 && soundSourceIndex<MAX_SOUND_SOURCES)
{
m_data->m_soundSources[soundSourceIndex] = 0;
}
}
b3AudioListenerInternalData* b3AudioListener::getTickData()
{
return m_data;
}
const b3AudioListenerInternalData* b3AudioListener::getTickData() const
{
return m_data;
}
double b3AudioListener::getSampleRate() const
{
return m_data->m_sampleRate;
}
int b3AudioListener::tick(void *outputBuffer,void *inputBuffer1,unsigned int nBufferFrames,
double streamTime,unsigned int status,void *dataPointer)
{
b3AudioListenerInternalData *data = (b3AudioListenerInternalData *)dataPointer;
register double outs[2],*samples = (double *)outputBuffer;
register double tempOuts[2];
int counter,nTicks = (int)nBufferFrames;
bool done = false;
while(nTicks > 0 && !done)
{
counter = MyMin(nTicks,data->m_numControlTicks);
bool newsynth = true;
if(newsynth)
{
for(int i = 0; i < counter; i++)
{
outs[0] = 0.;
outs[1] = 0.;
//make_sound_double(outs,1);
float numActiveSources = 0;
for (int i=0;i<MAX_SOUND_SOURCES;i++)
{
if (data->m_soundSources[i])
{
if (data->m_soundSources[i]->computeSamples(tempOuts,1, data->m_sampleRate))
{
numActiveSources++;
//simple mixer
outs[0] += tempOuts[0];
outs[1] += tempOuts[1];
}
}
}
//simple mixer
if (numActiveSources)
{
outs[0] *= 1./numActiveSources;
outs[1] *= 1./numActiveSources;
}
*samples++ = outs[0];
*samples++ = outs[1];
}
nTicks -= counter;
}
if(nTicks == 0)
break;
}
return 0;
}

View File

@ -0,0 +1,28 @@
#ifndef B3_AUDIO_LISTENER_H
#define B3_AUDIO_LISTENER_H
class b3SoundSource;
class b3AudioListener
{
struct b3AudioListenerInternalData* m_data;
public:
b3AudioListener();
virtual ~b3AudioListener();
static int tick(void *outputBuffer, void *inputBuffer1, unsigned int nBufferFrames,
double streamTime, unsigned int status, void *dataPointer);
int addSoundSource(b3SoundSource* source);
void removeSoundSource(int soundSourceIndex);
b3AudioListenerInternalData* getTickData();
const b3AudioListenerInternalData* getTickData() const;
double getSampleRate() const;
};
#endif //B3_AUDIO_LISTENER_H

View File

@ -0,0 +1,66 @@
#include "b3SoundSource.h"
#define MY2PI (2.*3.14159265)
#include <math.h>
struct b3SoundOscillator
{
int m_type;
double m_amplitude;
double m_phase;
double m_frequency;
double sampleWaveForm(double sampleRate)
{
while (m_phase >= MY2PI)
m_phase -= MY2PI;
double z = sinf(m_phase);
double sample = m_amplitude*z;
m_phase += MY2PI * (1./sampleRate) * m_frequency;
return sample;
}
b3SoundOscillator()
:m_phase(0),
m_amplitude(0.8),
m_frequency(442.)
{
}
};
struct b3SoundSourceInternalData
{
b3SoundOscillator m_oscillator;
};
b3SoundSource::b3SoundSource()
{
m_data = new b3SoundSourceInternalData();
}
b3SoundSource::~b3SoundSource()
{
delete m_data;
}
bool b3SoundSource::computeSamples(double* sampleBuffer, int numSamples, double sampleRate)
{
double* outputSamples = sampleBuffer;
for (int i=0;i<numSamples;i++)
{
double sample = m_data->m_oscillator.sampleWaveForm(sampleRate);
double sampleLeft = sample;
double sampleRight = sample;
*outputSamples++ = sampleLeft;
*outputSamples++ = sampleRight;
}
return true;
// return false;
}

View File

@ -0,0 +1,16 @@
#ifndef B3_SOUND_SOURCE_H
#define B3_SOUND_SOURCE_H
class b3SoundSource
{
struct b3SoundSourceInternalData* m_data;
public:
b3SoundSource();
virtual ~b3SoundSource();
virtual bool computeSamples(double *sampleBuffer, int numSamples, double sampleRate);
};
#endif //B3_SOUND_SOURCE_H

View File

@ -0,0 +1,38 @@
project "App_TinyAudioExample"
language "C++"
kind "ConsoleApp"
includedirs {
".",
"../../src",
}
defines {"B3_USE_STANDALONE_EXAMPLE", "__STK_REALTIME__"}
files {
"**.cpp",
"**.h",
"../StandaloneMain/main_console_single_example.cpp",
}
if os.is("Windows") then
links {"winmm","Wsock32","dsound"}
defines {"WIN32","__WINDOWS_MM__","__LITTLE_ENDIAN__","__WINDOWS_DS__"}
end
if os.is("Linux") then initX11()
defines {"__OS_LINUX__","__LINUX_ALSA__","__LITTLE_ENDIAN__"}
links {"asound","pthread"}
end
if os.is("MacOSX") then
links{"Cocoa.framework"}
links{"CoreAudio.framework", "coreMIDI.framework", "Cocoa.framework"}
defines {"__OS_MACOSX__","__LITTLE_ENDIAN__"}
end

View File

@ -130,9 +130,9 @@ struct Shader : public IShader {
float depth = p[2]; float depth = p[2];
p = p/p[3]; p = p/p[3];
int index_x = b3Max(0, b3Min(m_width-1, int(p[0]))); float index_x = b3Max(float(0.0), b3Min(float(m_width-1), p[0]));
int index_y = b3Max(0, b3Min(m_height-1, int(p[1]))); float index_y = b3Max(float(0.0), b3Min(float(m_height-1), p[1]));
int idx = index_x + index_y*m_width; // index in the shadowbuffer array int idx = int(index_x) + int(index_y)*m_width; // index in the shadowbuffer array
float shadow = 0.8+0.2*(m_shadowBuffer->at(idx)<-depth+0.05); // magic coeff to avoid z-fighting float shadow = 0.8+0.2*(m_shadowBuffer->at(idx)<-depth+0.05); // magic coeff to avoid z-fighting
Vec3f bn = (varying_nrm*bar).normalize(); Vec3f bn = (varying_nrm*bar).normalize();
@ -377,42 +377,93 @@ TinyRenderObjectData::~TinyRenderObjectData()
delete m_model; delete m_model;
} }
void TinyRenderer::renderObjectDepth(TinyRenderObjectData& renderData) static bool equals(const Vec4f& vA, const Vec4f& vB)
{ {
int width = renderData.m_rgbColorBuffer.get_width(); return false;
int height = renderData.m_rgbColorBuffer.get_height(); }
Vec3f light_dir_local = Vec3f(renderData.m_lightDirWorld[0],renderData.m_lightDirWorld[1],renderData.m_lightDirWorld[2]); static void clipEdge(const mat<4,3,float>& triangleIn, int vertexIndexA, int vertexIndexB, b3AlignedObjectArray<Vec4f>& vertices)
float light_distance = renderData.m_lightDistance; {
Model* model = renderData.m_model; Vec4f v0New = triangleIn.col(vertexIndexA);
if (0==model) Vec4f v1New = triangleIn.col(vertexIndexB);
return;
renderData.m_viewportMatrix = viewport(0,0,width, height); bool v0Inside = v0New[3] > 0.f && v0New[2] > -v0New[3];
bool v1Inside= v1New[3] > 0.f && v1New[2] > -v1New[3];
float* shadowBufferPtr = (renderData.m_shadowBuffer && renderData.m_shadowBuffer->size())?&renderData.m_shadowBuffer->at(0):0; if (v0Inside && v1Inside)
int* segmentationMaskBufferPtr = 0; {
TGAImage depthFrame(width, height, TGAImage::RGB); } else if (v0Inside || v1Inside)
{
float d0 = v0New[2]+v0New[3];
float d1 = v1New[2]+v1New[3];
float factor = 1.0 / (d1-d0);
Vec4f newVertex =(v0New*d1-v1New*d0)*factor;
if (v0Inside)
{
v1New = newVertex;
} else
{
v0New = newVertex;
}
} else
{
return;
}
{ if (vertices.size()==0 || !(equals(vertices[vertices.size()-1],v0New)))
// light target is set to be the origin, and the up direction is set to be vertical up. {
Matrix lightViewMatrix = lookat(light_dir_local*light_distance, Vec3f(0.0,0.0,0.0), Vec3f(0.0,0.0,1.0)); vertices.push_back(v0New);
Matrix lightModelViewMatrix = lightViewMatrix*renderData.m_modelMatrix; }
Matrix lightViewProjectionMatrix = renderData.m_projectionMatrix;
Vec3f localScaling(renderData.m_localScaling[0],renderData.m_localScaling[1],renderData.m_localScaling[2]);
DepthShader shader(model, lightModelViewMatrix, lightViewProjectionMatrix,renderData.m_modelMatrix, localScaling, light_distance); vertices.push_back(v1New);
}
for (int i=0; i<model->nfaces(); i++)
{
for (int j=0; j<3; j++) {
shader.vertex(i, j);
}
triangle(shader.varying_tri, shader, depthFrame, shadowBufferPtr, segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex);
}
}
static bool clipTriangleAgainstNearplane(const mat<4,3,float>& triangleIn, b3AlignedObjectArray<mat<4,3,float> >& clippedTrianglesOut)
{
//discard triangle if all vertices are behind near-plane
if (triangleIn[3][0]<0 && triangleIn[3][1] <0 && triangleIn[3][2] <0)
{
return true;
}
//accept triangle if all vertices are in front of the near-plane
if (triangleIn[3][0]>=0 && triangleIn[3][1] >=0 && triangleIn[3][2] >=0)
{
clippedTrianglesOut.push_back(triangleIn);
return false;
}
Vec4f vtxCache[5];
b3AlignedObjectArray<Vec4f> vertices;
vertices.initializeFromBuffer(vtxCache,0,5);
clipEdge(triangleIn,0,1,vertices);
clipEdge(triangleIn,1,2,vertices);
clipEdge(triangleIn,2,0,vertices);
if (vertices.size()<3)
return true;
if (equals(vertices[0],vertices[vertices.size()-1]))
{
vertices.pop_back();
}
//create a fan of triangles
for (int i=1;i<vertices.size()-1;i++)
{
mat<4,3,float>& vtx = clippedTrianglesOut.expand();
vtx.set_col(0,vertices[0]);
vtx.set_col(1,vertices[i]);
vtx.set_col(2,vertices[i+1]);
}
return true;
} }
void TinyRenderer::renderObject(TinyRenderObjectData& renderData) void TinyRenderer::renderObject(TinyRenderObjectData& renderData)
@ -449,7 +500,82 @@ void TinyRenderer::renderObject(TinyRenderObjectData& renderData)
for (int j=0; j<3; j++) { for (int j=0; j<3; j++) {
shader.vertex(i, j); shader.vertex(i, j);
} }
triangle(shader.varying_tri, shader, frame, &zbuffer[0], segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex);
mat<4,3,float> stackTris[3];
b3AlignedObjectArray< mat<4,3,float> > clippedTriangles;
clippedTriangles.initializeFromBuffer(stackTris,0,3);
bool hasClipped = clipTriangleAgainstNearplane(shader.varying_tri,clippedTriangles);
if (hasClipped)
{
for (int t=0;t<clippedTriangles.size();t++)
{
triangleClipped(clippedTriangles[t], shader.varying_tri, shader, frame, &zbuffer[0], segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex);
}
}
else
{
triangle(shader.varying_tri, shader, frame, &zbuffer[0], segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex);
}
}
}
}
void TinyRenderer::renderObjectDepth(TinyRenderObjectData& renderData)
{
int width = renderData.m_rgbColorBuffer.get_width();
int height = renderData.m_rgbColorBuffer.get_height();
Vec3f light_dir_local = Vec3f(renderData.m_lightDirWorld[0],renderData.m_lightDirWorld[1],renderData.m_lightDirWorld[2]);
float light_distance = renderData.m_lightDistance;
Model* model = renderData.m_model;
if (0==model)
return;
renderData.m_viewportMatrix = viewport(0,0,width, height);
float* shadowBufferPtr = (renderData.m_shadowBuffer && renderData.m_shadowBuffer->size())?&renderData.m_shadowBuffer->at(0):0;
int* segmentationMaskBufferPtr = 0;
TGAImage depthFrame(width, height, TGAImage::RGB);
{
// light target is set to be the origin, and the up direction is set to be vertical up.
Matrix lightViewMatrix = lookat(light_dir_local*light_distance, Vec3f(0.0,0.0,0.0), Vec3f(0.0,0.0,1.0));
Matrix lightModelViewMatrix = lightViewMatrix*renderData.m_modelMatrix;
Matrix lightViewProjectionMatrix = renderData.m_projectionMatrix;
Vec3f localScaling(renderData.m_localScaling[0],renderData.m_localScaling[1],renderData.m_localScaling[2]);
DepthShader shader(model, lightModelViewMatrix, lightViewProjectionMatrix,renderData.m_modelMatrix, localScaling, light_distance);
for (int i=0; i<model->nfaces(); i++)
{
for (int j=0; j<3; j++) {
shader.vertex(i, j);
}
mat<4,3,float> stackTris[3];
b3AlignedObjectArray< mat<4,3,float> > clippedTriangles;
clippedTriangles.initializeFromBuffer(stackTris,0,3);
bool hasClipped = clipTriangleAgainstNearplane(shader.varying_tri,clippedTriangles);
if (hasClipped)
{
for (int t=0;t<clippedTriangles.size();t++)
{
triangleClipped(clippedTriangles[t], shader.varying_tri, shader, depthFrame, shadowBufferPtr, segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex);
}
} else
{
triangle(shader.varying_tri, shader, depthFrame, shadowBufferPtr, segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex);
}
} }
} }

View File

@ -140,6 +140,13 @@ void Model::load_texture(std::string filename, const char *suffix, TGAImage &img
TGAColor Model::diffuse(Vec2f uvf) { TGAColor Model::diffuse(Vec2f uvf) {
if (diffusemap_.get_width() && diffusemap_.get_height()) if (diffusemap_.get_width() && diffusemap_.get_height())
{ {
double val;
// bool repeat = true;
// if (repeat)
{
uvf[0] = modf(uvf[0],&val);
uvf[1] = modf(uvf[1],&val);
}
Vec2i uv(uvf[0]*diffusemap_.get_width(), uvf[1]*diffusemap_.get_height()); Vec2i uv(uvf[0]*diffusemap_.get_width(), uvf[1]*diffusemap_.get_height());
return diffusemap_.get(uv[0], uv[1]); return diffusemap_.get(uv[0], uv[1]);
} }

View File

@ -70,6 +70,80 @@ Vec3f barycentric(Vec2f A, Vec2f B, Vec2f C, Vec2f P) {
return Vec3f(-1,1,1); // in this case generate negative coordinates, it will be thrown away by the rasterizator return Vec3f(-1,1,1); // in this case generate negative coordinates, it will be thrown away by the rasterizator
} }
void triangleClipped(mat<4,3,float> &clipc, mat<4,3,float> &orgClipc, IShader &shader, TGAImage &image, float *zbuffer, const Matrix& viewPortMatrix)
{
triangleClipped(clipc, orgClipc,shader,image,zbuffer,0,viewPortMatrix,0);
}
void triangleClipped(mat<4,3,float> &clipc, mat<4,3,float> &orgClipc, IShader &shader, TGAImage &image, float *zbuffer, int* segmentationMaskBuffer, const Matrix& viewPortMatrix, int objectIndex)
{
mat<3,4,float> screenSpacePts = (viewPortMatrix*clipc).transpose(); // transposed to ease access to each of the points
mat<3,2,float> pts2;
for (int i=0; i<3; i++)
{
pts2[i] = proj<2>(screenSpacePts[i]/screenSpacePts[i][3]);
}
Vec2f bboxmin( std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
Vec2f bboxmax(-std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());
Vec2f clamp(image.get_width()-1, image.get_height()-1);
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
bboxmin[j] = b3Max(0.f, b3Min(bboxmin[j], pts2[i][j]));
bboxmax[j] = b3Min(clamp[j], b3Max(bboxmax[j], pts2[i][j]));
}
}
Vec2i P;
TGAColor color;
mat<3,4,float> orgScreenSpacePts = (viewPortMatrix*orgClipc).transpose(); // transposed to ease access to each of the points
mat<3,2,float> orgPts2;
for (int i=0; i<3; i++)
{
orgPts2[i] = proj<2>(orgScreenSpacePts[i]/orgScreenSpacePts[i][3]);
}
for (P.x=bboxmin.x; P.x<=bboxmax.x; P.x++) {
for (P.y=bboxmin.y; P.y<=bboxmax.y; P.y++)
{
float frag_depth = 0;
{
Vec3f bc_screen = barycentric(pts2[0], pts2[1], pts2[2], P);
Vec3f bc_clip = Vec3f(bc_screen.x/screenSpacePts[0][3], bc_screen.y/screenSpacePts[1][3], bc_screen.z/screenSpacePts[2][3]);
bc_clip = bc_clip/(bc_clip.x+bc_clip.y+bc_clip.z);
frag_depth = -1*(clipc[2]*bc_clip);
if (bc_screen.x<0 || bc_screen.y<0 || bc_screen.z<0 ||
zbuffer[P.x+P.y*image.get_width()]>frag_depth)
continue;
}
Vec3f bc_screen2 = barycentric(orgPts2[0], orgPts2[1], orgPts2[2], P);
Vec3f bc_clip2 = Vec3f(bc_screen2.x/orgScreenSpacePts[0][3], bc_screen2.y/orgScreenSpacePts[1][3], bc_screen2.z/orgScreenSpacePts[2][3]);
bc_clip2 = bc_clip2/(bc_clip2.x+bc_clip2.y+bc_clip2.z);
float frag_depth2 = -1*(orgClipc[2]*bc_clip2);
bool discard = shader.fragment(bc_clip2, color);
if (!discard) {
zbuffer[P.x+P.y*image.get_width()] = frag_depth;
if (segmentationMaskBuffer)
{
segmentationMaskBuffer[P.x+P.y*image.get_width()] = objectIndex;
}
image.set(P.x, P.y, color);
}
}
}
}
void triangle(mat<4,3,float> &clipc, IShader &shader, TGAImage &image, float *zbuffer, const Matrix& viewPortMatrix) void triangle(mat<4,3,float> &clipc, IShader &shader, TGAImage &image, float *zbuffer, const Matrix& viewPortMatrix)
{ {
triangle(clipc,shader,image,zbuffer,0,viewPortMatrix,0); triangle(clipc,shader,image,zbuffer,0,viewPortMatrix,0);
@ -78,9 +152,7 @@ void triangle(mat<4,3,float> &clipc, IShader &shader, TGAImage &image, float *zb
void triangle(mat<4,3,float> &clipc, IShader &shader, TGAImage &image, float *zbuffer, int* segmentationMaskBuffer, const Matrix& viewPortMatrix, int objectIndex) { void triangle(mat<4,3,float> &clipc, IShader &shader, TGAImage &image, float *zbuffer, int* segmentationMaskBuffer, const Matrix& viewPortMatrix, int objectIndex) {
mat<3,4,float> pts = (viewPortMatrix*clipc).transpose(); // transposed to ease access to each of the points mat<3,4,float> pts = (viewPortMatrix*clipc).transpose(); // transposed to ease access to each of the points
//we don't clip triangles that cross the near plane, just discard them instead of showing artifacts
if (pts[0][3]<0 || pts[1][3] <0 || pts[2][3] <0)
return;
mat<3,2,float> pts2; mat<3,2,float> pts2;
for (int i=0; i<3; i++) pts2[i] = proj<2>(pts[i]/pts[i][3]); for (int i=0; i<3; i++) pts2[i] = proj<2>(pts[i]/pts[i][3]);
@ -119,4 +191,3 @@ void triangle(mat<4,3,float> &clipc, IShader &shader, TGAImage &image, float *zb
} }
} }
} }

View File

@ -18,5 +18,8 @@ struct IShader {
void triangle(mat<4,3,float> &pts, IShader &shader, TGAImage &image, float *zbuffer, const Matrix& viewPortMatrix); void triangle(mat<4,3,float> &pts, IShader &shader, TGAImage &image, float *zbuffer, const Matrix& viewPortMatrix);
void triangle(mat<4,3,float> &pts, IShader &shader, TGAImage &image, float *zbuffer, int* segmentationMaskBuffer, const Matrix& viewPortMatrix, int objectIndex); void triangle(mat<4,3,float> &pts, IShader &shader, TGAImage &image, float *zbuffer, int* segmentationMaskBuffer, const Matrix& viewPortMatrix, int objectIndex);
void triangleClipped(mat<4,3,float> &clippedPts, mat<4,3,float> &pts, IShader &shader, TGAImage &image, float *zbuffer, const Matrix& viewPortMatrix);
void triangleClipped(mat<4,3,float> &clippedPts, mat<4,3,float> &pts, IShader &shader, TGAImage &image, float *zbuffer, int* segmentationMaskBuffer, const Matrix& viewPortMatrix, int objectIndex);
#endif //__OUR_GL_H__ #endif //__OUR_GL_H__

View File

@ -84,6 +84,27 @@ int readMinitaurLogFile(const char* fileName, btAlignedObjectArray<std::string>&
switch (structTypes[i]) switch (structTypes[i])
{ {
case 'I': case 'I':
{
size_t s = fread(blaat,sizeof(int),1,f);
if (s != 1)
{
eof = true;
retVal = eCorruptValue;
break;
}
int v = (int) *(unsigned int*)blaat;
if (s==1)
{
if (verbose)
{
printf("%s = %d\n",structNames[i].c_str(),v);
}
record.m_values.push_back(v);
}
break;
}
case 'i':
{ {
size_t s = fread(blaat,sizeof(int),1,f); size_t s = fread(blaat,sizeof(int),1,f);
if (s != 1) if (s != 1)
@ -219,6 +240,7 @@ void appendMinitaurLogData(FILE* f, std::string& structTypes, const MinitaurLogR
{ {
switch(structTypes[i]) switch(structTypes[i])
{ {
case 'i':
case 'I': case 'I':
{ {
fwrite(&logData.m_values[i].m_intVal,sizeof(int),1,f); fwrite(&logData.m_values[i].m_intVal,sizeof(int),1,f);

View File

@ -101,11 +101,7 @@ ELSE(WIN32)
ENDIF(BUILD_PYBULLET_ENET) ENDIF(BUILD_PYBULLET_ENET)
IF(BUILD_PYBULLET_CLSOCKET) IF(BUILD_PYBULLET_CLSOCKET)
IF(APPLE) ADD_DEFINITIONS(${OSDEF})
ADD_DEFINITIONS(-D_DARWIN)
ELSE()
ADD_DEFINITIONS(-D_LINUX)
ENDIF()
ENDIF(BUILD_PYBULLET_CLSOCKET) ENDIF(BUILD_PYBULLET_CLSOCKET)
ENDIF(WIN32) ENDIF(WIN32)

View File

@ -0,0 +1,74 @@
import time
import math
from datetime import datetime
import struct
import sys
import os, fnmatch
import argparse
from time import sleep
def readLogFile(filename, verbose = True):
f = open(filename, 'rb')
print('Opened'),
print(filename)
keys = f.readline().decode('utf8').rstrip('\n').split(',')
fmt = f.readline().decode('utf8').rstrip('\n')
# The byte number of one record
sz = struct.calcsize(fmt)
# The type number of one record
ncols = len(fmt)
if verbose:
print('Keys:'),
print(keys)
print('Format:'),
print(fmt)
print('Size:'),
print(sz)
print('Columns:'),
print(ncols)
# Read data
wholeFile = f.read()
# split by alignment word
chunks = wholeFile.split(b'\xaa\xbb')
log = list()
if verbose:
print("num chunks:")
print(len(chunks))
chunkIndex = 0
for chunk in chunks:
print("len(chunk)=",len(chunk)," sz = ", sz)
if len(chunk) == sz:
print("chunk #",chunkIndex)
chunkIndex=chunkIndex+1
values = struct.unpack(fmt, chunk)
record = list()
for i in range(ncols):
record.append(values[i])
if verbose:
print(" ",keys[i],"=",values[i])
log.append(record)
return log
numArgs = len(sys.argv)
print ('Number of arguments:', numArgs, 'arguments.')
print ('Argument List:', str(sys.argv))
fileName = "log.bin"
if (numArgs>1):
fileName = sys.argv[1]
print("filename=")
print(fileName)
verbose = True
readLogFile(fileName,verbose)

View File

@ -10,6 +10,10 @@ int sensorPin3 = A3;
void setup() { void setup() {
// put your setup code here, to run once: // put your setup code here, to run once:
Serial.begin(115200); Serial.begin(115200);
digitalWrite(A0, INPUT_PULLUP);
digitalWrite(A1, INPUT_PULLUP);
digitalWrite(A2, INPUT_PULLUP);
digitalWrite(A3, INPUT_PULLUP);
} }
void loop() { void loop() {

View File

@ -20,12 +20,28 @@ objects = p.loadMJCF("MPL/MPL.xml")
hand=objects[0] hand=objects[0]
#clamp in range 400-600 #clamp in range 400-600
minV = 400 #minV = 400
maxV = 600 #maxV = 600
minVarray = [275,280,350,290]
maxVarray = [450,550,500,400]
pinkId = 0
middleId = 1
indexId = 2
thumbId = 3
p.setRealTimeSimulation(1) p.setRealTimeSimulation(1)
def convertSensor(x): def getSerialOrNone(portname):
try:
return serial.Serial(port=portname,baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS)
except:
return None
def convertSensor(x, fingerIndex):
minV = minVarray[fingerIndex]
maxV = maxVarray[fingerIndex]
v = minV v = minV
try: try:
v = float(x) v = float(x)
@ -36,22 +52,39 @@ def convertSensor(x):
if (v>maxV): if (v>maxV):
v=maxV v=maxV
b = (v-minV)/float(maxV-minV) b = (v-minV)/float(maxV-minV)
return (1.0-b) return (b)
ser = serial.Serial(port='COM13',baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS) ser = None
if (ser.isOpen()): portindex = 0
while (ser is None and portindex < 30):
portname = 'COM'+str(portindex)
print(portname)
ser = getSerialOrNone(portname)
if (ser is None):
portname = "/dev/cu.usbmodem14"+str(portindex)
print(portname)
ser = getSerialOrNone(portname)
if (ser is not None):
print("COnnected!")
portindex = portindex+1
if (ser is None):
ser = serial.Serial(port = "/dev/cu.usbmodem1421",baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS)
pi=3.141592
if (ser is not None and ser.isOpen()):
while True: while True:
while ser.inWaiting() > 0: while ser.inWaiting() > 0:
line = str(ser.readline()) line = str(ser.readline())
words = line.split(",") words = line.split(",")
if (len(words)==6): if (len(words)==6):
middle = convertSensor(words[1]) pink = convertSensor(words[1],pinkId)
pink = convertSensor(words[2]) middle = convertSensor(words[2],middleId)
index = convertSensor(words[3]) index = convertSensor(words[3],indexId)
thumb = convertSensor(words[4]) thumb = convertSensor(words[4],thumbId)
p.setJointMotorControl2(hand,7,p.POSITION_CONTROL,thumb) p.setJointMotorControl2(hand,7,p.POSITION_CONTROL,pi/4.)
p.setJointMotorControl2(hand,9,p.POSITION_CONTROL,thumb) p.setJointMotorControl2(hand,9,p.POSITION_CONTROL,thumb+pi/10)
p.setJointMotorControl2(hand,11,p.POSITION_CONTROL,thumb) p.setJointMotorControl2(hand,11,p.POSITION_CONTROL,thumb)
p.setJointMotorControl2(hand,13,p.POSITION_CONTROL,thumb) p.setJointMotorControl2(hand,13,p.POSITION_CONTROL,thumb)
@ -76,3 +109,5 @@ if (ser.isOpen()):
#print(pink) #print(pink)
#print(index) #print(index)
#print(thumb) #print(thumb)
else:
print("Cannot find port")

View File

@ -0,0 +1,30 @@
import pybullet as p
import time
import math
from datetime import datetime
from time import sleep
p.connect(p.GUI)
p.loadURDF("plane.urdf",[0,0,-0.3])
kukaId = p.loadURDF("kuka_iiwa/model.urdf",[0,0,0])
p.resetBasePositionAndOrientation(kukaId,[0,0,0],[0,0,0,1])
kukaEndEffectorIndex = 6
numJoints = p.getNumJoints(kukaId)
#Joint damping coefficents. Using large values for the joints that we don't want to move.
jd=[100.0,100.0,100.0,100.0,100.0,100.0,0.5]
#jd=[0.5,0.5,0.5,0.5,0.5,0.5,0.5]
p.setGravity(0,0,0)
while 1:
p.stepSimulation()
for i in range (1):
pos = [0,0,1.26]
orn = p.getQuaternionFromEuler([0,0,3.14])
jointPoses = p.calculateInverseKinematics(kukaId,kukaEndEffectorIndex,pos,orn,jointDamping=jd)
for i in range (numJoints):
p.setJointMotorControl2(bodyIndex=kukaId,jointIndex=i,controlMode=p.POSITION_CONTROL,targetPosition=jointPoses[i],targetVelocity=0,force=500,positionGain=0.03,velocityGain=1)
sleep(0.05)

View File

@ -1,7 +1,13 @@
import pybullet as p import pybullet as p
import time import time
p.connect(p.GUI) conid = p.connect(p.SHARED_MEMORY)
if (conid<0):
p.connect(p.GUI)
p.setInternalSimFlags(0)
p.resetSimulation()
p.loadURDF("plane.urdf",useMaximalCoordinates=True) p.loadURDF("plane.urdf",useMaximalCoordinates=True)
p.loadURDF("tray/traybox.urdf",useMaximalCoordinates=True) p.loadURDF("tray/traybox.urdf",useMaximalCoordinates=True)
@ -12,7 +18,7 @@ p.setPhysicsEngineParameter(numSolverIterations=10)
p.setPhysicsEngineParameter(contactBreakingThreshold=0.001) p.setPhysicsEngineParameter(contactBreakingThreshold=0.001)
for i in range (10): for i in range (10):
for j in range (10): for j in range (10):
for k in range (5): for k in range (10):
ob = p.loadURDF("sphere_1cm.urdf",[0.02*i,0.02*j,0.2+0.02*k],useMaximalCoordinates=True) ob = p.loadURDF("sphere_1cm.urdf",[0.02*i,0.02*j,0.2+0.02*k],useMaximalCoordinates=True)
p.setGravity(0,0,-10) p.setGravity(0,0,-10)
p.setRealTimeSimulation(1) p.setRealTimeSimulation(1)

View File

@ -143,7 +143,7 @@ p.setRealTimeSimulation(useRealTime)
print("quadruped Id = ") print("quadruped Id = ")
print(quadruped) print(quadruped)
p.saveWorld("quadru.py") p.saveWorld("quadru.py")
logId = p.startStateLogging(p.STATE_LOGGING_MINITAUR,"quadrupedLog.txt",[quadruped]) logId = p.startStateLogging(p.STATE_LOGGING_MINITAUR,"quadrupedLog.bin",[quadruped])

View File

@ -1,6 +1,9 @@
import pybullet as p import pybullet as p
#p.connect(p.UDP,"192.168.86.100") #p.connect(p.UDP,"192.168.86.100")
p.connect(p.SHARED_MEMORY)
cid = p.connect(p.SHARED_MEMORY)
if (cid<0):
p.connect(p.GUI)
p.resetSimulation() p.resetSimulation()
objects = [p.loadURDF("plane.urdf", 0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,1.000000)] objects = [p.loadURDF("plane.urdf", 0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,1.000000)]

View File

@ -0,0 +1,149 @@
#script to control a simulated robot hand using a VR glove
#see https://twitter.com/erwincoumans/status/821953216271106048
#and https://www.youtube.com/watch?v=I6s37aBXbV8
#vr glove was custom build using Spectra Symbolflex sensors (4.5")
#inside a Under Armour Batting Glove, using DFRobot Bluno BLE/Beetle
#with BLE Link to receive serial (for wireless bluetooth serial)
import serial
import time
import pybullet as p
#first try to connect to shared memory (VR), if it fails use local GUI
c = p.connect(p.SHARED_MEMORY)
if (c<0):
c = p.connect(p.GUI)
p.setInternalSimFlags(0)#don't load default robot assets etc
p.resetSimulation()
#p.resetSimulation()
p.setGravity(0,0,-10)
objects = [p.loadURDF("plane.urdf", 0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,1.000000)]
objects = [p.loadURDF("jenga/jenga.urdf", 1.300000,-0.700000,0.750000,0.000000,0.707107,0.000000,0.707107)]
objects = [p.loadURDF("jenga/jenga.urdf", 1.200000,-0.700000,0.750000,0.000000,0.707107,0.000000,0.707107)]
objects = [p.loadURDF("jenga/jenga.urdf", 1.100000,-0.700000,0.750000,0.000000,0.707107,0.000000,0.707107)]
objects = [p.loadURDF("jenga/jenga.urdf", 1.000000,-0.700000,0.750000,0.000000,0.707107,0.000000,0.707107)]
objects = [p.loadURDF("jenga/jenga.urdf", 0.900000,-0.700000,0.750000,0.000000,0.707107,0.000000,0.707107)]
objects = [p.loadURDF("jenga/jenga.urdf", 0.800000,-0.700000,0.750000,0.000000,0.707107,0.000000,0.707107)]
objects = [p.loadURDF("table/table.urdf", 1.000000,-0.200000,0.000000,0.000000,0.000000,0.707107,0.707107)]
objects = [p.loadURDF("cube_small.urdf", 0.950000,-0.100000,0.700000,0.000000,0.000000,0.707107,0.707107)]
objects = [p.loadURDF("sphere_small.urdf", 0.850000,-0.400000,0.700000,0.000000,0.000000,0.707107,0.707107)]
#load the MuJoCo MJCF hand
objects = p.loadMJCF("MPL/mpl2.xml")
hand=objects[0]
ho = p.getQuaternionFromEuler([3.14,-3.14/2,0])
hand_cid = p.createConstraint(hand,-1,-1,-1,p.JOINT_FIXED,[0,0,0],[-0.05,0,0.02],[0.500000,0.300006,0.700000],ho)
print ("hand_cid")
print (hand_cid)
for i in range (p.getNumJoints(hand)):
p.setJointMotorControl2(hand,i,p.POSITION_CONTROL,0,0)
#clamp in range 400-600
#minV = 400
#maxV = 600
minV = 250
maxV = 450
POSITION=1
ORIENTATION=2
BUTTONS=6
p.setRealTimeSimulation(1)
def convertSensor(x):
v = minV
try:
v = float(x)
except ValueError:
v = minV
if (v<minV):
v=minV
if (v>maxV):
v=maxV
b = (v-minV)/float(maxV-minV)
return (b)
controllerId = -1
serialSteps = 0
serialStepsUntilCheckVREvents = 3
def getSerialOrNone(portname):
try:
return serial.Serial(port=portname,baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS)
except:
return None
ser = None
portindex = 10
while (ser is None and portindex < 30):
portname = 'COM'+str(portindex)
print(portname)
ser = getSerialOrNone(portname)
if (ser is None):
portname = "/dev/cu.usbmodem14"+str(portindex)
print(portname)
ser = getSerialOrNone(portname)
if (ser is not None):
print("COnnected!")
portindex = portindex+1
p.saveWorld("setupTrackerWorld.py")
if (ser.isOpen()):
while True:
events = p.getVREvents(deviceTypeFilter=p.VR_DEVICE_GENERIC_TRACKER)
for e in (events):
p.changeConstraint(hand_cid,e[POSITION],e[ORIENTATION], maxForce=50)
serialSteps = 0
while ser.inWaiting() > 0:
serialSteps=serialSteps+1
if (serialSteps>serialStepsUntilCheckVREvents):
ser.flushInput()
break
line = str(ser.readline())
words = line.split(",")
if (len(words)==6):
pink = convertSensor(words[1])
middle = convertSensor(words[2])
index = convertSensor(words[3])
thumb = convertSensor(words[4])+0.2
p.setJointMotorControl2(hand,5,p.POSITION_CONTROL,1.3)
p.setJointMotorControl2(hand,7,p.POSITION_CONTROL,thumb)
p.setJointMotorControl2(hand,9,p.POSITION_CONTROL,thumb)
p.setJointMotorControl2(hand,11,p.POSITION_CONTROL,thumb)
p.setJointMotorControl2(hand,15,p.POSITION_CONTROL,index)
p.setJointMotorControl2(hand,17,p.POSITION_CONTROL,index)
p.setJointMotorControl2(hand,19,p.POSITION_CONTROL,index)
p.setJointMotorControl2(hand,22,p.POSITION_CONTROL,middle)
p.setJointMotorControl2(hand,24,p.POSITION_CONTROL,middle)
p.setJointMotorControl2(hand,26,p.POSITION_CONTROL,middle)
p.setJointMotorControl2(hand,38,p.POSITION_CONTROL,pink)
p.setJointMotorControl2(hand,40,p.POSITION_CONTROL,pink)
p.setJointMotorControl2(hand,42,p.POSITION_CONTROL,pink)
ringpos = 0.5*(pink+middle)
p.setJointMotorControl2(hand,30,p.POSITION_CONTROL,ringpos)
p.setJointMotorControl2(hand,32,p.POSITION_CONTROL,ringpos)
p.setJointMotorControl2(hand,34,p.POSITION_CONTROL,ringpos)
#print(middle)
#print(pink)
#print(index)
#print(thumb)

View File

@ -0,0 +1,89 @@
# See pybullet quickstart guide here:
# https://docs.google.com/document/d/10sXEhzFRSnvFcl3XxNGhnD4N2SedqwdAvK3dsihxVUA/edit#
# Create a Tiltbrush-like app, drawing lines using any controller
# Line width can be changed
import pybullet as p
CONTROLLER_ID = 0
POSITION=1
ORIENTATION=2
BUTTONS=6
#assume that the VR physics server is already started before
c = p.connect(p.SHARED_MEMORY)
print(c)
if (c<0):
p.connect(p.GUI)
p.setInternalSimFlags(0)#don't load default robot assets etc
p.resetSimulation()
p.loadURDF("plane.urdf")
p.loadURDF("cube.urdf",0,0,1)
p.setGravity(0,0,-10)
p.setRealTimeSimulation(1)
prevPosition=[None]*p.VR_MAX_CONTROLLERS
colors=[0.,0.5,0.5]*p.VR_MAX_CONTROLLERS
widths = [3]*p.VR_MAX_CONTROLLERS
a=[0,0,0]
#use a few default colors
colors[0] = [0,0,0]
colors[1] = [0.5,0,0]
colors[2] = [0,0.5,0]
colors[3] = [0,0,0.5]
colors[4] = [0.5,0.5,0.]
colors[5] = [.5,.5,.5]
p.startStateLogging(p.STATE_LOGGING_VR_CONTROLLERS, "vr_hmd.bin",deviceTypeFilter=p.VR_DEVICE_HMD)
p.startStateLogging(p.STATE_LOGGING_GENERIC_ROBOT, "generic_data.bin")
p.startStateLogging(p.STATE_LOGGING_CONTACT_POINTS, "contact_points.bin")
while True:
events = p.getVREvents(p.VR_DEVICE_HMD+p.VR_DEVICE_GENERIC_TRACKER)
for e in (events):
pos = e[POSITION]
mat = p.getMatrixFromQuaternion(e[ORIENTATION])
dir0 = [mat[0],mat[3],mat[6]]
dir1 = [mat[1],mat[4],mat[7]]
dir2 = [mat[2],mat[5],mat[8]]
lineLen = 0.1
dir = [-mat[2],-mat[5],-mat[8]]
to = [pos[0]+lineLen*dir[0],pos[1]+lineLen*dir[1],pos[2]+lineLen*dir[2]]
toX = [pos[0]+lineLen*dir0[0],pos[1]+lineLen*dir0[1],pos[2]+lineLen*dir0[2]]
toY = [pos[0]+lineLen*dir1[0],pos[1]+lineLen*dir1[1],pos[2]+lineLen*dir1[2]]
toZ = [pos[0]+lineLen*dir2[0],pos[1]+lineLen*dir2[1],pos[2]+lineLen*dir2[2]]
p.addUserDebugLine(pos,toX,[1,0,0],1)
p.addUserDebugLine(pos,toY,[0,1,0],1)
p.addUserDebugLine(pos,toZ,[0,0,1],1)
p.addUserDebugLine(pos,to,[0.5,0.5,0.],1,3)
events = p.getVREvents()
for e in (events):
if (e[BUTTONS][33]&p.VR_BUTTON_WAS_TRIGGERED):
prevPosition[e[CONTROLLER_ID]] = e[POSITION]
if (e[BUTTONS][32]&p.VR_BUTTON_WAS_TRIGGERED):
widths[e[CONTROLLER_ID]]=widths[e[0]]+1
if (widths[e[CONTROLLER_ID]]>20):
widths[e[CONTROLLER_ID]] = 1
if (e[BUTTONS][1]&p.VR_BUTTON_WAS_TRIGGERED):
p.resetSimulation()
#p.setGravity(0,0,-10)
p.removeAllUserDebugItems()
p.loadURDF("plane.urdf")
if (e[BUTTONS][33]==p.VR_BUTTON_IS_DOWN):
pt = prevPosition[e[CONTROLLER_ID]]
#print(prevPosition[e[0]])
#print(e[1])
diff = [pt[0]-e[POSITION][0],pt[1]-e[POSITION][1],pt[2]-e[POSITION][2]]
lenSqr = diff[0]*diff[0]+diff[1]*diff[1]+diff[2]*diff[2]
ptDistThreshold = 0.01
if (lenSqr>(ptDistThreshold*ptDistThreshold)):
p.addUserDebugLine(e[POSITION],prevPosition[e[CONTROLLER_ID]],colors[e[CONTROLLER_ID]],widths[e[CONTROLLER_ID]])
#p.loadURDF("cube_small.urdf",e[1])
colors[e[CONTROLLER_ID]] = [1-colors[e[CONTROLLER_ID]][0],1-colors[e[CONTROLLER_ID]][1],1-colors[e[CONTROLLER_ID]][2]]
prevPosition[e[CONTROLLER_ID]] = e[POSITION]

View File

@ -11,16 +11,25 @@
#include "../SharedMemory/PhysicsClientTCP_C_API.h" #include "../SharedMemory/PhysicsClientTCP_C_API.h"
#endif //BT_ENABLE_CLSOCKET #endif //BT_ENABLE_CLSOCKET
#ifdef __APPLE__ #if defined(__APPLE__) && (!defined(B3_NO_PYTHON_FRAMEWORK))
#include <Python/Python.h> #include <Python/Python.h>
#else #else
#include <Python.h> #include <Python.h>
#endif #endif
#ifdef B3_DUMP_PYTHON_VERSION
#define B3_VALUE_TO_STRING(x) #x
#define B3_VALUE(x) B3_VALUE_TO_STRING(x)
#define B3_VAR_NAME_VALUE(var) #var "=" B3_VALUE(var)
#pragma message(B3_VAR_NAME_VALUE(PY_MAJOR_VERSION))
#pragma message(B3_VAR_NAME_VALUE(PY_MINOR_VERSION))
#endif
#ifdef PYBULLET_USE_NUMPY #ifdef PYBULLET_USE_NUMPY
#include <numpy/arrayobject.h> #include <numpy/arrayobject.h>
#endif #endif
#if PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3
#define PyInt_FromLong PyLong_FromLong #define PyInt_FromLong PyLong_FromLong
#define PyString_FromString PyBytes_FromString #define PyString_FromString PyBytes_FromString
@ -400,8 +409,8 @@ static PyObject* pybullet_disconnectPhysicsServer(PyObject* self,
return Py_None; return Py_None;
} }
///to avoid memory leaks, disconnect all physics servers explicitly
void b3pybulletExitFunc() void b3pybulletExitFunc(void)
{ {
int i; int i;
for (i=0;i<MAX_PHYSICS_CLIENTS;i++) for (i=0;i<MAX_PHYSICS_CLIENTS;i++)
@ -2074,7 +2083,7 @@ static PyObject* pybullet_getJointInfo(PyObject* self, PyObject* args, PyObject*
int bodyUniqueId = -1; int bodyUniqueId = -1;
int jointIndex = -1; int jointIndex = -1;
int jointInfoSize = 12; // size of struct b3JointInfo int jointInfoSize = 13; // size of struct b3JointInfo
b3PhysicsClientHandle sm = 0; b3PhysicsClientHandle sm = 0;
int physicsClientId = 0; int physicsClientId = 0;
static char* kwlist[] = {"bodyUniqueId", "jointIndex", "physicsClientId", NULL}; static char* kwlist[] = {"bodyUniqueId", "jointIndex", "physicsClientId", NULL};
@ -2126,6 +2135,8 @@ static PyObject* pybullet_getJointInfo(PyObject* self, PyObject* args, PyObject*
PyFloat_FromDouble(info.m_jointMaxForce)); PyFloat_FromDouble(info.m_jointMaxForce));
PyTuple_SetItem(pyListJointInfo, 11, PyTuple_SetItem(pyListJointInfo, 11,
PyFloat_FromDouble(info.m_jointMaxVelocity)); PyFloat_FromDouble(info.m_jointMaxVelocity));
PyTuple_SetItem(pyListJointInfo, 12,
PyString_FromString(info.m_linkName));
return pyListJointInfo; return pyListJointInfo;
} }
@ -2683,12 +2694,13 @@ static PyObject* pybullet_startStateLogging(PyObject* self, PyObject* args, PyOb
int bodyUniqueIdB = -1; int bodyUniqueIdB = -1;
int linkIndexA = -2; int linkIndexA = -2;
int linkIndexB = -2; int linkIndexB = -2;
int deviceTypeFilter = -1;
static char* kwlist[] = {"loggingType", "fileName", "objectUniqueIds", "maxLogDof", "bodyUniqueIdA", "bodyUniqueIdB", "linkIndexA", "linkIndexB", "physicsClientId", NULL}; static char* kwlist[] = {"loggingType", "fileName", "objectUniqueIds", "maxLogDof", "bodyUniqueIdA", "bodyUniqueIdB", "linkIndexA", "linkIndexB", "deviceTypeFilter", "physicsClientId", NULL};
int physicsClientId = 0; int physicsClientId = 0;
if (!PyArg_ParseTupleAndKeywords(args, keywds, "is|Oiiiiii", kwlist, if (!PyArg_ParseTupleAndKeywords(args, keywds, "is|Oiiiiiii", kwlist,
&loggingType, &fileName, &objectUniqueIdsObj, &maxLogDof, &bodyUniqueIdA, &bodyUniqueIdB, &linkIndexA, &linkIndexB, &physicsClientId)) &loggingType, &fileName, &objectUniqueIdsObj, &maxLogDof, &bodyUniqueIdA, &bodyUniqueIdB, &linkIndexA, &linkIndexB, &deviceTypeFilter, &physicsClientId))
return NULL; return NULL;
sm = getPhysicsClient(physicsClientId); sm = getPhysicsClient(physicsClientId);
@ -2741,6 +2753,11 @@ static PyObject* pybullet_startStateLogging(PyObject* self, PyObject* args, PyOb
b3StateLoggingSetLinkIndexB(commandHandle, linkIndexB); b3StateLoggingSetLinkIndexB(commandHandle, linkIndexB);
} }
if (deviceTypeFilter>=0)
{
b3StateLoggingSetDeviceTypeFilter(commandHandle,deviceTypeFilter);
}
statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle); statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);
statusType = b3GetStatusType(statusHandle); statusType = b3GetStatusType(statusHandle);
if (statusType == CMD_STATE_LOGGING_START_COMPLETED) if (statusType == CMD_STATE_LOGGING_START_COMPLETED)
@ -2812,7 +2829,7 @@ static PyObject* pybullet_setTimeOut(PyObject* self, PyObject* args, PyObject* k
return Py_None; return Py_None;
} }
static PyObject* pybullet_rayTest(PyObject* self, PyObject* args, PyObject* keywds) static PyObject* pybullet_rayTestObsolete(PyObject* self, PyObject* args, PyObject* keywds)
{ {
b3SharedMemoryCommandHandle commandHandle; b3SharedMemoryCommandHandle commandHandle;
b3SharedMemoryStatusHandle statusHandle; b3SharedMemoryStatusHandle statusHandle;
@ -2896,6 +2913,154 @@ static PyObject* pybullet_rayTest(PyObject* self, PyObject* args, PyObject* keyw
return Py_None; return Py_None;
} }
static PyObject* pybullet_rayTestBatch(PyObject* self, PyObject* args, PyObject* keywds)
{
b3SharedMemoryCommandHandle commandHandle;
b3SharedMemoryStatusHandle statusHandle;
int statusType;
PyObject* rayFromObjList = 0;
PyObject* rayToObjList = 0;
b3PhysicsClientHandle sm = 0;
int sizeFrom = 0;
int sizeTo = 0;
static char* kwlist[] = {"rayFromPositions", "rayToPositions", "physicsClientId", NULL};
int physicsClientId = 0;
if (!PyArg_ParseTupleAndKeywords(args, keywds, "OO|i", kwlist,
&rayFromObjList, &rayToObjList, &physicsClientId))
return NULL;
sm = getPhysicsClient(physicsClientId);
if (sm == 0)
{
PyErr_SetString(SpamError, "Not connected to physics server.");
return NULL;
}
commandHandle = b3CreateRaycastBatchCommandInit(sm);
if (rayFromObjList)
{
PyObject* seqRayFromObj = PySequence_Fast(rayFromObjList, "expected a sequence of rayFrom positions");
PyObject* seqRayToObj = PySequence_Fast(rayToObjList, "expected a sequence of 'rayTo' positions");
if (seqRayFromObj && seqRayToObj)
{
int lenFrom = PySequence_Size(rayFromObjList);
int lenTo= PySequence_Size(seqRayToObj);
if (lenFrom!=lenTo)
{
PyErr_SetString(SpamError, "Size of from_positions need to be equal to size of to_positions.");
Py_DECREF(seqRayFromObj);
Py_DECREF(seqRayToObj);
return NULL;
} else
{
int i;
if (lenFrom >= MAX_RAY_INTERSECTION_BATCH_SIZE)
{
PyErr_SetString(SpamError, "Number of rays exceed the maximum batch size.");
Py_DECREF(seqRayFromObj);
Py_DECREF(seqRayToObj);
return NULL;
}
for (i = 0; i < lenFrom; i++)
{
PyObject* rayFromObj = PySequence_GetItem(rayFromObjList,i);
PyObject* rayToObj = PySequence_GetItem(seqRayToObj,i);
double rayFromWorld[3];
double rayToWorld[3];
if ((pybullet_internalSetVectord(rayFromObj, rayFromWorld)) &&
(pybullet_internalSetVectord(rayToObj, rayToWorld)))
{
b3RaycastBatchAddRay(commandHandle, rayFromWorld, rayToWorld);
} else
{
PyErr_SetString(SpamError, "Items in the from/to positions need to be an [x,y,z] list of 3 floats/doubles");
Py_DECREF(seqRayFromObj);
Py_DECREF(seqRayToObj);
Py_DECREF(rayFromObj);
Py_DECREF(rayToObj);
return NULL;
}
Py_DECREF(rayFromObj);
Py_DECREF(rayToObj);
}
}
} else
{
}
if (seqRayFromObj)
{
Py_DECREF(seqRayFromObj);
}
if (seqRayToObj)
{
Py_DECREF(seqRayToObj);
}
}
statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);
statusType = b3GetStatusType(statusHandle);
if (statusType == CMD_REQUEST_RAY_CAST_INTERSECTIONS_COMPLETED)
{
struct b3RaycastInformation raycastInfo;
PyObject* rayHitsObj = 0;
int i;
b3GetRaycastInformation(sm, &raycastInfo);
rayHitsObj = PyTuple_New(raycastInfo.m_numRayHits);
for (i = 0; i < raycastInfo.m_numRayHits; i++)
{
PyObject* singleHitObj = PyTuple_New(5);
{
PyObject* ob = PyInt_FromLong(raycastInfo.m_rayHits[i].m_hitObjectUniqueId);
PyTuple_SetItem(singleHitObj, 0, ob);
}
{
PyObject* ob = PyInt_FromLong(raycastInfo.m_rayHits[i].m_hitObjectLinkIndex);
PyTuple_SetItem(singleHitObj, 1, ob);
}
{
PyObject* ob = PyFloat_FromDouble(raycastInfo.m_rayHits[i].m_hitFraction);
PyTuple_SetItem(singleHitObj, 2, ob);
}
{
PyObject* posObj = PyTuple_New(3);
int p;
for (p = 0; p < 3; p++)
{
PyObject* ob = PyFloat_FromDouble(raycastInfo.m_rayHits[i].m_hitPositionWorld[p]);
PyTuple_SetItem(posObj, p, ob);
}
PyTuple_SetItem(singleHitObj, 3, posObj);
}
{
PyObject* normalObj = PyTuple_New(3);
int p;
for (p = 0; p < 3; p++)
{
PyObject* ob = PyFloat_FromDouble(raycastInfo.m_rayHits[i].m_hitNormalWorld[p]);
PyTuple_SetItem(normalObj, p, ob);
}
PyTuple_SetItem(singleHitObj, 4, normalObj);
}
PyTuple_SetItem(rayHitsObj, i, singleHitObj);
}
return rayHitsObj;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* pybullet_getMatrixFromQuaternion(PyObject* self, PyObject* args) static PyObject* pybullet_getMatrixFromQuaternion(PyObject* self, PyObject* args)
{ {
PyObject* quatObj; PyObject* quatObj;
@ -3018,10 +3183,11 @@ static PyObject* pybullet_getVREvents(PyObject* self, PyObject* args, PyObject*
b3SharedMemoryCommandHandle commandHandle; b3SharedMemoryCommandHandle commandHandle;
b3SharedMemoryStatusHandle statusHandle; b3SharedMemoryStatusHandle statusHandle;
int statusType; int statusType;
int deviceTypeFilter = VR_DEVICE_CONTROLLER;
int physicsClientId = 0; int physicsClientId = 0;
b3PhysicsClientHandle sm = 0; b3PhysicsClientHandle sm = 0;
static char* kwlist[] = {"physicsClientId", NULL}; static char* kwlist[] = {"deviceTypeFilter", "physicsClientId", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "|i", kwlist, &physicsClientId)) if (!PyArg_ParseTupleAndKeywords(args, keywds, "|ii", kwlist, &deviceTypeFilter, &physicsClientId))
{ {
return NULL; return NULL;
} }
@ -3034,6 +3200,9 @@ static PyObject* pybullet_getVREvents(PyObject* self, PyObject* args, PyObject*
} }
commandHandle = b3RequestVREventsCommandInit(sm); commandHandle = b3RequestVREventsCommandInit(sm);
b3VREventsSetDeviceTypeFilter(commandHandle, deviceTypeFilter);
statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle); statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);
statusType = b3GetStatusType(statusHandle); statusType = b3GetStatusType(statusHandle);
if (statusType == CMD_REQUEST_VR_EVENTS_DATA_COMPLETED) if (statusType == CMD_REQUEST_VR_EVENTS_DATA_COMPLETED)
@ -3046,7 +3215,7 @@ static PyObject* pybullet_getVREvents(PyObject* self, PyObject* args, PyObject*
vrEventsObj = PyTuple_New(vrEvents.m_numControllerEvents); vrEventsObj = PyTuple_New(vrEvents.m_numControllerEvents);
for (i = 0; i < vrEvents.m_numControllerEvents; i++) for (i = 0; i < vrEvents.m_numControllerEvents; i++)
{ {
PyObject* vrEventObj = PyTuple_New(7); PyObject* vrEventObj = PyTuple_New(8);
PyTuple_SetItem(vrEventObj, 0, PyInt_FromLong(vrEvents.m_controllerEvents[i].m_controllerId)); PyTuple_SetItem(vrEventObj, 0, PyInt_FromLong(vrEvents.m_controllerEvents[i].m_controllerId));
{ {
@ -3078,6 +3247,7 @@ static PyObject* pybullet_getVREvents(PyObject* self, PyObject* args, PyObject*
} }
PyTuple_SetItem(vrEventObj, 6, buttonsObj); PyTuple_SetItem(vrEventObj, 6, buttonsObj);
} }
PyTuple_SetItem(vrEventObj, 7, PyInt_FromLong(vrEvents.m_controllerEvents[i].m_deviceType));
PyTuple_SetItem(vrEventsObj, i, vrEventObj); PyTuple_SetItem(vrEventsObj, i, vrEventObj);
} }
return vrEventsObj; return vrEventsObj;
@ -3087,6 +3257,84 @@ static PyObject* pybullet_getVREvents(PyObject* self, PyObject* args, PyObject*
return Py_None; return Py_None;
} }
static PyObject* pybullet_getDebugVisualizerCamera(PyObject* self, PyObject* args, PyObject* keywds)
{
int physicsClientId = 0;
b3PhysicsClientHandle sm = 0;
static char* kwlist[] = {"physicsClientId", NULL};
b3SharedMemoryCommandHandle commandHandle;
int hasCamInfo;
b3SharedMemoryStatusHandle statusHandle;
struct b3OpenGLVisualizerCameraInfo camera;
PyObject* pyCameraList =0;
sm = getPhysicsClient(physicsClientId);
if (sm == 0)
{
PyErr_SetString(SpamError, "Not connected to physics server.");
return NULL;
}
commandHandle = b3InitRequestOpenGLVisualizerCameraCommand(sm);
statusHandle = b3SubmitClientCommandAndWaitStatus(sm, commandHandle);
hasCamInfo = b3GetStatusOpenGLVisualizerCamera(statusHandle, &camera);
if (hasCamInfo)
{
PyObject* item=0;
pyCameraList = PyTuple_New(8);
item = PyInt_FromLong(camera.m_width);
PyTuple_SetItem(pyCameraList,0,item);
item = PyInt_FromLong(camera.m_height);
PyTuple_SetItem(pyCameraList,1,item);
{
PyObject* viewMat16 = PyTuple_New(16);
PyObject* projMat16 = PyTuple_New(16);
int i;
for (i=0;i<16;i++)
{
item = PyFloat_FromDouble(camera.m_viewMatrix[i]);
PyTuple_SetItem(viewMat16,i,item);
item = PyFloat_FromDouble(camera.m_projectionMatrix[i]);
PyTuple_SetItem(projMat16,i,item);
}
PyTuple_SetItem(pyCameraList,2,viewMat16);
PyTuple_SetItem(pyCameraList,3,projMat16);
}
{
PyObject* item=0;
int i;
PyObject* camUp = PyTuple_New(3);
PyObject* camFwd = PyTuple_New(3);
PyObject* hor = PyTuple_New(3);
PyObject* vert= PyTuple_New(3);
for (i=0;i<3;i++)
{
item = PyFloat_FromDouble(camera.m_camUp[i]);
PyTuple_SetItem(camUp,i,item);
item = PyFloat_FromDouble(camera.m_camForward[i]);
PyTuple_SetItem(camFwd,i,item);
item = PyFloat_FromDouble(camera.m_horizontal[i]);
PyTuple_SetItem(hor,i,item);
item = PyFloat_FromDouble(camera.m_vertical[i]);
PyTuple_SetItem(vert,i,item);
}
PyTuple_SetItem(pyCameraList,4,camUp);
PyTuple_SetItem(pyCameraList,5,camFwd);
PyTuple_SetItem(pyCameraList,6,hor);
PyTuple_SetItem(pyCameraList,7,vert);
}
return pyCameraList;
}
PyErr_SetString(SpamError, "Cannot get OpenGL visualizer camera info.");
return NULL;
}
static PyObject* pybullet_configureDebugVisualizer(PyObject* self, PyObject* args, PyObject* keywds) static PyObject* pybullet_configureDebugVisualizer(PyObject* self, PyObject* args, PyObject* keywds)
{ {
int flag = 1; int flag = 1;
@ -5268,6 +5516,9 @@ static PyMethodDef SpamMethods[] = {
"Override the wireframe debug drawing color for a particular object unique id / link index." "Override the wireframe debug drawing color for a particular object unique id / link index."
"If you ommit the color, the custom color will be removed."}, "If you ommit the color, the custom color will be removed."},
{"getDebugVisualizerCamera", (PyCFunction)pybullet_getDebugVisualizerCamera, METH_VARARGS | METH_KEYWORDS,
"Get information about the 3D visualizer camera, such as width, height, view matrix, projection matrix etc."},
{"configureDebugVisualizer", (PyCFunction)pybullet_configureDebugVisualizer, METH_VARARGS | METH_KEYWORDS, {"configureDebugVisualizer", (PyCFunction)pybullet_configureDebugVisualizer, METH_VARARGS | METH_KEYWORDS,
"For the 3D OpenGL Visualizer, enable/disable GUI, shadows."}, "For the 3D OpenGL Visualizer, enable/disable GUI, shadows."},
@ -5319,9 +5570,14 @@ static PyMethodDef SpamMethods[] = {
"fileName, optional objectUniqueId, maxLogDof, bodyUniqueIdA, bodyUniqueIdB, linkIndexA, linkIndexB. Function returns int loggingUniqueId"}, "fileName, optional objectUniqueId, maxLogDof, bodyUniqueIdA, bodyUniqueIdB, linkIndexA, linkIndexB. Function returns int loggingUniqueId"},
{"stopStateLogging", (PyCFunction)pybullet_stopStateLogging, METH_VARARGS | METH_KEYWORDS, {"stopStateLogging", (PyCFunction)pybullet_stopStateLogging, METH_VARARGS | METH_KEYWORDS,
"Stop logging of robot state, given a loggingUniqueId."}, "Stop logging of robot state, given a loggingUniqueId."},
{"rayTest", (PyCFunction)pybullet_rayTest, METH_VARARGS | METH_KEYWORDS, {"rayTest", (PyCFunction)pybullet_rayTestObsolete, METH_VARARGS | METH_KEYWORDS,
"Cast a ray and return the first object hit, if any. " "Cast a ray and return the first object hit, if any. "
"Takes two arguments (from position [x,y,z] and to position [x,y,z] in Cartesian world coordinates"}, "Takes two arguments (from_position [x,y,z] and to_position [x,y,z] in Cartesian world coordinates"},
{"rayTestBatch", (PyCFunction)pybullet_rayTestBatch, METH_VARARGS | METH_KEYWORDS,
"Cast a batch of rays and return the result for each of the rays (first object hit, if any. or -1) "
"Takes two arguments (list of from_positions [x,y,z] and a list of to_positions [x,y,z] in Cartesian world coordinates"},
{"setTimeOut", (PyCFunction)pybullet_setTimeOut, METH_VARARGS | METH_KEYWORDS, {"setTimeOut", (PyCFunction)pybullet_setTimeOut, METH_VARARGS | METH_KEYWORDS,
"Set the timeOut in seconds, used for most of the API calls."}, "Set the timeOut in seconds, used for most of the API calls."},
// todo(erwincoumans) // todo(erwincoumans)
@ -5439,6 +5695,10 @@ initpybullet(void)
PyModule_AddIntConstant(m, "VR_MAX_CONTROLLERS", MAX_VR_CONTROLLERS); PyModule_AddIntConstant(m, "VR_MAX_CONTROLLERS", MAX_VR_CONTROLLERS);
PyModule_AddIntConstant(m, "VR_MAX_BUTTONS", MAX_VR_BUTTONS); PyModule_AddIntConstant(m, "VR_MAX_BUTTONS", MAX_VR_BUTTONS);
PyModule_AddIntConstant(m, "VR_DEVICE_CONTROLLER", VR_DEVICE_CONTROLLER);
PyModule_AddIntConstant(m, "VR_DEVICE_HMD", VR_DEVICE_HMD);
PyModule_AddIntConstant(m, "VR_DEVICE_GENERIC_TRACKER", VR_DEVICE_GENERIC_TRACKER);
PyModule_AddIntConstant(m, "KEY_IS_DOWN", eButtonIsDown); PyModule_AddIntConstant(m, "KEY_IS_DOWN", eButtonIsDown);
PyModule_AddIntConstant(m, "KEY_WAS_TRIGGERED", eButtonTriggered); PyModule_AddIntConstant(m, "KEY_WAS_TRIGGERED", eButtonTriggered);
PyModule_AddIntConstant(m, "KEY_WAS_RELEASED", eButtonReleased); PyModule_AddIntConstant(m, "KEY_WAS_RELEASED", eButtonReleased);
@ -5459,6 +5719,8 @@ initpybullet(void)
PyModule_AddIntConstant(m, "URDF_USE_INERTIA_FROM_FILE", URDF_USE_INERTIA_FROM_FILE); PyModule_AddIntConstant(m, "URDF_USE_INERTIA_FROM_FILE", URDF_USE_INERTIA_FROM_FILE);
PyModule_AddIntConstant(m, "URDF_USE_SELF_COLLISION", URDF_USE_SELF_COLLISION); PyModule_AddIntConstant(m, "URDF_USE_SELF_COLLISION", URDF_USE_SELF_COLLISION);
PyModule_AddIntConstant(m, "MAX_RAY_INTERSECTION_BATCH_SIZE", MAX_RAY_INTERSECTION_BATCH_SIZE);
PyModule_AddIntConstant(m, "B3G_F1", B3G_F1); PyModule_AddIntConstant(m, "B3G_F1", B3G_F1);
PyModule_AddIntConstant(m, "B3G_F2", B3G_F2); PyModule_AddIntConstant(m, "B3G_F2", B3G_F2);
PyModule_AddIntConstant(m, "B3G_F3", B3G_F3); PyModule_AddIntConstant(m, "B3G_F3", B3G_F3);

View File

@ -21,10 +21,26 @@ CXX_FLAGS += '-DGWEN_COMPILE_STATIC '
CXX_FLAGS += '-DBT_USE_DOUBLE_PRECISION ' CXX_FLAGS += '-DBT_USE_DOUBLE_PRECISION '
CXX_FLAGS += '-DBT_ENABLE_ENET ' CXX_FLAGS += '-DBT_ENABLE_ENET '
CXX_FLAGS += '-DBT_ENABLE_CLSOCKET ' CXX_FLAGS += '-DBT_ENABLE_CLSOCKET '
CXX_FLAGS += '-DB3_DUMP_PYTHON_VERSION '
# libraries += [current_python] # libraries += [current_python]
libraries = [] libraries = []
include_dirs = []
try:
import numpy
NP_DIRS = [numpy.get_include()]
except:
print("numpy is disabled. getCameraImage maybe slower.")
else:
print("numpy is enabled.")
CXX_FLAGS += '-DPYBULLET_USE_NUMPY '
for d in NP_DIRS:
print("numpy_include_dirs = %s" % d)
include_dirs += NP_DIRS
sources = ["examples/pybullet/pybullet.c"]\ sources = ["examples/pybullet/pybullet.c"]\
+["examples/ExampleBrowser/InProcessExampleBrowser.cpp"]\ +["examples/ExampleBrowser/InProcessExampleBrowser.cpp"]\
@ -365,20 +381,18 @@ if _platform == "linux" or _platform == "linux2":
CXX_FLAGS += '-DDYNAMIC_LOAD_X11_FUNCTIONS ' CXX_FLAGS += '-DDYNAMIC_LOAD_X11_FUNCTIONS '
CXX_FLAGS += '-DHAS_SOCKLEN_T ' CXX_FLAGS += '-DHAS_SOCKLEN_T '
CXX_FLAGS += '-fno-inline-functions-called-once' CXX_FLAGS += '-fno-inline-functions-called-once'
sources = ["examples/ThirdPartyLibs/enet/unix.c"]\ sources = sources + ["examples/ThirdPartyLibs/enet/unix.c"]\
+["examples/OpenGLWindow/X11OpenGLWindow.cpp"]\ +["examples/OpenGLWindow/X11OpenGLWindow.cpp"]\
+["examples/ThirdPartyLibs/Glew/glew.c"]\ +["examples/ThirdPartyLibs/Glew/glew.c"]
+ sources
elif _platform == "win32": elif _platform == "win32":
print("win32!") print("win32!")
libraries = ['Ws2_32','Winmm','User32','Opengl32','kernel32','glu32','Gdi32','Comdlg32'] libraries = ['Ws2_32','Winmm','User32','Opengl32','kernel32','glu32','Gdi32','Comdlg32']
CXX_FLAGS += '-DWIN32 ' CXX_FLAGS += '-DWIN32 '
CXX_FLAGS += '-DGLEW_STATIC ' CXX_FLAGS += '-DGLEW_STATIC '
sources = ["examples/ThirdPartyLibs/enet/win32.c"]\ sources = sources + ["examples/ThirdPartyLibs/enet/win32.c"]\
+["examples/OpenGLWindow/Win32Window.cpp"]\ +["examples/OpenGLWindow/Win32Window.cpp"]\
+["examples/OpenGLWindow/Win32OpenGLWindow.cpp"]\ +["examples/OpenGLWindow/Win32OpenGLWindow.cpp"]\
+["examples/ThirdPartyLibs/Glew/glew.c"]\ +["examples/ThirdPartyLibs/Glew/glew.c"]
+sources
elif _platform == "darwin": elif _platform == "darwin":
print("darwin!") print("darwin!")
os.environ['LDFLAGS'] = '-framework Cocoa -framework OpenGL' os.environ['LDFLAGS'] = '-framework Cocoa -framework OpenGL'
@ -388,10 +402,22 @@ elif _platform == "darwin":
sources = sources + ["examples/ThirdPartyLibs/enet/unix.c"]\ sources = sources + ["examples/ThirdPartyLibs/enet/unix.c"]\
+["examples/OpenGLWindow/MacOpenGLWindow.cpp"]\ +["examples/OpenGLWindow/MacOpenGLWindow.cpp"]\
+["examples/OpenGLWindow/MacOpenGLWindowObjC.m"] +["examples/OpenGLWindow/MacOpenGLWindowObjC.m"]
else:
print("bsd!")
os.environ['LDFLAGS'] = '-L/usr/X11R6/lib'
CXX_FLAGS += '-D_BSD '
CXX_FLAGS += '-I/usr/X11R6/include '
CXX_FLAGS += '-DHAS_SOCKLEN_T '
CXX_FLAGS += '-fno-inline-functions-called-once'
sources = ["examples/ThirdPartyLibs/enet/unix.c"]\
+["examples/OpenGLWindow/X11OpenGLWindow.cpp"]\
+["examples/ThirdPartyLibs/Glew/glew.c"]\
+ sources
setup( setup(
name = 'pybullet', name = 'pybullet',
version='0.1.6', version='1.0.1',
description='Official Python Interface for the Bullet Physics SDK Robotics Simulator', description='Official Python Interface for the Bullet Physics SDK Robotics Simulator',
long_description='pybullet is an easy to use Python module for physics simulation, robotics and machine learning based on the Bullet Physics SDK. With pybullet you can load articulated bodies from URDF, SDF and other file formats. pybullet provides forward dynamics simulation, inverse dynamics computation, forward and inverse kinematics and collision detection and ray intersection queries. Aside from physics simulation, pybullet supports to rendering, with a CPU renderer and OpenGL visualization and support for virtual reality headsets.', long_description='pybullet is an easy to use Python module for physics simulation, robotics and machine learning based on the Bullet Physics SDK. With pybullet you can load articulated bodies from URDF, SDF and other file formats. pybullet provides forward dynamics simulation, inverse dynamics computation, forward and inverse kinematics and collision detection and ray intersection queries. Aside from physics simulation, pybullet supports to rendering, with a CPU renderer and OpenGL visualization and support for virtual reality headsets.',
url='https://github.com/bulletphysics/bullet3', url='https://github.com/bulletphysics/bullet3',
@ -404,9 +430,9 @@ setup(
sources = sources, sources = sources,
libraries = libraries, libraries = libraries,
extra_compile_args=CXX_FLAGS.split(), extra_compile_args=CXX_FLAGS.split(),
include_dirs = ["src","examples/ThirdPartyLibs","examples/ThirdPartyLibs/Glew", "examples/ThirdPartyLibs/enet/include","examples/ThirdPartyLibs/clsocket/src"] include_dirs = include_dirs + ["src","examples/ThirdPartyLibs","examples/ThirdPartyLibs/Glew", "examples/ThirdPartyLibs/enet/include","examples/ThirdPartyLibs/clsocket/src"]
) ], ) ],
classifiers=['Development Status :: 4 - Beta', classifiers=['Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: zlib/libpng License', 'License :: OSI Approved :: zlib/libpng License',
'Operating System :: Microsoft :: Windows', 'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Linux',
@ -415,6 +441,8 @@ setup(
"Programming Language :: Python", "Programming Language :: Python",
'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Games/Entertainment :: Simulation', 'Topic :: Games/Entertainment :: Simulation',
'Framework :: Robot Framework'], 'Framework :: Robot Framework'],
package_data = { package_data = {

View File

@ -55,6 +55,23 @@ btScalar btMinkowskiSumShape::getMargin() const
void btMinkowskiSumShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const void btMinkowskiSumShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{ {
(void)mass; (void)mass;
btAssert(0); //inertia of the AABB of the Minkowski sum
inertia.setValue(0,0,0); btTransform identity;
identity.setIdentity();
btVector3 aabbMin,aabbMax;
getAabb(identity,aabbMin,aabbMax);
btVector3 halfExtents = (aabbMax-aabbMin)*btScalar(0.5);
btScalar margin = getMargin();
btScalar lx=btScalar(2.)*(halfExtents.x()+margin);
btScalar ly=btScalar(2.)*(halfExtents.y()+margin);
btScalar lz=btScalar(2.)*(halfExtents.z()+margin);
const btScalar x2 = lx*lx;
const btScalar y2 = ly*ly;
const btScalar z2 = lz*lz;
const btScalar scaledmass = mass * btScalar(0.08333333);
inertia = scaledmass * (btVector3(y2+z2,x2+z2,x2+y2));
} }