SubScene.cpp 13 KB

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