AnimatLab  2
Test
VsSimulator.cpp
1 // VsSimulator.cpp: implementation of the VsSimulator class.
2 //
4 
5 #include "stdafx.h"
6 #include <stdarg.h>
7 #include "VsMovableItem.h"
8 #include "VsBody.h"
9 #include "VsJoint.h"
10 #include "VsMotorizedJoint.h"
11 #include "VsRigidBody.h"
12 #include "VsOrganism.h"
13 #include "VsStructure.h"
14 #include "VsClassFactory.h"
15 #include "VsSimulator.h"
16 
17 //#include "VsSimulationRecorder.h"
18 #include "VsMouseSpring.h"
19 #include "VsLight.h"
20 #include "VsCameraManipulator.h"
21 #include "VsDragger.h"
22 #include "MeshMinVertexDistanceVisitor.h"
23 
24 namespace VortexAnimatSim
25 {
26 
28 // Construction/Destruction
30 
31 
32 VsSimulator::VsSimulator()
33 {
34  m_uUniverse = NULL;
35  m_grpScene = NULL;
36  m_vsWinMgr = NULL;
37  m_vsWinMgr = new VsSimulationWindowMgr;
38  m_lpWinMgr = m_vsWinMgr;
39  m_lpWinMgr->SetSystemPointers(this, NULL, NULL, NULL, true);
40  m_uUniverse = NULL;
41  m_vxFrame = NULL;
42  m_dblTotalStepTime = 0;
43  m_lStepTimeCount = 0;
44  m_dblTotalStepTime= 0;
45  m_lStepTimeCount = 0;
46  m_dblTotalVortexStepTime = 0;
47  m_lStepVortexTimeCount = 0;
48  m_lpMeshMgr = NULL;
49  m_osgAlphafunc = NULL;
50 }
51 
52 VsSimulator::~VsSimulator()
53 {
54 
55 try
56 {
57  if(m_lpMeshMgr)
58  {
59  delete m_lpMeshMgr;
60  m_lpMeshMgr = NULL;
61  }
62 
63  m_bShuttingDown = true;
64 
65  //Set this to NULL so all of the DeletePhysics calls will not try and remove
66  //entities from the universe when shutting down.
67  m_uUniverse = NULL;
68 
69  Reset();
70 }
71 catch(...)
72 {Std_TraceMsg(0, "Caught Error in desctructor of Simulator\r\n", "", -1, false, true);}
73 }
74 
75 VxUniverse *VsSimulator::Universe()
76 {return m_uUniverse;}
77 
78 Vx::VxFrame* VsSimulator::Frame()
79 {return m_vxFrame;}
80 
81 void VsSimulator::AlphaThreshold(float fltValue)
82 {
83  Simulator::AlphaThreshold(fltValue);
84 
85  if(m_osgAlphafunc)
86  m_osgAlphafunc->setFunction(osg::AlphaFunc::GEQUAL, m_fltAlphaThreshold);
87 }
88 
89 
90 #pragma region MutatorOverrides
91 
92 void VsSimulator::StabilityScale(float fltVal)
93 {
94  Simulator::StabilityScale(fltVal);
95  SetSimulationStabilityParams();
96 }
97 
98 void VsSimulator::LinearCompliance(float fltVal, bool bUseScaling)
99 {
100  Simulator::LinearCompliance(fltVal, bUseScaling);
101  SetSimulationStabilityParams();
102 }
103 
104 void VsSimulator::AngularCompliance(float fltVal, bool bUseScaling)
105 {
106  Simulator::AngularCompliance(fltVal, bUseScaling);
107  SetSimulationStabilityParams();
108 }
109 
110 void VsSimulator::LinearDamping(float fltVal, bool bUseScaling)
111 {
112  Simulator::LinearDamping(fltVal, bUseScaling);
113  SetSimulationStabilityParams();
114 }
115 
116 void VsSimulator::AngularDamping(float fltVal, bool bUseScaling)
117 {
118  Simulator::AngularDamping(fltVal, bUseScaling);
119  SetSimulationStabilityParams();
120 }
121 
122 void VsSimulator::LinearKineticLoss(float fltVal, bool bUseScaling)
123 {
124  Simulator::LinearKineticLoss(fltVal, bUseScaling);
125  SetSimulationStabilityParams();
126 }
127 
128 void VsSimulator::AngularKineticLoss(float fltVal, bool bUseScaling)
129 {
130  Simulator::AngularKineticLoss(fltVal, bUseScaling);
131  SetSimulationStabilityParams();
132 }
133 
135 {
136  Simulator::PhysicsTimeStep(fltVal);
137 
138  if(m_vxFrame)
139  {
140  m_vxFrame->setTimeStep(m_fltPhysicsTimeStep);
141  SetSimulationStabilityParams();
142  }
143 }
144 
145 void VsSimulator::Gravity(float fltVal, bool bUseScaling)
146 {
147  Simulator::Gravity(fltVal, bUseScaling);
148 
149  if(m_uUniverse)
150  m_uUniverse->setGravity(0, m_fltGravity, 0);
151 }
152 
153 int VsSimulator::GetMaterialID(std::string strID)
154 {
155  if(m_vxFrame)
156  {
157  VxMaterialTable *lpMat = m_vxFrame->getMaterialTable();
158 
159  if(lpMat)
160  return lpMat->getMaterialID(strID.c_str());
161  return -1;
162  }
163 
164  return -1;
165 }
166 
167 #pragma endregion
168 
169 
171 {
172 //NEED_TO_FIX
173  return NULL; //new VsSimulationRecorder;
174 }
175 
177 {
178  Simulator::Reset();
179 
180  if(m_vxFrame)
181  m_vxFrame->release();
182 
185 
186  if(m_osgCmdMgr.valid())
187  m_osgCmdMgr.release();
188 
189  if(m_lpMeshMgr)
190  {
191  delete m_lpMeshMgr;
192  m_lpMeshMgr = NULL;
193  }
194 
195 }
196 
198 {
199  Simulator::ResetSimulation();
200 
201  if(m_uUniverse)
202  {
203  m_uUniverse->resetDynamics();
204  m_uUniverse->resetContacts();
205  }
206  m_bSimRunning = false;
207 }
208 
210 {
211  if(m_bPaused)
212  SimStarting();
213  else
214  SimPausing();
215 
216  m_bPaused = !m_bPaused;
217 }
218 
220 {
221  SimStopping();
222  if(!m_bPaused)
224  m_bSimRunning = false;
225 }
226 
227 void VsSimulator::InitializeVortexViewer(int argc, const char **argv)
228 {
229  osg::ArgumentParser arguments(&argc, (char **) argv);
230 
231  osg::setNotifyLevel(osg::NotifySeverity::NOTICE); //ConvertTraceLevelToOSG());
232 
233  //osg::notify(osg::NOTICE) << "Setting OSG notice level to '" << Std_GetTraceLevel() << std::endl
234 
235  // set up the usage document, in case we need to print out how to use this program.
236  arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
237  arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
238  arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
239  arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
240 
241  //Ensure that our exe path is the only place it will attempt to find library files.
242  osgDB::FilePathList aryList = osgDB::getLibraryFilePathList();
243  std::string strPath = m_strExecutablePath.substr(0, m_strExecutablePath.length()-1);
244  aryList.clear();
245  aryList.push_front(strPath);
246  osgDB::setLibraryFilePathList(aryList);
247 
248  // add resource search paths
249  osgDB::getDataFilePathList().push_front("./Resources");
250  osgDB::getDataFilePathList().push_front("../Resources");
251  osgDB::getDataFilePathList().push_front("../../Resources");
252 
253  std::string strFile = osgDB::findLibraryFile("osgdb_freetype.dll");
254 
255  //This is the root of the scenegraph. Which will corrospond
256  //to the root of the simulation
257  m_grpScene = new osg::Group;
258  m_grpScene->setName("World");
259 
260  //Add the mouse spring lines to the scene
261  m_grpScene->addChild(VsMouseSpring::GetInstance()->GetNode());
262 
263  //Create the windows, cameras, and Huds
264  m_vsWinMgr->Initialize();
265 
266  //Create the command manager if needed.
267  if(!m_osgCmdMgr.valid())
268  m_osgCmdMgr = new osgManipulator::CommandManager;
269 
270  osg::StateSet* rootStateSet = m_grpScene->getOrCreateStateSet();
271  rootStateSet->setMode( GL_LIGHTING, osg::StateAttribute::ON );
272  rootStateSet->setMode( GL_LIGHT0, osg::StateAttribute::ON );
273  //rootStateSet->setMode( GL_LIGHT1, osg::StateAttribute::ON );
274 
275  // set up an alphafunc by default to speed up blending operations.
276  m_osgAlphafunc = new osg::AlphaFunc;
277  m_osgAlphafunc->setFunction(osg::AlphaFunc::GEQUAL, m_fltAlphaThreshold);
278  rootStateSet->setAttributeAndModes(m_osgAlphafunc, osg::StateAttribute::ON);
279 
280  m_oLightMgr.Initialize();
281 }
282 
283 void VsSimulator::SetSimulationStabilityParams()
284 {
285  if(m_uUniverse)
286  {
287  /* if(m_bCalcCriticalSimParams)
288  {*/
289  //VxReal halflife = 5;
290  //m_uUniverse->getSolverParameters(0)->setConstraintLinearCompliance(m_fltLinearCompliance);
291  //m_uUniverse->getSolverParameters(0)->setConstraintAngularCompliance(m_fltAngularCompliance);
292  //m_uUniverse->setCriticalConstraintParameters(0, halflife);
293  /*}
294  else
295  {
296  m_uUniverse->getSolverParameters(0)->setConstraintLinearCompliance(m_fltLinearCompliance);
297  m_uUniverse->getSolverParameters(0)->setConstraintLinearDamping(m_fltLinearDamping);
298  m_uUniverse->getSolverParameters(0)->setConstraintLinearKineticLoss(m_fltLinearKineticLoss);
299  m_uUniverse->getSolverParameters(0)->setConstraintAngularCompliance(m_fltAngularCompliance);
300  m_uUniverse->getSolverParameters(0)->setConstraintAngularDamping(m_fltAngularDamping);
301  m_uUniverse->getSolverParameters(0)->setConstraintAngularKineticLoss(m_fltAngularKineticLoss);
302  }*/
303 
304  //VxSolverParameters* sp = m_uUniverse->getSolverParameters(0);
305  //sp->setConstraintLinearKineticLoss(0.0006);
306  //sp->setConstraintLinearKineticLoss(0.0006);
307  //sp->setConstraintLinearCompliance(1e-5);
308  //sp->setConstraintAngularCompliance(1e-5);
309  //sp->setConstraintLinearDamping(1e4);
310  //sp->setConstraintAngularDamping(1e4);
311 
312  VxSolverParameters* sp = m_uUniverse->getSolverParameters(0);
313  sp->setConstraintLinearKineticLoss(sp->getConstraintLinearKineticLoss()*m_fltStabilityScale);
314  sp->setConstraintLinearKineticLoss(sp->getConstraintAngularKineticLoss()*m_fltStabilityScale);
315  sp->setConstraintLinearCompliance(sp->getConstraintLinearCompliance()/m_fltStabilityScale);
316  sp->setConstraintAngularCompliance(sp->getConstraintAngularCompliance()/m_fltStabilityScale);
317  sp->setConstraintLinearDamping(sp->getConstraintLinearDamping()*m_fltStabilityScale);
318  sp->setConstraintAngularDamping(sp->getConstraintAngularDamping()*m_fltStabilityScale);
319 
320  TRACE_DETAIL("Reset simulation stability params\r\n");
321  TRACE_DETAIL("Angular Compliance: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintAngularCompliance()) + "\r\n");
322  TRACE_DETAIL("Angular Damping: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintAngularDamping()) + "\r\n");
323  TRACE_DETAIL("Angular Kinetic Loss: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintAngularKineticLoss()) + "\r\n");
324  TRACE_DETAIL("Linear Compliance: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintLinearCompliance()) + "\r\n");
325  TRACE_DETAIL("Linear Damping: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintLinearDamping()) + "\r\n");
326  TRACE_DETAIL("Linear Kinetic Loss: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintLinearKineticLoss()) + "\r\n");
327  }
328 }
329 
330 //This function initializes the Vortex related
331 //classes and the vortex viewer.
332 void VsSimulator::InitializeVortex(int argc, const char **argv)
333 {
334  InitializeVortexViewer(argc, argv);
335 
336  int iObjectCount = 100 + m_iPhysicsBodyCount;
337  int iCollisionCount = iObjectCount*40;
338 
339  //create the frame
340  m_vxFrame = VxFrame::instance();
341  m_uUniverse = new Vx::VxUniverse(iObjectCount, iCollisionCount);
342  m_uUniverse->setGravity(0, m_fltGravity, 0);
343  //m_uUniverse->setGravity(0, 0, m_fltGravity);
344  m_vxFrame->addUniverse(m_uUniverse);
345 
346  //set the frame timestep
347  m_vxFrame->setTimeStep(m_fltPhysicsTimeStep);
348 
349  VxFrameRegisterAllInteractions(m_vxFrame);
350 
351  SetSimulationStabilityParams();
352 
353  // Register the simple callback to be notified at beginning and end of the interaction between parts and sensors.
354  m_uUniverse->addIntersectSubscriber(VxUniverse::kResponseSensor, VxUniverse::kResponsePart, VxUniverse::kEventFirst, &m_vsIntersect, 0);
355  m_uUniverse->addIntersectSubscriber(VxUniverse::kResponseSensor, VxUniverse::kResponsePart, VxUniverse::kEventDisjoint, &m_vsIntersect, 0);
356 
357 }
358 
359 Vx::VxTriangleMesh *VsSimulator::CreatTriangleMeshFromOsg(osg::Node *osgNode)
360 {
361  Vx::VxTriangleMesh *vxMesh = NULL;
362  vxMesh = VxTriangleMesh::createFromNode(osgNode);
363 
364  return vxMesh;
365 }
366 
367 osg::NotifySeverity VsSimulator::ConvertTraceLevelToOSG()
368 {
369  int iLevel = Std_GetTraceLevel();
370 
371  switch (iLevel)
372  {
373  case 0:
374  return osg::NotifySeverity::FATAL;
375  case 10:
376  return osg::NotifySeverity::WARN;
377  case 20:
378  return osg::NotifySeverity::INFO;
379  case 30:
380  return osg::NotifySeverity::DEBUG_INFO;
381  case 40:
382  return osg::NotifySeverity::DEBUG_FP;
383  default:
384  return osg::NotifySeverity::WARN;
385  }
386 }
387 
388 Vx::VxConvexMesh *VsSimulator::CreateConvexMeshFromOsg(osg::Node *osgNode)
389 {
390  Vx::VxConvexMesh *vxMesh = NULL;
391  vxMesh = VxConvexMesh::createFromNode(osgNode);
392 
393  return vxMesh;
394 }
395 
411 void VsSimulator::GenerateCollisionMeshFile(std::string strOriginalMeshFile, std::string strCollisionMeshFile, float fltScaleX, float fltScaleY, float fltScaleZ)
412 {
413  //First load the original mesh in.
414  std::string strPath = this->ProjectPath();
415  std::string strOrigFile = AnimatSim::GetFilePath(strPath, strOriginalMeshFile);
416  std::string strNewFile = AnimatSim::GetFilePath(strPath, strCollisionMeshFile);
417 
418  osg::ref_ptr<osg::Node> osgNode = MeshMgr()->LoadMesh(strOrigFile); //osgDB::readNodeFile(strOrigFile.c_str());
419 
420  //Make sure the mesh loaded is valid.
421  if(!osgNode.valid())
422  THROW_PARAM_ERROR(Vs_Err_lErrorLoadingMesh, Vs_Err_strErrorLoadingMesh, "Original Mesh file", strOriginalMeshFile);
423 
424  //Now create a convex mesh with the physics engine using the loaded mesh.
425  Vx::VxConvexMesh *vxMesh = VxConvexMesh::createFromNode(osgNode.get());
426 
427  //Now use that convexmesh geometry to create a new osg node.
428  osg::ref_ptr<osg::Geometry> osgGeom = CreateOsgFromVxConvexMesh(vxMesh);
429  osg::ref_ptr<osg::Geode> osgNewNode = new osg::Geode;
430  osgNewNode->addDrawable(osgGeom.get());
431 
432  osg::Matrix osgScale = osg::Matrix::scale(fltScaleX, fltScaleY, fltScaleZ);
433  osg::ref_ptr<osg::MatrixTransform> osgScaleMT = new osg::MatrixTransform(osgScale);
434  osgScaleMT->addChild(osgNewNode.get());
435  osgScaleMT->setDataVariance(osg::Object::STATIC);
436 
437  // Now do some OSG voodoo, which should spread the transform downward
438  // through the loaded model, and delete the transform.
439  osgUtil::Optimizer optimizer;
440  optimizer.optimize(osgScaleMT.get(), osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS);
441 
442  //Now save out the new collision mesh.
443  osgDB::writeNodeFile(*osgNewNode, strNewFile.c_str());
444 
445  //Make sure we stamp the new file tim on the file. For some reason osgDB is not settign that correctly.
446  //If we do not do this then the mesh mgr will not recognize that it has changed, and will not load it.
447  Std_SetFileTime(strNewFile);
448 }
449 
450 void VsSimulator::ConvertV1MeshFile(std::string strOriginalMeshFile, std::string strNewMeshFile, std::string strTexture)
451 {
452  //First load the original mesh in.
453  std::string strPath = this->ProjectPath();
454  std::string strOrigFile = AnimatSim::GetFilePath(strPath, strOriginalMeshFile);
455  std::string strNewFile = AnimatSim::GetFilePath(strPath, strNewMeshFile);
456  std::string strTextFile = "";
457 
458  if(!Std_IsBlank(strTexture))
459  strTextFile = AnimatSim::GetFilePath(strPath, strTexture);
460 
461  osg::ref_ptr<osg::Node> osgNode = osgDB::readNodeFile(strOrigFile.c_str());
462 
463  //Make sure the mesh loaded is valid.
464  if(!osgNode.valid())
465  THROW_PARAM_ERROR(Vs_Err_lErrorLoadingMesh, Vs_Err_strErrorLoadingMesh, "Original Mesh file", strOriginalMeshFile);
466 
467  CStdFPoint vPos(0, 0, 0), vRot( -(osg::PI/2), 0, 0);
468  ApplyVertexTransform(osgNode.get(), SetupMatrix(vPos, vRot));
469 
470  AddNodeTexture(osgNode.get(), strTextFile, GL_TEXTURE_2D);
471 
472  //Now save out the new collision mesh.
473  osgDB::writeNodeFile(*osgNode, strNewFile.c_str());
474 }
475 
476 
477 //
478 //float VsSimulator::FindMinMeshVertexDistance(osg::Node *osgNode)
479 //{
480 // MeshMinVertexDistanceVisitor ncv;
481 // osgNode->accept(ncv);
482 // return ncv.MinVertexDistance();
483 //}
484 
485 void VsSimulator::GetPositionAndRotationFromD3DMatrix(float (&aryTransform)[4][4], CStdFPoint &vPos, CStdFPoint &vRot)
486 {
487  osg::Matrix osgMT(aryTransform[0][0], aryTransform[0][1], aryTransform[0][2], aryTransform[0][3],
488  aryTransform[1][0], aryTransform[1][1], aryTransform[1][2], aryTransform[1][3],
489  aryTransform[2][0], aryTransform[2][1], aryTransform[2][2], aryTransform[2][3],
490  aryTransform[3][0], aryTransform[3][1], aryTransform[3][2], aryTransform[3][3]);
491 
492  osg::Matrix osgFinal;
493 
494  osgFinal = osgMT;
495 
496  //Lets get the current world coordinates for this body part and then recalculate the
497  //new local position for the part and then finally reset its new local position.
498  osg::Vec3 vL = osgFinal.getTrans();
499  vPos.Set(vL.x(), vL.y(), vL.z());
500  vPos.ClearNearZero();
501 
502  //Now lets get the euler angle rotation
503  Vx::VxReal44 vxTM;
504  VxOSG::copyOsgMatrix_to_VxReal44(osgFinal, vxTM);
505  Vx::VxTransform vTrans(vxTM);
506  Vx::VxReal3 vEuler;
507  vTrans.getRotationEulerAngles(vEuler);
508  vRot.Set(vEuler[0], vEuler[1] ,vEuler[2]);
509  vRot.ClearNearZero();
510 }
511 
512 //Timer Methods
513 unsigned long long VsSimulator::GetTimerTick()
514 {
515  m_lLastTickTaken = osg::Timer::instance()->tick();
516  return m_lLastTickTaken;
517 }
518 
519 double VsSimulator::TimerDiff_n(unsigned long long lStart, unsigned long long lEnd)
520 {return osg::Timer::instance()->delta_n(lStart, lEnd);}
521 
522 double VsSimulator::TimerDiff_u(unsigned long long lStart, unsigned long long lEnd)
523 {return osg::Timer::instance()->delta_u(lStart, lEnd);}
524 
525 double VsSimulator::TimerDiff_m(unsigned long long lStart, unsigned long long lEnd)
526 {return osg::Timer::instance()->delta_m(lStart, lEnd);}
527 
528 double VsSimulator::TimerDiff_s(unsigned long long lStart, unsigned long long lEnd)
529 {return osg::Timer::instance()->delta_s(lStart, lEnd);}
530 
531 void VsSimulator::MicroSleep(unsigned int iMicroTime)
532 {OpenThreads::Thread::microSleep(iMicroTime);}
533 
534 void VsSimulator::WriteToConsole(std::string strMessage)
535 {
536  osg::notify(osg::NOTICE) << strMessage << std::endl;
537 }
538 
539 void VsSimulator::Initialize(int argc, const char **argv)
540 {
541  InitializeVortex(argc, argv);
542 
544 
545  m_oDataChartMgr.Initialize();
546  m_oExternalStimuliMgr.Initialize();
547  if(m_lpSimRecorder) m_lpSimRecorder->Initialize();
548 
549  //realize the osg viewer
550  m_vsWinMgr->Realize();
551 
552  m_bInitialized = true;
553 }
554 
556 {
557  //if(m_lTimeSlice > 10 && m_lTimeSlice < 5000 && !m_timePeriod.TimerStarted())
558  // m_timePeriod.StartTimer();
559 
560 
561  try
562  {
563  //step the frame and update the windows
564  if (!m_bPaused)
565  {
566  Simulator::StepSimulation();
567 
568  unsigned long long lStart = GetTimerTick();
569  m_vxFrame->step();
570  double dblVal = TimerDiff_s(lStart, GetTimerTick());
571  m_fltPhysicsStepTime += dblVal;
572 
574 
575  if(m_lTimeSlice > 10 && m_lTimeSlice < 5000)
576  {
577  m_dblTotalVortexStepTime += dblVal;
578  m_lStepVortexTimeCount++;
579  }
580  else if(m_lTimeSlice == 5000)
581  {
582  double dblAvgStepTime = m_dblTotalVortexStepTime/m_lStepVortexTimeCount;
583  osg::notify(osg::NOTICE) << "Average step time: " << dblAvgStepTime << std::endl;
584  osg::notify(osg::NOTICE) << "Total vortex step time: " << m_dblTotalVortexStepTime << std::endl;
585  osg::notify(osg::NOTICE) << "Slice Time: " << m_lTimeSlice << std::endl;
586  osg::notify(osg::NOTICE) << "Sim Time: " << Time() << std::endl;
587  }
588  }
589 
590  }
591  catch(CStdErrorInfo oError)
592  {
593  std::string strError = "An error occurred while step the simulation.\nError: " + oError.m_strError;
594  HandleNonCriticalError(strError);
595  }
596 
597 
598  //double dblVal2 = m_timeSimulationStep.StopTimer();
599  //if(m_lTimeSlice > 10 && m_lTimeSlice < 5000)
600  //{
601  // m_dblTotalStepTime += dblVal2;
602  // m_lStepTimeCount++;
603  //}
604  //else if(m_lTimeSlice == 5000)
605  //{
606  // double dblAvgStepTime = m_dblTotalStepTime/m_lStepTimeCount;
607  // cout << "Average step time: " << dblAvgStepTime << std::endl;
608  // cout << "Total step time: " << m_dblTotalStepTime << ", " << m_lStepTimeCount << std::endl;
609  // cout << "Period time: " << m_timePeriod.StopTimer() << std::endl;
610  // cout << "Slice Time: " << m_lTimeSlice << std::endl;
611  // cout << "Sim Time: " << Time() << std::endl;
612  //}
613 
614 }
615 
616 void VsSimulator::UpdateSimulationWindows()
617 {
618  m_bStopSimulation = !m_vsWinMgr->Update();
619 }
620 
621 
623 {
624  m_vxFrame->release();
625  m_vxFrame = NULL;
626 }
627 
629 {
630  SimStopping();
631  m_bForceSimulationStop = true;
632 }
633 
635 {
636  SimPausing();
637  m_bPaused = true;
638  return true;
639 }
640 
642 {
643  m_lStartSimTick = GetTimerTick();
644 
645  SimStarting();
646  m_bSimRunning = true;
647  m_bPaused = false;
648  return true;
649 }
650 
651 float *VsSimulator::GetDataPointer(const std::string &strDataType)
652 {
653  float *lpData=NULL;
654  std::string strType = Std_CheckString(strDataType);
655 
656  //if(strType == "FRAMEDT")
657  // lpData = &m_fltFrameDt;
658  //else
659  //{
660  lpData = Simulator::GetDataPointer(strDataType);
661  if(!lpData)
662  THROW_TEXT_ERROR(Al_Err_lInvalidDataType, Al_Err_strInvalidDataType, "Simulator DataType: " + strDataType);
663  //}
664 
665  return lpData;
666 }
667 
669 {
671  m_lpSimStopPoint = dynamic_cast<KeyFrame *>(CreateObject("AnimatLab", "KeyFrame", "Snapshot"));
672  if(!m_lpSimStopPoint)
673  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "KeyFrame");
674 
675  m_lpSimStopPoint->StartSlice(m_lTimeSlice);
676  m_lpSimStopPoint->EndSlice(m_lTimeSlice);
677  m_lpSimStopPoint->Activate();
678 }
679 
680 VsSimulator *VsSimulator::ConvertSimulator(Simulator *lpSim)
681 {
682  if(!lpSim)
683  THROW_ERROR(Al_Err_lSimulationNotDefined, Al_Err_strSimulationNotDefined);
684 
685  VsSimulator *lpVsSim = dynamic_cast<VsSimulator *>(lpSim);
686 
687  if(!lpVsSim)
688  THROW_ERROR(Vs_Err_lUnableToConvertToVsSimulator, Vs_Err_strUnableToConvertToVsSimulator);
689 
690  return lpVsSim;
691 }
692 
693 void VsSimulator::Save(std::string strFile)
694 {
695  std::string strOsgFile = strFile + ".osg";
696  std::string strVxFile = strFile + ".vxf";
697  std::string strUcon = strFile + ".ucon";
698 
699  //Temp code. Lets save it out and make sure the collision stuff is actually correct.
700  try
701  {
702  VxPersistence::saveFrame(strVxFile.c_str(), VxPersistence::kStandard);
703  }
704  catch(std::exception ex)
705  {
706  int i= 5;
707  }
708  catch(...)
709  {
710  int i= 5;
711  }
712 
713  m_uUniverse->printContent(strUcon.c_str());
714 
715  osgDB::writeNodeFile(*OSGRoot(), strOsgFile.c_str());
716 }
717 
718 
719 /*
720 VsSimulator *VsSimulator::ConvertSimulator(Simulator *lpSim)
721 {
722  if(!lpSim)
723  THROW_ERROR(Al_Err_lSimulationNotDefined, Al_Err_strSimulationNotDefined);
724 
725  VsSimulator *lpVsSim = dynamic_cast<VsSimulator *>(lpSim);
726 
727  if(!lpVsSim)
728  THROW_ERROR(Vs_Err_lUnableToConvertToVsSimulator, Vs_Err_strUnableToConvertToVsSimulator);
729 
730  return lpVsSim;
731 }
732 */
733 
734 
735 /*
736 __declspec( dllexport ) void RunSimulator(void)
737 {
738  VsSimulator oSim;
739  oSim.ProjectPath("C:\\Projects\\bin\\Experiments\\Robot\\");
740 
741  oSim.Load("Robot.asim");
742  oSim.Initialize(0, NULL);
743  oSim.Simulate();
744 }
745 */
746 
747 } //VortexAnimatSim
virtual float LinearDamping()
Gets the linear damping of the simulation.
Definition: Simulator.cpp:834
KeyFrame * m_lpSimStopPoint
The pointer to a simulation stop point.
Definition: Simulator.h:448
bool m_bPaused
true if the simulation is paused.
Definition: Simulator.h:143
virtual float StabilityScale()
Sets the linear scaling factor that controls the simulation stability parameters. ...
Definition: Simulator.cpp:755
virtual float AngularKineticLoss()
Gets the angular kinetic loss of teh simulation.
Definition: Simulator.cpp:920
virtual void Reset()
Resets all objects of the simulation to their unloaded state.
virtual void SetSystemPointers(Simulator *lpSim, Structure *lpStructure, NeuralModule *lpModule, Node *lpNode, bool bVerify)
Sets the system pointers.
virtual void SimulateEnd()
Called at the end of the Simulate method.
virtual void Initialize()
Initializes this object.
virtual float Gravity()
Gets the gravity value.
Definition: Simulator.cpp:1225
float m_fltPhysicsStepTime
This is the time pers step for the physics engine.
Definition: Simulator.h:381
ExternalStimuliMgr m_oExternalStimuliMgr
Manager for external stimuli.
Definition: Simulator.h:103
bool m_bInitialized
true if the simulation has been initialized.
Definition: Simulator.h:146
virtual float PhysicsTimeStep()
Gets the integration time step for the physics engine.
Definition: Simulator.cpp:1163
virtual float LinearCompliance()
Gets the linear compliance of the simulation.
Definition: Simulator.cpp:776
virtual float LinearKineticLoss()
Gets the linear kinetic loss of the simulation.
Definition: Simulator.cpp:892
virtual Node * GetNode()
Gets the node.
Definition: AnimatBase.cpp:154
LightManager m_oLightMgr
Manager for the light objects.
Definition: Simulator.h:115
virtual void InitializeStructures()
Initializes all of the structures of this simulation.
Definition: Simulator.cpp:1928
bool m_bShuttingDown
True if the simulation is shutting down. This is used by other objects in their destructor to know wh...
Definition: Simulator.h:158
virtual float AngularCompliance()
Gets the angular compliance of the simulation.
Definition: Simulator.cpp:805
Declares the vortex organism class.
bool m_bForceSimulationStop
Set to true to stop the simulation. This is a more forceful way of stopping the sim.
Definition: Simulator.h:137
long m_lTimeSlice
The current time slice. This a long value.
Definition: Simulator.h:251
float m_fltAlphaThreshold
The threshold value to use when setting the AlphaFunc for the entire scene.
Definition: Simulator.h:312
bool m_bSimRunning
true if the simulation is running
Definition: Simulator.h:149
unsigned long long m_lLastTickTaken
This is the last tick taken by a GetTickCount. It is used in debugging.
Definition: Simulator.h:378
SimulationWindowMgr * m_lpWinMgr
Manager for SimulationWindows.
Definition: Simulator.h:112
virtual CStdSerialize * CreateObject(std::string strModule, std::string strClassName, std::string strType, bool bThrowError=true)
Creates an object using a class factory.
Definition: Simulator.cpp:3440
float m_fltStabilityScale
A linear scaling factor for setting the simulation parameters.
Definition: Simulator.h:210
bool m_bStopSimulation
Set to true to stop the simulation.
Definition: Simulator.h:134
virtual void AfterStepSimulation()
Method called for the base Simulator object to run code after the physics engine has been fully stepp...
Definition: Simulator.cpp:2478
virtual AnimatSim::Recording::SimulationRecorder * CreateSimulationRecorder()
Creates the simulation recorder.
virtual void ShutdownSimulation()
Shuts down the simulation.
virtual bool StartSimulation()
Starts the simulation.
DataChartMgr m_oDataChartMgr
Manager for data charts.
Definition: Simulator.h:100
int Std_GetTraceLevel()
Gets the trace level.
virtual float * GetDataPointer(const std::string &strDataType)
Returns a float pointer to a data item of interest in this object.
virtual std::string ProjectPath()
Gets the project path.
Definition: Simulator.cpp:287
virtual void StepSimulation()
Steps the entire simulation forward by one physics integration time step.
float m_fltGravity
The acceleration of gravity to use in the simulation.
Definition: Simulator.h:207
SimulationRecorder * m_lpSimRecorder
The pointer to a simulation recorder.
Definition: Simulator.h:106
Classes for implementing the cm-labs vortex physics engine for AnimatLab.
void Std_TraceMsg(const int iLevel, std::string strMessage, std::string strSourceFile, int iSourceLine, bool bLogToFile, bool bPrintHeader)
Traces a message to the debugger window.
virtual void ToggleSimulation()
Toggles the simulation between running and paused.
std::string m_strExecutablePath
The directory path where the executable is located.
Definition: Simulator.h:43
virtual void ResetSimulation()
Resets the the simulation to its orginal settings at time 0.
unsigned long long m_lStartSimTick
The tick count for when the simulation first begins running.
Definition: Simulator.h:267
virtual void Initialize()
Initializes this object with no argc/argv params.
Definition: Simulator.cpp:5304
bool Std_IsBlank(std::string strVal)
Trims a string and tests if a string is blank.
virtual void SimPausing()
Simulation pausing event.
Definition: Simulator.cpp:2739
virtual void Save(std::string strFile)
Saves the simulation file.
virtual bool Update()
Updates all of the windows.
std::string Std_CheckString(std::string strVal)
Converts a string to upper case and trims it.
Declares the vortex Light class.
virtual int GetMaterialID(std::string strID)
Gets a material identifier from the physics engine for the specified unique ID.
virtual void SnapshotStopFrame()
Takes a snapshot of the current frame.
virtual void SimStopping()
Simulation stopping event.
Definition: Simulator.cpp:2760
virtual float AngularDamping()
Gets the angular damping of the simulation.
Definition: Simulator.cpp:863
virtual float Time()
Gets the current simulation time in seconds.
Definition: Simulator.cpp:559
virtual void SimStarting()
Simulation starting event.
Definition: Simulator.cpp:2718
float m_fltPhysicsTimeStep
The time increment for each time slice of the physics simulation.
Definition: Simulator.h:278
virtual void GenerateCollisionMeshFile(std::string strOriginalMeshFile, std::string strCollisionMeshFile, float fltScaleX, float fltScaleY, float fltScaleZ)
Generates a collision mesh file.
IStdClassFactory * m_lpAnimatClassFactory
Definition: Simulator.h:78
virtual void StopSimulation()
Stops the simulation and resets it.
Declares the vortex structure class.
virtual bool PauseSimulation()
Pauses the simulation.