source: proiecte/SIMEO/Simeo/src/SimeoGui/DemoApplication.cpp @ 167

Last change on this file since 167 was 167, checked in by (none), 14 years ago

Simeo: added final project and also older proof of concept code.

We used Git for version control, so look at the Git repo
in SIMEO/Simeo/ for more info.

File size: 38.8 KB
Line 
1/*
2Bullet Continuous Collision Detection and Physics Library
3Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
4
5This software is provided 'as-is', without any express or implied warranty.
6In no event will the authors be held liable for any damages arising from the use of this software.
7Permission is granted to anyone to use this software for any purpose,
8including commercial applications, and to alter it and redistribute it freely,
9subject to the following restrictions:
10
111. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
122. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
133. This notice may not be removed or altered from any source distribution.
14*/
15
16
17#include "DemoApplication.h"
18#include "LinearMath/btIDebugDraw.h"
19#include "BulletDynamics/Dynamics/btDynamicsWorld.h"
20
21#include "BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h"//picking
22#include "BulletCollision/CollisionShapes/btCollisionShape.h"
23#include "BulletCollision/CollisionShapes/btBoxShape.h"
24#include "BulletCollision/CollisionShapes/btSphereShape.h"
25#include "BulletCollision/CollisionShapes/btCompoundShape.h"
26#include "BulletCollision/CollisionShapes/btUniformScalingShape.h"
27#include "BulletDynamics/ConstraintSolver/btConstraintSolver.h"
28#include "GL_ShapeDrawer.h"
29#include "LinearMath/btQuickprof.h"
30#include "LinearMath/btDefaultMotionState.h"
31
32#include "GLDebugFont.h"
33
34
35extern bool gDisableDeactivation;
36int numObjects = 0;
37const int maxNumObjects = 16384;
38btTransform startTransforms[maxNumObjects];
39btCollisionShape* gShapePtr[maxNumObjects];//1 rigidbody has 1 shape (no re-use of shapes)
40#define SHOW_NUM_DEEP_PENETRATIONS 1
41
42extern int gNumClampedCcdMotions;
43
44#ifdef SHOW_NUM_DEEP_PENETRATIONS
45extern int gNumDeepPenetrationChecks;
46
47extern int gNumSplitImpulseRecoveries;
48extern int gNumGjkChecks;
49extern int gNumAlignedAllocs;
50extern int gNumAlignedFree;
51extern int gTotalBytesAlignedAllocs;
52
53#endif //
54
55
56DemoApplication::DemoApplication()
57//see btIDebugDraw.h for modes
58:
59//m_dynamicsWorld(0),
60m_pickConstraint(0),
61m_shootBoxShape(0),
62m_cameraDistance(15.0),
63m_debugMode(0),
64m_ele(20.f),
65m_azi(0.f),
66m_cameraPosition(0.f,0.f,0.f),
67m_cameraTargetPosition(0.f,0.f,0.f),
68m_scaleBottom(0.5f),
69m_scaleFactor(2.f),
70m_cameraUp(0,1,0),
71m_forwardAxis(2),
72m_glutScreenWidth(0),
73m_glutScreenHeight(0),
74m_ShootBoxInitialSpeed(40.f),
75m_stepping(true),
76m_singleStep(false),
77m_idle(false),
78m_enableshadows(false),
79m_sundirection(btVector3(1,-2,1)*1000),
80m_ortho(0),
81m_mouseOldX(0),
82m_mouseOldY(0),
83m_mouseButtons(0),
84m_modifierKeys(0),
85m_textureinitialized(false),
86m_textureenabled(true)
87{
88#ifndef BT_NO_PROFILE
89        m_profileIterator = CProfileManager::Get_Iterator();
90#endif //BT_NO_PROFILE
91
92        m_shapeDrawer = new GL_ShapeDrawer ();
93        m_shapeDrawer->enableTexture(true);
94        m_enableshadows = false;
95
96        m_ele = 75;
97        updateCamera();
98        setCameraDistance(btScalar(20));
99}
100
101
102
103DemoApplication::~DemoApplication()
104{
105#ifndef BT_NO_PROFILE
106        CProfileManager::Release_Iterator(m_profileIterator);
107#endif //BT_NO_PROFILE
108
109        if (m_shootBoxShape)
110                delete m_shootBoxShape;
111
112        if (m_shapeDrawer)
113                delete m_shapeDrawer;
114}
115
116
117void DemoApplication::overrideGLShapeDrawer (GL_ShapeDrawer* shapeDrawer)
118{
119        shapeDrawer->enableTexture (m_shapeDrawer->hasTextureEnabled());
120        delete m_shapeDrawer;
121        m_shapeDrawer = shapeDrawer;
122}
123
124void DemoApplication::myinit(void)
125{
126
127        GLfloat light_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
128        GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
129        GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
130        /*      light_position is NOT default value     */
131        GLfloat light_position0[] = { 1.0, 10.0, 1.0, 0.0 };
132        GLfloat light_position1[] = { -1.0, -10.0, -1.0, 0.0 };
133
134        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
135        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
136        glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
137        glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
138
139        glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
140        glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
141        glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
142        glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
143
144        glEnable(GL_LIGHTING);
145        glEnable(GL_LIGHT0);
146        glEnable(GL_LIGHT1);
147
148
149        glShadeModel(GL_SMOOTH);
150        glEnable(GL_DEPTH_TEST);
151        glDepthFunc(GL_LESS);
152
153        glClearColor(0.7,0.7,0.7,0);
154
155        //  glEnable(GL_CULL_FACE);
156        //  glCullFace(GL_BACK);
157}
158
159
160void    DemoApplication::setCameraDistance(float dist)
161{
162        m_cameraDistance  = dist;
163}
164
165float   DemoApplication::getCameraDistance()
166{
167        return m_cameraDistance;
168}
169
170
171
172void DemoApplication::toggleIdle() {
173        if (m_idle) {
174                m_idle = false;
175        }
176        else {
177                m_idle = true;
178        }
179}
180
181
182
183
184void DemoApplication::updateCamera() {
185
186
187        glMatrixMode(GL_PROJECTION);
188        glLoadIdentity();
189        float rele = m_ele * 0.01745329251994329547;// rads per deg
190        float razi = m_azi * 0.01745329251994329547;// rads per deg
191
192
193        btQuaternion rot(m_cameraUp,razi);
194
195
196        btVector3 eyePos(0,0,0);
197        eyePos[m_forwardAxis] = -m_cameraDistance;
198
199        btVector3 forward(eyePos[0],eyePos[1],eyePos[2]);
200        if (forward.length2() < SIMD_EPSILON)
201        {
202                forward.setValue(1.f,0.f,0.f);
203        }
204        btVector3 right = m_cameraUp.cross(forward);
205        btQuaternion roll(right,-rele);
206
207        eyePos = btMatrix3x3(rot) * btMatrix3x3(roll) * eyePos;
208
209        m_cameraPosition[0] = eyePos.getX();
210        m_cameraPosition[1] = eyePos.getY();
211        m_cameraPosition[2] = eyePos.getZ();
212        m_cameraPosition += m_cameraTargetPosition;
213
214        if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0)
215                return;
216
217        btScalar aspect;
218        btVector3 extents;
219
220        if (m_glutScreenWidth > m_glutScreenHeight)
221        {
222                aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight;
223                extents.setValue(aspect * 1.0f, 1.0f,0);
224        } else
225        {
226                aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth;
227                extents.setValue(1.0f, aspect*1.f,0);
228        }
229
230
231        if (m_ortho)
232        {
233                // reset matrix
234                glLoadIdentity();
235
236
237                extents *= m_cameraDistance;
238                btVector3 lower = m_cameraTargetPosition - extents;
239                btVector3 upper = m_cameraTargetPosition + extents;
240                //gluOrtho2D(lower.x, upper.x, lower.y, upper.y);
241                glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000);
242
243                glMatrixMode(GL_MODELVIEW);
244                glLoadIdentity();
245                //glTranslatef(100,210,0);
246        } else
247        {
248                if (m_glutScreenWidth > m_glutScreenHeight)
249                {
250                        glFrustum (-aspect, aspect, -1.0, 1.0, 1.0, 10000.0);
251                } else
252                {
253                        glFrustum (-1.0, 1.0, -aspect, aspect, 1.0, 10000.0);
254                }
255                glMatrixMode(GL_MODELVIEW);
256                glLoadIdentity();
257                gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2],
258                        m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2],
259                        m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
260        }
261
262}
263
264
265
266const float STEPSIZE = 5;
267
268void DemoApplication::stepLeft()
269{
270        m_azi -= STEPSIZE; if (m_azi < 0) m_azi += 360; updateCamera();
271}
272void DemoApplication::stepRight()
273{
274        m_azi += STEPSIZE; if (m_azi >= 360) m_azi -= 360; updateCamera();
275}
276void DemoApplication::stepFront()
277{
278        m_ele += STEPSIZE; if (m_ele >= 360) m_ele -= 360; updateCamera();
279}
280void DemoApplication::stepBack()
281{
282        m_ele -= STEPSIZE; if (m_ele < 0) m_ele += 360; updateCamera();
283}
284void DemoApplication::zoomIn()
285{
286        m_cameraDistance -= 0.4; updateCamera();
287        if (m_cameraDistance < 0.1)
288                m_cameraDistance = 0.1;
289
290}
291void DemoApplication::zoomOut()
292{
293        m_cameraDistance += 0.4; updateCamera();
294
295}
296
297void DemoApplication::reshape(int w, int h)
298{
299        GLDebugResetFont(w,h);
300
301        m_glutScreenWidth = w;
302        m_glutScreenHeight = h;
303
304        glViewport(0, 0, w, h);
305        updateCamera();
306}
307
308void DemoApplication::keyboardCallback(unsigned char key, int x, int y)
309{
310        (void)x;
311        (void)y;
312
313        m_lastKey = 0;
314
315#ifndef BT_NO_PROFILE
316        if (key >= 0x31 && key <= 0x39)
317        {
318                int child = key-0x31;
319                m_profileIterator->Enter_Child(child);
320        }
321        if (key==0x30)
322        {
323                m_profileIterator->Enter_Parent();
324        }
325#endif //BT_NO_PROFILE
326
327        switch (key)
328        {
329        case 'q' :
330#ifdef BT_USE_FREEGLUT
331                //return from glutMainLoop(), detect memory leaks etc.
332                glutLeaveMainLoop();
333#else
334                exit(0);
335#endif
336                break;
337
338        case 'l' : stepLeft(); break;
339        case 'r' : stepRight(); break;
340        case 'f' : stepFront(); break;
341        case 'b' : stepBack(); break;
342        case 'z' : zoomIn(); break;
343        case 'x' : zoomOut(); break;
344        case 'i' : toggleIdle(); break;
345        case 'g' : m_enableshadows=!m_enableshadows;break;
346        case 'u' : m_shapeDrawer->enableTexture(!m_shapeDrawer->enableTexture(false));break;
347        case 'h':
348                if (m_debugMode & btIDebugDraw::DBG_NoHelpText)
349                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_NoHelpText);
350                else
351                        m_debugMode |= btIDebugDraw::DBG_NoHelpText;
352                break;
353
354        case 'w':
355                if (m_debugMode & btIDebugDraw::DBG_DrawWireframe)
356                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawWireframe);
357                else
358                        m_debugMode |= btIDebugDraw::DBG_DrawWireframe;
359                break;
360
361        case 'p':
362                if (m_debugMode & btIDebugDraw::DBG_ProfileTimings)
363                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_ProfileTimings);
364                else
365                        m_debugMode |= btIDebugDraw::DBG_ProfileTimings;
366                break;
367
368        case 'm':
369                if (m_debugMode & btIDebugDraw::DBG_EnableSatComparison)
370                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_EnableSatComparison);
371                else
372                        m_debugMode |= btIDebugDraw::DBG_EnableSatComparison;
373                break;
374
375        case 'n':
376                if (m_debugMode & btIDebugDraw::DBG_DisableBulletLCP)
377                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DisableBulletLCP);
378                else
379                        m_debugMode |= btIDebugDraw::DBG_DisableBulletLCP;
380                break;
381
382        case 't' :
383                if (m_debugMode & btIDebugDraw::DBG_DrawText)
384                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawText);
385                else
386                        m_debugMode |= btIDebugDraw::DBG_DrawText;
387                break;
388        case 'y':
389                if (m_debugMode & btIDebugDraw::DBG_DrawFeaturesText)
390                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawFeaturesText);
391                else
392                        m_debugMode |= btIDebugDraw::DBG_DrawFeaturesText;
393                break;
394        case 'a':
395                if (m_debugMode & btIDebugDraw::DBG_DrawAabb)
396                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawAabb);
397                else
398                        m_debugMode |= btIDebugDraw::DBG_DrawAabb;
399                break;
400        case 'c' :
401                if (m_debugMode & btIDebugDraw::DBG_DrawContactPoints)
402                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawContactPoints);
403                else
404                        m_debugMode |= btIDebugDraw::DBG_DrawContactPoints;
405                break;
406        case 'C' :
407                if (m_debugMode & btIDebugDraw::DBG_DrawConstraints)
408                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawConstraints);
409                else
410                        m_debugMode |= btIDebugDraw::DBG_DrawConstraints;
411                break;
412        case 'L' :
413                if (m_debugMode & btIDebugDraw::DBG_DrawConstraintLimits)
414                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_DrawConstraintLimits);
415                else
416                        m_debugMode |= btIDebugDraw::DBG_DrawConstraintLimits;
417                break;
418
419        case 'd' :
420                if (m_debugMode & btIDebugDraw::DBG_NoDeactivation)
421                        m_debugMode = m_debugMode & (~btIDebugDraw::DBG_NoDeactivation);
422                else
423                        m_debugMode |= btIDebugDraw::DBG_NoDeactivation;
424                if (m_debugMode & btIDebugDraw::DBG_NoDeactivation)
425                {
426                        gDisableDeactivation = true;
427                } else
428                {
429                        gDisableDeactivation = false;
430                }
431                break;
432
433
434
435
436        case 'o' :
437                {
438                        m_ortho = !m_ortho;//m_stepping = !m_stepping;
439                        break;
440                }
441        case 's' : clientMoveAndDisplay(); break;
442                //    case ' ' : newRandom(); break;
443        case ' ':
444                clientResetScene();
445                break;
446        case '1':
447                {
448                        if (m_debugMode & btIDebugDraw::DBG_EnableCCD)
449                                m_debugMode = m_debugMode & (~btIDebugDraw::DBG_EnableCCD);
450                        else
451                                m_debugMode |= btIDebugDraw::DBG_EnableCCD;
452                        break;
453                }
454
455        case '.':
456                {
457                        shootBox(getRayTo(x,y));//getCameraTargetPosition());
458                        break;
459                }
460
461        case '+':
462                {
463                        m_ShootBoxInitialSpeed += 10.f;
464                        break;
465                }
466        case '-':
467                {
468                        m_ShootBoxInitialSpeed -= 10.f;
469                        break;
470                }
471
472        default:
473                //        std::cout << "unused key : " << key << std::endl;
474                break;
475        }
476
477//      if (getDynamicsWorld() && getDynamicsWorld()->getDebugDrawer())
478//              getDynamicsWorld()->getDebugDrawer()->setDebugMode(m_debugMode);
479
480
481
482}
483
484void    DemoApplication::setDebugMode(int mode)
485{
486        m_debugMode = mode;
487//      if (getDynamicsWorld() && getDynamicsWorld()->getDebugDrawer())
488//              getDynamicsWorld()->getDebugDrawer()->setDebugMode(mode);
489}
490
491
492
493void DemoApplication::clientMoveAndDisplay()
494{
495                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
496
497                renderme();
498
499                glFlush();
500                glutSwapBuffers();
501}
502
503
504void DemoApplication::moveAndDisplay()
505{
506        if (!m_idle)
507                clientMoveAndDisplay();
508        else
509                displayCallback();
510}
511
512
513
514
515void DemoApplication::displayCallback()
516{
517}
518
519#define NUM_SPHERES_ON_DIAGONAL 9
520
521void    DemoApplication::setShootBoxShape ()
522{
523        if (!m_shootBoxShape)
524        {
525                m_shootBoxShape = new btBoxShape(btVector3(.5f,.5f,.5f));
526        }
527}
528
529void    DemoApplication::shootBox(const btVector3& destination)
530{
531        /*
532        if (m_dynamicsWorld)
533        {
534                float mass = 1.f;
535                btTransform startTransform;
536                startTransform.setIdentity();
537                btVector3 camPos = getCameraPosition();
538                startTransform.setOrigin(camPos);
539
540                setShootBoxShape ();
541
542                btRigidBody* body = this->localCreateRigidBody(mass, startTransform,m_shootBoxShape);
543                body->setLinearFactor(btVector3(1,1,1));
544
545                btVector3 linVel(destination[0]-camPos[0],destination[1]-camPos[1],destination[2]-camPos[2]);
546                linVel.normalize();
547                linVel*=m_ShootBoxInitialSpeed;
548
549                body->getWorldTransform().setOrigin(camPos);
550                body->getWorldTransform().setRotation(btQuaternion(0,0,0,1));
551                body->setLinearVelocity(linVel);
552                body->setAngularVelocity(btVector3(0,0,0));
553                body->setCcdMotionThreshold(1.);
554                body->setCcdSweptSphereRadius(0.2f);
555        }
556        */
557}
558
559
560int gPickingConstraintId = 0;
561btVector3 gOldPickingPos;
562btVector3 gHitPos(-1,-1,-1);
563float gOldPickingDist  = 0.f;
564btRigidBody* pickedBody = 0;//for deactivation state
565
566
567btVector3       DemoApplication::getRayTo(int x,int y)
568{
569
570
571
572        if (m_ortho)
573        {
574
575                btScalar aspect;
576                btVector3 extents;
577                if (m_glutScreenWidth > m_glutScreenHeight)
578                {
579                        aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight;
580                        extents.setValue(aspect * 1.0f, 1.0f,0);
581                } else
582                {
583                        aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth;
584                        extents.setValue(1.0f, aspect*1.f,0);
585                }
586
587                extents *= m_cameraDistance;
588                btVector3 lower = m_cameraTargetPosition - extents;
589                btVector3 upper = m_cameraTargetPosition + extents;
590
591                btScalar u = x / btScalar(m_glutScreenWidth);
592                btScalar v = (m_glutScreenHeight - y) / btScalar(m_glutScreenHeight);
593
594                btVector3       p(0,0,0);
595                p.setValue((1.0f - u) * lower.getX() + u * upper.getX(),(1.0f - v) * lower.getY() + v * upper.getY(),m_cameraTargetPosition.getZ());
596                return p;
597        }
598
599        float top = 1.f;
600        float bottom = -1.f;
601        float nearPlane = 1.f;
602        float tanFov = (top-bottom)*0.5f / nearPlane;
603        float fov = 2.0 * atanf (tanFov);
604
605        btVector3       rayFrom = getCameraPosition();
606        btVector3 rayForward = (getCameraTargetPosition()-getCameraPosition());
607        rayForward.normalize();
608        float farPlane = 10000.f;
609        rayForward*= farPlane;
610
611        btVector3 rightOffset;
612        btVector3 vertical = m_cameraUp;
613
614        btVector3 hor;
615        hor = rayForward.cross(vertical);
616        hor.normalize();
617        vertical = hor.cross(rayForward);
618        vertical.normalize();
619
620        float tanfov = tanf(0.5f*fov);
621
622
623        hor *= 2.f * farPlane * tanfov;
624        vertical *= 2.f * farPlane * tanfov;
625
626        btScalar aspect;
627
628        if (m_glutScreenWidth > m_glutScreenHeight)
629        {
630                aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight;
631
632                hor*=aspect;
633        } else
634        {
635                aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth;
636                vertical*=aspect;
637        }
638
639
640        btVector3 rayToCenter = rayFrom + rayForward;
641        btVector3 dHor = hor * 1.f/float(m_glutScreenWidth);
642        btVector3 dVert = vertical * 1.f/float(m_glutScreenHeight);
643
644
645        btVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical;
646        rayTo += x * dHor;
647        rayTo -= y * dVert;
648        return rayTo;
649}
650
651btScalar mousePickClamping = 30.f;
652
653
654void DemoApplication::mouseFunc(int button, int state, int x, int y)
655{
656        if (state == 0)
657        {
658        m_mouseButtons |= 1<<button;
659    } else
660        {
661        m_mouseButtons = 0;
662    }
663
664        m_mouseOldX = x;
665    m_mouseOldY = y;
666
667        updateModifierKeys();
668        if ((m_modifierKeys& BT_ACTIVE_ALT) && (state==0))
669        {
670                return;
671        }
672
673        //printf("button %i, state %i, x=%i,y=%i\n",button,state,x,y);
674        //button 0, state 0 means left mouse down
675
676        btVector3 rayTo = getRayTo(x,y);
677
678        switch (button)
679        {
680        case 2:
681                {
682                        if (state==0)
683                        {
684
685                                shootBox(rayTo);
686                        }
687                        break;
688                };
689        case 1:
690                {
691
692
693                        if (state==0)
694                        {
695
696#if 0
697                                //apply an impulse
698                                if (m_dynamicsWorld)
699                                {
700                                        btCollisionWorld::ClosestRayResultCallback rayCallback(m_cameraPosition,rayTo);
701                                        m_dynamicsWorld->rayTest(m_cameraPosition,rayTo,rayCallback);
702                                        if (rayCallback.hasHit())
703                                        {
704
705                                                btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject);
706                                                if (body)
707                                                {
708                                                        body->setActivationState(ACTIVE_TAG);
709                                                        btVector3 impulse = rayTo;
710                                                        impulse.normalize();
711                                                        float impulseStrength = 10.f;
712                                                        impulse *= impulseStrength;
713                                                        btVector3 relPos = rayCallback.m_hitPointWorld - body->getCenterOfMassPosition();
714                                                        body->applyImpulse(impulse,relPos);
715                                                }
716                                        }
717                                }
718#endif
719
720
721
722                        } else
723                        {
724
725                        }
726                        break;
727                }
728        case 0:
729                {
730
731#if 0
732                        if (state==0)
733                        {
734                                //add a point to point constraint for picking
735                                if (m_dynamicsWorld)
736                                {
737
738                                        btVector3 rayFrom;
739                                        if (m_ortho)
740                                        {
741                                                rayFrom = rayTo;
742                                                rayFrom.setZ(-100.f);
743                                        } else
744                                        {
745                                                rayFrom = m_cameraPosition;
746                                        }
747
748                                        btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo);
749                                        m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback);
750                                        if (rayCallback.hasHit())
751                                        {
752
753
754                                                btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject);
755                                                if (body)
756                                                {
757                                                        //other exclusions?
758                                                        if (!(body->isStaticObject() || body->isKinematicObject()))
759                                                        {
760                                                                pickedBody = body;
761                                                                pickedBody->setActivationState(DISABLE_DEACTIVATION);
762
763
764                                                                btVector3 pickPos = rayCallback.m_hitPointWorld;
765                                                                printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());
766
767
768                                                                btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;
769
770                                                                btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body,localPivot);
771                                                                p2p->m_setting.m_impulseClamp = mousePickClamping;
772
773                                                                m_dynamicsWorld->addConstraint(p2p);
774                                                                m_pickConstraint = p2p;
775
776                                                                //save mouse position for dragging
777                                                                gOldPickingPos = rayTo;
778                                                                gHitPos = pickPos;
779
780                                                                gOldPickingDist  = (pickPos-rayFrom).length();
781
782                                                                //very weak constraint for picking
783                                                                p2p->m_setting.m_tau = 0.1f;
784                                                        }
785                                                }
786                                        }
787                                }
788
789                        } else
790                        {
791
792                                if (m_pickConstraint && m_dynamicsWorld)
793                                {
794                                        m_dynamicsWorld->removeConstraint(m_pickConstraint);
795                                        delete m_pickConstraint;
796                                        //printf("removed constraint %i",gPickingConstraintId);
797                                        m_pickConstraint = 0;
798                                        pickedBody->forceActivationState(ACTIVE_TAG);
799                                        pickedBody->setDeactivationTime( 0.f );
800                                        pickedBody = 0;
801                                }
802
803
804                        }
805#endif
806
807                        break;
808
809                }
810        default:
811                {
812                }
813        }
814
815}
816
817void    DemoApplication::mouseMotionFunc(int x,int y)
818{
819/*
820        if (m_pickConstraint)
821        {
822                //move the constraint pivot
823                btPoint2PointConstraint* p2p = static_cast<btPoint2PointConstraint*>(m_pickConstraint);
824                if (p2p)
825                {
826                        //keep it at the same picking distance
827
828                        btVector3 newRayTo = getRayTo(x,y);
829                        btVector3 rayFrom;
830                        btVector3 oldPivotInB = p2p->getPivotInB();
831                        btVector3 newPivotB;
832                        if (m_ortho)
833                        {
834                                newPivotB = oldPivotInB;
835                                newPivotB.setX(newRayTo.getX());
836                                newPivotB.setY(newRayTo.getY());
837                        } else
838                        {
839                                rayFrom = m_cameraPosition;
840                                btVector3 dir = newRayTo-rayFrom;
841                                dir.normalize();
842                                dir *= gOldPickingDist;
843
844                                newPivotB = rayFrom + dir;
845                        }
846
847
848
849                        p2p->setPivotB(newPivotB);
850                }
851
852        }
853*/
854
855        float dx, dy;
856    dx = x - m_mouseOldX;
857    dy = y - m_mouseOldY;
858
859
860        ///only if ALT key is pressed (Maya style)
861        if (m_modifierKeys& BT_ACTIVE_ALT)
862        {
863                if(m_mouseButtons & 2)
864                {
865                        btVector3 hor = getRayTo(0,0)-getRayTo(1,0);
866                        btVector3 vert = getRayTo(0,0)-getRayTo(0,1);
867                        btScalar multiplierX = 0.01;
868                        btScalar multiplierY = 0.01;
869                        if (m_ortho)
870                        {
871                                multiplierX = 1;
872                                multiplierY = 1;
873                        }
874
875
876                        m_cameraTargetPosition += hor* dx * multiplierX;
877                        m_cameraTargetPosition += vert* dy * multiplierY;
878                }
879
880                if(m_mouseButtons & (2 << 2) && m_mouseButtons & 1)
881                {
882                }
883                else if(m_mouseButtons & 1)
884                {
885                        m_azi += dx * 0.2;
886                        m_azi = fmodf(m_azi, 180.f);
887                        m_ele += dy * 0.2;
888                        m_ele = fmodf(m_ele, 180.f);
889                }
890                else if(m_mouseButtons & 4)
891                {
892                        m_cameraDistance -= dy * 0.2f;
893                        if (m_cameraDistance<0.1)
894                                m_cameraDistance = 0.1;
895
896
897                }
898        }
899
900
901        m_mouseOldX = x;
902    m_mouseOldY = y;
903        updateCamera();
904
905
906}
907
908
909
910btRigidBody*    DemoApplication::localCreateRigidBody(float mass, const btTransform& startTransform,btCollisionShape* shape)
911{
912        btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
913
914        //rigidbody is dynamic if and only if mass is non zero, otherwise static
915        bool isDynamic = (mass != 0.f);
916
917        btVector3 localInertia(0,0,0);
918        if (isDynamic)
919                shape->calculateLocalInertia(mass,localInertia);
920
921        //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
922
923#define USE_MOTIONSTATE 1
924#ifdef USE_MOTIONSTATE
925        btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
926
927        btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia);
928
929        btRigidBody* body = new btRigidBody(cInfo);
930
931#else
932        btRigidBody* body = new btRigidBody(mass,0,shape,localInertia);
933        body->setWorldTransform(startTransform);
934#endif//
935
936//      m_dynamicsWorld->addRigidBody(body);
937
938        return body;
939}
940
941//See http://www.lighthouse3d.com/opengl/glut/index.php?bmpfontortho
942void DemoApplication::setOrthographicProjection()
943{
944
945        // switch to projection mode
946        glMatrixMode(GL_PROJECTION);
947
948        // save previous matrix which contains the
949        //settings for the perspective projection
950        glPushMatrix();
951        // reset matrix
952        glLoadIdentity();
953        // set a 2D orthographic projection
954        gluOrtho2D(0, m_glutScreenWidth, 0, m_glutScreenHeight);
955        glMatrixMode(GL_MODELVIEW);
956        glLoadIdentity();
957
958        // invert the y axis, down is positive
959        glScalef(1, -1, 1);
960        // mover the origin from the bottom left corner
961        // to the upper left corner
962        glTranslatef(0, -m_glutScreenHeight, 0);
963
964}
965
966void DemoApplication::resetPerspectiveProjection()
967{
968
969        glMatrixMode(GL_PROJECTION);
970        glPopMatrix();
971        glMatrixMode(GL_MODELVIEW);
972        updateCamera();
973}
974
975
976
977
978extern CProfileIterator * m_profileIterator;
979
980void DemoApplication::displayProfileString(int xOffset,int yStart,char* message)
981{
982        glRasterPos3f(xOffset,yStart,0);
983        GLDebugDrawString(xOffset,yStart,message);
984}
985
986
987void DemoApplication::showProfileInfo(int& xOffset,int& yStart, int yIncr)
988{
989#ifndef BT_NO_PROFILE
990
991        static double time_since_reset = 0.f;
992        if (!m_idle)
993        {
994                time_since_reset = CProfileManager::Get_Time_Since_Reset();
995        }
996
997
998        {
999                //recompute profiling data, and store profile strings
1000
1001                char blockTime[128];
1002
1003                double totalTime = 0;
1004
1005                int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset();
1006
1007                m_profileIterator->First();
1008
1009                double parent_time = m_profileIterator->Is_Root() ? time_since_reset : m_profileIterator->Get_Current_Parent_Total_Time();
1010
1011                {
1012                        sprintf(blockTime,"--- Profiling: %s (total running time: %.3f ms) ---",        m_profileIterator->Get_Current_Parent_Name(), parent_time );
1013                        displayProfileString(xOffset,yStart,blockTime);
1014                        yStart += yIncr;
1015                        sprintf(blockTime,"press number (1,2...) to display child timings, or 0 to go up to parent" );
1016                        displayProfileString(xOffset,yStart,blockTime);
1017                        yStart += yIncr;
1018
1019                }
1020
1021
1022                double accumulated_time = 0.f;
1023
1024                for (int i = 0; !m_profileIterator->Is_Done(); m_profileIterator->Next())
1025                {
1026                        double current_total_time = m_profileIterator->Get_Current_Total_Time();
1027                        accumulated_time += current_total_time;
1028                        double fraction = parent_time > SIMD_EPSILON ? (current_total_time / parent_time) * 100 : 0.f;
1029
1030                        sprintf(blockTime,"%d -- %s (%.2f %%) :: %.3f ms / frame (%d calls)",
1031                                ++i, m_profileIterator->Get_Current_Name(), fraction,
1032                                (current_total_time / (double)frames_since_reset),m_profileIterator->Get_Current_Total_Calls());
1033                        displayProfileString(xOffset,yStart,blockTime);
1034                        yStart += yIncr;
1035                        totalTime += current_total_time;
1036                }
1037
1038                sprintf(blockTime,"%s (%.3f %%) :: %.3f ms", "Unaccounted",
1039                        // (min(0, time_since_reset - totalTime) / time_since_reset) * 100);
1040                        parent_time > SIMD_EPSILON ? ((parent_time - accumulated_time) / parent_time) * 100 : 0.f, parent_time - accumulated_time);
1041
1042                displayProfileString(xOffset,yStart,blockTime);
1043                yStart += yIncr;
1044
1045
1046
1047                sprintf(blockTime,"-------------------------------------------------");
1048                displayProfileString(xOffset,yStart,blockTime);
1049                yStart += yIncr;
1050
1051        }
1052#endif//BT_NO_PROFILE
1053
1054
1055}
1056
1057void DemoApplication::draw(guiObject *obj, const btVector3&color)
1058{
1059        if (!obj->ad || !obj->ud)
1060                return;
1061
1062        int index = 0;
1063
1064        glPushMatrix();
1065        btglMultMatrix(obj->ud->m);
1066
1067        int i;
1068//      printf("numIndices=%d\n", obj->ad->numIndices);
1069        for (i = 0; i < 16; i++) {
1070//              printf("m[%d]: %f\n", i, obj->ud->m[i]);
1071        }
1072        for (i = 0; i < obj->ad->numIndices; i++)
1073        {
1074//              printf("indexPointer[%d]: %d\n", i, obj->ad->indexPointer[i]);
1075        }
1076
1077        if(m_textureenabled&&(!m_textureinitialized))
1078        {
1079                GLubyte*        image=new GLubyte[256*256*3];
1080                for(int y=0;y<256;++y)
1081                {
1082                        const int       t=y>>4;
1083                        GLubyte*        pi=image+y*256*3;
1084                        for(int x=0;x<256;++x)
1085                        {
1086                                const int               s=x>>4;
1087                                const GLubyte   b=180;
1088                                GLubyte                 c=b+(((s+t)&1)&1)*(255-b);
1089                                pi[0]=pi[1]=pi[2]=c;pi+=3;
1090                        }
1091                }
1092
1093                glGenTextures(1,(GLuint*)&m_texturehandle);
1094                glBindTexture(GL_TEXTURE_2D,m_texturehandle);
1095                glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
1096                glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
1097                glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR);
1098                glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
1099                glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
1100                gluBuild2DMipmaps(GL_TEXTURE_2D,3,256,256,GL_RGB,GL_UNSIGNED_BYTE,image);
1101                delete[] image;
1102
1103                glMatrixMode(GL_TEXTURE);
1104                glLoadIdentity();
1105                glScalef(0.025,0.025,0.025);
1106
1107
1108        }
1109
1110
1111        static const GLfloat    planex[]={1,0,0,0};
1112//      static const GLfloat    planey[]={0,1,0,0};
1113        static const GLfloat    planez[]={0,0,1,0};
1114
1115        if (!m_textureinitialized) {
1116                glTexGenfv(GL_S,GL_OBJECT_PLANE,planex);
1117                glTexGenfv(GL_T,GL_OBJECT_PLANE,planez);
1118                glTexGeni(GL_S,GL_TEXTURE_GEN_MODE,GL_OBJECT_LINEAR);
1119                glTexGeni(GL_T,GL_TEXTURE_GEN_MODE,GL_OBJECT_LINEAR);
1120                glEnable(GL_TEXTURE_GEN_S);
1121                glEnable(GL_TEXTURE_GEN_T);
1122                glEnable(GL_TEXTURE_GEN_R);
1123                m_textureinitialized=true;
1124        }
1125
1126        glEnable(GL_COLOR_MATERIAL);
1127        if(m_textureenabled)
1128        {
1129                glEnable(GL_TEXTURE_2D);
1130                glBindTexture(GL_TEXTURE_2D,m_texturehandle);
1131        } else
1132        {
1133                glDisable(GL_TEXTURE_2D);
1134        }
1135
1136        glColor3f(color.x(),color.y(), color.z());
1137
1138        glBegin (GL_TRIANGLES);
1139
1140        for (i = 0; i < (obj->ad->numIndices / 3); i++)
1141        {
1142                int i1 = index++;
1143                int i2 = index++;
1144                int i3 = index++;
1145
1146                btAssert(i1 < ad->numIndices &&
1147                        i2 < ad->numIndices &&
1148                        i3 < ad->numIndices);
1149
1150                int index1 = obj->ad->indexPointer[i1];
1151                int index2 = obj->ad->indexPointer[i2];
1152                int index3 = obj->ad->indexPointer[i3];
1153                btAssert(index1 < ad->numVertices &&
1154                        index2 < ad->numVertices &&
1155                        index3 < ad->numVertices);
1156
1157                btVector3 v1 = obj->ad->vertexPointer[index1];
1158                btVector3 v2 = obj->ad->vertexPointer[index2];
1159                btVector3 v3 = obj->ad->vertexPointer[index3];
1160                btVector3 normal = (v3-v1).cross(v2-v1);
1161                normal.normalize ();
1162
1163                glNormal3f(normal.getX(),normal.getY(),normal.getZ());
1164                glVertex3f (v1.x(), v1.y(), v1.z());
1165                glVertex3f (v2.x(), v2.y(), v2.z());
1166                glVertex3f (v3.x(), v3.y(), v3.z());
1167        }
1168
1169        glPopMatrix();
1170
1171        glEnd ();
1172}
1173
1174//TODO
1175void DemoApplication::updateInfo(map<int, guiObject *> objects)
1176{
1177        m_cache = objects;
1178}
1179
1180//
1181//void  DemoApplication::renderscene(int pass)
1182void DemoApplication::renderscene(int pass)
1183{
1184//      btScalar        m[16];
1185//      btMatrix3x3     rot;rot.setIdentity();
1186
1187//      const int       numObjects=m_dynamicsWorld->getNumCollisionObjects();
1188        btVector3 wireColor(1,0,0);
1189
1190        map<int, guiObject *>::iterator it = m_cache.begin();
1191        for ( ; it != m_cache.end(); it ++) {
1192                btVector3 wireColor(1.f,1.0f,0.5f); //wants deactivation
1193#if 0
1194        for(int i=0;i<numObjects;i++)
1195        {
1196                btCollisionObject*      colObj=m_dynamicsWorld->getCollisionObjectArray()[i];
1197                btRigidBody*            body=btRigidBody::upcast(colObj);
1198                if(body&&body->getMotionState())
1199                {
1200                        btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
1201                        myMotionState->m_graphicsWorldTrans.getOpenGLMatrix(m);
1202                        rot=myMotionState->m_graphicsWorldTrans.getBasis();
1203                }
1204                else
1205                {
1206                        colObj->getWorldTransform().getOpenGLMatrix(m);
1207                        rot=colObj->getWorldTransform().getBasis();
1208                }
1209                btVector3 wireColor(1.f,1.0f,0.5f); //wants deactivation
1210                if(i&1) wireColor=btVector3(0.f,0.0f,1.f);
1211                ///color differently for active, sleeping, wantsdeactivation states
1212                if (colObj->getActivationState() == 1) //active
1213                {
1214                        if (i & 1)
1215                        {
1216                                wireColor += btVector3 (1.f,0.f,0.f);
1217                        }
1218                        else
1219                        {
1220                                wireColor += btVector3 (.5f,0.f,0.f);
1221                        }
1222                }
1223                if(colObj->getActivationState()==2) //ISLAND_SLEEPING
1224                {
1225                        if(i&1)
1226                        {
1227                                wireColor += btVector3 (0.f,1.f, 0.f);
1228                        }
1229                        else
1230                        {
1231                                wireColor += btVector3 (0.f,0.5f,0.f);
1232                        }
1233                }
1234
1235                btVector3 aabbMin,aabbMax;
1236                m_dynamicsWorld->getBroadphase()->getBroadphaseAabb(aabbMin,aabbMax);
1237
1238                aabbMin-=btVector3(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
1239                aabbMax+=btVector3(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
1240//              printf("aabbMin=(%f,%f,%f)\n",aabbMin.getX(),aabbMin.getY(),aabbMin.getZ());
1241//              printf("aabbMax=(%f,%f,%f)\n",aabbMax.getX(),aabbMax.getY(),aabbMax.getZ());
1242//              m_dynamicsWorld->getDebugDrawer()->drawAabb(aabbMin,aabbMax,btVector3(1,1,1));
1243#endif
1244/*
1245                switch(pass)
1246                {
1247                case    0:      m_shapeDrawer->drawOpenGL(it->second->ud->m,colObj->getCollisionShape(),wireColor,getDebugMode(),it->second->ud->aabbMin, it->second->ud->aabbMax);break;
1248                case    1:      m_shapeDrawer->drawShadow(it->second->ud->m,m_sundirection*rot,colObj->getCollisionShape(),it->second->ud->aabbMin, it->second->ud->aabbMax);break;
1249                case    2:      m_shapeDrawer->drawOpenGL(it->second->ud->m,colObj->getCollisionShape(),wireColor*0.3,0,it->second->ud->aabbMin, it->second->ud->aabbMax);break;
1250                }*/
1251
1252                switch(pass)
1253                {
1254//                      case    0:      m_shapeDrawer->draw(it->second->ud->m,it->second->ad,it->second->ud->aabbMin, it->second->ud->aabbMax);break;
1255//                      case    1:      m_shapeDrawer->drawShadow(it->second->ud->m,m_sundirection*rot,it->second->ad,it->second->ud->aabbMin, it->second->ud->aabbMax);break;
1256//                      case    2:      m_shapeDrawer->draw(it->second->ud->m,it->second->ad,it->second->ud->aabbMin, it->second->ud->aabbMax);break;
1257                        case    0: draw(it->second, wireColor);
1258                        case    2: draw(it->second, wireColor);
1259                }
1260        }
1261
1262}
1263
1264//
1265void DemoApplication::renderme()
1266{
1267        myinit();
1268
1269        updateCamera();
1270
1271        m_enableshadows = false;
1272        if(m_enableshadows)
1273        {
1274                glClear(GL_STENCIL_BUFFER_BIT);
1275                glEnable(GL_CULL_FACE);
1276                renderscene(0);
1277
1278                glDisable(GL_LIGHTING);
1279                glDepthMask(GL_FALSE);
1280                glDepthFunc(GL_LEQUAL);
1281                glEnable(GL_STENCIL_TEST);
1282                glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
1283                glStencilFunc(GL_ALWAYS,1,0xFFFFFFFFL);
1284                glFrontFace(GL_CCW);
1285                glStencilOp(GL_KEEP,GL_KEEP,GL_INCR);
1286                renderscene(1);
1287                glFrontFace(GL_CW);
1288                glStencilOp(GL_KEEP,GL_KEEP,GL_DECR);
1289                renderscene(1);
1290                glFrontFace(GL_CCW);
1291
1292                glPolygonMode(GL_FRONT,GL_FILL);
1293                glPolygonMode(GL_BACK,GL_FILL);
1294                glShadeModel(GL_SMOOTH);
1295                glEnable(GL_DEPTH_TEST);
1296                glDepthFunc(GL_LESS);
1297                glEnable(GL_LIGHTING);
1298                glDepthMask(GL_TRUE);
1299                glCullFace(GL_BACK);
1300                glFrontFace(GL_CCW);
1301                glEnable(GL_CULL_FACE);
1302                glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
1303
1304                glDepthFunc(GL_LEQUAL);
1305                glStencilFunc( GL_NOTEQUAL, 0, 0xFFFFFFFFL );
1306                glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
1307                glDisable(GL_LIGHTING);
1308                renderscene(2);
1309                glEnable(GL_LIGHTING);
1310                glDepthFunc(GL_LESS);
1311                glDisable(GL_STENCIL_TEST);
1312                glDisable(GL_CULL_FACE);
1313        }
1314        else
1315        {
1316                glDisable(GL_CULL_FACE);
1317                renderscene(0);
1318        }
1319
1320        int     xOffset = 10;
1321        int yStart = 20;
1322        int yIncr = 20;
1323        char buf[124];
1324
1325        glDisable(GL_LIGHTING);
1326        glColor3f(0, 0, 0);
1327
1328        if ((m_debugMode & btIDebugDraw::DBG_NoHelpText)==0)
1329        {
1330                setOrthographicProjection();
1331
1332                showProfileInfo(xOffset,yStart,yIncr);
1333
1334#ifdef USE_QUICKPROF
1335
1336
1337                if ( getDebugMode() & btIDebugDraw::DBG_ProfileTimings)
1338                {
1339                        static int counter = 0;
1340                        counter++;
1341                        std::map<std::string, hidden::ProfileBlock*>::iterator iter;
1342                        for (iter = btProfiler::mProfileBlocks.begin(); iter != btProfiler::mProfileBlocks.end(); ++iter)
1343                        {
1344                                char blockTime[128];
1345                                sprintf(blockTime, "%s: %lf",&((*iter).first[0]),btProfiler::getBlockTime((*iter).first, btProfiler::BLOCK_CYCLE_SECONDS));//BLOCK_TOTAL_PERCENT));
1346                                glRasterPos3f(xOffset,yStart,0);
1347                                GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),blockTime);
1348                                yStart += yIncr;
1349
1350                        }
1351
1352                }
1353#endif //USE_QUICKPROF
1354
1355
1356                sprintf(buf,"mouse to interact");
1357                GLDebugDrawString(xOffset,yStart,buf);
1358                yStart += yIncr;
1359
1360                sprintf(buf,"ALT + mouse to move camera");
1361                GLDebugDrawString(xOffset,yStart,buf);
1362                yStart += yIncr;
1363
1364                sprintf(buf,"space to reset");
1365                GLDebugDrawString(xOffset,yStart,buf);
1366                yStart += yIncr;
1367
1368                sprintf(buf,"cursor keys and z,x to navigate");
1369                GLDebugDrawString(xOffset,yStart,buf);
1370                yStart += yIncr;
1371
1372                sprintf(buf,"i to toggle simulation, s single step");
1373                GLDebugDrawString(xOffset,yStart,buf);
1374                yStart += yIncr;
1375
1376                sprintf(buf,"q to quit");
1377                GLDebugDrawString(xOffset,yStart,buf);
1378                yStart += yIncr;
1379
1380                sprintf(buf,". to shoot box");
1381                GLDebugDrawString(xOffset,yStart,buf);
1382                yStart += yIncr;
1383
1384                // not yet hooked up again after refactoring...
1385
1386                sprintf(buf,"d to toggle deactivation");
1387                GLDebugDrawString(xOffset,yStart,buf);
1388                yStart += yIncr;
1389
1390
1391                sprintf(buf,"g to toggle mesh animation (ConcaveDemo)");
1392                GLDebugDrawString(xOffset,yStart,buf);
1393                yStart += yIncr;
1394
1395
1396                sprintf(buf,"h to toggle help text");
1397                GLDebugDrawString(xOffset,yStart,buf);
1398                yStart += yIncr;
1399
1400                sprintf(buf,"o to toggle orthogonal/perspective view");
1401                GLDebugDrawString(xOffset,yStart,buf);
1402                yStart += yIncr;
1403
1404
1405                //bool useBulletLCP = !(getDebugMode() & btIDebugDraw::DBG_DisableBulletLCP);
1406                //bool useCCD = (getDebugMode() & btIDebugDraw::DBG_EnableCCD);
1407                //glRasterPos3f(xOffset,yStart,0);
1408                //sprintf(buf,"1 CCD mode (adhoc) = %i",useCCD);
1409                //GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),buf);
1410                //yStart += yIncr;
1411
1412
1413
1414                sprintf(buf,"+- shooting speed = %10.2f",m_ShootBoxInitialSpeed);
1415                GLDebugDrawString(xOffset,yStart,buf);
1416                yStart += yIncr;
1417
1418#ifdef SHOW_NUM_DEEP_PENETRATIONS
1419
1420
1421                sprintf(buf,"gNumDeepPenetrationChecks = %d",gNumDeepPenetrationChecks);
1422                GLDebugDrawString(xOffset,yStart,buf);
1423                yStart += yIncr;
1424
1425                sprintf(buf,"gNumGjkChecks= %d",gNumGjkChecks);
1426                GLDebugDrawString(xOffset,yStart,buf);
1427                yStart += yIncr;
1428
1429                sprintf(buf,"gNumClampedCcdMotions = %d",gNumClampedCcdMotions);
1430                GLDebugDrawString(xOffset,yStart,buf);
1431                yStart += yIncr;
1432
1433                sprintf(buf,"gNumSplitImpulseRecoveries= %d",gNumSplitImpulseRecoveries);
1434                GLDebugDrawString(xOffset,yStart,buf);
1435                yStart += yIncr;
1436
1437                sprintf(buf,"gNumAlignedAllocs = %d",gNumAlignedAllocs);
1438                GLDebugDrawString(xOffset,yStart,buf);
1439                yStart += yIncr;
1440
1441                sprintf(buf,"gNumAlignedFree= %d",gNumAlignedFree);
1442                GLDebugDrawString(xOffset,yStart,buf);
1443                yStart += yIncr;
1444
1445                sprintf(buf,"# alloc-free = %d",gNumAlignedAllocs-gNumAlignedFree);
1446                GLDebugDrawString(xOffset,yStart,buf);
1447                yStart += yIncr;
1448
1449                //enable BT_DEBUG_MEMORY_ALLOCATIONS define in Bullet/src/LinearMath/btAlignedAllocator.h for memory leak detection
1450#ifdef BT_DEBUG_MEMORY_ALLOCATIONS
1451                glRasterPos3f(xOffset,yStart,0);
1452                sprintf(buf,"gTotalBytesAlignedAllocs = %d",gTotalBytesAlignedAllocs);
1453                GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),buf);
1454                yStart += yIncr;
1455#endif //BT_DEBUG_MEMORY_ALLOCATIONS
1456
1457/*              if (getDynamicsWorld())
1458                {
1459                        glRasterPos3f(xOffset,yStart,0);
1460                        sprintf(buf,"# objects = %d",getDynamicsWorld()->getNumCollisionObjects());
1461                        GLDebugDrawString(xOffset,yStart,buf);
1462                        yStart += yIncr;
1463                        glRasterPos3f(xOffset,yStart,0);
1464                        sprintf(buf,"# pairs = %d",getDynamicsWorld()->getBroadphase()->getOverlappingPairCache()->getNumOverlappingPairs());
1465                        GLDebugDrawString(xOffset,yStart,buf);
1466                        yStart += yIncr;
1467                        sprintf(buf,"# hitPos = %f,%f,%f",gHitPos.getX(),gHitPos.getY(),gHitPos.getZ());
1468                        GLDebugDrawString(xOffset,yStart,buf);
1469                        yStart += yIncr;
1470
1471                }*/
1472
1473
1474#endif //SHOW_NUM_DEEP_PENETRATIONS
1475
1476                resetPerspectiveProjection();
1477        }
1478
1479        glEnable(GL_LIGHTING);
1480
1481
1482
1483        updateCamera();
1484
1485}
1486#include "BulletCollision/BroadphaseCollision/btAxisSweep3.h"
1487
1488void    DemoApplication::clientResetScene()
1489{
1490#ifdef SHOW_NUM_DEEP_PENETRATIONS
1491        gNumDeepPenetrationChecks = 0;
1492        gNumGjkChecks = 0;
1493#endif //SHOW_NUM_DEEP_PENETRATIONS
1494
1495        gNumClampedCcdMotions = 0;
1496//      int numObjects = 0;
1497//      int i;
1498
1499#if 0
1500        if (m_dynamicsWorld)
1501        {
1502                numObjects = m_dynamicsWorld->getNumCollisionObjects();
1503
1504                ///create a copy of the array, not a reference!
1505                btCollisionObjectArray copyArray = m_dynamicsWorld->getCollisionObjectArray();
1506
1507
1508
1509
1510                for (i=0;i<numObjects;i++)
1511                {
1512                        btCollisionObject* colObj = copyArray[i];
1513                        btRigidBody* body = btRigidBody::upcast(colObj);
1514                        if (body)
1515                        {
1516                                if (body->getMotionState())
1517                                {
1518                                        btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
1519                                        myMotionState->m_graphicsWorldTrans = myMotionState->m_startWorldTrans;
1520                                        body->setCenterOfMassTransform( myMotionState->m_graphicsWorldTrans );
1521                                        colObj->setInterpolationWorldTransform( myMotionState->m_startWorldTrans );
1522                                        colObj->forceActivationState(ACTIVE_TAG);
1523                                        colObj->activate();
1524                                        colObj->setDeactivationTime(0);
1525                                        //colObj->setActivationState(WANTS_DEACTIVATION);
1526                                }
1527                                //removed cached contact points (this is not necessary if all objects have been removed from the dynamics world)
1528                                //m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(colObj->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher());
1529
1530                                btRigidBody* body = btRigidBody::upcast(colObj);
1531                                if (body && !body->isStaticObject())
1532                                {
1533                                        btRigidBody::upcast(colObj)->setLinearVelocity(btVector3(0,0,0));
1534                                        btRigidBody::upcast(colObj)->setAngularVelocity(btVector3(0,0,0));
1535                                }
1536                        }
1537
1538                }
1539
1540                ///reset some internal cached data in the broadphase
1541                m_dynamicsWorld->getBroadphase()->resetPool(getDynamicsWorld()->getDispatcher());
1542                m_dynamicsWorld->getConstraintSolver()->reset();
1543
1544        }
1545#endif
1546
1547}
1548
1549void DemoApplication::updateModifierKeys()
1550{
1551        m_modifierKeys = 0;
1552        if (glutGetModifiers() & GLUT_ACTIVE_ALT)
1553                m_modifierKeys |= BT_ACTIVE_ALT;
1554
1555        if (glutGetModifiers() & GLUT_ACTIVE_CTRL)
1556                m_modifierKeys |= BT_ACTIVE_CTRL;
1557
1558        if (glutGetModifiers() & GLUT_ACTIVE_SHIFT)
1559                m_modifierKeys |= BT_ACTIVE_SHIFT;
1560}
1561
1562void DemoApplication::specialKeyboard(int key, int x, int y)
1563{
1564        (void)x;
1565        (void)y;
1566
1567        switch (key)
1568        {
1569        case GLUT_KEY_F1:
1570                {
1571
1572                        break;
1573                }
1574
1575        case GLUT_KEY_F2:
1576                {
1577
1578                        break;
1579                }
1580
1581
1582        case GLUT_KEY_END:
1583                {
1584                        /*
1585                        int numObj = getDynamicsWorld()->getNumCollisionObjects();
1586                        if (numObj)
1587                        {
1588                                btCollisionObject* obj = getDynamicsWorld()->getCollisionObjectArray()[numObj-1];
1589
1590                                getDynamicsWorld()->removeCollisionObject(obj);
1591                                btRigidBody* body = btRigidBody::upcast(obj);
1592                                if (body && body->getMotionState())
1593                                {
1594                                        delete body->getMotionState();
1595                                }
1596                                delete obj;
1597
1598
1599                        }
1600                        */
1601                        break;
1602                }
1603        case GLUT_KEY_LEFT : stepLeft(); break;
1604        case GLUT_KEY_RIGHT : stepRight(); break;
1605        case GLUT_KEY_UP : stepFront(); break;
1606        case GLUT_KEY_DOWN : stepBack(); break;
1607        case GLUT_KEY_PAGE_UP : zoomIn(); break;
1608        case GLUT_KEY_PAGE_DOWN : zoomOut(); break;
1609        case GLUT_KEY_HOME : toggleIdle(); break;
1610        default:
1611                //        std::cout << "unused (special) key : " << key << std::endl;
1612                break;
1613        }
1614
1615        glutPostRedisplay();
1616
1617}
1618
1619void DemoApplication::swapBuffers()
1620{
1621        glutSwapBuffers();
1622
1623}
Note: See TracBrowser for help on using the repository browser.