SubScene.cpp 12 KB

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