SubScene.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. #include "SubScene.h"
  2. #include "gameMode.h"
  3. #include "console/persistenceManager.h"
  4. #include "console/script.h"
  5. #include "environment/meshRoad.h"
  6. #include "environment/river.h"
  7. #include "scene/sceneRenderState.h"
  8. #include "renderInstance/renderPassManager.h"
  9. #include "gfx/gfxDrawUtil.h"
  10. #include "gfx/gfxTransformSaver.h"
  11. #include "gui/editor/inspector/group.h"
  12. #include "gui/worldEditor/editor.h"
  13. #include "math/mathIO.h"
  14. #include "T3D/gameBase/gameBase.h"
  15. bool SubScene::smTransformChildren = false;
  16. IMPLEMENT_CO_NETOBJECT_V1(SubScene);
  17. S32 SubScene::mUnloadTimeoutMs = 5000;
  18. IMPLEMENT_CALLBACK(SubScene, onLoaded, void, (), (),
  19. "@brief Called when a subScene has been loaded and has game mode implications.\n\n");
  20. IMPLEMENT_CALLBACK(SubScene, onUnloaded, void, (), (),
  21. "@brief Called when a subScene has been unloaded and has game mode implications.\n\n");
  22. SubScene::SubScene() :
  23. mSubSceneAssetId(StringTable->EmptyString()),
  24. mGameModesNames(StringTable->EmptyString()),
  25. mScopeDistance(-1),
  26. mLoaded(false),
  27. mFreezeLoading(false),
  28. mTickPeriodMS(1000),
  29. mCurrTick(0),
  30. mGlobalLayer(false),
  31. mSaving(false),
  32. mUseSeparateLoadBounds(false),
  33. mLoadBounds(Point3F::One)
  34. {
  35. mNetFlags.set(Ghostable | ScopeAlways);
  36. mTypeMask |= StaticObjectType;
  37. }
  38. SubScene::~SubScene()
  39. {
  40. }
  41. bool SubScene::onAdd()
  42. {
  43. if (!Parent::onAdd())
  44. return false;
  45. setProcessTick(true);
  46. return true;
  47. }
  48. void SubScene::onRemove()
  49. {
  50. if (isClientObject())
  51. removeFromScene();
  52. unload();
  53. Parent::onRemove();
  54. }
  55. void SubScene::initPersistFields()
  56. {
  57. addGroup("SubScene");
  58. addField("isGlobalLayer", TypeBool, Offset(mGlobalLayer, SubScene), "");
  59. INITPERSISTFIELD_SUBSCENEASSET(SubScene, SubScene, "The subscene asset to load.");
  60. addField("tickPeriodMS", TypeS32, Offset(mTickPeriodMS, SubScene), "evaluation rate (ms)");
  61. addField("gameModes", TypeGameModeList, Offset(mGameModesNames, SubScene), "The game modes that this subscene is associated with.");
  62. addField("UseSeparateLoadBounds", TypeBool, Offset(mUseSeparateLoadBounds, SubScene), "If true, this subscene will utilize a separate bounds for triggering loading/unloading than it's object bounds");
  63. addField("LoadBounds", TypePoint3F, Offset(mLoadBounds, SubScene), "If UseSeparateLoadBounds is true, this subscene will use this value to set up the load/unload bounds");
  64. endGroup("SubScene");
  65. addGroup("LoadingManagement");
  66. addField("freezeLoading", TypeBool, Offset(mFreezeLoading, SubScene), "If true, will prevent the zone from being changed from it's current loading state.");
  67. addField("loadIf", TypeCommand, Offset(mLoadIf, SubScene), "evaluation condition (true/false)");
  68. addField("tickPeriodMS", TypeS32, Offset(mTickPeriodMS, SubScene), "evaluation rate (ms)");
  69. addField("onLoadCommand", TypeCommand, Offset(mOnLoadCommand, SubScene), "The command to execute when the subscene is loaded. Maximum 1023 characters.");
  70. addField("onUnloadCommand", TypeCommand, Offset(mOnUnloadCommand, SubScene), "The command to execute when subscene is unloaded. Maximum 1023 characters.");
  71. endGroup("LoadingManagement");
  72. Parent::initPersistFields();
  73. }
  74. void SubScene::consoleInit()
  75. {
  76. Parent::consoleInit();
  77. Con::addVariable("$SubScene::UnloadTimeoutMS", TypeBool, &SubScene::mUnloadTimeoutMs, "The amount of time in milliseconds it takes for a SubScene to be unloaded if it's inactive.\n"
  78. "@ingroup Editors\n");
  79. Con::addVariable("$SubScene::transformChildren", TypeBool, &SubScene::smTransformChildren,
  80. "@brief If true, then transform manipulations modify child objects. If false, only triggering bounds is manipulated\n\n"
  81. "@ingroup Editors");
  82. }
  83. void SubScene::addObject(SimObject* object)
  84. {
  85. SceneObject::addObject(object);
  86. }
  87. void SubScene::removeObject(SimObject* object)
  88. {
  89. SceneObject::removeObject(object);
  90. }
  91. U32 SubScene::packUpdate(NetConnection* conn, U32 mask, BitStream* stream)
  92. {
  93. U32 retMask = Parent::packUpdate(conn, mask, stream);
  94. stream->writeFlag(mGlobalLayer);
  95. if(stream->writeFlag(mUseSeparateLoadBounds))
  96. {
  97. mathWrite(*stream, mLoadBounds);
  98. }
  99. return retMask;
  100. }
  101. void SubScene::unpackUpdate(NetConnection* conn, BitStream* stream)
  102. {
  103. Parent::unpackUpdate(conn, stream);
  104. mGlobalLayer = stream->readFlag();
  105. mUseSeparateLoadBounds = stream->readFlag();
  106. if(mUseSeparateLoadBounds)
  107. {
  108. mathRead(*stream, &mLoadBounds);
  109. }
  110. }
  111. void SubScene::onInspect(GuiInspector* inspector)
  112. {
  113. Parent::onInspect(inspector);
  114. #ifdef TORQUE_TOOLS
  115. //Put the SubScene group before everything that'd be SubScene-effecting, for orginazational purposes
  116. GuiInspectorGroup* subsceneGrp = inspector->findExistentGroup(StringTable->insert("SubScene"));
  117. if (!subsceneGrp)
  118. return;
  119. GuiControl* stack = dynamic_cast<GuiControl*>(subsceneGrp->findObjectByInternalName(StringTable->insert("Stack")));
  120. //Save button
  121. GuiInspectorField* saveFieldGui = subsceneGrp->createInspectorField();
  122. saveFieldGui->init(inspector, subsceneGrp);
  123. saveFieldGui->setSpecialEditField(true);
  124. saveFieldGui->setTargetObject(this);
  125. StringTableEntry fldnm = StringTable->insert("SaveSubScene");
  126. saveFieldGui->setSpecialEditVariableName(fldnm);
  127. saveFieldGui->setInspectorField(NULL, fldnm);
  128. saveFieldGui->setDocs("");
  129. stack->addObject(saveFieldGui);
  130. GuiButtonCtrl* saveButton = new GuiButtonCtrl();
  131. saveButton->registerObject();
  132. saveButton->setDataField(StringTable->insert("profile"), NULL, "ToolsGuiButtonProfile");
  133. saveButton->setText("Save SubScene");
  134. saveButton->resize(Point2I::Zero, saveFieldGui->getExtent());
  135. saveButton->setHorizSizing(GuiControl::horizResizeWidth);
  136. saveButton->setVertSizing(GuiControl::vertResizeHeight);
  137. char szBuffer[512];
  138. dSprintf(szBuffer, 512, "%d.save();", this->getId());
  139. saveButton->setConsoleCommand(szBuffer);
  140. saveFieldGui->addObject(saveButton);
  141. #endif
  142. }
  143. void SubScene::inspectPostApply()
  144. {
  145. Parent::inspectPostApply();
  146. setMaskBits(-1);
  147. }
  148. void SubScene::setTransform(const MatrixF& mat)
  149. {
  150. if(SubScene::smTransformChildren)
  151. {
  152. Parent::setTransform(mat);
  153. }
  154. else
  155. {
  156. SceneObject::setTransform(mat);
  157. }
  158. }
  159. void SubScene::setRenderTransform(const MatrixF& mat)
  160. {
  161. if (SubScene::smTransformChildren)
  162. {
  163. Parent::setRenderTransform(mat);
  164. }
  165. else
  166. {
  167. SceneObject::setRenderTransform(mat);
  168. }
  169. }
  170. bool SubScene::evaluateCondition()
  171. {
  172. if (!mLoadIf.isEmpty())
  173. {
  174. //test the mapper plugged in condition line
  175. String resVar = getIdString() + String(".result");
  176. Con::setBoolVariable(resVar.c_str(), false);
  177. String command = resVar + "=" + mLoadIf + ";";
  178. Con::evaluatef(command.c_str());
  179. return Con::getBoolVariable(resVar.c_str());
  180. }
  181. return true;
  182. }
  183. bool SubScene::testBox(const Box3F& testBox)
  184. {
  185. bool passes = mGlobalLayer;
  186. if (!passes)
  187. {
  188. if(mUseSeparateLoadBounds)
  189. {
  190. Box3F loadBox = Box3F(-mLoadBounds.x, -mLoadBounds.y, -mLoadBounds.z,
  191. mLoadBounds.x, mLoadBounds.y, mLoadBounds.z);
  192. loadBox.setCenter(getPosition());
  193. passes = loadBox.isOverlapped(testBox);
  194. }
  195. else
  196. {
  197. passes = getWorldBox().isOverlapped(testBox);
  198. }
  199. }
  200. if (passes)
  201. passes = evaluateCondition();
  202. return passes;
  203. }
  204. void SubScene::write(Stream& stream, U32 tabStop, U32 flags)
  205. {
  206. MutexHandle handle;
  207. handle.lock(mMutex);
  208. // export selected only?
  209. if ((flags & SelectedOnly) && !isSelected())
  210. {
  211. for (U32 i = 0; i < size(); i++)
  212. (*this)[i]->write(stream, tabStop, flags);
  213. return;
  214. }
  215. stream.writeTabs(tabStop);
  216. char buffer[2048];
  217. const U32 bufferWriteLen = dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() && !(flags & NoName) ? getName() : "");
  218. stream.write(bufferWriteLen, buffer);
  219. writeFields(stream, tabStop + 1);
  220. //The only meaningful difference between this and simSet for writing is we skip the children, since they're just the levelAsset contents
  221. stream.writeTabs(tabStop);
  222. stream.write(4, "};\r\n");
  223. }
  224. void SubScene::processTick(const Move* move)
  225. {
  226. mCurrTick += TickMs;
  227. if (mCurrTick > mTickPeriodMS)
  228. {
  229. mCurrTick = 0;
  230. //re-evaluate
  231. if (!evaluateCondition())
  232. unload();
  233. }
  234. }
  235. void SubScene::_onFileChanged(const Torque::Path& path)
  236. {
  237. if (gEditingMission)
  238. return;
  239. if(mSubSceneAsset.isNull() || Torque::Path(mSubSceneAsset->getLevelPath()) != path)
  240. return;
  241. if (mSaving)
  242. return;
  243. AssertFatal(path == mSubSceneAsset->getLevelPath(), "SubScene::_onFileChanged - path does not match filename.");
  244. _closeFile(false);
  245. _loadFile(false);
  246. setMaskBits(U32_MAX);
  247. }
  248. void SubScene::_removeContents(SimGroupIterator set)
  249. {
  250. for (SimGroupIterator itr(set); *itr; ++itr)
  251. {
  252. SimGroup* child = dynamic_cast<SimGroup*>(*itr);
  253. if (child)
  254. {
  255. _removeContents(SimGroupIterator(child));
  256. GameBase* asGameBase = dynamic_cast<GameBase*>(child);
  257. if (asGameBase)
  258. {
  259. asGameBase->scriptOnRemove();
  260. }
  261. Sim::cancelPendingEvents(child);
  262. child->safeDeleteObject();
  263. }
  264. }
  265. }
  266. void SubScene::_closeFile(bool removeFileNotify)
  267. {
  268. AssertFatal(isServerObject(), "Trying to close out a subscene file on the client is bad!");
  269. _removeContents(SimGroupIterator(this));
  270. if (removeFileNotify && mSubSceneAsset.notNull() && mSubSceneAsset->getLevelPath() != StringTable->EmptyString())
  271. {
  272. Torque::FS::RemoveChangeNotification(mSubSceneAsset->getLevelPath(), this, &SubScene::_onFileChanged);
  273. }
  274. mGameModesList.clear();
  275. }
  276. void SubScene::_loadFile(bool addFileNotify)
  277. {
  278. AssertFatal(isServerObject(), "Trying to load a SubScene file on the client is bad!");
  279. if(mSubSceneAsset.isNull() || mSubSceneAsset->getLevelPath() == StringTable->EmptyString())
  280. return;
  281. String evalCmd = String::ToString("exec(\"%s\");", mSubSceneAsset->getLevelPath());
  282. String instantGroup = Con::getVariable("InstantGroup");
  283. Con::setIntVariable("InstantGroup", this->getId());
  284. Con::evaluate((const char*)evalCmd.c_str(), false, mSubSceneAsset->getLevelPath());
  285. Con::setVariable("InstantGroup", instantGroup.c_str());
  286. if (addFileNotify)
  287. Torque::FS::AddChangeNotification(mSubSceneAsset->getLevelPath(), this, &SubScene::_onFileChanged);
  288. }
  289. void SubScene::load()
  290. {
  291. mStartUnloadTimerMS = -1; //reset unload timers
  292. //no need to load multiple times
  293. if (mLoaded)
  294. return;
  295. if (mFreezeLoading)
  296. return;
  297. if (mSaving)
  298. return;
  299. GameMode::findGameModes(mGameModesNames, &mGameModesList);
  300. if (!isSelected() && (String(mGameModesNames).isNotEmpty() && mGameModesList.size() == 0) || !evaluateCondition())
  301. {
  302. mLoaded = false;
  303. return;
  304. }
  305. _loadFile(true);
  306. mLoaded = true;
  307. onLoaded_callback();
  308. for (U32 i = 0; i < mGameModesList.size(); i++)
  309. {
  310. mGameModesList[i]->onSubsceneLoaded_callback(this);
  311. }
  312. }
  313. void SubScene::unload()
  314. {
  315. if (!mLoaded)
  316. return;
  317. if (mFreezeLoading)
  318. return;
  319. if (mSaving)
  320. return;
  321. if (isSelected())
  322. {
  323. mStartUnloadTimerMS = Sim::getCurrentTime();
  324. return; //if a child is selected, then we don't want to unload
  325. }
  326. //scan down through our child objects, see if any are marked as selected,
  327. //if so, skip unloading and reset the timer
  328. for (SimGroupIterator itr(this); *itr; ++itr)
  329. {
  330. SimGroup* childGrp = dynamic_cast<SimGroup*>(*itr);
  331. if (childGrp)
  332. {
  333. if (childGrp->isSelected())
  334. {
  335. mStartUnloadTimerMS = Sim::getCurrentTime();
  336. return; //if a child is selected, then we don't want to unload
  337. }
  338. for (SimGroupIterator cldItr(childGrp); *cldItr; ++cldItr)
  339. {
  340. SimObject* chldChld = dynamic_cast<SimObject*>(*cldItr);
  341. if (chldChld && chldChld->isSelected())
  342. {
  343. mStartUnloadTimerMS = Sim::getCurrentTime();
  344. return; //if a child is selected, then we don't want to unload
  345. }
  346. }
  347. }
  348. }
  349. onUnloaded_callback();
  350. for (U32 i = 0; i < mGameModesList.size(); i++)
  351. {
  352. mGameModesList[i]->onSubsceneUnloaded_callback(this);
  353. }
  354. if (!mOnUnloadCommand.isEmpty())
  355. {
  356. String command = "%this = " + String(getIdString()) + "; " + mOnUnloadCommand + ";";
  357. Con::evaluatef(command.c_str());
  358. }
  359. _closeFile(true);
  360. mLoaded = false;
  361. }
  362. bool SubScene::save(const String& filename)
  363. {
  364. if (!isServerObject())
  365. return false;
  366. //if there's nothing TO save, don't bother
  367. if (size() == 0 || !isLoaded())
  368. return false;
  369. if (mSubSceneAsset.isNull())
  370. return false;
  371. if (mSaving)
  372. return false;
  373. //If we're flagged for unload, push back the unload timer so we can't accidentally trip be saving partway through an unload
  374. if (mStartUnloadTimerMS != -1)
  375. mStartUnloadTimerMS = Sim::getCurrentTime();
  376. mSaving = true;
  377. PersistenceManager prMger;
  378. StringTableEntry levelPath = mSubSceneAsset->getLevelPath();
  379. if (filename.isNotEmpty())
  380. levelPath = StringTable->insert(filename.c_str());
  381. FileStream fs;
  382. fs.open(levelPath, Torque::FS::File::Write);
  383. fs.close();
  384. for (SimGroupIterator itr(this); *itr; ++itr)
  385. {
  386. SimObject* childObj = (*itr);
  387. if (!prMger.isDirty(childObj))
  388. {
  389. if ((*itr)->isMethod("onSaving"))
  390. {
  391. Con::executef((*itr), "onSaving", mSubSceneAssetId);
  392. }
  393. if (childObj->getGroup() == this)
  394. {
  395. prMger.setDirty((*itr), levelPath);
  396. }
  397. }
  398. if(dynamic_cast<MeshRoad*>(childObj) || dynamic_cast<River*>(childObj))
  399. {
  400. prMger.addRemoveField(childObj, "position");
  401. }
  402. }
  403. prMger.saveDirty();
  404. //process our gameModeList and write it out to the levelAsset for metadata stashing
  405. bool saveSuccess = false;
  406. //Get the level asset
  407. if (mSubSceneAsset.isNull())
  408. return saveSuccess;
  409. //update the gamemode list as well
  410. mSubSceneAsset->setDataField(StringTable->insert("gameModesNames"), NULL, StringTable->insert(mGameModesNames));
  411. //Finally, save
  412. saveSuccess = mSubSceneAsset->saveAsset();
  413. mSaving = false;
  414. return saveSuccess;
  415. }
  416. void SubScene::_onSelected()
  417. {
  418. if (!isLoaded() && isServerObject())
  419. load();
  420. }
  421. void SubScene::_onUnselected()
  422. {
  423. }
  424. void SubScene::prepRenderImage(SceneRenderState* state)
  425. {
  426. // only render if selected or render flag is set
  427. if (/*!smRenderTriggers && */!isSelected())
  428. return;
  429. ObjectRenderInst* ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  430. ri->renderDelegate.bind(this, &SubScene::renderObject);
  431. ri->type = RenderPassManager::RIT_Editor;
  432. ri->translucentSort = true;
  433. ri->defaultKey = 1;
  434. state->getRenderPass()->addInst(ri);
  435. }
  436. void SubScene::renderObject(ObjectRenderInst* ri,
  437. SceneRenderState* state,
  438. BaseMatInstance* overrideMat)
  439. {
  440. if (overrideMat)
  441. return;
  442. GFXStateBlockDesc desc;
  443. desc.setZReadWrite(true, false);
  444. desc.setBlend(true);
  445. // Trigger polyhedrons are set up with outward facing normals and CCW ordering
  446. // so can't enable backface culling.
  447. desc.setCullMode(GFXCullNone);
  448. GFXTransformSaver saver;
  449. MatrixF mat = getRenderTransform();
  450. GFX->multWorld(mat);
  451. GFXDrawUtil* drawer = GFX->getDrawUtil();
  452. //Box3F scale = getScale()
  453. //Box3F bounds = Box3F(-m)
  454. if(mUseSeparateLoadBounds && !mGlobalLayer)
  455. {
  456. Box3F loadBounds = Box3F(-mLoadBounds.x, -mLoadBounds.y, -mLoadBounds.z,
  457. mLoadBounds.x, mLoadBounds.y, mLoadBounds.z);
  458. //bounds.setCenter(getPosition());
  459. ColorI loadBoundsColor = ColorI(200, 200, 100, 50);
  460. drawer->drawCube(desc, loadBounds, loadBoundsColor);
  461. // Render wireframe.
  462. desc.setFillModeWireframe();
  463. drawer->drawCube(desc, loadBounds, ColorI::BLACK);
  464. desc.setFillModeSolid();
  465. }
  466. Point3F scale = getScale();
  467. Box3F bounds = Box3F(-scale / 2, scale / 2);
  468. ColorI boundsColor = ColorI(135, 206, 235, 50);
  469. if (mGlobalLayer)
  470. boundsColor = ColorI(200, 100, 100, 25);
  471. else if (mLoaded)
  472. boundsColor = ColorI(50, 200, 50, 50);
  473. drawer->drawCube(desc, bounds, boundsColor);
  474. // Render wireframe.
  475. desc.setFillModeWireframe();
  476. drawer->drawCube(desc, bounds, ColorI::BLACK);
  477. }
  478. DefineEngineMethod(SubScene, save, bool, (const char* filename), (""),
  479. "Save out the subScene.\n"
  480. "@param filename (optional) If empty, the subScene will save to it's regular asset path. If defined, it will save out to the filename provided")
  481. {
  482. return object->save(filename);
  483. }
  484. DefineEngineMethod(SubScene, load, void, (), ,
  485. "Loads the SubScene's level file.\n")
  486. {
  487. object->load();
  488. }
  489. DefineEngineMethod(SubScene, unload, void, (), ,
  490. "Unloads the SubScene's level file.\n")
  491. {
  492. object->unload();
  493. }