AnimatLab  2
Test
Simulator.cpp
Go to the documentation of this file.
1 
7 #include "StdAfx.h"
8 #include "IMovableItemCallback.h"
9 #include "ISimGUICallback.h"
10 #include "AnimatBase.h"
11 
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <time.h>
15 #include "Gain.h"
16 #include "Node.h"
17 #include "Link.h"
18 #include "IPhysicsMovableItem.h"
19 #include "IPhysicsBody.h"
20 #include "BoundingBox.h"
21 #include "MovableItem.h"
22 #include "BodyPart.h"
23 #include "Joint.h"
24 #include "ReceptiveField.h"
25 #include "ContactSensor.h"
26 #include "RigidBody.h"
27 #include "Structure.h"
28 #include "NeuralModule.h"
29 #include "Adapter.h"
30 #include "NervousSystem.h"
31 #include "Organism.h"
32 #include "ActivatedItem.h"
33 #include "ActivatedItemMgr.h"
34 #include "DataChartMgr.h"
35 #include "ExternalStimuliMgr.h"
36 #include "KeyFrame.h"
37 #include "SimulationRecorder.h"
38 #include "OdorType.h"
39 #include "Odor.h"
40 #include "Light.h"
41 #include "LightManager.h"
42 #include "Simulator.h"
43 #include "SimulationThread.h"
44 #include "SimulationMgr.h"
45 
46 namespace AnimatSim
47 {
48 
49 
50 Simulator *g_lpSimulator = NULL;
51 Simulator ANIMAT_PORT *GetSimulator()
52 {return g_lpSimulator;};
53 
61 {
62  m_bSteppingSim = false;
63  m_bShuttingDown = false;
64  m_strID = "SIMULATOR";
66  m_fltTime = 0;
67  m_fltTimeStep = -1;
69  m_fltPhysicsTimeStep = (float) 0.01;
71  m_fltPhysicsSubstepTime = (float) 0.01;
72  m_lTimeSlice = 0;
73  m_fltEndSimTime = -1;
74  m_lEndSimTimeSlice = -1;
75  m_bStopSimulation = false;
76  m_bForceSimulationStop = false;
77  m_bBlockSimulation = false;
78  m_bSimBlockConfirm = false;
82  m_iVideoLoops = 0;
85 
86  m_fltGravity = (float) -9.81;
87  m_fltDistanceUnits = (float) 0.01; //use centimeters
90  m_fltMassUnits = (float) 0.001; //use grams
92  m_fltDisplayMassUnits = 0.01f;
98  m_fltStabilityScale = 1.0;
99  m_fltLinearCompliance = 0.1e-9f;
100  m_fltAngularCompliance = 0.1e-9f;
101  m_fltLinearDamping = 50e9f;
102  m_fltAngularDamping = 5e12f;
103  m_fltLinearKineticLoss = 0.1e-9f;
104  m_fltAngularKineticLoss = 1e-12f;
105 
106  m_bForceFastMoving = true;
107  m_iSelectionMode = COLLISION_SELECTION_MODE;
108  m_bAddBodiesMode = false;
109  m_fltRecFieldSelRadius = 0.05f;
111 
112  m_bPaused = true;
113  m_bInitialized = false;
114  m_bSimRunning = false;
115  m_fltAlphaThreshold = 0.2f;
116 
117  m_lpSelOrganism = NULL;
118  m_lpSelStructure = NULL;
119  m_bManualStepSimulation = false;
120  m_lpVideoRecorder = NULL;
121  m_lpVideoPlayback = NULL;
122  m_lpSimRecorder = NULL;
123  m_lpSimStopPoint = NULL;
124  m_bEnableSimRecording = false;
126 
128  m_iManualRandomSeed = 12345;
129 
130  m_iPlaybackControlMode = PLAYBACK_MODE_MATCH_PHYSICS_STEP;
140  m_fltRealTime = 0;
149 
150  m_iDesiredFrameRate = 30;
153 
154  m_bRecordVideo = false;
155  m_strVideoFilename = "Video.avi";
157  m_fltVideoPlaybackFrameTime = 100e-3f;
159  m_fltVideoEndTime = 1;
160  m_iVideoStepSize = -1;
161  m_iVideoStepSize = 0;
162  m_lVideoStartSlice = -1;
163  m_lVideoEndSlice = -1;
164  m_lVideoFrame = 0;
165 
166  m_vBackgroundColor.Set(0.2f, 0.2f, 0.6f, 1);
167 
168  m_lpSimCallback = NULL;
169  m_lpWinMgr = NULL;
170  m_oDataChartMgr.SetSystemPointers(this, NULL, NULL, NULL, true);
171  m_oExternalStimuliMgr.SetSystemPointers(this, NULL, NULL, NULL, true);
172  m_oMaterialMgr.SetSystemPointers(this, NULL, NULL, NULL, true);
173  m_oLightMgr.SetSystemPointers(this, NULL, NULL, NULL, true);
174 
175  m_dblTotalStepTime = 0;
176  m_lStepTimeCount = 0;
177 
178  m_bInDrag = false;
179  m_bIsResetting = false;
180 
181  m_lpNeuralThread = NULL;
182  m_lpPhysicsThread = NULL;
183  m_lpIOThread = NULL;
184 
185  m_bRobotAdpaterSynch = false;
186  m_bForceNoWindows = false;
187 
188  m_lpScript = NULL;
189 }
190 
198 {
199 
200 try
201 {
202  m_bSteppingSim = false;
203  m_bShuttingDown = true;
204  g_lpSimulator = NULL;
206  m_aryOrganisms.RemoveAll();
207  m_aryStructures.RemoveAll();
208  m_aryAllStructures.RemoveAll();
209  if(m_lpSimRecorder)
210  {
211  delete m_lpSimRecorder;
212  m_lpSimRecorder = NULL;
213  }
214 
215  if(m_lpSimStopPoint)
216  {
217  delete m_lpSimStopPoint;
218  m_lpSimStopPoint = NULL;
219  }
220 
221  if(m_lpWinMgr)
222  {
223  m_lpWinMgr->Close();
224  delete m_lpWinMgr;
225  m_lpWinMgr = NULL;
226  }
227 
228  if(m_lpSimCallback)
229  {
230  //We do not own this callback.
231  m_lpSimCallback = NULL;
232  }
233 
234  //if(m_lpNeuralThread)
235  //{
236  // delete m_lpNeuralThread;
237  // m_lpNeuralThread = NULL;
238  //}
239 
240  //if(m_lpPhysicsThread)
241  //{
242  // delete m_lpPhysicsThread;
243  // m_lpPhysicsThread = NULL;
244  //}
245 
246  //if(m_lpIOThread)
247  //{
248  // delete m_lpIOThread;
249  // m_lpIOThread = NULL;
250  //}
251 
252  if(m_lpScript)
253  {
254  delete m_lpScript;
255  m_lpScript = NULL;
256  }
257 
258  m_aryNeuralModuleFactories.RemoveAll();
259 
260  m_arySourcePhysicsAdapters.RemoveAll();
261  m_aryTargetPhysicsAdapters.RemoveAll();
263  m_iExtraDataCount = 0;
264 
265  m_aryOdorTypes.RemoveAll();
266  m_aryFoodSources.RemoveAll();
267 
268  m_aryExtraDataParts.RemoveAll();
269 }
270 catch(...)
271 {Std_TraceMsg(0, "Caught Error in desctructor of Simulator\r\n", "", -1, false, true);}
272 }
273 
274 
275 #pragma region AccessorMutators
276 
277 #pragma region ProjectVariables
278 
288 
297 void Simulator::ProjectPath(std::string strPath) {m_strProjectPath = strPath;}
298 
308 
317 void Simulator::ExecutablePath(std::string strPath) {m_strExecutablePath = strPath;}
318 
328 
337 void Simulator::SimulationFile(std::string strFile) {m_strSimulationFile = strFile;}
338 
347 bool Simulator::Paused() {return m_bPaused;}
348 
360 void Simulator::Paused(bool bVal) {m_bPaused = bVal;}
361 
371 
380 void Simulator::Initialized(bool bVal) {m_bInitialized = bVal;}
381 
390 CStdMap<std::string, AnimatBase *> *Simulator::ObjectList() {return &m_aryObjectList;}
391 
401 
411 
421 
431 
441 
451 
461 
474 {
475  if(iVal <0 || iVal > SIMULATION_SELECTION_MODE)
476  THROW_PARAM_ERROR(Al_Err_lInvalidSelMode, Al_Err_strInvalidSelMode, "Selection Mode", iVal);
477 
478  m_iSelectionMode = iVal;
479 
480  //Go through and call VisualSelectionModeChanged for all objects.
481  CStdMap<std::string, AnimatBase *>::iterator oPos;
482  AnimatBase *lpBase = NULL;
483  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
484  {
485  lpBase = oPos->second;
486  if(lpBase && lpBase != this)
488  }
489 };
490 
500 
514 
526 
537 void Simulator::SimCallBack(ISimGUICallback *lpCallback) {m_lpSimCallback = lpCallback;}
538 
546 
547 #pragma endregion
548 
549 #pragma region EnvironmentVariables
550 
559 float Simulator::Time() {return m_fltTime;}
560 
569 long Simulator::Millisecond() {return (long) (Time() * 1000);}
570 
581 long Simulator::MillisecondToSlice(long lMillisecond) {return (long) (lMillisecond / (m_fltTimeStep * 1000));}
582 
593 long Simulator::SliceToMillisecond(long lSlice) {return (long) (lSlice * m_fltTimeStep * 1000);}
594 
603 unsigned long long Simulator::StartSimTick() {return m_lStartSimTick;}
604 
614 
623 void Simulator::TimeSlice(long lVal) {m_lTimeSlice = lVal;}
624 
634 
644 
654 
664 
674 
686 
696 
706 
716 
726 
736 
746 
756 
765 void Simulator::StabilityScale(float fltVal) {m_fltStabilityScale = fltVal;}
766 
767 
777 
787 void Simulator::LinearCompliance(float fltVal, bool bUseScaling)
788 {
789  Std_IsAboveMin((float) 0, fltVal, true, "LinearCompliance");
790 
791  if(bUseScaling)
792  fltVal *= m_fltMassUnits;
793 
794  m_fltLinearCompliance = fltVal;
795 }
796 
806 
816 void Simulator::AngularCompliance(float fltVal, bool bUseScaling)
817 {
818  Std_IsAboveMin((float) 0, fltVal, true, "AngularCompliance");
819 
820  if(bUseScaling)
822 
823  m_fltAngularCompliance = fltVal;
824 }
825 
835 
845 void Simulator::LinearDamping(float fltVal, bool bUseScaling)
846 {
847  Std_IsAboveMin((float) 0, fltVal, true, "LinearDamping");
848 
849  if(bUseScaling)
850  fltVal = fltVal/this->DisplayMassUnits();
851 
852  m_fltLinearDamping = fltVal;
853 }
854 
864 
874 void Simulator::AngularDamping(float fltVal, bool bUseScaling)
875 {
876  Std_IsAboveMin((float) 0, fltVal, true, "AngularDamping");
877 
878  if(bUseScaling)
879  fltVal = fltVal/this->DisplayMassUnits();
880 
881  m_fltAngularDamping = fltVal;
882 }
883 
893 
902 void Simulator::LinearKineticLoss(float fltVal, bool bUseScaling)
903 {
904  Std_IsAboveMin((float) 0, fltVal, true, "LinearKineticLoss");
905 
906  if(bUseScaling)
907  fltVal = fltVal * this->DisplayMassUnits();
908 
909  m_fltLinearKineticLoss = fltVal;
910 }
911 
921 
930 void Simulator::AngularKineticLoss(float fltVal, bool bUseScaling)
931 {
932  Std_IsAboveMin((float) 0, fltVal, true, "AngularKineticLoss");
933 
934  if(bUseScaling)
935  fltVal = fltVal * this->DisplayMassUnits();
936 
937  m_fltAngularKineticLoss = fltVal;
938 }
939 
940 
952 {return m_fltTimeStep;}
953 
963 
972 void Simulator::SetEndSimTime(bool bVal) {m_bSetEndSim = bVal;}
973 
983 
992 void Simulator::EndSimTime(float fltVal)
993 {
994  Std_IsAboveMin((float) 0, fltVal, true, "EndSimTime");
995 
996  m_fltEndSimTime = fltVal;
998 }
999 
1009 
1019 {
1020  Std_IsAboveMin((long) 0, lVal, true, "EndSimTimeSlice");
1021 
1022  m_lEndSimTimeSlice = lVal;
1024 }
1025 
1035 
1045 
1057 
1067 {
1068  Std_IsAboveMin((int) 0, iVal, true, "FrameRate");
1069 
1070  m_iDesiredFrameRate = iVal;
1071  m_fltDesiredFrameStep = ((1/ (float) m_iDesiredFrameRate)*1);
1072 }
1073 
1074 
1083 {return m_fltRealTime;}
1084 
1098 
1112 {
1113  if(iVal == 0) iVal = 1;
1114  Std_IsAboveMin((int) 0, (int) iVal, true, "PhysicsStepInterval");
1115  m_iPhysicsStepInterval = iVal;
1116 }
1117 
1126 void Simulator::PhysicsTimeStep(float fltVal)
1127 {
1128  Std_IsAboveMin((float) 0, fltVal, true, "PhysicsTimeStep");
1129 
1130  //Set it so that it will be taken into consideration when finding min value.
1131  m_fltPhysicsTimeStep = fltVal;
1132 
1133  //Find min time step.
1134  float fltMin = MinTimeStep();
1135 
1136  if(fltMin > 0 && m_iPhysicsSubsteps > 0)
1137  {
1138  //Division
1139  int iDiv = (int) ((fltVal / fltMin) + 0.5f);
1140 
1141  //Find the number of timeslices that need to occur before the physics system is updated
1142  PhysicsStepInterval(iDiv);
1143 
1144  //Now recaculate the physics time step using the minimum time step as the base.
1146 
1147  //Now reset the m_fltTimeStep of the sim.
1148  if(m_iPhysicsStepInterval == 1) fltMin = MinTimeStep();
1149 
1150  //Reset the physics substep time if required.
1152  }
1153 }
1154 
1164 
1177 
1190 {
1191  Std_IsAboveMin((int) 0, iVal, true, "PhysicsSubsteps");
1192 
1193  m_iPhysicsSubsteps = iVal;
1195 }
1196 
1206 
1216 
1226 
1236 void Simulator::Gravity(float fltVal, bool bUseScaling)
1237 {
1238  //We must convert the gravity to use the correct scale.
1239  if(bUseScaling)
1240  fltVal /= m_fltDistanceUnits;
1241 
1242  m_fltGravity = fltVal;
1243 }
1244 
1256 
1266 void Simulator::MouseSpringStiffness(float fltVal, bool bUseScaling)
1267 {
1268  Std_IsAboveMin((float) 0, fltVal, true, "MouseSpringStiffness", true);
1269 
1270  if(bUseScaling)
1271  fltVal *= this->InverseMassUnits();
1272 
1273  m_fltMouseSpringStiffness = fltVal;
1274 }
1275 
1287 
1297 void Simulator::MouseSpringDamping(float fltVal, bool bUseScaling)
1298 {
1299  Std_IsAboveMin((float) 0, fltVal, true, "MouseSpringDamping", true);
1300 
1301  if(bUseScaling)
1302  fltVal = fltVal/this->DisplayMassUnits();
1303  m_ftlMouseSpringDamping = fltVal;
1304 }
1305 
1315 
1325 void Simulator::MouseSpringForceMagnitude(float fltVal, bool bUseScaling)
1326 {
1327  //We must convert the gravity to use the correct scale.
1328  if(bUseScaling)
1329  fltVal /= (InverseMassUnits() * InverseDistanceUnits());
1330 
1332 }
1333 
1343 
1353 void Simulator::MouseSpringDampingForceMagnitude(float fltVal, bool bUseScaling)
1354 {
1355  //We must convert the gravity to use the correct scale.
1356  if(bUseScaling)
1357  fltVal /= (InverseMassUnits() * InverseDistanceUnits());
1358 
1360 }
1361 
1371 
1381 void Simulator::MouseSpringLengthMagnitude(float fltVal, bool bUseScaling)
1382 {
1383  if(bUseScaling)
1385  else
1387 }
1388 
1403 
1418 {
1419  m_bSimulateHydrodynamics = bVal;
1420 }
1421 
1434 int Simulator::GetMaterialID(std::string strID) {return -1;}
1435 
1445 {
1447  return true;
1448  else
1449  return false;
1450 }
1451 
1461 
1471 {
1472  m_vBackgroundColor = aryColor;
1474 }
1475 
1484 void Simulator::BackgroundColor(float *aryColor)
1485 {
1486  CStdColor vColor(aryColor[0], aryColor[1], aryColor[2], aryColor[3], 1);
1487  BackgroundColor(vColor);
1488 }
1489 
1498 void Simulator::BackgroundColor(std::string strXml)
1499 {
1500  CStdColor vColor(1);
1501  vColor.Load(strXml, "Color");
1502  BackgroundColor(vColor);
1503 }
1504 
1505 float Simulator::AlphaThreshold() {return m_fltAlphaThreshold;}
1506 
1507 void Simulator::AlphaThreshold(float fltValue)
1508 {
1509  Std_InValidRange((float) 0, (float) 1, fltValue, true, "AlphaThreshold");
1510  m_fltAlphaThreshold = fltValue;
1511 }
1512 
1513 float Simulator::RecFieldSelRadius() {return m_fltRecFieldSelRadius;}
1514 
1515 void Simulator::RecFieldSelRadius(float fltValue, bool bUseScaling, bool bUpdateAllBodies)
1516 {
1517  if(bUseScaling)
1518  m_fltRecFieldSelRadius = fltValue * this->InverseDistanceUnits();
1519  else
1520  m_fltRecFieldSelRadius = fltValue;
1521 
1522  if(bUpdateAllBodies)
1523  {
1524  CStdMap<std::string, AnimatBase *>::iterator oPos;
1525  AnimatBase *lpBase = NULL;
1526  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
1527  {
1528  lpBase = oPos->second;
1529  IPhysicsBody *lpBody = dynamic_cast<IPhysicsBody *>(lpBase);
1530  if(lpBody && lpBase != this)
1531  lpBody->Physics_ResizeSelectedReceptiveFieldVertex();
1532  }
1533  }
1534 }
1535 
1536 
1560 {return m_iPlaybackControlMode;}
1561 
1586 {
1587  if(iMode != PLAYBACK_MODE_FASTEST_POSSIBLE && iMode != PLAYBACK_MODE_MATCH_PHYSICS_STEP && iMode != PLAYBACK_MODE_PRESET_VALUE)
1588  THROW_PARAM_ERROR(Al_Err_lInvalidPlaybackMode, Al_Err_strInvalidPlaybackMode, "Mode", STR(iMode));
1589 
1590  m_iPlaybackControlMode = iMode;
1591 }
1592 
1605 
1617 void Simulator::PresetPlaybackTimeStep(float fltTimeStep)
1618 {
1619  if(fltTimeStep < 0)
1620  THROW_PARAM_ERROR(Al_Err_lInvalidPresetPlaybackTimeStep, Al_Err_strInvalidPresetPlaybackTimeStep, "Time Step", STR((float) fltTimeStep));
1621 
1622  m_fltPresetPlaybackTimeStep = fltTimeStep;
1623 }
1624 
1625 unsigned long long Simulator::StepStartTick()
1626 {return m_lStepStartTick;}
1627 
1628 unsigned long long Simulator::StepSimEndTick()
1629 {return m_lStepSimEndTick;}
1630 
1631 double Simulator::CurrentRealTimeForStep_n()
1632 {return TimerDiff_u(m_lStepStartTick, GetTimerTick());}
1633 
1634 double Simulator::CurrentRealTimeForStep_s()
1635 {return TimerDiff_s(m_lStepStartTick, GetTimerTick());}
1636 
1646 
1656 {
1657  m_bRobotAdpaterSynch = bVal;
1658 }
1659 
1673 bool Simulator::InSimulation() {return true;}
1674 
1675 
1676 bool Simulator::ForceNoWindows() {return m_bForceNoWindows;}
1677 
1678 void Simulator::ForceNoWindows(bool bVal)
1679 {
1680  m_bForceNoWindows = bVal;
1681 
1682  if(bVal && m_lpWinMgr)
1684 }
1685 
1686 void Simulator::Script(ScriptProcessor *lpScript)
1687 {
1688  if(m_lpScript)
1689  {
1690  delete m_lpScript;
1691  m_lpScript = NULL;
1692  }
1693 
1694  m_lpScript = lpScript;
1695 }
1696 
1697 ScriptProcessor *Simulator::Script() {return m_lpScript;}
1698 
1699 #pragma endregion
1700 
1701 #pragma region UnitScalingVariables
1702 
1717 void Simulator::DistanceUnits(std::string strUnits)
1718 {
1722 }
1723 
1733 
1743 
1757 
1772 void Simulator::MassUnits(std::string strUnits)
1773 {
1774  m_fltMassUnits = ConvertMassUnits(strUnits);
1777 }
1778 
1788 
1798 
1811 
1812 #pragma endregion
1813 
1814 #pragma region RecordingVariables
1815 
1825 
1835 
1845 
1854 void Simulator::VideoLoops(int iVal) {m_iVideoLoops = iVal;}
1855 
1856 
1858 void Simulator::VideoRecorder(KeyFrame *lpFrame) {m_lpVideoRecorder = lpFrame;}
1859 
1861 void Simulator::VideoPlayback(KeyFrame *lpFrame) {m_lpVideoPlayback = lpFrame;}
1862 
1872 
1882 
1892 
1893 #pragma endregion
1894 
1895 #pragma endregion
1896 
1897 #pragma region Methods
1898 
1899 #pragma region SimulationMethods
1900 
1908 {
1909  //Set the random number generator seed
1911  GenerateAutoSeed();
1912  else
1913  {
1915  srand(m_iManualRandomSeed);
1916  }
1917 }
1918 
1929 {
1930  //if(!m_lpNeuralThread)
1931  // m_lpNeuralThread = new ThreadProcessor();
1932 
1933  //if(!m_lpPhysicsThread)
1934  // m_lpPhysicsThread = new ThreadProcessor();
1935 
1936  //if(!m_lpNeuralThread)
1937  // m_lpNeuralThread = new ThreadProcessor();
1938 
1940 
1942 
1943  //We need to rerun the code to set the physics time step here in initialize. The reason is that we set this when
1944  //loading the simulator and neural modules, but if one of the neural modules has the miniumum time step then
1945  //we need to recalculate the time slice per step for all modules in initialize after everything has loaded.
1946  // Once everything is loaded and initialized, then if a given time step is changed then that one is changed in
1947  // the sim, and events will change it for the rest of them afterwards, so the values should be correct.
1949 
1950  CStdMap<std::string, Structure *>::iterator oPos;
1951  Structure *lpStructure = NULL;
1952  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
1953  {
1954  lpStructure = oPos->second;
1955  lpStructure->Create();
1956  }
1957 
1960 
1961  if(m_bRecordVideo)
1962  {
1966  m_iVideoStep = 0;
1967 
1968  //First lets check if there is already an existing video file with that same
1969  //name. If there is then get rid of it.
1970  std::string strVideoFile = m_strProjectPath + m_strVideoFilename;
1971  struct stat f__stat;
1972  bool bFileExists = (stat(strVideoFile.c_str(), &f__stat) != 0);
1973  if(bFileExists)
1974  remove(strVideoFile.c_str( ));
1975  }
1976 
1977  if(m_lpScript)
1978  m_lpScript->Initialize();
1979 }
1980 
1988 {
1989  //Go through and call TimeStepModified for all objects.
1990  CStdMap<std::string, AnimatBase *>::iterator oPos;
1991  AnimatBase *lpBase = NULL;
1992  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
1993  {
1994  lpBase = oPos->second;
1995  if(lpBase && lpBase != this)
1996  lpBase->TimeStepModified();
1997  }
1998 }
1999 
2000 
2001 void Simulator::NotifyRigidBodyAdded(std::string strID)
2002 {
2003  CStdMap<std::string, AnimatBase *>::iterator oPos;
2004  AnimatBase *lpBase = NULL;
2005  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
2006  {
2007  lpBase = oPos->second;
2008  if(lpBase)
2009  lpBase->RigidBodyAdded(strID);
2010  }
2011 }
2012 
2013 void Simulator::NotifyRigidBodyRemoved(std::string strID)
2014 {
2015  CStdMap<std::string, AnimatBase *>::iterator oPos;
2016  AnimatBase *lpBase = NULL;
2017  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
2018  {
2019  lpBase = oPos->second;
2020  if(lpBase)
2021  lpBase->RigidBodyRemoved(strID);
2022  }
2023 }
2024 
2037 
2049 
2063 
2080 {
2081  if(!m_bSteppingSim)
2082  return true;
2083 
2084  m_bBlockSimulation = true;
2085  long lTime = 0;
2086  bool bDone = false;
2087  while(!bDone)
2088  {
2089  if(!m_bSimBlockConfirm)
2090  {
2091  Std_Sleep(10);
2092 
2093  lTime+=10;
2094  if(lTimeout > 0 && lTime >= lTimeout)
2095  {
2096  bDone = true;
2097  m_bBlockSimulation = false;
2098  }
2099  }
2100  else
2101  bDone = true;
2102  }
2103 
2104  return m_bSimBlockConfirm;
2105 }
2106 
2120 {
2121  if(m_bBlockSimulation)
2122  {
2123  m_bSimBlockConfirm = true;
2124  Std_Sleep(1);
2125  }
2126  else
2127  m_bSimBlockConfirm = false;
2128 
2129  return m_bSimBlockConfirm;
2130 }
2131 
2142 {
2143  m_bShuttingDown = true;
2144  m_fltTime = 0;
2145  m_fltTimeStep = -1;
2147  m_fltPhysicsTimeStep = (float) 0.01;
2148  m_iPhysicsSubsteps = 1;
2149  m_fltPhysicsSubstepTime = (float) 0.01;
2150  m_iPhysicsStepCount = 0;
2151  m_lTimeSlice = 0;
2152  m_fltEndSimTime = -1;
2154  m_lVideoSliceCount = 0;
2155  m_iVideoLoops = 0;
2156  m_bSimulateHydrodynamics = false;
2157  m_fltGravity = (float) -9.8;
2158  m_fltDistanceUnits = (float) 0.01; //use centimeters
2161  m_fltMassUnits = (float) 0.001; //use grams
2163  m_fltDisplayMassUnits = 0.01f;
2165  m_ftlMouseSpringDamping = 2.8f;
2169  m_fltStabilityScale = 1.0;
2170  m_fltLinearCompliance = 0.1e-9f;
2171  m_fltAngularCompliance = 0.1e-9f;
2172  m_fltLinearDamping = 50e9f;
2173  m_fltAngularDamping = 5e12f;
2174  m_fltLinearKineticLoss = 0.1e-9f;
2175  m_fltAngularKineticLoss = 1e-12f;
2176  m_iPhysicsBodyCount = 0;
2177 
2178  m_bForceFastMoving = true;
2179  m_bSteppingSim = false;
2180 
2181  if(m_lpWinMgr)
2182  m_lpWinMgr->Close();
2183 
2185  m_aryOrganisms.RemoveAll();
2186  m_aryStructures.RemoveAll();
2187  m_aryAllStructures.RemoveAll();
2188  m_lpVideoRecorder = NULL; //Do not delete this object. It is in the list of Keyframes.
2189  m_lpVideoPlayback = NULL; //Do not delete this object. It is in the list of Keyframes.
2190  m_bEnableSimRecording = false;
2191  m_lSnapshotByteSize = 0;
2192  m_iPlaybackControlMode = PLAYBACK_MODE_MATCH_PHYSICS_STEP;
2202  m_fltRealTime = 0;
2211 
2212  m_iDesiredFrameRate = 30;
2215 
2216  m_bPaused = true;
2217  m_bInitialized = false;
2218  m_bSimRunning = false;
2219 
2220  m_bRecordVideo = false;
2221  m_strVideoFilename = "Video.avi";
2222  m_fltVideoRecordFrameTime = 1e-3f;
2223  m_fltVideoPlaybackFrameTime = 100e-3f;
2224  m_fltVideoStartTime = 0;
2225  m_fltVideoEndTime = 1;
2226  m_iVideoStepSize = -1;
2227  m_iVideoStepSize = 0;
2228  m_lVideoStartSlice = -1;
2229  m_lVideoEndSlice = -1;
2230  m_lVideoFrame = 0;
2231 
2235  m_oLightMgr.Reset();
2236  if(m_lpSimRecorder)
2237  {
2238  delete m_lpSimRecorder;
2239  m_lpSimRecorder = NULL;
2240  }
2241 
2242  if(m_lpSimStopPoint)
2243  {
2244  delete m_lpSimStopPoint;
2245  m_lpSimStopPoint = NULL;
2246  }
2247 
2248  if(m_lpSimCallback)
2249  {
2250  //We do not own this callback.
2251  m_lpSimCallback = NULL;
2252  }
2253 
2254  //if(m_lpNeuralThread)
2255  //{
2256  // delete m_lpNeuralThread;
2257  // m_lpNeuralThread = NULL;
2258  //}
2259 
2260  //if(m_lpPhysicsThread)
2261  //{
2262  // delete m_lpPhysicsThread;
2263  // m_lpPhysicsThread = NULL;
2264  //}
2265 
2266  //if(m_lpIOThread)
2267  //{
2268  // delete m_lpIOThread;
2269  // m_lpIOThread = NULL;
2270  //}
2271 
2272  if(m_lpScript)
2273  {
2274  delete m_lpScript;
2275  m_lpScript = NULL;
2276  }
2277 
2278  m_aryNeuralModuleFactories.RemoveAll();
2279 
2280  m_arySourcePhysicsAdapters.RemoveAll();
2281  m_aryTargetPhysicsAdapters.RemoveAll();
2283  m_iExtraDataCount = 0;
2284 
2285  m_aryOdorTypes.RemoveAll();
2286  m_aryFoodSources.RemoveAll();
2287 
2288  m_aryExtraDataParts.RemoveAll();
2289 
2290  //Reference pointers only
2291  m_lpSelOrganism = NULL;
2292  m_lpSelStructure = NULL;
2293  m_bShuttingDown = false;
2294 
2295  m_bRobotAdpaterSynch = false;
2296 }
2297 
2305 {
2306  m_bIsResetting = true;
2307  m_fltTime = 0;
2308  m_lTimeSlice = 0;
2310  m_lVideoSliceCount = 0;
2311  m_iPhysicsStepCount = 0;
2312  m_bPaused = true;
2313  m_bSimRunning = false;
2317 
2319 
2320  CStdMap<std::string, Structure *>::iterator oPos;
2321  Structure *lpStructure = NULL;
2322  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
2323  {
2324  lpStructure = oPos->second;
2325  lpStructure->ResetSimulation();
2326  }
2327 
2328  int iSize = m_arySourcePhysicsAdapters.GetSize();
2329  for(int iIndex=0; iIndex<iSize; iIndex++)
2331 
2332  iSize = m_aryTargetPhysicsAdapters.GetSize();
2333  for(int iIndex=0; iIndex<iSize; iIndex++)
2335 
2340 
2341  if(m_lpSimRecorder)
2343 
2344  if(m_lpScript)
2345  m_lpScript->ResetSimulation();
2346 
2347  m_bIsResetting = false;
2348 }
2349 
2350 float Simulator::MinTimeStep()
2351 {
2353  CStdMap<std::string, Structure *>::iterator oPos;
2354  Structure *lpStructure = NULL;
2355  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
2356  {
2357  lpStructure = oPos->second;
2358  lpStructure->MinTimeStep(m_fltTimeStep);
2359  }
2360 
2361  return m_fltTimeStep;
2362 }
2363 
2364 void Simulator::MicroWait(unsigned int iMicroTime)
2365 {
2366  //std::cout << "MicroWait: " << iMicroTime << "\r\n";
2367  unsigned long long lStart = GetTimerTick();
2368  int iRemaining = iMicroTime;
2369  int iCount=0;
2370 
2371  while(iRemaining > 0)
2372  {
2373  iRemaining = iMicroTime - (unsigned int) TimerDiff_u(lStart, GetTimerTick());
2374 
2375  iCount++;
2377  if(iCount == 10000)
2378  THROW_ERROR(Al_Err_lTimedOutInMicroWait, Al_Err_strTimedOutInMicroWait);
2379  }
2380 
2381  //unsigned int iWait = (unsigned int) TimerDiff_u(lStart, GetTimerTick());
2382  //std::cout << "Waited: " << iWait << "\r\n";
2383 }
2384 
2385 void Simulator::StepPlaybackControl()
2386 {
2387  RecordSimulationStepTimer();
2388 
2389  //If paused or stepping fastest possible then just step the video frame and exit.
2390  if(m_bPaused || m_iPlaybackControlMode == PLAYBACK_MODE_FASTEST_POSSIBLE
2391  || (m_iPlaybackControlMode == PLAYBACK_MODE_PRESET_VALUE && m_fltPresetPlaybackTimeStep <= 0))
2392  StepVideoFrame();
2393  else
2394  {
2395  double dblRemainingTime = 0;
2396 
2397  do {
2398  dblRemainingTime = (CalculateRemainingPlaybackTime()); //scale the remaining time back by 10% to account for the time of other things.
2399 
2400  if(dblRemainingTime > 0)
2401  {
2402  if(dblRemainingTime > m_fltDesiredFrameStep)
2403  {
2406  //MicroSleep(m_fltDesiredFrameStep*1000000);
2407  }
2408  else if(dblRemainingTime > 100e-6)
2409  {
2410  m_fltTotalMicroSleepTime+=dblRemainingTime;
2412  //MicroSleep(dblRemainingTime*1000000);
2413  }
2414  else
2415  {
2416  m_fltTotalMicroWaitTime+=dblRemainingTime;
2417  //MicroWait(dblRemainingTime*1000000);
2418  }
2419  }
2420 
2421  StepVideoFrame();
2422 
2423  } while(dblRemainingTime > 0);
2424  }
2425 
2426  RecordAddedPlaybackTime();
2427 }
2428 
2429 void Simulator::StepVideoFrame()
2430 {
2431  double dblTime = TimeBetweenVideoFrames();
2432  //std::cout << "Stepping video. between: " << dblTime << "\r\n";
2433  if(dblTime > m_fltDesiredFrameStep)
2434  {
2435  UpdateSimulationWindows();
2436  StartVideoFrameTimer();
2437  }
2438  else if(m_bPaused)
2439  MicroSleep((unsigned int) (RemainingVideoFrameTime()*1000000));
2440 }
2441 
2442 
2450 {
2451  unsigned long long lStart = GetTimerTick();
2452 
2453  if(m_lpScript)
2454  m_lpScript->BeforeStepNeuralEngine();
2455 
2456  for(m_oOrganismIterator=m_aryOrganisms.begin();
2459  {
2462  }
2463 
2464  if(m_lpScript)
2465  m_lpScript->AfterStepNeuralEngine();
2466 
2467  m_fltTotalNeuralStepTime += TimerDiff_s(lStart, GetTimerTick());
2468 }
2469 
2479 {
2480  //Now lets look thorugh all of the parts that have been tagged as needing to gather extra data
2481  //and make the call to allow them to do that.
2482  //This must be done after the physics step simulation is called in order to get any force info
2483  // added by the physics engine itself for this time step.
2484  for(int iIndex=0; iIndex<m_iExtraDataCount; iIndex++)
2485  m_aryExtraDataParts[iIndex]->UpdateExtraData();
2486 
2487  if(m_lpScript)
2488  m_lpScript->AfterStepPhysicsEngine();
2489 
2490 }
2491 
2499 {
2500  unsigned long long lStart = GetTimerTick();
2501 
2502  if(m_lpScript)
2503  m_lpScript->BeforeStepPhysicsEngine();
2504 
2508  {
2511  }
2512 
2513  for(int iIndex=0; iIndex<m_iTargetAdapterCount; iIndex++)
2515 
2516  if(m_bRecordVideo)
2517  RecordVideoFrame();
2518 
2520 
2521  m_fltPhysicsStepTime += TimerDiff_s(lStart, GetTimerTick());
2522 }
2523 
2524 void Simulator::StepExternalStimuli()
2525 {
2526  unsigned long long lStart = GetTimerTick();
2527 
2529 
2530  m_fltExternalStimuliStepTime += TimerDiff_s(lStart, GetTimerTick());
2531 }
2532 
2533 void Simulator::StepDataCharts()
2534 {
2535  unsigned long long lStart = GetTimerTick();
2536 
2538 
2539  m_fltDataChartStepTime += TimerDiff_s(lStart, GetTimerTick());
2540 }
2541 
2542 void Simulator::StepSimRecorder()
2543 {
2544  unsigned long long lStart = GetTimerTick();
2545 
2547 
2548  m_fltSimRecorderStepTime += TimerDiff_s(lStart, GetTimerTick());
2549 }
2550 
2558 {
2559  StepExternalStimuli();
2560 
2563 
2564  StepNeuralEngine();
2565 
2566  if(m_lpSimRecorder)
2567  StepSimRecorder();
2568 
2569  //Must be last in order to get all data changes that were previously made.
2570  StepDataCharts();
2571 
2572  m_lTimeSlice++;
2573 
2575 }
2576 
2583 {
2591 }
2592 
2610 {
2613  Step();
2614 }
2615 
2623 {
2624  //Initialize all of our epoch counters at the start of the simulation so we do not get assertions on times being wrong.
2625  m_lStartSimTick = GetTimerTick();
2630 
2631  m_bSteppingSim = true;
2632 
2633  std::cout << "starting sim" << "\r\n";
2634 }
2635 
2643 {
2644 }
2645 
2653 {
2654  try
2655  {
2656  //If we are blocking the simulation stepping code for multi-threaded access then don't do this code..
2657  if(!CheckSimulationBlock())
2658  {
2659  StartSimulationStepTimer();
2660  StepSimulation();
2661  StepPlaybackControl();
2662 
2664  RecordSimulationTotalStepTimer();
2665  }
2666  }
2667  catch(CStdErrorInfo oError)
2668  {
2669  //A critical simulation error has occurred if we catch an exception here. We need to shut the app down.
2670  std::string strError = "An error occurred while stepping the simulation.\nError: " + oError.m_strError;
2671  HandleNonCriticalError(strError);
2672  }
2673  catch(...)
2674  {
2675  //A critical simulation error has occurred if we catch an exception here. We need to shut the app down.
2676  HandleCriticalError(Al_Err_strCriticalSimError);
2677  }
2678 }
2679 
2681 {
2682  SimulateBegin();
2683 
2684  do
2685  {
2687  }
2689 
2690  SimulateEnd();
2691 }
2692 
2703 {
2704  Load(SimulationFile());
2705  Initialize(0, NULL);
2706  Simulate();
2707 }
2708 
2719 {
2720  CStdMap<std::string, AnimatBase *>::iterator oPos;
2721  AnimatBase *lpBase = NULL;
2722  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
2723  {
2724  lpBase = oPos->second;
2725  if(lpBase != this)
2726  lpBase->SimStarting();
2727  }
2728 }
2729 
2740 {
2741  CStdMap<std::string, AnimatBase *>::iterator oPos;
2742  AnimatBase *lpBase = NULL;
2743  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
2744  {
2745  lpBase = oPos->second;
2746  if(lpBase != this)
2747  lpBase->SimPausing();
2748  }
2749 }
2750 
2761 {
2762  CStdMap<std::string, AnimatBase *>::iterator oPos;
2763  AnimatBase *lpBase = NULL;
2764  for(oPos=m_aryObjectList.begin(); oPos!=m_aryObjectList.end(); ++oPos)
2765  {
2766  lpBase = oPos->second;
2767  if(lpBase != this)
2768  lpBase->SimStopping();
2769  }
2770 
2771  WriteToConsole("Simulation stopped. Time: " + STR(m_fltTime));
2772 }
2773 
2774 void Simulator::HandleCriticalError(std::string strError)
2775 {
2776  WriteToConsole("Critical error occurred: " + strError);
2777  this->ShutdownSimulation();
2778  if(m_lpSimCallback)
2779  m_lpSimCallback->HandleCriticalError(Al_Err_strCriticalSimError);
2780 
2781 }
2782 
2783 void Simulator::HandleNonCriticalError(std::string strError)
2784 {
2785  WriteToConsole("Non critical error occurred: " + strError);
2786  this->ResetSimulation();
2787  if(m_lpSimCallback)
2789 }
2790 
2791 void Simulator::StartSimulationStepTimer()
2792 {
2793  m_lStepStartTick = GetTimerTick();
2795  //std::cout << "Real Time: " << m_fltRealTime << "\r\n";
2796 }
2797 
2798 void Simulator::RecordSimulationStepTimer()
2799 {
2800  m_lStepSimEndTick = GetTimerTick();
2802 
2808 }
2809 
2810 void Simulator::RecordSimulationTotalStepTimer()
2811 {
2812  unsigned long long lEnd = GetTimerTick();
2814  m_fltTotalRealTimeForStep = (float) TimerDiff_s(m_lStepStartTick, lEnd);
2815 
2817 
2819 
2820  if(m_lTimeSlice > 10 && m_lTimeSlice < 5000)
2821  {
2823  m_lStepTimeCount++;
2824  }
2825  else if(m_lTimeSlice == 5000)
2826  {
2827  double dblAvgStepTime = m_dblTotalStepTime/m_lStepTimeCount;
2828  //WriteToConsole("Average total step time: " + STR(dblAvgStepTime));
2829  }
2830 
2831 }
2832 
2833 double Simulator::CalculateRemainingPlaybackTime()
2834 {
2835  if(m_iPlaybackControlMode == PLAYBACK_MODE_FASTEST_POSSIBLE)
2836  return 0;
2837  else if(m_iPlaybackControlMode == PLAYBACK_MODE_MATCH_PHYSICS_STEP)
2838  return m_fltPhysicsTimeStep - CurrentRealTimeForStep_s();
2839  else
2840  return m_fltPresetPlaybackTimeStep - CurrentRealTimeForStep_s();
2841 }
2842 
2843 void Simulator::RecordAddedPlaybackTime()
2844 {
2845  unsigned long long lEnd = GetTimerTick();
2846  m_fltPlaybackAdditionRealTimeToStep = (float) TimerDiff_s(m_lStepSimEndTick, lEnd);
2847 }
2848 
2849 void Simulator::StartVideoFrameTimer()
2850 {
2851  double dblTime = TimeBetweenVideoFrames();
2852  m_fltActualFrameRate = (float) 1.0/(dblTime);
2853  m_lVideoFrameStartTick = GetTimerTick();
2854 }
2855 
2856 double Simulator::TimeBetweenVideoFrames()
2857 {
2858  double dblTime = TimerDiff_s(m_lVideoFrameStartTick, GetTimerTick());
2859  return dblTime;
2860 }
2861 
2862 double Simulator::RemainingVideoFrameTime()
2863 {
2864  double dblRemaining = (m_fltDesiredFrameStep - TimeBetweenVideoFrames());
2865  if(dblRemaining < 0) dblRemaining = 0;
2866  return dblRemaining;
2867 }
2868 
2869 
2877 {
2878  //NEED TO TEST
2879  time_t rawtime;
2880  struct tm * timeinfo;
2881 
2882  time ( &rawtime );
2883  timeinfo = localtime ( &rawtime );
2884 
2885  m_iManualRandomSeed = (unsigned) (timeinfo->tm_sec + timeinfo->tm_hour + Std_IRand(0, 1000));
2887  srand(m_iManualRandomSeed);
2888 }
2889 
2903 {
2904  //If we are running for a set time then lets stop once we reach that point.
2905  if(m_bSetEndSim && !m_bPaused)
2906  {
2907  if(m_fltEndSimTime >0 && this->Time() >= m_fltEndSimTime)
2908  {
2909  if(m_lpSimCallback)
2910  {
2911  PauseSimulation();
2913  }
2914  else
2916  }
2917  }
2918 }
2919 
2920 #pragma endregion
2921 
2922 #pragma region LoadMethods
2923 
2924 
2933 void Simulator::Load(std::string strFileName)
2934 {
2935  CStdXml oXml;
2936 
2937  TRACE_DEBUG("Loading simulator config file.\r\nFileName: " + strFileName);
2938 
2939  if(Std_IsBlank(strFileName))
2940  {
2942  THROW_ERROR(Al_Err_lSimFileBlank, Al_Err_strSimFileBlank);
2943  }
2944  else
2945  m_strSimulationFile = strFileName;
2946 
2947  oXml.Load(AnimatSim::GetFilePath(m_strProjectPath, m_strSimulationFile));
2948 
2949  oXml.FindElement("Simulation");
2950  oXml.FindChildElement("");
2951 
2952  Load(oXml);
2953 
2954  TRACE_DEBUG("Finished loading simulator config file.");
2955 }
2956 
2965 void Simulator::Save(std::string strFilename) {};
2966 
2967 
2969 {
2970  TRACE_DEBUG("Loading simulator config from Xml.");
2971 
2972  Reset();
2973 
2974  AddToObjectList(this);
2975 
2977  m_strProjectPath = oXml.GetChildString("ProjectPath", "");
2978 
2979  //m_lUpdateDataInterval = oXml.GetChildLong("UpdateDataInterval", m_lUpdateDataInterval);
2980  m_bPaused = oXml.GetChildBool("StartPaused", m_bPaused);
2981  m_bEnableSimRecording = oXml.GetChildBool("EnableSimRecording", m_bEnableSimRecording);
2982 
2983  SetEndSimTime(oXml.GetChildBool("SetSimEnd", false));
2984  EndSimTime(oXml.GetChildFloat("SimEndTime", m_fltEndSimTime));
2985 
2986  PlaybackControlMode(oXml.GetChildInt("PlaybackControlMode", m_iPlaybackControlMode));
2987  PresetPlaybackTimeStep(oXml.GetChildFloat("PresetPlaybackTimeStep", m_fltPresetPlaybackTimeStep));
2988 
2991 
2992  //Other stuff Later
2993  LoadEnvironment(oXml);
2994  m_oDataChartMgr.Load(oXml);
2995 
2996  if(m_lpWinMgr)
2997  m_lpWinMgr->Load(oXml);
2998 
2999  if(oXml.FindChildElement("ExternalStimuli", false))
3000  m_oExternalStimuliMgr.Load(oXml);
3001 
3002  if(m_lpSimRecorder && oXml.FindChildElement("RecorderKeyFrames", false))
3003  m_lpSimRecorder->Load(oXml);
3004 
3005  TRACE_DEBUG("Finished loading simulator config from Xml.");
3006 }
3007 
3019 IStdClassFactory *Simulator::LoadClassFactory(std::string strModuleName, bool bThrowError)
3020 {
3021  IStdClassFactory *lpFactory=NULL;
3022 
3023 try
3024 {
3025 #ifdef WIN32
3026  int iFindDebug = Std_ToLower(strModuleName).find("_vc10d");
3027  if(iFindDebug == -1) iFindDebug = Std_ToLower(strModuleName).find("_d.");
3028 #else
3029  int iFindDebug = Std_ToLower(strModuleName).find("_debug");
3030  if(iFindDebug == -1) iFindDebug = Std_ToLower(strModuleName).find("_d.");
3031 #endif
3032 
3033 #ifdef _DEBUG
3034  if(iFindDebug == -1 )
3035  {
3036  if(bThrowError)
3037  THROW_PARAM_ERROR(Al_Err_lLoadingReleaseLib, Al_Err_strLoadingReleaseLib, "Module Name", strModuleName);
3038  else
3039  return NULL;
3040  }
3041 #else
3042  if(iFindDebug != -1)
3043  {
3044  if(bThrowError)
3045  THROW_PARAM_ERROR(Al_Err_lLoadingDebugLib, Al_Err_strLoadingDebugLib, "Module Name", strModuleName);
3046  else
3047  return NULL;
3048  }
3049 #endif
3050 
3051  lpFactory = IStdClassFactory::LoadModule(strModuleName, bThrowError);
3052  return lpFactory;
3053 }
3054 catch(CStdErrorInfo oError)
3055 {
3056  if(lpFactory) delete lpFactory;
3057  RELAY_ERROR(oError);
3058  return NULL;
3059 }
3060 catch(...)
3061 {
3062  if(lpFactory) delete lpFactory;
3063  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3064  return NULL;
3065 }
3066 }
3067 
3068 
3078 {
3079  TRACE_DEBUG("Loading structures from Xml.");
3080 
3082  THROW_ERROR(Al_Err_lClassFactoryNotDefined, Al_Err_strClassFactoryNotDefined);
3083 
3084  m_aryOrganisms.RemoveAll();
3085  m_aryStructures.RemoveAll();
3086  m_aryOdorTypes.RemoveAll();
3087 
3088  oXml.IntoChildElement("Environment"); //Into Environment Element
3089 
3090  DistanceUnits(oXml.GetChildString("DistanceUnits", "centimeter"));
3091  MassUnits(oXml.GetChildString("MassUnits", "gram"));
3092  Gravity(oXml.GetChildFloat("Gravity", m_fltGravity));
3093 
3094  //We do NOT call the TimeStep mutator here because we need to call it only after all modules are loaded so we can calculate the min time step correctly.
3095  m_fltPhysicsTimeStep = oXml.GetChildFloat("PhysicsTimeStep", m_fltPhysicsTimeStep);
3096 
3097  m_iPhysicsSubsteps = oXml.GetChildInt("PhysicSubsteps", 1);
3098 
3099  SimulateHydrodynamics(oXml.GetChildBool("SimulateHydrodynamics", m_bSimulateHydrodynamics));
3100 
3101  AutoGenerateRandomSeed(oXml.GetChildBool("AutoGenerateRandomSeed", m_bAutoGenerateRandomSeed));
3102  ManualRandomSeed(oXml.GetChildInt("ManualRandomSeed", m_iManualRandomSeed));
3103 
3104  DesiredFrameRate(oXml.GetChildInt("FrameRate", m_iDesiredFrameRate));
3105  ForceFastMoving(oXml.GetChildBool("FastMoving", m_bForceFastMoving));
3106 
3107  MouseSpringStiffness(oXml.GetChildFloat("MouseSpringStiffness", m_fltMouseSpringStiffness));
3108  MouseSpringDamping(oXml.GetChildFloat("MouseSpringDamping", m_ftlMouseSpringDamping));
3109 
3110  StabilityScale(oXml.GetChildFloat("StabilityScale", m_fltStabilityScale));
3111  //LinearCompliance(oXml.GetChildFloat("LinearCompliance", m_fltLinearCompliance));
3112  //AngularCompliance(oXml.GetChildFloat("AngularCompliance", m_fltAngularCompliance));
3113 
3114  //if(!m_bCalcCriticalSimParams)
3115  //{
3116  // LinearDamping(oXml.GetChildFloat("LinearDamping", m_fltLinearDamping));
3117  // AngularDamping(oXml.GetChildFloat("AngularDamping", m_fltAngularDamping));
3118  // LinearKineticLoss(oXml.GetChildFloat("LinearKineticLoss", m_fltLinearKineticLoss));
3119  // AngularKineticLoss(oXml.GetChildFloat("AngularKineticLoss", m_fltAngularKineticLoss));
3120  //}
3121 
3122  RecFieldSelRadius(oXml.GetChildFloat("RecFieldSelRadius", m_fltRecFieldSelRadius));
3123 
3124  m_vBackgroundColor.Load(oXml, "BackgroundColor", false);
3125 
3126  m_fltAlphaThreshold = oXml.GetChildFloat("AlphaThreshold", m_fltAlphaThreshold);
3127 
3128  m_oMaterialMgr.Load(oXml);
3129 
3130  if(oXml.FindChildElement("OdorTypes", false))
3131  {
3132  oXml.IntoElem(); //Into Odors Element
3133  int iChildCount = oXml.NumberOfChildren();
3134 
3135  for(int iIndex=0; iIndex<iChildCount; iIndex++)
3136  {
3137  oXml.FindChildByIndex(iIndex);
3138  LoadOdorType(oXml);
3139  }
3140  oXml.OutOfElem(); //OutOf Odors Element
3141  }
3142 
3143  if(oXml.FindChildElement("Organisms", false))
3144  {
3145  oXml.IntoElem(); //Into Organisms Element
3146  int iCount = oXml.NumberOfChildren();
3147 
3148  for(int iIndex=0; iIndex<iCount; iIndex++)
3149  {
3150  oXml.FindChildByIndex(iIndex);
3151  LoadOrganism(oXml);
3152  }
3153  oXml.OutOfElem(); //OutOf Organisms Element
3154  }
3155 
3156  if(oXml.FindChildElement("Structures", false))
3157  {
3158  oXml.IntoElem(); //Into Structures Element
3159  int iCount = oXml.NumberOfChildren();
3160 
3161  for(int iIndex=0; iIndex<iCount; iIndex++)
3162  {
3163  oXml.FindChildByIndex(iIndex);
3164  LoadStructure(oXml);
3165  }
3166  oXml.OutOfElem(); //OutOf Structures Element
3167 
3168  }
3169 
3170  m_oLightMgr.Load(oXml);
3171 
3172  if(oXml.FindChildElement("Script", false))
3173  Script(LoadScript(oXml));
3174 
3175  oXml.OutOfElem(); //OutOf Environment Element
3176 
3177  TRACE_DEBUG("Finished loading structures from Xml.");
3178 }
3179 
3192 {
3193  Structure *lpStructure = NULL;
3194 
3195 try
3196 {
3197  lpStructure = dynamic_cast<Structure *>(m_lpAnimatClassFactory->CreateObject("Structure", "Structure", true));
3198  lpStructure->SetSystemPointers(this, NULL, NULL, NULL, true);
3199  lpStructure->Load(oXml);
3200 
3201  AddStructure(lpStructure);
3202  return lpStructure;
3203 }
3204 catch(CStdErrorInfo oError)
3205 {
3206  if(lpStructure) delete lpStructure;
3207  RELAY_ERROR(oError);
3208  return NULL;
3209 }
3210 catch(...)
3211 {
3212  if(lpStructure) delete lpStructure;
3213  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3214  return NULL;
3215 }
3216 }
3217 
3230 {
3231  Organism *lpOrganism = NULL;
3232  std::string strModule;
3233  std::string strType;
3234 
3235 try
3236 {
3237  oXml.IntoElem(); //Into Child Element
3238  strModule = oXml.GetChildString("ModuleName", "");
3239  strType = oXml.GetChildString("Type");
3240  oXml.OutOfElem(); //OutOf Child Element
3241 
3242  lpOrganism = dynamic_cast<Organism *>(CreateObject(strModule, "Organism", strType));
3243  if(!lpOrganism)
3244  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Organism");
3245 
3246  lpOrganism->SetSystemPointers(this, NULL, NULL, NULL, true);
3247  lpOrganism->Load(oXml);
3248 
3249  AddOrganism(lpOrganism);
3250  return lpOrganism;
3251 }
3252 catch(CStdErrorInfo oError)
3253 {
3254  if(lpOrganism) delete lpOrganism;
3255  RELAY_ERROR(oError);
3256  return NULL;
3257 }
3258 catch(...)
3259 {
3260  if(lpOrganism) delete lpOrganism;
3261  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3262  return NULL;
3263 }
3264 }
3265 
3279 {
3280  OdorType *lpOdorType = NULL;
3281 
3282 try
3283 {
3284  lpOdorType = new OdorType();
3285 
3286  lpOdorType->SetSystemPointers(this, NULL, NULL, NULL, true);
3287  lpOdorType->Load(oXml);
3288 
3289  AddOdorType(lpOdorType);
3290  return lpOdorType;
3291 }
3292 catch(CStdErrorInfo oError)
3293 {
3294  if(lpOdorType) delete lpOdorType;
3295  RELAY_ERROR(oError);
3296  return NULL;
3297 }
3298 catch(...)
3299 {
3300  if(lpOdorType) delete lpOdorType;
3301  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3302  return NULL;
3303 }
3304 }
3305 
3317 {
3318  std::string strModule;
3319  std::string strType;
3320  ScriptProcessor *lpScript = NULL;
3321 
3322 try
3323 {
3324  oXml.IntoElem(); //Into Child Element
3325  strModule = oXml.GetChildString("ModuleName", "");
3326  strType = oXml.GetChildString("Type");
3327  oXml.OutOfElem(); //OutOf Child Element
3328 
3329  lpScript = dynamic_cast<ScriptProcessor *>(CreateObject(strModule, "ScriptProcessor", strType));
3330  if(!lpScript)
3331  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Script");
3332 
3333  lpScript->SetSystemPointers(this, NULL, NULL, NULL, true);
3334 
3335  lpScript->Load(oXml);
3336 
3337  return lpScript;
3338 }
3339 catch(CStdErrorInfo oError)
3340 {
3341  if(lpScript) delete lpScript;
3342  lpScript = NULL;
3343  RELAY_ERROR(oError);
3344  return NULL;
3345 }
3346 catch(...)
3347 {
3348  if(lpScript) delete lpScript;
3349  lpScript = NULL;
3350  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3351  return NULL;
3352 }
3353 }
3354 
3364 void Simulator::LoadAnimatModuleName(std::string strFile, std::string &strAnimatModule)
3365 {
3366  std::ifstream ifSimFile;
3367  char sBuffer[1000];
3368 
3369  if(!Std_FileExists(strFile))
3370  THROW_PARAM_ERROR(Al_Err_lSimFileNotFound, Al_Err_strSimFileNotFound, "Simulation File", strFile);
3371 
3372  ifSimFile.open(strFile);
3373 
3374  if(ifSimFile.is_open())
3375  {
3376  ifSimFile.read(sBuffer, 1000); // read the first 1000 chars. Assume the sim lib text is in it.
3377  ifSimFile.close();
3378 
3379  std::string strText = sBuffer;
3380 
3381  int iModuleStart = strText.find("<AnimatModule>");
3382  int iModuleEnd = strText.find("</AnimatModule>");
3383 
3384  if(iModuleStart == -1)
3385  THROW_PARAM_ERROR(Al_Err_lAnimatModuleTagNotFound, Al_Err_strAnimatModuleTagNotFound, "Simulation File", strFile);
3386 
3387  if(iModuleEnd == -1)
3388  THROW_PARAM_ERROR(Al_Err_lAnimatModuleTagNotFound, Al_Err_strAnimatModuleTagNotFound, "Simulation File", strFile);
3389 
3390  int iLen = iModuleEnd - iModuleStart - 14; //Take off the <AnimatModule>
3391 
3392  strAnimatModule = strText.substr((iModuleStart+14), iLen);
3393  }
3394  else
3395  THROW_PARAM_ERROR(Al_Err_lSimFileNotFound, Al_Err_strSimFileNotFound, "Simulation File", strFile);
3396 
3397  if(strAnimatModule.length() == 0)
3398  THROW_PARAM_ERROR(Al_Err_lAnimatModuleTagNotFound, Al_Err_strAnimatModuleTagNotFound, "Simulation File", strFile);
3399 }
3400 
3410 void Simulator::LoadAnimatModuleName(CStdXml &oXml, std::string &strAnimatModule)
3411 {
3412  oXml.FindElement("Simulation");
3413  oXml.FindChildElement("");
3414 
3415  strAnimatModule = oXml.GetChildString("AnimatModule");
3416 }
3417 
3418 #pragma endregion
3419 
3420 #pragma region CreateMethods
3421 
3440 CStdSerialize *Simulator::CreateObject(std::string strModule, std::string strClassName, std::string strType, bool bThrowError)
3441 {
3442  std::string strModuleCheck = Std_CheckString(strModule);
3443 
3444  if(strModuleCheck == "" || strModuleCheck == "ANIMATLAB")
3445  {
3447  THROW_ERROR(Al_Err_lClassFactoryNotDefined, Al_Err_strClassFactoryNotDefined);
3448 
3449  return m_lpAnimatClassFactory->CreateObject(strClassName, strType, bThrowError);
3450  }
3451  else
3452  {
3453  IStdClassFactory *lpFactory = FindNeuralModuleFactory(strModule, false);
3454 
3455  if(lpFactory)
3456  return lpFactory->CreateObject(strClassName, strType, bThrowError);
3457  else
3458  {
3459  std::string strFullPathModule = m_strExecutablePath + strModule;
3460 
3461  //Lets load the dynamic library and get a pointer to the class factory.
3462  lpFactory = LoadClassFactory(strFullPathModule, false);
3463 
3464  //If we could not load it using a full path then try just using the module name
3465  if(!lpFactory)
3466  lpFactory = LoadClassFactory(strModule);
3467 
3468  //Now create an instance of a neural module. There is only one type of
3469  CStdSerialize *lpObj = lpFactory->CreateObject(strClassName, strType, false);
3470 
3471  delete lpFactory;
3472 
3473  return lpObj;
3474  }
3475  }
3476 
3477  return NULL;
3478 }
3479 
3493 Simulator *Simulator::CreateSimulator(int argc, const char **argv)
3494 {
3495  std::string strExecutablePath, strExeFile;
3496 
3497  std::string strBuffer = Std_ExecutablePath();
3498  Std_SplitPathAndFile(strBuffer, strExecutablePath, strExeFile);
3499 
3500  //Set the log file prefix
3501  if(Std_DirectoryExists(strExecutablePath + "Logs"))
3502  Std_SetLogFilePrefix(strExecutablePath + "Logs\\AnimatSimulator");
3503  else
3504  Std_SetLogFilePrefix(strExecutablePath + "AnimatSimulator");
3505 
3506  if(argc != 2)
3507  THROW_ERROR(Al_Err_lNoProjectParamOnCommandLine, Al_Err_strNoProjectParamOnCommandLine);
3508 
3509  std::string strProject = argv[1];
3510  std::string strAnimatModule = ""; //Get it from the file
3511 
3512  if(Std_IsBlank(strProject))
3513  THROW_ERROR(Al_Err_lNoProjectParamOnCommandLine, Al_Err_strNoProjectParamOnCommandLine);
3514 
3515  return CreateSimulator(strAnimatModule, strProject);
3516 }
3517 
3532 Simulator *Simulator::CreateSimulator(std::string strSimFile, bool bForceNoWindows)
3533 {
3534  std::string strExecutablePath, strExeFile;
3535 
3536  std::string strBuffer = Std_ExecutablePath();
3537  Std_SplitPathAndFile(strBuffer, strExecutablePath, strExeFile);
3538 
3539  //Set the log file prefix
3540  if(Std_DirectoryExists(strExecutablePath + "Logs"))
3541  Std_SetLogFilePrefix(strExecutablePath + "Logs\\AnimatSimulator");
3542  else
3543  Std_SetLogFilePrefix(strExecutablePath + "AnimatSimulator");
3544 
3545  std::string strProject = strSimFile;
3546  std::string strAnimatModule = ""; //Get it from the file
3547 
3548  if(Std_IsBlank(strProject))
3549  THROW_ERROR(Al_Err_lNoProjectParamOnCommandLine, Al_Err_strNoProjectParamOnCommandLine);
3550 
3551  return CreateSimulator(strAnimatModule, strProject, bForceNoWindows);
3552 }
3553 
3568 Simulator *Simulator::CreateAndInitializeSimulator(std::string strSimFile, bool bForceNoWindows)
3569 {
3570  Simulator *lpSim = NULL;
3571 
3572  try
3573  {
3574  lpSim = CreateSimulator(strSimFile, bForceNoWindows);
3575  lpSim->Load();
3576  lpSim->Initialize();
3577  return lpSim;
3578  }
3579  catch(CStdErrorInfo oError)
3580  {
3581  if(lpSim) delete lpSim;
3582  RELAY_ERROR(oError);
3583  return NULL;
3584  }
3585  catch(...)
3586  {
3587  if(lpSim) delete lpSim;
3588  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3589  return NULL;
3590  }
3591 }
3592 
3593 
3604 Simulator *Simulator::CreateSimulator(std::string strAnimatModule, std::string strSimulationFile, bool bForceNoWindows)
3605 {
3606  Simulator *lpSim = NULL;
3607  IStdClassFactory *lpAnimatFactory=NULL;
3608 
3609  std::string strProjectPath, strProjectFile;
3610  std::string strExecutablePath, strExeFile;
3611 
3612 try
3613 {
3614  std::string strBuffer = Std_ExecutablePath();
3615  Std_SplitPathAndFile(strBuffer, strExecutablePath, strExeFile);
3616 
3617  //_getcwd( strBuffer, 2000 );
3618  //Std_SetLogFilePrefix(strExecutablePath + "Logs\\AnimatSimulator");
3619 
3620  if(!Std_FileExists(strSimulationFile))
3621  THROW_PARAM_ERROR(Al_Err_lSimFileNotFound, Al_Err_strSimFileNotFound, "Simulation File", strSimulationFile);
3622 
3623  Std_SplitPathAndFile(strSimulationFile, strProjectPath, strProjectFile);
3624 
3625  if(!Std_IsFullPath(strSimulationFile))
3626  {
3627  strProjectPath = strExecutablePath;
3628  strSimulationFile = strProjectPath + strSimulationFile;
3629  }
3630 
3631  if(Std_IsBlank(strAnimatModule))
3632  LoadAnimatModuleName(strSimulationFile, strAnimatModule);
3633 
3634  lpAnimatFactory = LoadClassFactory(strAnimatModule);
3635 
3636  //Now we need to get the simulation application itself. This ALWAYS
3637  //comes from the animat engine because the animat engine uses the
3638  //neural engine it is higher up the food chain and it decides the
3639  //actual simulator that needs to be used.
3640  lpSim = dynamic_cast<Simulator *>(lpAnimatFactory->CreateObject("Simulator", ""));
3641  if(!lpSim)
3642  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Simulator");
3643  ActiveSim(lpSim);
3644 
3645  lpSim->ProjectPath(strProjectPath);
3646  lpSim->ExecutablePath(strExecutablePath);
3647  lpSim->SimulationFile(strProjectFile);
3648  lpSim->ForceNoWindows(bForceNoWindows);
3649 
3650  if(lpAnimatFactory)
3651  {delete lpAnimatFactory; lpAnimatFactory = NULL;}
3652 
3653  g_lpSimulator = lpSim;
3654  return lpSim;
3655 }
3656 catch(CStdErrorInfo oError)
3657 {
3658  if(lpSim) delete lpSim;
3659  if(lpAnimatFactory) delete lpAnimatFactory;
3660  RELAY_ERROR(oError);
3661  return NULL;
3662 }
3663 catch(...)
3664 {
3665  if(lpSim) delete lpSim;
3666  if(lpAnimatFactory) delete lpAnimatFactory;
3667  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3668  return NULL;
3669 }
3670 }
3671 
3682 Simulator *Simulator::CreateSimulator(std::string strAnimatModule, CStdXml &oXml)
3683 {
3684  Simulator *lpSim = NULL;
3685  IStdClassFactory *lpAnimatFactory=NULL;
3686 
3687  std::string strProjectPath, strProjectFile;
3688  std::string strExecutablePath, strExeFile;
3689 
3690 try
3691 {
3692  std::string strBuffer = Std_ExecutablePath();
3693  Std_SplitPathAndFile(strBuffer, strExecutablePath, strExeFile);
3694 
3695  if(Std_IsBlank(strAnimatModule))
3696  LoadAnimatModuleName(oXml, strAnimatModule);
3697 
3698  lpAnimatFactory = LoadClassFactory(strAnimatModule);
3699 
3700  //Now we need to get the simulation application itself. This ALWAYS
3701  //comes from the animat engine because the animat engine uses the
3702  //neural engine it is higher up the food chain and it decides the
3703  //actual simulator that needs to be used.
3704  lpSim = dynamic_cast<Simulator *>(lpAnimatFactory->CreateObject("Simulator", ""));
3705  if(!lpSim)
3706  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Simulator");
3707  ActiveSim(lpSim);
3708 
3709  lpSim->ProjectPath(strProjectPath);
3710  lpSim->ExecutablePath(strExecutablePath);
3711 
3712  if(lpAnimatFactory)
3713  {delete lpAnimatFactory; lpAnimatFactory = NULL;}
3714 
3715  g_lpSimulator = lpSim;
3716  return lpSim;
3717 }
3718 catch(CStdErrorInfo oError)
3719 {
3720  if(lpSim) delete lpSim;
3721  if(lpAnimatFactory) delete lpAnimatFactory;
3722  RELAY_ERROR(oError);
3723  return NULL;
3724 }
3725 catch(...)
3726 {
3727  if(lpSim) delete lpSim;
3728  if(lpAnimatFactory) delete lpAnimatFactory;
3729  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3730  return NULL;
3731 }
3732 }
3733 
3746 Simulator *Simulator::CreateSimulator(std::string strAnimatModule, std::string strProjectPath, std::string strExecutablePath)
3747 {
3748  Simulator *lpSim = NULL;
3749  IStdClassFactory *lpAnimatFactory=NULL;
3750 
3751 
3752 try
3753 {
3754  lpAnimatFactory = LoadClassFactory(strAnimatModule);
3755 
3756  //Now we need to get the simulation application itself. This ALWAYS
3757  //comes from the animat engine because the animat engine uses the
3758  //neural engine it is higher up the food chain and it decides the
3759  //actual simulator that needs to be used.
3760  lpSim = dynamic_cast<Simulator *>(lpAnimatFactory->CreateObject("Simulator", ""));
3761  if(!lpSim)
3762  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Simulator");
3763  ActiveSim(lpSim);
3764 
3765  lpSim->ProjectPath(strProjectPath);
3766  lpSim->ExecutablePath(strExecutablePath);
3767 
3768  if(lpAnimatFactory)
3769  {delete lpAnimatFactory; lpAnimatFactory = NULL;}
3770 
3771  g_lpSimulator = lpSim;
3772  return lpSim;
3773 }
3774 catch(CStdErrorInfo oError)
3775 {
3776  if(lpSim) delete lpSim;
3777  if(lpAnimatFactory) delete lpAnimatFactory;
3778  RELAY_ERROR(oError);
3779  return NULL;
3780 }
3781 catch(...)
3782 {
3783  if(lpSim) delete lpSim;
3784  if(lpAnimatFactory) delete lpAnimatFactory;
3785  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
3786  return NULL;
3787 }
3788 }
3789 
3790 
3791 #pragma endregion
3792 
3793 #pragma region FindMethods
3794 
3807 IStdClassFactory *Simulator::FindNeuralModuleFactory(std::string strModuleName, bool bThrowError)
3808 {
3809  IStdClassFactory *lpFactory = NULL;
3810  CStdMap<std::string, IStdClassFactory *>::iterator oPos;
3811  oPos = m_aryNeuralModuleFactories.find(Std_CheckString(strModuleName));
3812 
3813  if(oPos != m_aryNeuralModuleFactories.end())
3814  lpFactory = oPos->second;
3815  else if(bThrowError)
3816  THROW_PARAM_ERROR(Al_Err_lModuleNameNotFound, Al_Err_strModuleNameNotFound, "ModuleName", strModuleName);
3817 
3818  return lpFactory;
3819 }
3820 
3835 Organism *Simulator::FindOrganism(std::string strOrganismID, bool bThrowError)
3836 {
3837  Organism *lpOrganism = NULL;
3838  CStdPtrMap<std::string, Organism>::iterator oPos;
3839  oPos = m_aryOrganisms.find(Std_CheckString(strOrganismID));
3840 
3841  if(oPos != m_aryOrganisms.end())
3842  lpOrganism = oPos->second;
3843  else if(bThrowError)
3844  THROW_PARAM_ERROR(Al_Err_lOrganismIDNotFound, Al_Err_strOrganismIDNotFound, "OrganismID", strOrganismID);
3845 
3846  return lpOrganism;
3847 }
3848 
3849 
3850 
3865 Structure *Simulator::FindStructure(std::string strStructureID, bool bThrowError)
3866 {
3867  Structure *lpStructure = NULL;
3868  CStdPtrMap<std::string, Structure>::iterator oPos;
3869  oPos = m_aryStructures.find(Std_CheckString(strStructureID));
3870 
3871  if(oPos != m_aryStructures.end())
3872  lpStructure = oPos->second;
3873  else if(bThrowError)
3874  THROW_PARAM_ERROR(Al_Err_lStructureIDNotFound, Al_Err_strStructureIDNotFound, "StructureID", strStructureID);
3875 
3876  return lpStructure;
3877 }
3878 
3891 OdorType *Simulator::FindOdorType(std::string strOdorID, bool bThrowError)
3892 {
3893  OdorType *lpOdorType = NULL;
3894  CStdPtrMap<std::string, OdorType>::iterator oPos;
3895  oPos = m_aryOdorTypes.find(Std_CheckString(strOdorID));
3896 
3897  if(oPos != m_aryOdorTypes.end())
3898  lpOdorType = oPos->second;
3899  else if(bThrowError)
3900  THROW_PARAM_ERROR(Al_Err_lOdorIDNotFound, Al_Err_strOdorIDNotFound, "OdorID", strOdorID);
3901 
3902  return lpOdorType;
3903 }
3904 
3905 
3920 Structure *Simulator::FindStructureFromAll(std::string strStructureID, bool bThrowError)
3921 {
3922  Structure *lpStructure = NULL;
3923  CStdPtrMap<std::string, Structure>::iterator oPos;
3924  oPos = m_aryAllStructures.find(Std_CheckString(strStructureID));
3925 
3926  if(oPos != m_aryAllStructures.end())
3927  lpStructure = oPos->second;
3928  else if(bThrowError)
3929  THROW_PARAM_ERROR(Al_Err_lStructureIDNotFound, Al_Err_strStructureIDNotFound, "StructureID", strStructureID);
3930 
3931  return lpStructure;
3932 }
3933 
3954 Joint *Simulator::FindJoint(std::string strStructureID, std::string strJointID, bool bThrowError)
3955 {
3956  Structure *lpStructure = FindStructureFromAll(strStructureID, bThrowError);
3957 
3958  if(lpStructure)
3959  return lpStructure->FindJoint(strJointID, bThrowError);
3960  else
3961  return NULL;
3962 }
3963 
3983 RigidBody *Simulator::FindRigidBody(std::string strStructureID, std::string strBodyID, bool bThrowError)
3984 {
3985  Structure *lpStructure = FindStructureFromAll(strStructureID, bThrowError);
3986 
3987  if(lpStructure)
3988  return lpStructure->FindRigidBody(strBodyID, bThrowError);
3989  else
3990  return NULL;
3991 }
3992 
4008 AnimatBase *Simulator::FindByID(std::string strID, bool bThrowError)
4009 {
4010  AnimatBase *lpFind = NULL;
4011  CStdMap<std::string, AnimatBase *>::iterator oPos;
4012  oPos = m_aryObjectList.find(Std_CheckString(strID));
4013 
4014  if(oPos != m_aryObjectList.end())
4015  lpFind = oPos->second;
4016  else if(bThrowError)
4017  THROW_PARAM_ERROR(Al_Err_lIDNotFound, Al_Err_strIDNotFound, "ID", strID);
4018 
4019  return lpFind;
4020 }
4021 
4033 void Simulator::FindClosestFoodSources(CStdFPoint &oMouthPos, float fltMinRadius, CStdArray<RigidBody *> &arySources, CStdArray<float> &aryDistances)
4034 {
4035  RigidBody *lpFood = NULL, *lpMinFood = NULL;
4036  float fltDist=0, fltMinDist=0;
4037  int iCount = m_aryFoodSources.GetSize();
4038 
4039  arySources.RemoveAll();
4040  aryDistances.RemoveAll();
4041 
4042  for(int iIndex=0; iIndex<iCount; iIndex++)
4043  {
4044  lpFood = m_aryFoodSources[iIndex];
4045  CStdFPoint oPos = lpFood->GetCurrentPosition();
4046  fltDist = Std_CalculateDistance(oMouthPos, oPos);
4047 
4048  if( (fltDist <= fltMinRadius) && ((fltDist < fltMinDist) || !lpMinFood))
4049  {
4050  arySources.Add(lpFood);
4051  aryDistances.Add(fltDist);
4052  }
4053  }
4054 }
4055 
4056 #pragma endregion
4057 
4058 #pragma region AddRemoveMethods
4059 
4069 {
4070  if(FindByID(lpItem->ID(), false) != NULL)
4071  THROW_PARAM_ERROR(Al_Err_lDuplicateAddOfObject, Al_Err_strDuplicateAddOfObject, "ID", lpItem->ID());
4072 
4073  m_aryObjectList.Add(lpItem->ID(), lpItem);
4074 }
4075 
4085 {
4086  if(FindByID(lpItem->ID(), false))
4087  m_aryObjectList.Remove(lpItem->ID());
4088 }
4089 
4101 void Simulator::AddNeuralModuleFactory(std::string strModuleName, NeuralModule *lpModule)
4102 {
4103  if(!lpModule->ClassFactory())
4104  THROW_PARAM_ERROR(Al_Err_lModuleClassFactoryNotDefined, Al_Err_strModuleClassFactoryNotDefined, "ModuleName", strModuleName);
4105 
4106  if(!FindNeuralModuleFactory(strModuleName, false))
4107  m_aryNeuralModuleFactories.Add(Std_CheckString(strModuleName), lpModule->ClassFactory());
4108 }
4109 
4110 
4111 int Simulator::FindAdapterListIndex(CStdArray<Adapter *> aryAdapters, std::string strID, bool bThrowError)
4112 {
4113  int iCount = aryAdapters.GetSize();
4114  for(int iIdx=0; iIdx<iCount; iIdx++)
4115  if(aryAdapters[iIdx]->ID() == strID)
4116  return iIdx;
4117 
4118  if(bThrowError)
4119  THROW_PARAM_ERROR(Al_Err_lAdapterIDNotFound, Al_Err_strAdapterIDNotFound, "ID", strID);
4120 
4121  return -1;
4122 }
4123 
4133 void Simulator::AttachSourceAdapter(Structure *lpStructure, Adapter *lpAdapter)
4134 {
4135  std::string strModuleName = Std_CheckString(lpAdapter->SourceModule());
4136 
4137  //If no neural module name is specified then this must be getting attached to the physics engine.
4138  //Otherwise it gets attached to the specified neural module in an organism
4139  if(strModuleName == "" || strModuleName == "ANIMATLAB")
4140  {
4141  if(FindAdapterListIndex(m_arySourcePhysicsAdapters, lpAdapter->ID(), false) == -1)
4142  m_arySourcePhysicsAdapters.Add(lpAdapter);
4143  }
4144  else
4145  {
4146  Organism *lpOrganism = dynamic_cast<Organism *>(lpStructure);
4147  if(!lpOrganism)
4148  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Organism");
4149 
4150  NeuralModule *lpModule = lpOrganism->GetNervousSystem()->FindNeuralModule(strModuleName);
4151  lpModule->AttachSourceAdapter(lpAdapter);
4152  }
4153 }
4154 
4164 void Simulator::RemoveSourceAdapter(Structure *lpStructure, Adapter *lpAdapter)
4165 {
4166  std::string strModuleName = Std_CheckString(lpAdapter->SourceModule());
4167 
4168  //If no neural module name is specified then this must be getting attached to the physics engine.
4169  //Otherwise it gets attached to the specified neural module in an organism
4170  if(strModuleName == "" || strModuleName == "ANIMATLAB")
4171  {
4172  int iIdx = FindAdapterListIndex(m_arySourcePhysicsAdapters, lpAdapter->ID(), false);
4173  if(iIdx > -1)
4174  m_arySourcePhysicsAdapters.RemoveAt(iIdx);
4175  }
4176  else
4177  {
4178  Organism *lpOrganism = dynamic_cast<Organism *>(lpStructure);
4179  if(!lpOrganism)
4180  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Organism");
4181 
4182  NeuralModule *lpModule = lpOrganism->GetNervousSystem()->FindNeuralModule(strModuleName);
4183  lpModule->RemoveSourceAdapter(lpAdapter);
4184  }
4185 }
4186 
4196 void Simulator::AttachTargetAdapter(Structure *lpStructure, Adapter *lpAdapter)
4197 {
4198  std::string strModuleName = Std_CheckString(lpAdapter->TargetModule());
4199 
4200  //If no neural module name is specified then this must be getting attached to the physics engine.
4201  //Otherwise it gets attached to the specified neural module in an organism
4202  if(strModuleName == "" || strModuleName == "ANIMATLAB")
4203  {
4204  if(FindAdapterListIndex(m_aryTargetPhysicsAdapters, lpAdapter->ID(), false) == -1)
4205  {
4206  m_aryTargetPhysicsAdapters.Add(lpAdapter);
4208  }
4209  }
4210  else
4211  {
4212  Organism *lpOrganism = dynamic_cast<Organism *>(lpStructure);
4213  if(!lpOrganism)
4214  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Organism");
4215 
4216  NeuralModule *lpModule = lpOrganism->GetNervousSystem()->FindNeuralModule(strModuleName);
4217  lpModule->AttachTargetAdapter(lpAdapter);
4218 
4219  //Attach the target neural module to the adapter.
4220  lpAdapter->SetSystemPointers(this, lpStructure, lpModule, NULL, true);
4221  }
4222 }
4223 
4233 void Simulator::RemoveTargetAdapter(Structure *lpStructure, Adapter *lpAdapter)
4234 {
4235  std::string strModuleName = Std_CheckString(lpAdapter->TargetModule());
4236 
4237  //If no neural module name is specified then this must be getting attached to the physics engine.
4238  //Otherwise it gets attached to the specified neural module in an organism
4239  if(strModuleName == "" || strModuleName == "ANIMATLAB")
4240  {
4241  int iIdx = FindAdapterListIndex(m_aryTargetPhysicsAdapters, lpAdapter->ID(), false);
4242  if(iIdx > -1)
4243  {
4244  m_aryTargetPhysicsAdapters.RemoveAt(iIdx);
4246  }
4247  }
4248  else
4249  {
4250  Organism *lpOrganism = dynamic_cast<Organism *>(lpStructure);
4251  if(!lpOrganism)
4252  THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Organism");
4253 
4254  NeuralModule *lpModule = lpOrganism->GetNervousSystem()->FindNeuralModule(strModuleName);
4255  lpModule->RemoveTargetAdapter(lpAdapter);
4256  }
4257 }
4258 
4267 bool Simulator::IsPhysicsAdapter(Adapter *lpAdapter)
4268 {
4269  int iIdx1 = FindAdapterListIndex(m_arySourcePhysicsAdapters, lpAdapter->ID(), false);
4270  int iIdx2 = FindAdapterListIndex(m_aryTargetPhysicsAdapters, lpAdapter->ID(), false);
4271 
4272  if(iIdx1 > -1 || iIdx2 > -1)
4273  return true;
4274  else
4275  return false;
4276 }
4277 
4278 
4287 void Simulator::AddFoodSource(RigidBody *lpFood)
4288 {
4289  int iIndex = FindFoodSourceIndex(lpFood);
4290  if(iIndex < 0)
4291  m_aryFoodSources.Add(lpFood);
4292 }
4293 
4302 void Simulator::RemoveFoodSource(RigidBody *lpFood)
4303 {
4304  int iIndex = FindFoodSourceIndex(lpFood);
4305  if(iIndex >= 0)
4306  m_aryFoodSources.RemoveAt(iIndex);
4307 }
4308 
4320 {
4321  int iCount = m_aryFoodSources.GetSize();
4322  for(int iIdx=0; iIdx<iCount; iIdx++)
4323  if(m_aryFoodSources[iIdx] == lpFood)
4324  return iIdx;
4325 
4326  return -1;
4327 }
4328 
4329 void Simulator::AddToExtractExtraData(BodyPart *lpPart)
4330 {
4331  int iIndex = FindExtraDataIndex(lpPart);
4332  if(iIndex < 0)
4333  m_aryExtraDataParts.Add(lpPart);
4335 }
4336 
4337 void Simulator::RemoveFromExtractExtraData(BodyPart *lpPart)
4338 {
4339  int iIndex = FindExtraDataIndex(lpPart);
4340  if(iIndex >= 0)
4341  m_aryExtraDataParts.RemoveAt(iIndex);
4343 }
4344 
4345 int Simulator::FindExtraDataIndex(BodyPart *lpPart)
4346 {
4347  int iCount = m_aryExtraDataParts.GetSize();
4348  for(int iIdx=0; iIdx<iCount; iIdx++)
4349  if(m_aryExtraDataParts[iIdx] == lpPart)
4350  return iIdx;
4351 
4352  return -1;
4353 }
4354 
4355 void Simulator::AddOrganism(Organism *lpOrganism)
4356 {
4357  if(!lpOrganism)
4358  THROW_ERROR(Al_Err_lStructureNotDefined, Al_Err_strStructureNotDefined);
4359 
4360  try
4361  {
4362  m_aryAllStructures.Add(lpOrganism->ID(), lpOrganism);
4363  m_aryOrganisms.Add(lpOrganism->ID(), lpOrganism);
4364  }
4365  catch(CStdErrorInfo oError)
4366  {
4367  oError.m_strError += " Duplicate Organism Key: " + lpOrganism->ID();
4368  RELAY_ERROR(oError);
4369  }
4370 }
4371 
4382 void Simulator::AddOrganism(std::string strXml)
4383 {
4384  CStdXml oXml;
4385  oXml.Deserialize(strXml);
4386  oXml.FindElement("Root");
4387  oXml.FindChildElement("Organism");
4388 
4389  Organism *lpOrg = LoadOrganism(oXml);
4390  lpOrg->Create();
4391 }
4392 
4404 void Simulator::RemoveOrganism(std::string strID, bool bThrowError)
4405 {
4406  m_aryAllStructures.Remove(strID);
4407  m_aryOrganisms.Remove(strID);
4408 }
4409 
4410 void Simulator::AddStructure(Structure *lpStructure)
4411 {
4412  if(!lpStructure)
4413  THROW_ERROR(Al_Err_lStructureNotDefined, Al_Err_strStructureNotDefined);
4414 
4415  try
4416  {
4417  m_aryAllStructures.Add(lpStructure->ID(), lpStructure);
4418  m_aryStructures.Add(lpStructure->ID(), lpStructure);
4419  }
4420  catch(CStdErrorInfo oError)
4421  {
4422  oError.m_strError += " Duplicate structure Key: " + lpStructure->ID();
4423  RELAY_ERROR(oError);
4424  }
4425 }
4426 
4437 void Simulator::AddStructure(std::string strXml)
4438 {
4439  CStdXml oXml;
4440  oXml.Deserialize(strXml);
4441  oXml.FindElement("Root");
4442  oXml.FindChildElement("Structure");
4443 
4444  Structure *lpStruct = LoadStructure(oXml);
4445  lpStruct->Create();
4446 }
4447 
4460 void Simulator::RemoveStructure(std::string strID, bool bThrowError)
4461 {
4462  m_aryAllStructures.Remove(strID);
4463  m_aryStructures.Remove(strID);
4464 }
4465 
4474 void Simulator::AddOdorType(OdorType *lpOdorType)
4475 {
4476  if(!lpOdorType)
4477  THROW_ERROR(Al_Err_lOdorNotDefined, Al_Err_strOdorNotDefined);
4478 
4479  try
4480  {
4481  m_aryOdorTypes.Add(lpOdorType->ID(), lpOdorType);
4482  }
4483  catch(CStdErrorInfo oError)
4484  {
4485  oError.m_strError += " Duplicate odor type Key: " + lpOdorType->ID();
4486  RELAY_ERROR(oError);
4487  }
4488 }
4489 
4490 void Simulator::AddOdorType(std::string strXml, bool bDoNotInit)
4491 {
4492  CStdXml oXml;
4493  oXml.Deserialize(strXml);
4494  oXml.FindElement("Root");
4495  oXml.FindChildElement("OdorType");
4496 
4497  OdorType *lpType = LoadOdorType(oXml);
4498 
4499  if(!bDoNotInit)
4500  lpType->Initialize();
4501 }
4502 
4503 void Simulator::RemoveOdorType(std::string strID, bool bThrowError)
4504 {
4505  m_aryOdorTypes.Remove(strID);
4506 }
4507 
4508 void Simulator::IncrementPhysicsBodyCount()
4509 {
4511 }
4524 void Simulator::AddScript(std::string strXml)
4525 {
4526  ScriptProcessor *lpScript = NULL;
4527  try
4528  {
4529  CStdXml oXml;
4530  oXml.Deserialize(strXml);
4531  oXml.FindElement("Root");
4532  oXml.FindChildElement("Script");
4533 
4534  lpScript = LoadScript(oXml);
4535  lpScript->Initialize();
4536  m_lpScript = lpScript;
4537  }
4538  catch(CStdErrorInfo oError)
4539  {
4540  if(lpScript) delete lpScript;
4541  lpScript = NULL;
4542  RELAY_ERROR(oError);
4543  }
4544  catch(...)
4545  {
4546  if(lpScript) delete lpScript;
4547  lpScript = NULL;
4548  THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
4549  }
4550 }
4551 
4566 void Simulator::RemoveScript(std::string strID, bool bThrowError)
4567 {
4568  if(m_lpScript && m_lpScript->ID() == strID)
4569  {
4570  delete m_lpScript;
4571  m_lpScript = NULL;
4572  }
4573  else
4574  THROW_PARAM_ERROR(Al_Err_lRigidBodyIDNotFound, Al_Err_strRigidBodyIDNotFound, "ID", strID);
4575 }
4576 
4577 #pragma endregion
4578 
4579 #pragma region DataAccesMethods
4580 
4581 float *Simulator::GetDataPointer(const std::string &strDataType)
4582 {
4583  float *lpData=NULL;
4584  std::string strType = Std_CheckString(strDataType);
4585 
4586  if(strType == "TIME")
4587  lpData = &m_fltTime;
4588  else if(strType == "PHYSICSTIMESTEP")
4589  lpData = &m_fltPhysicsTimeStep;
4590  else if(strType == "PHYSICSSUBSTEPTIME")
4591  lpData = &m_fltPhysicsSubstepTime;
4592  else if(strType == "SIMULATIONREALTIMETOSTEP")
4594  else if(strType == "PLAYBACKADDITIONREALTIMETOSTEP")
4596  else if(strType == "TOTALREALTIMEFORSTEP")
4597  lpData = &m_fltTotalRealTimeForStep;
4598  else if(strType == "ACTUALFRAMERATE")
4599  lpData = &m_fltActualFrameRate;
4600  else if(strType == "REALTIME")
4601  lpData = &m_fltRealTime;
4602  else if(strType == "TOTALREALTIMEFORSTEPSMOOTHED")
4604  else if(strType == "PHYSICSREALTIMEFORSTEP")
4605  lpData = &m_fltPrevPhysicsStepTime;
4606  else if(strType == "NEURALREALTIMEFORSTEP")
4607  lpData = &m_fltTotalNeuralStepTime;
4608  else if(strType == "EXTERNALSTIMULIREALTIMEFORSTEP")
4609  lpData = &m_fltExternalStimuliStepTime;
4610  else if(strType == "DATACHARTREALTIMEFORSTEP")
4611  lpData = &m_fltDataChartStepTime;
4612  else if(strType == "SIMRECORDERREALTIMEFORSTEP")
4613  lpData = &m_fltSimRecorderStepTime;
4614  else if(strType == "REMAININGSTEPTIME")
4615  lpData = &m_fltRemainingStepTime;
4616  else if(strType == "MOUSESPRINGFORCEMAGNITUDE")
4618  else if(strType == "MOUSESPRINGDAMPINGFORCEMAGNITUDE")
4620  else if(strType == "MOUSESPRINGLENGTHMAGNITUDE")
4622  else if(strType == "TOTALMICROSLEEPTIME")
4623  lpData = &m_fltTotalMicroSleepTime;
4624  else if(strType == "TOTALMICROSLEEPCOUNT")
4625  lpData = &m_fltTotalMicroSleepCount;
4626  else if(strType == "TOTALMICROWAITTIME")
4627  lpData = &m_fltTotalMicroWaitTime;
4628  else if(strType == "TOTALMICROWAITCOUNT")
4629  lpData = &m_fltTotalMicroWaitCount;
4630  else
4631  THROW_TEXT_ERROR(Al_Err_lInvalidDataType, Al_Err_strInvalidDataType, "Simulator DataType: " + strDataType);
4632 
4633  return lpData;
4634 }
4635 
4636 bool Simulator::SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError)
4637 {
4638  std::string strType = Std_CheckString(strDataType);
4639 
4640  if(strType == "VISUALSELECTIONMODE")
4641  {
4642  VisualSelectionMode(atoi(strValue.c_str()));
4643  return true;
4644  }
4645  else if(strType == "ADDBODIESMODE")
4646  {
4647  AddBodiesMode(Std_ToBool(strValue));
4648  return true;
4649  }
4650  else if(strType == "DISTANCEUNITS")
4651  {
4652  DistanceUnits(strValue);
4653  return true;
4654  }
4655  else if(strType == "MASSUNITS")
4656  {
4657  MassUnits(strValue);
4658  return true;
4659  }
4660  else if(strType == "GRAVITY")
4661  {
4662  Gravity((float) atof(strValue.c_str()));
4663  return true;
4664  }
4665  else if(strType == "PHYSICSTIMESTEP")
4666  {
4667  PhysicsTimeStep((float) atof(strValue.c_str()));
4668  return true;
4669  }
4670  else if(strType == "PHYSICSSUBSTEPS")
4671  {
4672  PhysicsSubsteps((int) atoi(strValue.c_str()));
4673  return true;
4674  }
4675  else if(strType == "SIMULATEHYDRODYNAMICS")
4676  {
4677  SimulateHydrodynamics(Std_ToBool(strValue));
4678  return true;
4679  }
4680  else if(strType == "AUTOGENERATERANDOMSEED")
4681  {
4683  return true;
4684  }
4685  else if(strType == "MANUALRANDOMSEED")
4686  {
4687  ManualRandomSeed((float) atof(strValue.c_str()));
4688  return true;
4689  }
4690  else if(strType == "FRAMERATE")
4691  {
4692  DesiredFrameRate(atoi(strValue.c_str()));
4693  return true;
4694  }
4695  else if(strType == "FORCEFASTMOVING")
4696  {
4697  ForceFastMoving(atoi(strValue.c_str()));
4698  return true;
4699  }
4700  else if(strType == "MOUSESPRINGSTIFFNESS")
4701  {
4702  MouseSpringStiffness((float) atof(strValue.c_str()));
4703  return true;
4704  }
4705  else if(strType == "MOUSESPRINGDAMPING")
4706  {
4707  MouseSpringDamping((float) atof(strValue.c_str()));
4708  return true;
4709  }
4710  else if(strType == "LINEARCOMPLIANCE")
4711  {
4712  LinearCompliance((float) atof(strValue.c_str()));
4713  return true;
4714  }
4715  else if(strType == "ANGULARCOMPLIANCE")
4716  {
4717  AngularCompliance((float) atof(strValue.c_str()));
4718  return true;
4719  }
4720  else if(strType == "LINEARDAMPING")
4721  {
4722  LinearDamping((float) atof(strValue.c_str()));
4723  return true;
4724  }
4725  else if(strType == "ANGULARDAMPING")
4726  {
4727  AngularDamping((float) atof(strValue.c_str()));
4728  return true;
4729  }
4730  else if(strType == "LINEARKINETICLOSS")
4731  {
4732  LinearKineticLoss((float) atof(strValue.c_str()));
4733  return true;
4734  }
4735  else if(strType == "ANGULARKINETICLOSS")
4736  {
4737  AngularKineticLoss((float) atof(strValue.c_str()));
4738  return true;
4739  }
4740  else if(strType == "SETENDSIMTIME")
4741  {
4742  SetEndSimTime(Std_ToBool(strValue));
4743  return true;
4744  }
4745  else if(strType == "ENDSIMTIME")
4746  {
4747  EndSimTime((float) atof(strValue.c_str()));
4748  return true;
4749  }
4750  else if(strType == "RECFIELDSELRADIUS")
4751  {
4752  RecFieldSelRadius((float) atof(strValue.c_str()));
4753  return true;
4754  }
4755  else if(strDataType == "BACKGROUNDCOLOR")
4756  {
4757  BackgroundColor(strValue);
4758  return true;
4759  }
4760  else if(strDataType == "ALPHATHRESHOLD")
4761  {
4762  AlphaThreshold((float) atof(strValue.c_str()));
4763  return true;
4764  }
4765  else if(strDataType == "BACKGROUNDCOLOR.RED")
4766  {
4767  float aryVal[4] = {(float) atof(strValue.c_str()), m_vBackgroundColor.g(), m_vBackgroundColor.b(), m_vBackgroundColor.a()};
4768  BackgroundColor(aryVal);
4769  return true;
4770  }
4771  else if(strDataType == "BACKGROUNDCOLOR.GREEN")
4772  {
4773  float aryVal[4] = {m_vBackgroundColor.r(), (float) atof(strValue.c_str()), m_vBackgroundColor.b(), m_vBackgroundColor.a()};
4774  BackgroundColor(aryVal);
4775  return true;
4776  }
4777  else if(strDataType == "BACKGROUNDCOLOR.BLUE")
4778  {
4779  float aryVal[4] = {m_vBackgroundColor.r(), m_vBackgroundColor.g(), (float) atof(strValue.c_str()), m_vBackgroundColor.a()};
4780  BackgroundColor(aryVal);
4781  return true;
4782  }
4783  else if(strDataType == "BACKGROUNDCOLOR.ALPHA")
4784  {
4785  float aryVal[4] = {m_vBackgroundColor.r(), m_vBackgroundColor.g(), m_vBackgroundColor.b(), (float) atof(strValue.c_str())};
4786  BackgroundColor(aryVal);
4787  return true;
4788  }
4789  else if(strDataType == "TIMESTEPMODIFIED")
4790  {
4792  return true;
4793  }
4794  else if(strDataType == "PLAYBACKCONTROLMODE")
4795  {
4796  PlaybackControlMode(atoi(strValue.c_str()));
4797  return true;
4798  }
4799  else if(strDataType == "PRESETPLAYBACKTIMESTEP")
4800  {
4801  PresetPlaybackTimeStep((float) atof(strValue.c_str()));
4802  return true;
4803  }
4804  else if(strDataType == "STABILITYSCALE")
4805  {
4806  StabilityScale((float) atof(strValue.c_str()));
4807  return true;
4808  }
4809 
4810  //If it was not one of those above then we have a problem.
4811  if(bThrowError)
4812  THROW_PARAM_ERROR(Al_Err_lInvalidDataType, Al_Err_strInvalidDataType, "Data Type", strDataType);
4813 
4814  return false;
4815 }
4816 
4817 void Simulator::QueryProperties(CStdPtrArray<TypeProperty> &aryProperties)
4818 {
4819  AnimatBase::QueryProperties(aryProperties);
4820 
4821  aryProperties.Add(new TypeProperty("Time", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4822  aryProperties.Add(new TypeProperty("PhysicsSubStepTime", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4823  aryProperties.Add(new TypeProperty("SimulationRealTimeToStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4824  aryProperties.Add(new TypeProperty("PlaybackAdditionalRealTimeToStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4825  aryProperties.Add(new TypeProperty("TotalRealTimeForStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4826  aryProperties.Add(new TypeProperty("AcutalFrameRate", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4827  aryProperties.Add(new TypeProperty("RealTime", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4828  aryProperties.Add(new TypeProperty("TotalRealTimeForStepSmoothed", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4829  aryProperties.Add(new TypeProperty("PhysicsRealTimeForStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4830  aryProperties.Add(new TypeProperty("NeuralRealTimeForStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4831  aryProperties.Add(new TypeProperty("ExternalStimuliRealTimeForStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4832  aryProperties.Add(new TypeProperty("DataChartRealTimeForStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4833  aryProperties.Add(new TypeProperty("SimRecorderRealTimeForStep", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4834  aryProperties.Add(new TypeProperty("RemainingStepTime", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
4835 
4836  aryProperties.Add(new TypeProperty("VisualSelectionMode", AnimatPropertyType::Integer, AnimatPropertyDirection::Set));
4837  aryProperties.Add(new TypeProperty("AddBodiesMode", AnimatPropertyType::Boolean, AnimatPropertyDirection::Set));
4838  aryProperties.Add(new TypeProperty("DistanceUnits", AnimatPropertyType::String, AnimatPropertyDirection::Set));
4839  aryProperties.Add(new TypeProperty("MassUnits", AnimatPropertyType::String, AnimatPropertyDirection::Set));
4840  aryProperties.Add(new TypeProperty("Gravity", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4841  aryProperties.Add(new TypeProperty("PhysicsTimeStep", AnimatPropertyType::Float, AnimatPropertyDirection::Both));
4842  aryProperties.Add(new TypeProperty("SimulateHydrodynamics", AnimatPropertyType::Boolean, AnimatPropertyDirection::Set));
4843  aryProperties.Add(new TypeProperty("AutoGenerateRandomSeed", AnimatPropertyType::Boolean, AnimatPropertyDirection::Set));
4844  aryProperties.Add(new TypeProperty("ManualRandomSeed", AnimatPropertyType::Integer, AnimatPropertyDirection::Set));
4845  aryProperties.Add(new TypeProperty("FrameRate", AnimatPropertyType::Integer, AnimatPropertyDirection::Set));
4846  aryProperties.Add(new TypeProperty("ForceFastMoving", AnimatPropertyType::Integer, AnimatPropertyDirection::Set));
4847  aryProperties.Add(new TypeProperty("MouseSpringStiffness", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4848  aryProperties.Add(new TypeProperty("MouseSpringDamping", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4849  aryProperties.Add(new TypeProperty("CalcCriticalSimParams", AnimatPropertyType::Boolean, AnimatPropertyDirection::Set));
4850  aryProperties.Add(new TypeProperty("LinearCompliance", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4851  aryProperties.Add(new TypeProperty("AngularCompliance", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4852  aryProperties.Add(new TypeProperty("LinearDamping", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4853  aryProperties.Add(new TypeProperty("AngularDamping", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4854  aryProperties.Add(new TypeProperty("LinearKineticLoss", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4855  aryProperties.Add(new TypeProperty("AngularKineticLoss", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4856  aryProperties.Add(new TypeProperty("SetEndSimTime", AnimatPropertyType::Boolean, AnimatPropertyDirection::Set));
4857  aryProperties.Add(new TypeProperty("EndSimTime", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4858  aryProperties.Add(new TypeProperty("RecFieldSelRadius", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4859  aryProperties.Add(new TypeProperty("BackgroundColor", AnimatPropertyType::Xml, AnimatPropertyDirection::Set));
4860  aryProperties.Add(new TypeProperty("BackgroundColor.Red", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4861  aryProperties.Add(new TypeProperty("BackgroundColor.Blue", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4862  aryProperties.Add(new TypeProperty("BackgroundColor.Green", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4863  aryProperties.Add(new TypeProperty("BackgroundColor.Alpha", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4864  aryProperties.Add(new TypeProperty("PlaybackControlMode", AnimatPropertyType::Integer, AnimatPropertyDirection::Set));
4865  aryProperties.Add(new TypeProperty("PresetPlaybackTimeStep", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4866  aryProperties.Add(new TypeProperty("StabilityScale", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4867  aryProperties.Add(new TypeProperty("AlphaThreshold", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
4868 }
4869 
4870 bool Simulator::AddItem(const std::string &strItemType, const std::string &strXml, bool bThrowError, bool bDoNotInit)
4871 {
4872  std::string strType = Std_CheckString(strItemType);
4873 
4874  if(strType == "STIMULUS")
4875  return m_oExternalStimuliMgr.AddStimulus(strXml);
4876  else if(strType == "DATACHART")
4877  return m_oDataChartMgr.AddDataChart(strXml);
4878  else if(strType == "LIGHT")
4879  return m_oLightMgr.AddItem(strItemType, strXml, bThrowError);
4880  else if(strType == "STRUCTURE")
4881  {
4882  AddStructure(strXml);
4883  return true;
4884  }
4885  else if(strType == "ORGANISM")
4886  {
4887  AddOrganism(strXml);
4888  return true;
4889  }
4890  else if(strType == "HUDITEM")
4891  {
4892  if(m_lpWinMgr)
4893  return m_lpWinMgr->AddItem(strType, strXml, true);
4894  return false;
4895  }
4896  else if(strType == "ODORTYPE")
4897  {
4898  AddOdorType(strXml, bDoNotInit);
4899  return true;
4900  }
4901  else if(strType == "SCRIPT")
4902  {
4903  AddScript(strXml);
4904  return true;
4905  }
4906  else if(strType == "MATERIALTYPE" || strType == "MATERIALPAIR")
4907  return m_oMaterialMgr.AddItem(strItemType, strXml, bThrowError, bDoNotInit);
4908 
4909  //If it was not one of those above then we have a problem.
4910  if(bThrowError)
4911  THROW_PARAM_ERROR(Al_Err_lInvalidItemType, Al_Err_strInvalidItemType, "Item Type", strItemType);
4912 
4913  return false;
4914 }
4915 
4916 bool Simulator::RemoveItem(const std::string &strItemType, const std::string &strID, bool bThrowError)
4917 {
4918  std::string strType = Std_CheckString(strItemType);
4919 
4920  if(strType == "STIMULUS")
4921  return m_oExternalStimuliMgr.RemoveStimulus(strID);
4922  else if(strType == "DATACHART")
4923  return m_oDataChartMgr.RemoveDataChart(strID);
4924  else if(strType == "LIGHT")
4925  return m_oLightMgr.RemoveItem(strItemType, strID, bThrowError);
4926  else if(strType == "STRUCTURE")
4927  {
4928  RemoveStructure(strID);
4929  return true;
4930  }
4931  else if(strType == "ORGANISM")
4932  {
4933  RemoveOrganism(strID);
4934  return true;
4935  }
4936  else if(strType == "ODORTYPE")
4937  {
4938  RemoveOdorType(strID);
4939  return true;
4940  }
4941  else if(strType == "SCRIPT")
4942  {
4943  RemoveScript(strID);
4944  return true;
4945  }
4946  else if(strType == "MATERIALTYPE" || strType == "MATERIALPAIR")
4947  return m_oMaterialMgr.RemoveItem(strItemType, strID, bThrowError);
4948  else if(strType == "SCRIPTEDSIMWINDOW")
4949  return true; //Nothing to remove here. It is actually removed elsewhere in the simulationwindowmgr
4950 
4951  //If it was not one of those above then we have a problem.
4952  if(bThrowError)
4953  THROW_PARAM_ERROR(Al_Err_lInvalidItemType, Al_Err_strInvalidItemType, "Item Type", strItemType);
4954 
4955  return false;
4956 }
4957 
4958 #pragma endregion
4959 
4960 #pragma region RecorderMethods
4961 
4970 void Simulator::EnableVideoPlayback(std::string strKeyFrameID)
4971 {
4972  if(!m_lpSimRecorder)
4973  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
4974 
4975  if(m_lpVideoPlayback && m_lpVideoPlayback->ID() == strKeyFrameID)
4976  return;
4977 
4978  KeyFrame *lpFrame = dynamic_cast<KeyFrame *>(m_lpSimRecorder->Find(strKeyFrameID));
4979  lpFrame->EnableVideoPlayback();
4980 }
4981 
4989 {
4990  if(!m_lpSimRecorder)
4991  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
4992 
4993  if(m_lpVideoPlayback)
4995 }
4996 
5004 {
5005  if(!m_lpSimRecorder)
5006  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5007 
5008  if(m_lpVideoPlayback)
5010 }
5011 
5019 {
5020  if(!m_lpSimRecorder)
5021  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5022 
5023  if(m_lpVideoPlayback)
5025 }
5026 
5035 void Simulator::StepVideoPlayback(int iFrameCount)
5036 {
5037  if(!m_lpSimRecorder)
5038  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5039 
5040  if(m_lpVideoPlayback)
5041  m_lpVideoPlayback->StepVideoPlayback( iFrameCount);
5042 }
5043 
5052 void Simulator::SaveVideo(std::string strPath)
5053 {
5054  if(!m_lpSimRecorder)
5055  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5056 
5057  if(m_lpVideoPlayback)
5058  m_lpVideoPlayback->SaveVideo(strPath);
5059 }
5060 
5073 std::string Simulator::AddKeyFrame(std::string strType, long lStart, long lEnd)
5074 {
5075  if(!m_lpSimRecorder)
5076  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5077 
5078  KeyFrame *lpFrame = m_lpSimRecorder->Add(strType, lStart, lEnd);
5079  return lpFrame->ID();
5080 }
5081 
5090 void Simulator::RemoveKeyFrame(std::string strID)
5091 {
5092  if(!m_lpSimRecorder)
5093  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5094 
5095  m_lpSimRecorder->Remove(strID);
5096 }
5097 
5110 std::string Simulator::MoveKeyFrame(std::string strID, long lStart, long lEnd)
5111 {
5112  if(!m_lpSimRecorder)
5113  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5114 
5115  KeyFrame *lpFrame = dynamic_cast<KeyFrame *>(m_lpSimRecorder->Find(strID));
5116 
5117  //If neither the start or end slice is changed then jump out of here.
5118  if(lpFrame->StartSlice() == lStart && lpFrame->EndSlice() == lEnd)
5119  return lpFrame->ID();
5120 
5121  //unsigned char iType = lpFrame->Type();
5122  m_lpSimRecorder->Remove(strID);
5123  lpFrame = m_lpSimRecorder->Add(lpFrame->Type(), lStart, lEnd);
5124  return lpFrame->ID();
5125 }
5126 
5135 void Simulator::MoveSimulationToKeyFrame(std::string strKeyFrameID)
5136 {
5137  if(!m_lpSimRecorder)
5138  THROW_ERROR(Al_Err_lNoRecorderDefined, Al_Err_strNoRecorderDefined);
5139 
5140  if(!Std_IsBlank(strKeyFrameID))
5141  {
5142  KeyFrame *lpFrame = dynamic_cast<KeyFrame *>(m_lpSimRecorder->Find(strKeyFrameID));
5143  lpFrame->MakeCurrentFrame();
5144  }
5145  else if(m_lpSimStopPoint)
5147 }
5148 
5158 {
5159  long lByteSize = 0;
5160  CStdMap<std::string, Structure *>::iterator oPos;
5161  Structure *lpStructure = NULL;
5162  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
5163  {
5164  lpStructure = oPos->second;
5165  lByteSize += lpStructure->CalculateSnapshotByteSize();
5166  }
5167 
5168  return lByteSize;
5169 }
5170 
5180 void Simulator::SaveKeyFrameSnapshot(byte *aryBytes, long &lIndex)
5181 {
5182  CStdMap<std::string, Structure *>::iterator oPos;
5183  Structure *lpStructure = NULL;
5184  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
5185  {
5186  lpStructure = oPos->second;
5187  lpStructure->SaveKeyFrameSnapshot(aryBytes, lIndex);
5188  }
5189 }
5190 
5200 void Simulator::LoadKeyFrameSnapshot(byte *aryBytes, long &lIndex)
5201 {
5202  CStdMap<std::string, Structure *>::iterator oPos;
5203  Structure *lpStructure = NULL;
5204  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
5205  {
5206  lpStructure = oPos->second;
5207  lpStructure->LoadKeyFrameSnapshot(aryBytes, lIndex);
5208  }
5209 }
5210 
5218 {
5219 }
5220 
5221 #pragma endregion
5222 
5223 #pragma region CollisionMethods
5224 
5236 void Simulator::EnableCollisions(Structure *lpStruct, CStdPtrArray<CollisionPair> &m_aryCollisionList)
5237 {
5238  //Now lets disable any collisions that have been added to the exclusion list.
5239  int iCount = m_aryCollisionList.GetSize();
5240  CollisionPair *lpPair = NULL;
5241  RigidBody *lpPart1=NULL, *lpPart2=NULL;
5242 
5243  for(int iIndex=0; iIndex<iCount; iIndex++)
5244  {
5245  lpPair = m_aryCollisionList[iIndex];
5246  lpPart1 = lpStruct->FindRigidBody(lpPair->m_strPart1ID);
5247  lpPart2 = lpStruct->FindRigidBody(lpPair->m_strPart2ID);
5248 
5249  lpPart1->EnableCollision(lpPart2);
5250  }
5251 }
5252 
5254 {
5255  CStdMap<std::string, Structure *>::iterator oPos;
5256  Structure *lpStructure = NULL;
5257  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
5258  {
5259  lpStructure = oPos->second;
5260  lpStructure->EnableCollision(lpBody);
5261  }
5262 }
5263 
5275 void Simulator::DisableCollisions(Structure *lpStruct, CStdPtrArray<CollisionPair> &m_aryCollisionList)
5276 {
5277  //Now lets disable any collisions that have been added to the exclusion list.
5278  int iCount = m_aryCollisionList.GetSize();
5279  CollisionPair *lpPair = NULL;
5280  RigidBody *lpPart1=NULL, *lpPart2=NULL;
5281 
5282  for(int iIndex=0; iIndex<iCount; iIndex++)
5283  {
5284  lpPair = m_aryCollisionList[iIndex];
5285  lpPart1 = lpStruct->FindRigidBody(lpPair->m_strPart1ID);
5286  lpPart2 = lpStruct->FindRigidBody(lpPair->m_strPart2ID);
5287 
5288  lpPart1->DisableCollision(lpPart2);
5289  }
5290 }
5291 
5292 
5294 {
5295  CStdMap<std::string, Structure *>::iterator oPos;
5296  Structure *lpStructure = NULL;
5297  for(oPos=m_aryAllStructures.begin(); oPos!=m_aryAllStructures.end(); ++oPos)
5298  {
5299  lpStructure = oPos->second;
5300  lpStructure->DisableCollision(lpBody);
5301  }
5302 }
5303 
5305 {
5306  Initialize(0, NULL);
5307 }
5308 
5309 #pragma endregion
5310 
5311 #pragma region UnitScaleMethods
5312 
5326 float Simulator::ConvertDistanceUnits(std::string strUnits)
5327 {
5328  strUnits = Std_CheckString(strUnits);
5329 
5330  if(strUnits == "KILOMETERS" || strUnits == "KILOMETER")
5331  return (float) 1000;
5332 
5333  if(strUnits == "CENTAMETERS" || strUnits == "CENTAMETER")
5334  return (float) 100;
5335 
5336  if(strUnits == "DECAMETERS" || strUnits == "DECAMETER")
5337  return (float) 10;
5338 
5339  if(strUnits == "METERS" || strUnits == "METER")
5340  return (float) 1;
5341 
5342  if(strUnits == "DECIMETERS" || strUnits == "DECIMETER")
5343  return (float) 0.1;
5344 
5345  if(strUnits == "CENTIMETERS" || strUnits == "CENTIMETER")
5346  return (float) 0.01;
5347 
5348  if(strUnits == "MILLIMETERS" || strUnits == "MILLIMETER")
5349  return (float) 0.001;
5350 
5351  THROW_PARAM_ERROR(Al_Err_lInvalidDistanceUnits, Al_Err_strInvalidDistanceUnits, "DistanceUnits", strUnits);
5352 
5353  return (float) 1;
5354 }
5355 
5370 {
5371  strUnits = Std_CheckString(strUnits);
5372 
5373  if(strUnits == "KILOMETERS" || strUnits == "KILOMETER")
5374  return (float) 1;
5375 
5376  if(strUnits == "CENTAMETERS" || strUnits == "CENTAMETER")
5377  return (float) 1;
5378 
5379  if(strUnits == "DECAMETERS" || strUnits == "DECAMETER") //1 Unit = 10 m
5380  return (float) 10;
5381 
5382  if(strUnits == "METERS" || strUnits == "METER")
5383  return (float) 1;
5384 
5385  if(strUnits == "DECIMETERS" || strUnits == "DECIMETER") //1 Unit = 10 cm
5386  return (float) 10;
5387 
5388  if(strUnits == "CENTIMETERS" || strUnits == "CENTIMETER")
5389  return (float) 1;
5390 
5391  if(strUnits == "MILLIMETERS" || strUnits == "MILLIMETER")
5392  return (float) 1;
5393 
5394  THROW_PARAM_ERROR(Al_Err_lInvalidDistanceUnits, Al_Err_strInvalidDistanceUnits, "DenominatorDistanceUnits", strUnits);
5395 
5396  return (float) 1;
5397 }
5398 
5412 float Simulator::ConvertMassUnits(std::string strUnits)
5413 {
5414  strUnits = Std_CheckString(strUnits);
5415 
5416  if(strUnits == "KILOGRAMS" || strUnits == "KILOGRAM")
5417  return (float) 1;
5418 
5419  if(strUnits == "CENTAGRAMS" || strUnits == "CENTAGRAM")
5420  return (float) 0.1;
5421 
5422  if(strUnits == "DECAGRAMS" || strUnits == "DECAGRAM")
5423  return (float) 0.01;
5424 
5425  if(strUnits == "GRAMS" || strUnits == "GRAM")
5426  return (float) 0.001;
5427 
5428  if(strUnits == "DECIGRAMS" || strUnits == "DECIGRAM")
5429  return (float) 1e-4;
5430 
5431  if(strUnits == "CENTIGRAMS" || strUnits == "CENTIGRAM")
5432  return (float) 1e-5;
5433 
5434  if(strUnits == "MILLIGRAMS" || strUnits == "MILLIGRAM")
5435  return (float) 1e-6;
5436 
5437  THROW_PARAM_ERROR(Al_Err_lInvalidMassUnits, Al_Err_strInvalidMassUnits, "MassUnits", strUnits);
5438 
5439  return (float) 1;
5440 }
5441 
5457 float Simulator::ConvertDisplayMassUnits(std::string strUnits)
5458 {
5459  strUnits = Std_CheckString(strUnits);
5460 
5461  if(strUnits == "KILOGRAMS" || strUnits == "KILOGRAM")
5462  return (float) 1000;
5463 
5464  if(strUnits == "CENTAGRAMS" || strUnits == "CENTAGRAM")
5465  return (float) 100;
5466 
5467  if(strUnits == "DECAGRAMS" || strUnits == "DECAGRAM")
5468  return (float) 10;
5469 
5470  if(strUnits == "GRAMS" || strUnits == "GRAM")
5471  return (float) 1;
5472 
5473  if(strUnits == "DECIGRAMS" || strUnits == "DECIGRAM")
5474  return (float) 0.1;
5475 
5476  if(strUnits == "CENTIGRAMS" || strUnits == "CENTIGRAM")
5477  return (float) 0.01;
5478 
5479  if(strUnits == "MILLIGRAMS" || strUnits == "MILLIGRAM")
5480  return (float) 0.001;
5481 
5482  THROW_PARAM_ERROR(Al_Err_lInvalidMassUnits, Al_Err_strInvalidMassUnits, "MassUnits", strUnits);
5483 
5484  return (float) 1;
5485 }
5486 
5487 #pragma endregion
5488 
5489 #pragma endregion
5490 
5491 } //AnimatSim
long m_lVideoFrame
The video frame.
Definition: Simulator.h:482
virtual void SetSystemPointers(Simulator *lpSim, Structure *lpStructure, NeuralModule *lpModule, Node *lpNode, bool bVerify)
Sets the system pointers.
float m_fltPrevTotalRealTimeForStep
Previous total time for the step. Used for exponential smoothing algorithm.
Definition: Simulator.h:352
virtual void RemoveKeyFrame(std::string strID)
Removes the key frame described by strID.
Definition: Simulator.cpp:5090
virtual void ResetSimulation()
Resets the simulation back to time 0.
Definition: AnimatBase.cpp:587
virtual void Deserialize(std::string &strXml)
Deserializes a string into an xml document.
Definition: StdXml.cpp:162
CStdPtrMap< std::string, Organism > m_aryOrganisms
Definition: Simulator.h:50
The base class for all of the joint type of objects.
Definition: Joint.h:40
float m_fltMouseSpringForceMagnitude
The magnitude of the force being applied by the mosue spring at each step.
Definition: Simulator.h:300
virtual float LinearDamping()
Gets the linear damping of the simulation.
Definition: Simulator.cpp:834
virtual IStdClassFactory * ClassFactory()
Gets the class factory.
bool m_bSetEndSim
true if we the user has manually set the simulation end time.
Definition: Simulator.h:258
virtual void RemoveScript(std::string strID, bool bThrowError=true)
Removes the script based on ID.
Definition: Simulator.cpp:4566
virtual void Save(std::string strFilename)
Saves the simulation file.
Definition: Simulator.cpp:2965
long m_lSnapshotByteSize
Size of a memory snapshot in bytes.
Definition: Simulator.h:433
virtual DataChartMgr * GetDataChartMgr()
Gets the data chart manager.
Definition: Simulator.cpp:400
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 void SaveVideo(std::string strPath)=0
Saves a video.
Base class file for all Animat simulation objects.
virtual float StabilityScale()
Sets the linear scaling factor that controls the simulation stability parameters. ...
Definition: Simulator.cpp:755
virtual void ResetSimulation()
Resets the simulation back to time 0.
Standard color class.
Definition: StdColor.h:22
virtual std::string ExecutablePath()
Gets the directory path to the executable.
Definition: Simulator.cpp:307
CStdPtrMap< std::string, Structure > m_aryStructures
Definition: Simulator.h:55
Declares the nervous system class.
virtual float MassUnits()
Gets the mass units.
Definition: Simulator.cpp:1787
virtual bool EnableSimRecording()
Tells whehter simulation recording is enabled.
Definition: Simulator.cpp:1871
float m_fltAngularDamping
The angular damping of the simulation environment.
Definition: Simulator.h:222
virtual float MouseSpringDamping()
Gets the mouse spring damping.
Definition: Simulator.cpp:1286
This class is derived from the ActivatedItemMgr and it handles all of the external stimuli...
virtual void RemoveSourceAdapter(Adapter *lpAdapter)
Removes a source adapter.
Declares the simulation recorder class.
float m_fltTotalMicroSleepTime
Total time we were in microsleep during playback pause calculations;.
Definition: Simulator.h:405
virtual void RemoveFromObjectList(AnimatBase *lpItem)
Removes an object from the list of all simulation objects.
Definition: Simulator.cpp:4084
virtual float AngularKineticLoss()
Gets the angular kinetic loss of teh simulation.
Definition: Simulator.cpp:920
virtual std::string TargetModule()
Gets the name of the target NeuralModule.
Definition: Adapter.cpp:189
virtual Materials * GetMaterialMgr()
Gets the material manager.
Definition: Simulator.cpp:440
virtual void SetSystemPointers(Simulator *lpSim, Structure *lpStructure, NeuralModule *lpModule, Node *lpNode, bool bVerify)
Sets the system pointers.
Simulator()
Default constructor.
Definition: Simulator.cpp:60
Simulates the entire environment.
Definition: Simulator.h:31
virtual void DisableCollision(RigidBody *lpBody)
Disables collision between the past-in object and this object.
Definition: RigidBody.cpp:1374
virtual int VideoLoops()
Gets the video loops.
Definition: Simulator.cpp:1844
virtual bool FindChildElement(std::string strElementName, bool fThrowError=true)
Finds a child element by name.
Definition: StdXml.cpp:256
virtual bool InSimulation()
Used to determine if we are running in a simulation, or in a real control mode.
Definition: Simulator.cpp:1673
virtual std::string SourceModule()
Gets the name of the source NeuralModule.
Definition: Adapter.cpp:104
virtual KeyFrame * VideoPlayback()
Gets the video playback frame.
Definition: Simulator.cpp:1860
Root namespace for the base simulation library for AnimatLab.
short m_iPhysicsStepInterval
Definition: Simulator.h:275
virtual void SimPausing()
Called just before the simulation pauses.
Definition: AnimatBase.cpp:665
void Set(float R, float G, float B, float A)
Sets the color values.
Definition: StdColor.cpp:153
virtual void ProcessSimulationStep()
Process the an entire step of the simulation. This includes the simulation portion, video and calculating timing.
Definition: Simulator.cpp:2652
virtual void EnableCollision(RigidBody *lpBody)
Enables collision between the past-in object and this object.
Definition: RigidBody.cpp:1343
virtual void RemoveOrganism(std::string strID, bool bThrowError=true)
Removes an organism by its ID.
Definition: Simulator.cpp:4404
virtual float InverseMassUnits()
Gets the inverse mass units.
Definition: Simulator.cpp:1797
virtual void ResetSimulation()
Resets the simulation back to time 0.
float m_fltSimulationRealTimeToStep
Definition: Simulator.h:346
virtual void StepNeuralEngine()
Step neural engine.
Definition: Organism.cpp:141
int m_iVideoLoops
Zero-based index of the video loops.
Definition: Simulator.h:439
virtual IStdClassFactory * FindNeuralModuleFactory(std::string strModuleName, bool bThrowError=false)
Searches for the first neural module factory with the matching name.
Definition: Simulator.cpp:3807
bool m_bEnableSimRecording
true to enable simulation recording
Definition: Simulator.h:430
virtual bool AddStimulus(std::string strXml)
Creates a new stimulus from an xml definition and adds it to the manager.
virtual float Gravity()
Gets the gravity value.
Definition: Simulator.cpp:1225
CStdMap< std::string, Organism * >::iterator m_oOrganismIterator
An organism iterator.
Definition: Simulator.h:490
float m_fltPhysicsStepTime
This is the time pers step for the physics engine.
Definition: Simulator.h:381
virtual void SimulateEnd()
Called at the end of the Simulate method.
Definition: Simulator.cpp:2642
Declares the body part class.
virtual RigidBody * FindRigidBody(std::string strStructureID, std::string strBodyID, bool bThrowError=true)
Finds a rigid body with the specified ID in the specified structure.
Definition: Simulator.cpp:3983
virtual std::string SimulationFile()
Gets the simulation filename.
Definition: Simulator.cpp:327
ExternalStimuliMgr m_oExternalStimuliMgr
Manager for external stimuli.
Definition: Simulator.h:103
float m_fltLinearCompliance
The linear compliance of the simulation environment.
Definition: Simulator.h:213
CStdMap< std::string, Structure * > m_aryAllStructures
Definition: Simulator.h:59
static void LoadAnimatModuleName(std::string strFile, std::string &strAnimatModule)
Loads an animat module name.
Definition: Simulator.cpp:3364
void Load(CStdXml &oXml, std::string strParamName, bool bThrowError=true)
Loads the color.
Definition: StdColor.cpp:540
virtual ExternalStimuliMgr * GetExternalStimuliMgr()
Gets the external stimuli manager.
Definition: Simulator.cpp:410
virtual long MillisecondToSlice(long lMillisecond)
Calculates the number of time slices from a supplied number of milliseconds.
Definition: Simulator.cpp:581
bool m_bInitialized
true if the simulation has been initialized.
Definition: Simulator.h:146
Organism * m_lpSelOrganism
The pointer to a selected organism.
Definition: Simulator.h:496
int m_iDesiredFrameRate
Desired frame rate of the simulation video.
Definition: Simulator.h:366
bool m_bInDrag
Tells if we are in the middle of a mouse drag operation to move or rotate a part. ...
Definition: Simulator.h:161
virtual std::string Type()
returns the string type name of this object.
Definition: AnimatBase.cpp:221
bool m_bManualStepSimulation
If true then the user is manually stepping the simulation.
Definition: Simulator.h:140
virtual void Reset()
Resets this object.
Definition: Materials.cpp:59
virtual void MoveSimulationToKeyFrame(std::string strKeyFrameID)
Move simulation to key frame.
Definition: Simulator.cpp:5135
std::string m_strError
The error message.
Definition: StdErrorInfo.h:26
float m_fltPlaybackAdditionRealTimeToStep
Definition: Simulator.h:363
void Std_SplitPathAndFile(std::string &strFullPath, std::string &strPath, std::string &strFile)
Splits the path from the actual filename.
virtual bool FindElement(std::string strElementName, bool fThrowError=true)
Finds an element with the specified name.
Definition: StdXml.cpp:179
float m_fltActualFrameRate
The frame rate for the current frame.
Definition: Simulator.h:375
virtual void StopVideoPlayback()=0
Stop video playback.
virtual float PhysicsTimeStep()
Gets the integration time step for the physics engine.
Definition: Simulator.cpp:1163
virtual void UpdateBackgroundColor()
Updates the background color for all simulation windows.
virtual bool AutoGenerateRandomSeed()
Gets whether to automatically generate a random seed.
Definition: Simulator.cpp:715
virtual short PhysicsStepInterval()
Gets the physics step interval.
Definition: Simulator.cpp:1097
virtual int FindFoodSourceIndex(RigidBody *lpFood)
Searches for the index of the food source.
Definition: Simulator.cpp:4319
virtual LightManager * GetLightMgr()
Gets the light manager.
Definition: Simulator.cpp:430
virtual void StepVideoPlayback(int iFrameCount)=0
Step video playback.
virtual bool Paused()
Gets whether the Simulation is paused.
Definition: Simulator.cpp:347
virtual bool Initialized()
Tells if the simulation has been initialized or not.
Definition: Simulator.cpp:370
Information about the standard error.
Definition: StdErrorInfo.h:19
virtual std::string ID()
Gets the unique GUID ID of this object.
Definition: AnimatBase.cpp:167
virtual float LinearCompliance()
Gets the linear compliance of the simulation.
Definition: Simulator.cpp:776
bool m_bAutoGenerateRandomSeed
Definition: Simulator.h:287
virtual bool IntoElem()
Goes into the next element where the cursor is located.
Definition: StdXml.cpp:42
virtual void RunSimulation()
Runs the simulation.
Definition: Simulator.cpp:2702
long m_lPhysicsSliceCount
The number of slices that the physics engine has been updated.
Definition: Simulator.h:270
virtual float LinearKineticLoss()
Gets the linear kinetic loss of the simulation.
Definition: Simulator.cpp:892
std::string m_strPart2ID
GUID ID of the second part of the collision pair.
Definition: Structure.h:44
virtual float PresetPlaybackTimeStep()
Gets the preset playback time step.
Definition: Simulator.cpp:1603
virtual float DesiredFrameStep()
Gets the frame step time.
Definition: Simulator.cpp:1056
virtual bool WaitForSimulationBlock(long lTimeout=6000)
Wait for simulation block.
Definition: Simulator.cpp:2079
bool m_bForceNoWindows
If this is set to true then no graphical simulation windows will be created regardless of what the co...
Definition: Simulator.h:423
float m_fltDesiredFrameStep
The desired time value duration of the video frame step.
Definition: Simulator.h:369
virtual float DenominatorDistanceUnits()
Gets the denominator distance units.
Definition: Simulator.cpp:1756
float m_fltInverseDistanceUnits
The inverse of the distance units.
Definition: Simulator.h:186
virtual Structure * FindStructure(std::string strStructureID, bool bThrowError=true)
Searches for the first structure with the specified ID.
Definition: Simulator.cpp:3865
Class that stores information about types for QueryProperty information.
Definition: TypeProperty.h:35
virtual float * GetDataPointer(const std::string &strDataType)
Returns a float pointer to a data item of interest in this object.
Definition: Simulator.cpp:4581
virtual void TimeStepModified()
Notification method that the time step modified has been modified. Objects should recalculate any sli...
Definition: AnimatBase.cpp:685
virtual Organism * FindOrganism(std::string strOrganismID, bool bThrowError=true)
Searches for the first organism with the specified ID.
Definition: Simulator.cpp:3835
virtual void LoadEnvironment(CStdXml &oXml)
Loads all structures from from the configuration file for this simulation.
Definition: Simulator.cpp:3077
virtual float MouseSpringForceMagnitude()
Gets the magnitude of the mouse spring force applied at each time step.
Definition: Simulator.cpp:1314
virtual bool RemoveStimulus(std::string strID)
Removes the stimulus described by strID.
float m_fltDataChartStepTime
time to process data charts for this step.
Definition: Simulator.h:395
virtual bool PauseSimulation()=0
Pauses the simulation.
LightManager m_oLightMgr
Manager for the light objects.
Definition: Simulator.h:115
static Simulator * CreateSimulator(std::string strAnimatModule, std::string strSimulationFile, bool bForceNoWindows=false)
Creates a simulator from a simulator file.
Definition: Simulator.cpp:3604
virtual void LoadKeyFrameSnapshot(byte *aryBytes, long &lIndex)
Loads a key frame snapshot.
Definition: Simulator.cpp:5200
virtual void Initialize()
Initializes this object.
Definition: AnimatBase.cpp:573
virtual bool IsResetting()
Returns true if the simulation is in the process of resetting. False otherwise.
Definition: Simulator.cpp:545
virtual void StartVideoPlayback()=0
Starts a video playback.
virtual void StepSimulation()
Steps the entire simulation forward by one physics integration time step.
Definition: Simulator.cpp:2609
KeyFrame * m_lpVideoRecorder
The pointer to a video recorder.
Definition: Simulator.h:442
Records the simulation keyframes and videos.
virtual void SimStarting()
Called just before the simulation starts.
Definition: AnimatBase.cpp:654
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 bool AddItem(const std::string &strItemType, const std::string &strXml, bool bThrowError=true, bool bDoNotInit=false)
Adds a new object to this parent.
Definition: Simulator.cpp:4870
virtual float DistanceUnits()
Gets the distance units used in the simulation.
Definition: Simulator.cpp:1732
Declares the key frame class.
virtual void SaveVideo(std::string strPath)
Saves a video.
Definition: Simulator.cpp:5052
unsigned long long m_lStepSimEndTick
The tick count for when the simulation procressing of the step ends.
Definition: Simulator.h:342
CStdArray< BodyPart * > m_aryExtraDataParts
Definition: Simulator.h:91
virtual float AngularCompliance()
Gets the angular compliance of the simulation.
Definition: Simulator.cpp:805
float m_fltDenominatorDistanceUnits
Definition: Simulator.h:191
bool m_bSimBlockConfirm
true to confirm that a simulation block is in place.
Definition: Simulator.h:127
int m_iSelectionMode
This is the currect visual selection mode used within the GUI.
Definition: Simulator.h:118
ThreadProcessor * m_lpPhysicsThread
The pointer to the physics thread processor.
Definition: Simulator.h:170
virtual CStdColor * BackgroundColor()
Gets the background color.
Definition: Simulator.cpp:1460
bool Std_InValidRange(int iMinVal, int iMaxVal, int iVal, bool bThrowError, std::string strParamName)
Tests whether a number is within a valid range.
float m_fltExternalStimuliStepTime
Time to process external stimuli for this step.
Definition: Simulator.h:392
int m_iVideoStepSize
Size of the i video step.
Definition: Simulator.h:470
virtual bool IsPhysicsBeingUpdated()
Query if this object is physics being updated on this time slice.
Definition: Simulator.cpp:1444
virtual int PlaybackControlMode()
Gets the playback control mode.
Definition: Simulator.cpp:1559
virtual bool ShuttingDown()
Tells whether the simulation is shutting down or not.
Definition: Simulator.cpp:685
bool m_bSimulateHydrodynamics
Definition: Simulator.h:234
bool m_bForceSimulationStop
Set to true to stop the simulation. This is a more forceful way of stopping the sim.
Definition: Simulator.h:137
virtual void DisableCollision(RigidBody *lpBody)
Disables collision between the past-in body and all rigid bodies of the simulator.
virtual bool AddItem(const std::string &strItemType, const std::string &strXml, bool bThrowError=true, bool bDoNotInit=false)
Adds a new object to this parent.
Declares the joint class.
virtual void AttachSourceAdapter(Adapter *lpAdapter)
Attaches a source adapter.
long m_lTimeSlice
The current time slice. This a long value.
Definition: Simulator.h:251
virtual void RecordVideoFrame()
Record video frame.
Definition: Simulator.cpp:5217
static Simulator * CreateAndInitializeSimulator(std::string strSimFile, bool bForceNoWindows=false)
Creates a simulator from a specified file and initializes it.
Definition: Simulator.cpp:3568
CStdArray< RigidBody * > m_aryFoodSources
An Array of RigidBody parts that also act as food sources within the environment. ...
Definition: Simulator.h:66
virtual void InitializeRandomNumbers()
Initializes the random number generation system.
Definition: Simulator.cpp:1907
Declares the organism class.
float m_fltAlphaThreshold
The threshold value to use when setting the AlphaFunc for the entire scene.
Definition: Simulator.h:312
virtual void SimulateBegin()
Called at the beginning of the Simulate method.
Definition: Simulator.cpp:2622
virtual bool SimRunning()
Gets whether the simulation is running.
Definition: Simulator.cpp:673
virtual int GetChildInt(std::string strElementName)
Gets an integer value from the element with the specified name.
Definition: StdXml.cpp:456
virtual void EnableVideoPlayback(std::string strKeyFrameID)
Enables the video playback.
Definition: Simulator.cpp:4970
virtual void StopVideoPlayback()
Stop video playback.
Definition: Simulator.cpp:5018
virtual int VisualSelectionMode()
Gets the visual selection mode.
Definition: Simulator.cpp:460
virtual long PhysicsSliceCount()
Gets the physics time slice count.
Definition: Simulator.cpp:633
float m_fltTotalRealTimeForStep
This is the total time it takes to complete one physics time step.
Definition: Simulator.h:349
float m_ftlMouseSpringDamping
The damping of the user mouse spring.
Definition: Simulator.h:297
long m_lVideoStartSlice
The video start slice.
Definition: Simulator.h:476
Standard class factory.
bool Std_IsAboveMin(int iMinVal, int iVal, bool bThrowError, std::string strParamName, bool bInclusiveLimit)
Tests if a number is above a minimum value.
std::string m_strID
The unique Id for this object.
Definition: AnimatBase.h:55
virtual int GetMaterialID(std::string strID)
Gets a material identifier from the physics engine for the specified unique ID.
Definition: Simulator.cpp:1434
bool Std_DirectoryExists(std::string strPath)
Queries if a given directory exists.
virtual void StepVideoPlayback(int iFrameCount=1)
Step video playback.
Definition: Simulator.cpp:5035
virtual float PhysicsSubstepTime()
Gets the physics substep time.
Definition: Simulator.cpp:1215
bool m_bSimRunning
true if the simulation is running
Definition: Simulator.h:149
Declares a light object.
std::string m_strProjectPath
The directory path where the simulation configuration files are located.
Definition: Simulator.h:40
virtual bool AddDataChart(std::string strXml)
Adds a data chart to the manager.
static IStdClassFactory * LoadClassFactory(std::string strModuleName, bool bThrowError=true)
Loads the class factory specified in the DLL module name.
Definition: Simulator.cpp:3019
CStdMap< std::string, Structure * >::iterator m_oStructureIterator
A structure iterator.
Definition: Simulator.h:493
virtual long PhysicsStepCount()
Gets the physics step count.
Definition: Simulator.cpp:1176
virtual bool RemoveItem(const std::string &strItemType, const std::string &strID, bool bThrowError=true)
Removes a child item from this parent.
virtual void NotifyTimeStepModified()
Notifies the objects that time step has been modified.
Definition: Simulator.cpp:1987
Declares the activated item class.
int Std_IRand(int low, int high)
Generates a random number between two values.
unsigned long long m_lLastTickTaken
This is the last tick taken by a GetTickCount. It is used in debugging.
Definition: Simulator.h:378
virtual void AttachTargetAdapter(Adapter *lpAdapter)
Attaches a target adapter.
virtual float DisplayMassUnits()
Gets the density mass units.
Definition: Simulator.cpp:1810
virtual float TimeStep()
Gets the smallest integration time step used within the simulation.
Definition: Simulator.cpp:951
float m_fltTotalMicroSleepCount
Total number of times we called microsleep during playback pause calculations.
Definition: Simulator.h:408
SimulationWindowMgr * m_lpWinMgr
Manager for SimulationWindows.
Definition: Simulator.h:112
virtual long SnapshotByteSize()
Gets the snapshot byte size.
Definition: Simulator.cpp:1891
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
virtual void BlockSimulation()
Blocks the simulation from stepping.
Definition: Simulator.cpp:2036
Declares a light manager object.
float m_fltStabilityScale
A linear scaling factor for setting the simulation parameters.
Definition: Simulator.h:210
virtual bool RemoveItem(const std::string &strItemType, const std::string &strID, bool bThrowError=true)
Removes a child item from this parent.
Definition: Materials.cpp:166
virtual bool RobotAdpaterSynch()
Gets whether we need to synch the physics adapters in a simulation to the robot physics time step...
Definition: Simulator.cpp:1645
bool m_bStopSimulation
Set to true to stop the simulation.
Definition: Simulator.h:134
float m_lEndSimTimeSlice
The time slice when the simulation should end.
Definition: Simulator.h:264
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 void Reset()
Resets this object.
Definition: AnimatBase.cpp:559
Materials m_oMaterialMgr
Manager for Materials.
Definition: Simulator.h:109
virtual Joint * FindJoint(std::string strStructureID, std::string strJointID, bool bThrowError=true)
Finds a joint with the specified ID in the specified structure.
Definition: Simulator.cpp:3954
bool m_bBlockSimulation
true to block simulation. See WaitForBlock for more info.
Definition: Simulator.h:124
OdorType * LoadOdorType(CStdXml &oXml)
Loads an odor type.
Definition: Simulator.cpp:3278
float m_fltRemainingStepTime
Definition: Simulator.h:402
Declares the bounding box class.
virtual long StartSlice()
Returns the starts slice for activation.
virtual float MouseSpringLengthMagnitude()
Gets the magnitude of the mouse spring length at each time step.
Definition: Simulator.cpp:1370
virtual long CalculateSnapshotByteSize()
Calculates the snapshot byte size.
Definition: Simulator.cpp:5157
Manager for simulation windows.
Declares the gain base class.
virtual void LoadKeyFrameSnapshot(byte *aryBytes, long &lIndex)
Loads a key frame snapshot.
Definition: Structure.cpp:884
virtual void Load(std::string strFilename)
Loads an xml data file.
Definition: StdXml.cpp:1685
CStdMap< std::string, AnimatBase * > m_aryObjectList
A list of all animatbase objects in the simulation.
Definition: Simulator.h:81
virtual CStdFPoint GetCurrentPosition()
Gets the current position of this part.
float m_fltAngularCompliance
The angular compliance of the simulation environment.
Definition: Simulator.h:216
virtual void Close()
Closes all windows.
virtual void ResetSimulation()
Resets the simulation back to time 0.
Definition: Structure.cpp:249
virtual long CalculateSnapshotByteSize()
Calculates the snapshot byte size.
Definition: Structure.cpp:850
virtual void Simulate()
Simulates the system.
Definition: Simulator.cpp:2680
A standard xml manipulation class.
Definition: StdXml.h:19
float m_fltPhysicsSubstepTime
Definition: Simulator.h:248
virtual int PhysicsSubsteps()
Gets the physics substeps.
Definition: Simulator.cpp:1205
Odor type that can be emitted from a RigidBody and sensed by an OdorSensor.
Definition: OdorType.h:27
float m_fltEndSimTime
The time when the simulation should end.
Definition: Simulator.h:261
virtual bool SimulationBlockConfirm()
Confirms that the simulation has been blocked.
Definition: Simulator.cpp:2062
A "static" structure in the simulation.
Definition: Structure.h:84
virtual ~Simulator()
Destructor.
Definition: Simulator.cpp:197
virtual OdorType * FindOdorType(std::string strOdorID, bool bThrowError=true)
Searches for the first odor type with the specified ID.
Definition: Simulator.cpp:3891
virtual void StepSimulation()
Step the simulation for this object.
virtual bool AddItem(const std::string &strItemType, const std::string &strXml, bool bThrowError=true, bool bDoNotInit=false)
Adds a new object to this parent.
Definition: AnimatBase.cpp:513
float m_fltDisplayMassUnits
Tells how many kilograms/m^3 each unit of density is worth within the simulation environment.
Definition: Simulator.h:200
virtual CStdMap< std::string, AnimatBase * > * ObjectList()
Gets the list of pointers to all objects in the simulation.
Definition: Simulator.cpp:390
DataChartMgr m_oDataChartMgr
Manager for data charts.
Definition: Simulator.h:100
virtual ISimGUICallback * SimCallback()
Calback object from the simulation.
Definition: Simulator.cpp:525
virtual void Reset()
Resets this manager.
int m_iTargetAdapterCount
Number of target adapters.
Definition: Simulator.h:94
virtual ScriptProcessor * LoadScript(CStdXml &oXml)
Loads the script.
Definition: Simulator.cpp:3316
Declares the node class.
virtual void DisableCollision(RigidBody *lpCollisionBody)
Disables collision between the past-in object and all rigid bodies of this structure.
Definition: Structure.cpp:825
CStdPtrMap< std::string, OdorType > m_aryOdorTypes
Definition: Simulator.h:63
float m_fltTotalMicroWaitCount
Total number of loop iterations for microwait during playback pause calculations. ...
Definition: Simulator.h:414
virtual void ResetSimulationTimingParams()
Resets the variables that are used to keep track of the time that each component of the time step tak...
Definition: Simulator.cpp:2582
CStdMap< std::string, IStdClassFactory * > m_aryNeuralModuleFactories
Definition: Simulator.h:71
virtual void RemoveTargetAdapter(Adapter *lpAdapter)
Removes a target adapter.
int m_iPlaybackControlMode
Determines the mode used for playback control. See the accessor method for more details.
Definition: Simulator.h:332
float m_fltLinearDamping
The linear damping of the simulation environment.
Definition: Simulator.h:219
virtual std::string ProjectPath()
Gets the project path.
Definition: Simulator.cpp:287
KeyFrame * m_lpVideoPlayback
The pointer to a video playback.
Definition: Simulator.h:445
void r(float fltR, bool bThrowError=true)
Sets the red value of the color.
Definition: StdColor.cpp:51
virtual void QueryProperties(CStdPtrArray< TypeProperty > &aryProperties)
Queries this object for a list of properties that can be changed using SetData.
Definition: AnimatBase.cpp:447
Base class for all body parts and joints.
Definition: BodyPart.h:25
virtual bool RemoveDataChart(std::string strID)
Removes the data chart described by ID.
virtual bool SetEndSimTime()
Gets whether to use the set simulation end time.
Definition: Simulator.cpp:962
float m_fltMouseSpringLengthMagnitude
The magnitude of the length of the mouse spring at each step.
Definition: Simulator.h:306
Keeps track of all of the materials and the various material pair interaction parameters for the enti...
Definition: Materials.h:23
float m_fltSimRecorderStepTime
Time to process simulation recorder for this step.
Definition: Simulator.h:398
virtual std::string GetChildString(std::string strElementName)
Gets a string value from the element with the specified name.
Definition: StdXml.cpp:307
ISimGUICallback * m_lpSimCallback
Definition: Simulator.h:131
virtual Joint * FindJoint(std::string strJointID, bool bThrowError=true)
Finds a joint with a specified ID within this structure.
Definition: Structure.cpp:457
virtual AnimatBase * FindByID(std::string strID, bool bThrowError=true)
Searches for the object with the specified ID.
Definition: Simulator.cpp:4008
float m_fltGravity
The acceleration of gravity to use in the simulation.
Definition: Simulator.h:207
unsigned long long m_lVideoFrameStartTick
The tick when a new video frame time starts.
Definition: Simulator.h:372
SimulationRecorder * m_lpSimRecorder
The pointer to a simulation recorder.
Definition: Simulator.h:106
virtual void GenerateAutoSeed()
Generates an automatic seed value based on the current time.
Definition: Simulator.cpp:2876
virtual void ResetSimulation()
Resets the the simulation to its orginal settings at time 0.
Definition: Simulator.cpp:2304
virtual CStdSerialize * CreateObject(std::string strClassType, std::string strObjectType, bool bThrowError=true)=0
Creates an object of the specified class and object types.
virtual void DisableVideoPlayback()
Disables the video playback.
Definition: Simulator.cpp:4988
Structure * m_lpSelStructure
The pointer to a selected structure.
Definition: Simulator.h:499
float ConvertDisplayMassUnits(std::string strUnits)
Convert the string ID of the display units to a conversion factor.
Definition: Simulator.cpp:5457
virtual bool SimulateHydrodynamics()
Gets whether the simulation uses hydrodynamics.
Definition: Simulator.cpp:1402
virtual void CloseAllWindows()
Closes all windows internally.
virtual void AddOrganism(Organism *lpOrganism)
Adds a new organism to the list of structures for this simulation.
bool Std_ToBool(int iVal)
Converts a value toa bool.
virtual void EnableCollision(RigidBody *lpCollisionBody)
Enables collision between the past-in object and all rigid bodies of this structure.
Definition: Structure.cpp:802
virtual void StepPhysicsEngine()
Allows the organism and its parts to update at each time slice.
Definition: Structure.cpp:286
virtual void Load(StdUtils::CStdXml &oXml)
Loads the item using an XML data packet.
Definition: AnimatBase.cpp:771
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 SaveKeyFrameSnapshot(byte *aryBytes, long &lIndex)
Saves a key frame snapshot.
Definition: Simulator.cpp:5180
virtual bool GetChildBool(std::string strElementName)
Gets a bool value from the element with the specified name.
Definition: StdXml.cpp:699
virtual KeyFrame * VideoRecorder()
Gets the video recorder.
Definition: Simulator.cpp:1857
virtual bool CheckSimulationBlock()
Checks whether or not a simulation block has been requested.
Definition: Simulator.cpp:2119
void Std_SRand(unsigned long lSeed)
Sets the seed for generating a random number.
virtual float MouseSpringDampingForceMagnitude()
Gets the magnitude of the mouse spring damping force applied at each time step.
Definition: Simulator.cpp:1342
bool m_bIsResetting
True if we are in the process of resetting the simulation. False otherwise.
Definition: Simulator.h:164
virtual SimulationWindowMgr * GetWindowMgr()
Gets the window manager.
Definition: Simulator.cpp:450
Callback methods for the simulation object.
float m_fltTimeStep
This is the minimum integration time step taken for all neural modules and the physics engine...
Definition: Simulator.h:237
virtual SimulationRecorder * CreateSimulationRecorder()=0
Creates the simulation recorder.
long m_lStepTimeCount
This is a temp variable for measuring sim time for a set period for each simulation.
Definition: Simulator.h:420
virtual void StepPhysicsEngine()
Calls StepPhysicsEngine of all structures.
Definition: Simulator.cpp:2498
virtual void Load(std::string strFileName="")
Loads the simulation from an xml configuration file.
Definition: Simulator.cpp:2933
virtual void Reset()
Resets all objects of the simulation to their unloaded state.
Definition: Simulator.cpp:2141
Animat base class.
Definition: AnimatBase.h:36
long m_lVideoSliceCount
Current video slice time slice.
Definition: Simulator.h:436
virtual ActivatedItem * Find(std::string strID, int &iIndex, bool bThrowError)
Searches for an item with the specified ID and sets its index in the array.
std::string Std_ToLower(std::string strVal)
Converts a string to lower case.
virtual float MouseSpringStiffness()
Gets the mouse spring stiffness.
Definition: Simulator.cpp:1255
float ConvertDistanceUnits(std::string strUnits)
Convert the string ID of the distance units to a conversion factor.
Definition: Simulator.cpp:5326
float m_fltVideoRecordFrameTime
Time of the video record frame.
Definition: Simulator.h:458
std::string Std_ExecutablePath()
Finds the name and path of the current executable.
virtual void SimCallBack(ISimGUICallback *lpCallback)
Sets the calback object from the simulation.
Definition: Simulator.cpp:537
std::string m_strExecutablePath
The directory path where the executable is located.
Definition: Simulator.h:43
float ConvertMassUnits(std::string strUnits)
Convert the string ID of the mass units to a conversion factor.
Definition: Simulator.cpp:5412
virtual int NumberOfChildren()
Gets the number of children of the current element.
Definition: StdXml.cpp:202
A dynamic organism that is controlled by a neural network.
Definition: Organism.h:31
CStdArray< Adapter * > m_aryTargetPhysicsAdapters
Array of target physics adapters.
Definition: Simulator.h:87
Manager for data charts.
Definition: DataChartMgr.h:22
ThreadProcessor * m_lpNeuralThread
The pointer to a neural thread processor.
Definition: Simulator.h:167
virtual void AddStructure(Structure *lpStructure)
Adds a new "static" structure to the list of structures for this simulation.
Organism * LoadOrganism(CStdXml &oXml)
Loads an organism.
Definition: Simulator.cpp:3229
virtual void EnableCollision(RigidBody *lpBody)
Enables collision between the past-in body and all rigid bodies of the simulator. ...
virtual long EndSlice()
Gets the end time slice for deactivation.
bool m_bForceFastMoving
true if we need to set the physics system to force handling of fast moving objects.
Definition: Simulator.h:155
float m_fltVideoStartTime
Time of the video start.
Definition: Simulator.h:464
virtual bool OutOfElem()
Goes out of the element where the cursor is located.
Definition: StdXml.cpp:56
float m_fltDistanceUnits
Tells how many meters each unit of distance is worth within the simulation environment.
Definition: Simulator.h:183
virtual void StepNeuralEngine()
Step the neural engine of each organism.
Definition: Simulator.cpp:2449
float m_fltPrevPhysicsStepTime
Definition: Simulator.h:386
int m_iVideoStep
Zero-based index of the video step.
Definition: Simulator.h:473
bool m_bSteppingSim
true if stepping of simulation has begun. This is set to true once the Simulate methods has been call...
Definition: Simulator.h:152
virtual float RealTime()
Returns the real time since the simulation was started.
Definition: Simulator.cpp:1082
virtual bool RemoveItem(const std::string &strItemType, const std::string &strID, bool bThrowError=true)
Removes a child item from this parent.
Definition: Simulator.cpp:4916
unsigned long long m_lStartSimTick
The tick count for when the simulation first begins running.
Definition: Simulator.h:267
bool m_bAddBodiesMode
true if the AddBodies mode is enabled within the GUI.
Definition: Simulator.h:121
virtual void Initialize()
Initializes this object.
Definition: Materials.cpp:133
virtual void Initialize()
Initializes this object with no argc/argv params.
Definition: Simulator.cpp:5304
virtual void MakeCurrentFrame()=0
Makes the current frame.
virtual void Initialize(int argc, const char **argv)=0
Initializes this object.
virtual bool Stopped()
Tells if the simulation has been stopped.
Definition: Simulator.cpp:1034
virtual Structure * FindStructureFromAll(std::string strStructureID, bool bThrowError=true)
Searches for the first structure with the specified ID.
Definition: Simulator.cpp:3920
bool Std_IsBlank(std::string strVal)
Trims a string and tests if a string is blank.
Declares the data chart manager class.
virtual void ShutdownSimulation()=0
Shuts down the simulation.
long m_lVideoEndSlice
The video end slice.
Definition: Simulator.h:479
float m_fltRealTime
This keeps track of the real time from the begginning of the simulation.
Definition: Simulator.h:358
float m_fltTotalNeuralStepTime
Total time for processing of all neural items for this step.
Definition: Simulator.h:389
virtual void Step()
Steps the simulation forward by one time slice.
Definition: Simulator.cpp:2557
CStdArray< Adapter * > m_arySourcePhysicsAdapters
Array of source physics adapters.
Definition: Simulator.h:84
std::string m_strPart1ID
GUID ID of the first part of the collision pair.
Definition: Structure.h:42
virtual void SimPausing()
Simulation pausing event.
Definition: Simulator.cpp:2739
Declares the rigid body class.
float m_fltVideoPlaybackFrameTime
Time of the video playback frame.
Definition: Simulator.h:461
ThreadProcessor * m_lpIOThread
The pointer to an i/o thread processor.
Definition: Simulator.h:173
virtual unsigned long long StartSimTick()
The time slice tick at which the simulation start.
Definition: Simulator.cpp:603
virtual bool IntoChildElement(std::string strElementName, bool bThrowError=true)
Goes into the child element with the specified name.
Definition: StdXml.cpp:278
std::string Std_CheckString(std::string strVal)
Converts a string to upper case and trims it.
virtual void HandleCriticalError(std::string strError)=0
Handle critical-errors in the GUI. A critical error will report the error and then shut the entire ap...
virtual void SimStopping()
Called just before the simulation stops.
Definition: AnimatBase.cpp:676
std::string m_strSimulationFile
The name of the Animat Simulation (ASIM) file.
Definition: Simulator.h:46
bool m_bRecordVideo
true to record video
Definition: Simulator.h:452
double m_dblTotalStepTime
This is a temp variable for measuring sim time for a set period for each simulation.
Definition: Simulator.h:417
virtual void AddScript(std::string strXml)
Creates and adds a scripting object to this structure.
Definition: Simulator.cpp:4524
float m_fltTime
The current simulation time.
Definition: Simulator.h:254
virtual void Remove(std::string strID, bool bThrowError=true)
Removes the item with the specified ID.
virtual int ManualRandomSeed()
Gets the manual random seed value.
Definition: Simulator.cpp:735
virtual long TimeSlice()
Gets the current time slice.
Definition: Simulator.cpp:613
Declares the structure class.
virtual bool ManualStepSimulation()
Gets whether the simulation is being stepped manually by the user.
Definition: Simulator.cpp:653
std::string m_strVideoFilename
Filename of the video file.
Definition: Simulator.h:455
bool Std_IsFullPath(std::string strPath)
determines if this is a full path name.
virtual void CheckEndSimulationTime()
Checks the simulation end time.
Definition: Simulator.cpp:2902
virtual void VisualSelectionModeChanged(int iNewMode)
Visual selection mode changed.
Definition: AnimatBase.cpp:754
Declares the odor type class.
float m_fltVideoEndTime
Time of the video end.
Definition: Simulator.h:467
virtual void Add(ActivatedItem *lpItem)
Adds a new ActivatedItem to be managed.
virtual void RemoveStructure(std::string strID, bool bThrowError=true)
Removes a structure by its ID.
Definition: Simulator.cpp:4460
unsigned long long m_lStepStartTick
This is the tick count that is taken when a step is started.
Definition: Simulator.h:339
virtual long Millisecond()
Gets the current simulation time in millisecond.
Definition: Simulator.cpp:569
Standard serialize class.
Definition: StdSerialize.h:20
virtual long SliceToMillisecond(long lSlice)
Calculates the number of milliseconds from a supplied number of time slices.
Definition: Simulator.cpp:593
virtual void SimStopping()
Simulation stopping event.
Definition: Simulator.cpp:2760
float m_fltAngularKineticLoss
The angular kinetic loss of the simulation environment.
Definition: Simulator.h:228
float m_fltMassUnits
Tells how many kilograms each unit of mass is worth within the simulation environment.
Definition: Simulator.h:194
virtual void NeedToStopSimulation()=0
Callback to inform that GUI that the currently running simulation needs to be stopped.
float m_fltRecFieldSelRadius
Definition: Simulator.h:317
virtual float AngularDamping()
Gets the angular damping of the simulation.
Definition: Simulator.cpp:863
bool Std_FileExists(std::string strFullPath)
Finds if a given file exists.
virtual bool SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError=true)
Set a variable based on a string data type name.
Definition: Simulator.cpp:4636
virtual float InverseDistanceUnits()
Gets the inverse distance units.
Definition: Simulator.cpp:1742
virtual void StartVideoPlayback()
Starts a video playback.
Definition: Simulator.cpp:5003
virtual NeuralModule * FindNeuralModule(std::string strModuleName, bool bThrowError=true)
Searches for a neural module with a matching module name.
float m_fltTotalMicroWaitTime
Total time we were in microwait during playback pause calculations;.
Definition: Simulator.h:411
virtual void DisableVideoPlayback()=0
Disables the video playback.
virtual void QueryProperties(CStdPtrArray< TypeProperty > &aryProperties)
Queries this object for a list of properties that can be changed using SetData.
Definition: Simulator.cpp:4817
void g(float fltG, bool bThrowError=true)
Sets the green value of the color.
Definition: StdColor.cpp:76
float m_fltLinearKineticLoss
The linear kinetic loss of the simulation environment.
Definition: Simulator.h:225
float ConvertDenominatorDistanceUnits(std::string strUnits)
Convert the string ID of the distance units to a conversion factor for the denominator of the distanc...
Definition: Simulator.cpp:5369
virtual void EnableVideoPlayback()=0
Enables the video playback.
Declares the odor class.
Declares the simulator class.
float m_fltTotalRealTimeForStepSmooth
Current value of the exponential smoothing algorith for real time step.
Definition: Simulator.h:355
Declares the neural module class.
virtual bool FindChildByIndex(int iIndex, bool bThrowError=true)
Finds a child element by index.
Definition: StdXml.cpp:225
virtual void HandleNonCriticalError(std::string strError)=0
Handle a non-critical error in the GUI. Non-critical errors are simply reported and the simulation st...
float m_fltInverseMassUnits
The inverse of the mass units.
Definition: Simulator.h:197
virtual float Time()
Gets the current simulation time in seconds.
Definition: Simulator.cpp:559
virtual std::string MoveKeyFrame(std::string strID, long lStart, long lEnd)
Move key frame.
Definition: Simulator.cpp:5110
virtual bool ForceFastMoving()
Gets whether we have set the simulation to force fast moving calculations.
Definition: Simulator.cpp:695
int m_iExtraDataCount
Number of parts that require extra data to be collected.
Definition: Simulator.h:97
virtual void SimStarting()
Simulation starting event.
Definition: Simulator.cpp:2718
Declares the activated item manager class.
virtual bool AddBodiesMode()
Gets the Adds bodies mode.
Definition: Simulator.cpp:499
float m_fltPhysicsTimeStep
The time increment for each time slice of the physics simulation.
Definition: Simulator.h:278
void Std_SetLogFilePrefix(std::string strFilePrefix)
Sets the log file prefix.
Structure * LoadStructure(CStdXml &oXml)
Loads a structure.
Definition: Simulator.cpp:3191
Declares the contact sensor class.
virtual void SaveKeyFrameSnapshot(byte *aryBytes, long &lIndex)
Saves a key frame snapshot.
Definition: Structure.cpp:867
Declares the external stimuli manager class.
float m_fltPresetPlaybackTimeStep
Definition: Simulator.h:336
virtual void UnblockSimulation()
Unblock simulation.
Definition: Simulator.cpp:2048
virtual RigidBody * FindRigidBody(std::string strBodyID, bool bThrowError=true)
Finds a rigid body with a specified ID within this structure.
Definition: Structure.cpp:489
float m_fltMouseSpringDampingForceMagnitude
The magnitude of the damping component of the force being applied by the mosue spring at each step...
Definition: Simulator.h:303
virtual void AddToObjectList(AnimatBase *lpItem)
Adds an object to the list of all simulation objects.
Definition: Simulator.cpp:4068
virtual bool AddItem(const std::string &strItemType, const std::string &strXml, bool bThrowError=true, bool bDoNotInit=false)
Adds a new object to this parent.
Definition: Materials.cpp:149
void a(float fltA, bool bThrowError=true)
Sets the alpha value of the color.
Definition: StdColor.cpp:126
virtual SimulationRecorder * GetSimulationRecorder()
Gets the simulation recorder.
Definition: Simulator.cpp:420
The base class for all of the basic rigid body type of objects.
Definition: RigidBody.h:66
Declares the receptive field class.
double Std_CalculateDistance(CStdIPoint &ptA, CStdIPoint &ptB)
Calculates the distance between two points.
virtual int DesiredFrameRate()
Gets the frame rate used for the simulation windows in cylces per second.
Definition: Simulator.cpp:1044
std::string m_strName
The name for this object.
Definition: AnimatBase.h:61
virtual float GetChildFloat(std::string strElementName)
Gets a float value from the element with the specified name.
Definition: StdXml.cpp:617
virtual long VideoSliceCount()
Gets the video slice count.
Definition: Simulator.cpp:1824
IStdClassFactory * m_lpAnimatClassFactory
Definition: Simulator.h:78
virtual long EndSimTimeSlice()
Gets the time slice at which to automatically end the simulation.
Definition: Simulator.cpp:1008
virtual std::string AddKeyFrame(std::string strType, long lStart, long lEnd)
Adds a key frame.
Definition: Simulator.cpp:5073
float m_fltMouseSpringStiffness
The stiffness of the user mouse spring.
Definition: Simulator.h:294
virtual float EndSimTime()
Gets the time at which to automatically end the simulation.
Definition: Simulator.cpp:982
void b(float fltB, bool bThrowError=true)
Sets the blue value of the color.
Definition: StdColor.cpp:101
CStdColor m_vBackgroundColor
The background color to use when drawing the environment.
Definition: Simulator.h:309