simManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "platform/threads/mutex.h"
  24. #include "console/simBase.h"
  25. #include "console/simPersistID.h"
  26. #include "core/stringTable.h"
  27. #include "console/console.h"
  28. #include "core/stream/fileStream.h"
  29. #include "core/fileObject.h"
  30. #include "console/consoleInternal.h"
  31. #include "console/engineAPI.h"
  32. #include "core/idGenerator.h"
  33. #include "core/util/safeDelete.h"
  34. #include "platform/platformIntrinsics.h"
  35. #include "platform/profiler.h"
  36. #include "math/mMathFn.h"
  37. extern ExprEvalState gEvalState;
  38. //---------------------------------------------------------------------------
  39. //---------------------------------------------------------------------------
  40. // We comment out the implementation of the Con namespace when doxygenizing because
  41. // otherwise Doxygen decides to ignore our docs in console.h
  42. #ifndef DOXYGENIZING
  43. namespace Sim
  44. {
  45. //---------------------------------------------------------------------------
  46. //---------------------------------------------------------------------------
  47. // event queue variables:
  48. SimTime gCurrentTime;
  49. SimTime gTargetTime;
  50. void *gEventQueueMutex;
  51. SimEvent *gEventQueue;
  52. U32 gEventSequence;
  53. //---------------------------------------------------------------------------
  54. // event queue init/shutdown
  55. static void initEventQueue()
  56. {
  57. gCurrentTime = 0;
  58. gTargetTime = 0;
  59. gEventSequence = 1;
  60. gEventQueue = NULL;
  61. gEventQueueMutex = Mutex::createMutex();
  62. }
  63. static void shutdownEventQueue()
  64. {
  65. // Delete all pending events
  66. Mutex::lockMutex(gEventQueueMutex);
  67. SimEvent *walk = gEventQueue;
  68. while(walk)
  69. {
  70. SimEvent *temp = walk->nextEvent;
  71. delete walk;
  72. walk = temp;
  73. }
  74. Mutex::unlockMutex(gEventQueueMutex);
  75. Mutex::destroyMutex(gEventQueueMutex);
  76. }
  77. //---------------------------------------------------------------------------
  78. // event post
  79. U32 postEvent(SimObject *destObject, SimEvent* event,U32 time)
  80. {
  81. AssertFatal(time == -1 || time >= getCurrentTime(),
  82. "Sim::postEvent() - Event time must be greater than or equal to the current time." );
  83. AssertFatal(destObject, "Sim::postEvent() - Destination object for event doesn't exist.");
  84. Mutex::lockMutex(gEventQueueMutex);
  85. if( time == -1 )
  86. time = gCurrentTime;
  87. event->time = time;
  88. event->startTime = gCurrentTime;
  89. event->destObject = destObject;
  90. if(!destObject)
  91. {
  92. delete event;
  93. Mutex::unlockMutex(gEventQueueMutex);
  94. return InvalidEventId;
  95. }
  96. event->sequenceCount = gEventSequence++;
  97. SimEvent **walk = &gEventQueue;
  98. SimEvent *current;
  99. while((current = *walk) != NULL && (current->time < event->time))
  100. walk = &(current->nextEvent);
  101. // [tom, 6/24/2005] This ensures that SimEvents are dispatched in the same order that they are posted.
  102. // This is needed to ensure Con::threadSafeExecute() executes script code in the correct order.
  103. while((current = *walk) != NULL && (current->time == event->time))
  104. walk = &(current->nextEvent);
  105. event->nextEvent = current;
  106. *walk = event;
  107. U32 seqCount = event->sequenceCount;
  108. Mutex::unlockMutex(gEventQueueMutex);
  109. return seqCount;
  110. }
  111. //---------------------------------------------------------------------------
  112. // event cancellation
  113. void cancelEvent(U32 eventSequence)
  114. {
  115. Mutex::lockMutex(gEventQueueMutex);
  116. SimEvent **walk = &gEventQueue;
  117. SimEvent *current;
  118. while((current = *walk) != NULL)
  119. {
  120. if(current->sequenceCount == eventSequence)
  121. {
  122. *walk = current->nextEvent;
  123. delete current;
  124. Mutex::unlockMutex(gEventQueueMutex);
  125. return;
  126. }
  127. else
  128. walk = &(current->nextEvent);
  129. }
  130. Mutex::unlockMutex(gEventQueueMutex);
  131. }
  132. void cancelPendingEvents(SimObject *obj)
  133. {
  134. Mutex::lockMutex(gEventQueueMutex);
  135. SimEvent **walk = &gEventQueue;
  136. SimEvent *current;
  137. while((current = *walk) != NULL)
  138. {
  139. if(current->destObject == obj)
  140. {
  141. *walk = current->nextEvent;
  142. delete current;
  143. }
  144. else
  145. walk = &(current->nextEvent);
  146. }
  147. Mutex::unlockMutex(gEventQueueMutex);
  148. }
  149. //---------------------------------------------------------------------------
  150. // event pending test
  151. bool isEventPending(U32 eventSequence)
  152. {
  153. Mutex::lockMutex(gEventQueueMutex);
  154. for(SimEvent *walk = gEventQueue; walk; walk = walk->nextEvent)
  155. if(walk->sequenceCount == eventSequence)
  156. {
  157. Mutex::unlockMutex(gEventQueueMutex);
  158. return true;
  159. }
  160. Mutex::unlockMutex(gEventQueueMutex);
  161. return false;
  162. }
  163. U32 getEventTimeLeft(U32 eventSequence)
  164. {
  165. Mutex::lockMutex(gEventQueueMutex);
  166. for(SimEvent *walk = gEventQueue; walk; walk = walk->nextEvent)
  167. if(walk->sequenceCount == eventSequence)
  168. {
  169. SimTime t = walk->time - getCurrentTime();
  170. Mutex::unlockMutex(gEventQueueMutex);
  171. return t;
  172. }
  173. Mutex::unlockMutex(gEventQueueMutex);
  174. return 0;
  175. }
  176. U32 getScheduleDuration(U32 eventSequence)
  177. {
  178. for(SimEvent *walk = gEventQueue; walk; walk = walk->nextEvent)
  179. if(walk->sequenceCount == eventSequence)
  180. return (walk->time-walk->startTime);
  181. return 0;
  182. }
  183. U32 getTimeSinceStart(U32 eventSequence)
  184. {
  185. for(SimEvent *walk = gEventQueue; walk; walk = walk->nextEvent)
  186. if(walk->sequenceCount == eventSequence)
  187. return (getCurrentTime()-walk->startTime);
  188. return 0;
  189. }
  190. //---------------------------------------------------------------------------
  191. // event timing
  192. void advanceToTime(SimTime targetTime)
  193. {
  194. AssertFatal(targetTime >= getCurrentTime(),
  195. "Sim::advanceToTime() - Target time is less than the current time." );
  196. Mutex::lockMutex(gEventQueueMutex);
  197. gTargetTime = targetTime;
  198. while(gEventQueue && gEventQueue->time <= targetTime)
  199. {
  200. SimEvent *event = gEventQueue;
  201. gEventQueue = gEventQueue->nextEvent;
  202. AssertFatal(event->time >= gCurrentTime,
  203. "Sim::advanceToTime() - Event time is less than current time.");
  204. gCurrentTime = event->time;
  205. SimObject *obj = event->destObject;
  206. if(!obj->isDeleted())
  207. event->process(obj);
  208. delete event;
  209. }
  210. gCurrentTime = targetTime;
  211. Mutex::unlockMutex(gEventQueueMutex);
  212. }
  213. void advanceTime(SimTime delta)
  214. {
  215. advanceToTime(getCurrentTime() + delta);
  216. }
  217. U32 getCurrentTime()
  218. {
  219. return dAtomicRead( gCurrentTime);
  220. }
  221. U32 getTargetTime()
  222. {
  223. return dAtomicRead( gTargetTime );
  224. }
  225. //---------------------------------------------------------------------------
  226. //---------------------------------------------------------------------------
  227. SimGroup *gRootGroup = NULL;
  228. SimManagerNameDictionary *gNameDictionary;
  229. SimIdDictionary *gIdDictionary;
  230. U32 gNextObjectId;
  231. static void initRoot()
  232. {
  233. gIdDictionary = new SimIdDictionary;
  234. gNameDictionary = new SimManagerNameDictionary;
  235. gRootGroup = new SimGroup();
  236. gRootGroup->incRefCount();
  237. gRootGroup->setId(RootGroupId);
  238. gRootGroup->assignName("RootGroup");
  239. gRootGroup->registerObject();
  240. gNextObjectId = DynamicObjectIdFirst;
  241. }
  242. static void shutdownRoot()
  243. {
  244. gRootGroup->decRefCount();
  245. if( engineAPI::gUseConsoleInterop )
  246. gRootGroup->deleteObject();
  247. gRootGroup = NULL;
  248. SAFE_DELETE(gNameDictionary);
  249. SAFE_DELETE(gIdDictionary);
  250. }
  251. //---------------------------------------------------------------------------
  252. SimObject* findObject(const char* fileName, S32 declarationLine)
  253. {
  254. PROFILE_SCOPE(SimFindObjectByLine);
  255. if (!fileName)
  256. return NULL;
  257. if (declarationLine < 0)
  258. return NULL;
  259. if (!gRootGroup)
  260. return NULL;
  261. return gRootGroup->findObjectByLineNumber(fileName, declarationLine, true);
  262. }
  263. SimObject* findObject(ConsoleValueRef &ref)
  264. {
  265. return findObject((const char*)ref);
  266. }
  267. SimObject* findObject(const char* name)
  268. {
  269. PROFILE_SCOPE(SimFindObject);
  270. // Play nice with bad code - JDD
  271. if( !name )
  272. return NULL;
  273. SimObject *obj;
  274. char c = *name;
  275. if (c == '%')
  276. {
  277. if (gEvalState.getStackDepth())
  278. {
  279. Dictionary::Entry* ent = gEvalState.getCurrentFrame().lookup(StringTable->insert(name));
  280. if (ent)
  281. return Sim::findObject(ent->getIntValue());
  282. }
  283. }
  284. if(c == '/')
  285. return gRootGroup->findObject(name + 1 );
  286. if(c >= '0' && c <= '9')
  287. {
  288. // it's an id group
  289. const char* temp = name + 1;
  290. for(;;)
  291. {
  292. c = *temp++;
  293. if(!c)
  294. return findObject(dAtoi(name));
  295. else if(c == '/')
  296. {
  297. obj = findObject(dAtoi(name));
  298. if(!obj)
  299. return NULL;
  300. return obj->findObject(temp);
  301. }
  302. }
  303. }
  304. S32 len;
  305. for(len = 0; name[len] != 0 && name[len] != '/'; len++)
  306. ;
  307. StringTableEntry stName = StringTable->lookupn(name, len);
  308. if(!stName)
  309. return NULL;
  310. obj = gNameDictionary->find(stName);
  311. if(!name[len])
  312. return obj;
  313. if(!obj)
  314. return NULL;
  315. return obj->findObject(name + len + 1);
  316. }
  317. SimObject* findObject(SimObjectId id)
  318. {
  319. return gIdDictionary->find(id);
  320. }
  321. SimObject *spawnObject(String spawnClass, String spawnDataBlock, String spawnName,
  322. String spawnProperties, String spawnScript)
  323. {
  324. if (spawnClass.isEmpty())
  325. {
  326. Con::errorf("Unable to spawn an object without a spawnClass");
  327. return NULL;
  328. }
  329. String spawnString;
  330. spawnString += "$SpawnObject = new " + spawnClass + "(" + spawnName + ") { ";
  331. if (spawnDataBlock.isNotEmpty() && !spawnDataBlock.equal( "None", String::NoCase ) )
  332. spawnString += "datablock = " + spawnDataBlock + "; ";
  333. if (spawnProperties.isNotEmpty())
  334. spawnString += spawnProperties + " ";
  335. spawnString += "};";
  336. // Evaluate our spawn string
  337. Con::evaluate(spawnString.c_str());
  338. // Get our spawnObject id
  339. const char* spawnObjectId = Con::getVariable("$SpawnObject");
  340. // Get the actual spawnObject
  341. SimObject* spawnObject = findObject(spawnObjectId);
  342. // If we have a spawn script go ahead and execute it last
  343. if (spawnScript.isNotEmpty())
  344. Con::evaluate(spawnScript.c_str(), true);
  345. return spawnObject;
  346. }
  347. SimGroup *getRootGroup()
  348. {
  349. return gRootGroup;
  350. }
  351. String getUniqueName( const char *inName )
  352. {
  353. String outName( inName );
  354. if ( outName.isEmpty() )
  355. return String::EmptyString;
  356. SimObject *dummy;
  357. if ( !Sim::findObject( outName, dummy ) )
  358. return outName;
  359. S32 suffixNumb = -1;
  360. String nameStr( String::GetTrailingNumber( outName, suffixNumb ) );
  361. suffixNumb = mAbs( suffixNumb ) + 1;
  362. #define MAX_TRIES 100
  363. for ( U32 i = 0; i < MAX_TRIES; i++ )
  364. {
  365. outName = String::ToString( "%s%d", nameStr.c_str(), suffixNumb );
  366. if ( !Sim::findObject( outName, dummy ) )
  367. return outName;
  368. suffixNumb++;
  369. }
  370. Con::errorf( "Sim::getUniqueName( %s ) - failed after %d attempts", inName, MAX_TRIES );
  371. return String::EmptyString;
  372. }
  373. String getUniqueInternalName( const char *inName, SimSet *inSet, bool searchChildren )
  374. {
  375. // Since SimSet::findObjectByInternalName operates with StringTableEntry(s)
  376. // we have to muck up the StringTable with our attempts.
  377. // But then again, so does everywhere else.
  378. StringTableEntry outName = StringTable->insert( inName );
  379. if ( !outName || !outName[0] )
  380. return String::EmptyString;
  381. if ( !inSet->findObjectByInternalName( outName, searchChildren ) )
  382. return String(outName);
  383. S32 suffixNumb = -1;
  384. String nameStr( String::GetTrailingNumber( outName, suffixNumb ) );
  385. suffixNumb++;
  386. static char tempStr[512];
  387. #define MAX_TRIES 100
  388. for ( U32 i = 0; i < MAX_TRIES; i++ )
  389. {
  390. dSprintf( tempStr, 512, "%s%d", nameStr.c_str(), suffixNumb );
  391. outName = StringTable->insert( tempStr );
  392. if ( !inSet->findObjectByInternalName( outName, searchChildren ) )
  393. return String(outName);
  394. suffixNumb++;
  395. }
  396. Con::errorf( "Sim::getUniqueInternalName( %s ) - failed after %d attempts", inName, MAX_TRIES );
  397. return String::EmptyString;
  398. }
  399. bool isValidObjectName( const char* name )
  400. {
  401. if( !name || !name[ 0 ] )
  402. return true; // Anonymous object.
  403. if( !dIsalpha( name[ 0 ] ) && name[ 0 ] != '_' )
  404. return false;
  405. for( U32 i = 1; name[ i ]; ++ i )
  406. if( !dIsalnum( name[ i ] ) && name[ i ] != '_' )
  407. return false;
  408. return true;
  409. }
  410. //---------------------------------------------------------------------------
  411. //---------------------------------------------------------------------------
  412. #define InstantiateNamedSet(set) g##set = new SimSet; g##set->registerObject(#set); g##set->setNameChangeAllowed(false); gRootGroup->addObject(g##set); SIMSET_SET_ASSOCIATION((*g##set))
  413. #define InstantiateNamedGroup(set) g##set = new SimGroup; g##set->registerObject(#set); g##set->setNameChangeAllowed(false); gRootGroup->addObject(g##set); SIMSET_SET_ASSOCIATION((*g##set))
  414. static bool sgIsShuttingDown;
  415. SimDataBlockGroup *gDataBlockGroup;
  416. SimDataBlockGroup *getDataBlockGroup()
  417. {
  418. return gDataBlockGroup;
  419. }
  420. void init()
  421. {
  422. initEventQueue();
  423. initRoot();
  424. InstantiateNamedSet(ActiveActionMapSet);
  425. InstantiateNamedSet(GhostAlwaysSet);
  426. InstantiateNamedSet(WayPointSet);
  427. InstantiateNamedSet(fxReplicatorSet);
  428. InstantiateNamedSet(fxFoliageSet);
  429. InstantiateNamedSet(MaterialSet);
  430. InstantiateNamedSet(SFXSourceSet);
  431. InstantiateNamedSet(SFXDescriptionSet);
  432. InstantiateNamedSet(SFXTrackSet);
  433. InstantiateNamedSet(SFXEnvironmentSet);
  434. InstantiateNamedSet(SFXStateSet);
  435. InstantiateNamedSet(SFXAmbienceSet);
  436. InstantiateNamedSet(TerrainMaterialSet);
  437. InstantiateNamedSet(DataBlockSet);
  438. InstantiateNamedGroup(ActionMapGroup);
  439. InstantiateNamedGroup(ClientGroup);
  440. InstantiateNamedGroup(GuiGroup);
  441. InstantiateNamedGroup(GuiDataGroup);
  442. InstantiateNamedGroup(TCPGroup);
  443. InstantiateNamedGroup(ClientConnectionGroup);
  444. InstantiateNamedGroup(SFXParameterGroup);
  445. InstantiateNamedSet(BehaviorSet);
  446. InstantiateNamedSet(sgMissionLightingFilterSet);
  447. gDataBlockGroup = new SimDataBlockGroup();
  448. gDataBlockGroup->registerObject("DataBlockGroup");
  449. gRootGroup->addObject(gDataBlockGroup);
  450. SimPersistID::init();
  451. }
  452. void shutdown()
  453. {
  454. sgIsShuttingDown = true;
  455. shutdownRoot();
  456. shutdownEventQueue();
  457. SimPersistID::shutdown();
  458. }
  459. bool isShuttingDown()
  460. {
  461. return sgIsShuttingDown;
  462. }
  463. }
  464. #endif // DOXYGENIZING.
  465. SimDataBlockGroup::SimDataBlockGroup()
  466. {
  467. mLastModifiedKey = 0;
  468. }
  469. S32 QSORT_CALLBACK SimDataBlockGroup::compareModifiedKey(const void* a,const void* b)
  470. {
  471. const SimDataBlock* dba = *((const SimDataBlock**)a);
  472. const SimDataBlock* dbb = *((const SimDataBlock**)b);
  473. return dba->getModifiedKey() - dbb->getModifiedKey();
  474. }
  475. void SimDataBlockGroup::sort()
  476. {
  477. if(mLastModifiedKey != SimDataBlock::getNextModifiedKey())
  478. {
  479. mLastModifiedKey = SimDataBlock::getNextModifiedKey();
  480. dQsort(objectList.address(),objectList.size(),sizeof(SimObject *),compareModifiedKey);
  481. }
  482. }