SubScene.cpp 15 KB

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