SubScene.cpp 14 KB

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