prefab.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "T3D/prefab.h"
  24. #include "math/mathIO.h"
  25. #include "core/stream/bitStream.h"
  26. #include "scene/sceneRenderState.h"
  27. #include "gfx/gfxTransformSaver.h"
  28. #include "renderInstance/renderPassManager.h"
  29. #include "console/consoleTypes.h"
  30. #include "core/volume.h"
  31. #include "console/engineAPI.h"
  32. #include "T3D/physics/physicsShape.h"
  33. #include "core/util/path.h"
  34. #include "T3D/Scene.h"
  35. // We use this locally ( within this file ) to prevent infinite recursion
  36. // while loading prefab files that contain other prefabs.
  37. static Vector<String> sPrefabFileStack;
  38. Map<SimObjectId,SimObjectId> Prefab::smChildToPrefabMap;
  39. IMPLEMENT_CO_NETOBJECT_V1(Prefab);
  40. ConsoleDocClass( Prefab,
  41. "@brief A collection of arbitrary objects which can be allocated and manipulated as a group.\n\n"
  42. "%Prefab always points to a (.prefab) file which defines its objects. In "
  43. "fact more than one %Prefab can reference this file and both will update "
  44. "if the file is modified.\n\n"
  45. "%Prefab is a very simple object and only exists on the server. When it is "
  46. "created it allocates children objects by reading the (.prefab) file like "
  47. "a list of instructions. It then sets their transform relative to the %Prefab "
  48. "and Torque networking handles the rest by ghosting the new objects to clients. "
  49. "%Prefab itself is not ghosted.\n\n"
  50. "@ingroup enviroMisc"
  51. );
  52. IMPLEMENT_CALLBACK( Prefab, onLoad, void, ( SimGroup *children ), ( children ),
  53. "Called when the prefab file is loaded and children objects are created.\n"
  54. "@param children SimGroup containing all children objects.\n"
  55. );
  56. Prefab::Prefab()
  57. {
  58. // Not ghosted unless we're editing
  59. mNetFlags.clear(Ghostable);
  60. mTypeMask |= StaticObjectType;
  61. mFilename = StringTable->EmptyString();
  62. }
  63. Prefab::~Prefab()
  64. {
  65. }
  66. void Prefab::initPersistFields()
  67. {
  68. docsURL;
  69. addGroup( "Prefab" );
  70. addProtectedField( "filename", TypePrefabFilename, Offset( mFilename, Prefab ),
  71. &protectedSetFile, &defaultProtectedGetFn,
  72. "(.prefab) File describing objects within this prefab." );
  73. endGroup( "Prefab" );
  74. Parent::initPersistFields();
  75. }
  76. StringTableEntry Prefab::getTypeHint() const
  77. {
  78. return (mFilename != StringTable->EmptyString()) ? StringTable->insert(Torque::Path(mFilename).getFileName().c_str()) : StringTable->EmptyString();
  79. }
  80. extern bool gEditingMission;
  81. bool Prefab::onAdd()
  82. {
  83. if ( !Parent::onAdd() )
  84. return false;
  85. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ),
  86. Point3F( 0.5f, 0.5f, 0.5f ) );
  87. resetWorldBox();
  88. // Not added to the scene unless we are editing.
  89. if ( gEditingMission )
  90. onEditorEnable();
  91. // Only the server-side prefab needs to create/update child objects.
  92. // We rely on regular Torque ghosting of the individual child objects
  93. // to take care of the rest.
  94. if ( isServerObject() )
  95. {
  96. _loadFile( true );
  97. _updateChildren();
  98. }
  99. return true;
  100. }
  101. void Prefab::onRemove()
  102. {
  103. if ( isServerObject() )
  104. _closeFile( true );
  105. removeFromScene();
  106. Parent::onRemove();
  107. }
  108. void Prefab::onEditorEnable()
  109. {
  110. if ( isClientObject() )
  111. return;
  112. // Just in case we are already in the scene, lets not cause an assert.
  113. if ( mContainer != NULL )
  114. return;
  115. // Enable ghosting so we can see this on the client.
  116. mNetFlags.set(Ghostable);
  117. setScopeAlways();
  118. addToScene();
  119. Parent::onEditorEnable();
  120. }
  121. void Prefab::onEditorDisable()
  122. {
  123. if ( isClientObject() )
  124. return;
  125. // Just in case we are not in the scene, lets not cause an assert.
  126. if ( mContainer == NULL )
  127. return;
  128. // Do not need this on the client if we are not editing.
  129. removeFromScene();
  130. mNetFlags.clear(Ghostable);
  131. clearScopeAlways();
  132. Parent::onEditorDisable();
  133. }
  134. void Prefab::inspectPostApply()
  135. {
  136. Parent::inspectPostApply();
  137. }
  138. void Prefab::setTransform(const MatrixF & mat)
  139. {
  140. Parent::setTransform( mat );
  141. if ( isServerObject() )
  142. {
  143. setMaskBits( TransformMask );
  144. _updateChildren();
  145. }
  146. }
  147. void Prefab::setScale(const VectorF & scale)
  148. {
  149. Parent::setScale( scale );
  150. if ( isServerObject() )
  151. {
  152. setMaskBits( TransformMask );
  153. _updateChildren();
  154. }
  155. }
  156. U32 Prefab::packUpdate( NetConnection *conn, U32 mask, BitStream *stream )
  157. {
  158. U32 retMask = Parent::packUpdate( conn, mask, stream );
  159. mathWrite(*stream,mObjBox);
  160. if ( stream->writeFlag( mask & FileMask ) )
  161. {
  162. stream->writeString( mFilename );
  163. }
  164. if ( stream->writeFlag( mask & TransformMask ) )
  165. {
  166. mathWrite(*stream, getTransform());
  167. mathWrite(*stream, getScale());
  168. }
  169. return retMask;
  170. }
  171. void Prefab::unpackUpdate(NetConnection *conn, BitStream *stream)
  172. {
  173. Parent::unpackUpdate(conn, stream);
  174. mathRead(*stream, &mObjBox);
  175. resetWorldBox();
  176. // FileMask
  177. if ( stream->readFlag() )
  178. {
  179. mFilename = stream->readSTString();
  180. }
  181. // TransformMask
  182. if ( stream->readFlag() )
  183. {
  184. mathRead(*stream, &mObjToWorld);
  185. mathRead(*stream, &mObjScale);
  186. setTransform( mObjToWorld );
  187. }
  188. }
  189. bool Prefab::protectedSetFile( void *object, const char *index, const char *data )
  190. {
  191. Prefab *prefab = static_cast<Prefab*>(object);
  192. prefab->setFile( StringTable->insert(Platform::makeRelativePathName(data, Platform::getMainDotCsDir())));
  193. return false;
  194. }
  195. void Prefab::setFile( StringTableEntry file )
  196. {
  197. AssertFatal( isServerObject(), "Prefab-bad" );
  198. if ( !isProperlyAdded() )
  199. {
  200. mFilename = file;
  201. return;
  202. }
  203. // Client-side Prefab(s) do not create/update/reference children, everything
  204. // is handled on the server-side. In normal usage this will never actually
  205. // be called for the client-side prefab but maybe the user did so accidentally.
  206. if ( isClientObject() )
  207. {
  208. Con::errorf( "Prefab::setFile( %s ) - Should not be called on a client-side Prefab.", file );
  209. return;
  210. }
  211. _closeFile( true );
  212. mFilename = file;
  213. if ( isProperlyAdded() )
  214. _loadFile( true );
  215. }
  216. SimGroup* Prefab::explode()
  217. {
  218. Scene* scene = Scene::getRootScene();
  219. if ( !scene)
  220. {
  221. Con::errorf( "Prefab::explode, Scene was not found." );
  222. return NULL;
  223. }
  224. if ( !mChildGroup )
  225. return NULL;
  226. SimGroup *group = mChildGroup;
  227. Vector<SceneObject*> foundObjects;
  228. group->findObjectByType( foundObjects );
  229. if ( foundObjects.empty() )
  230. return NULL;
  231. for ( S32 i = 0; i < foundObjects.size(); i++ )
  232. {
  233. SceneObject *child = foundObjects[i];
  234. _updateChildTransform( child );
  235. smChildToPrefabMap.erase( child->getId() );
  236. }
  237. scene->addObject(group);
  238. mChildGroup = NULL;
  239. mChildMap.clear();
  240. return group;
  241. }
  242. void Prefab::_closeFile( bool removeFileNotify )
  243. {
  244. AssertFatal( isServerObject(), "Prefab-bad" );
  245. mChildMap.clear();
  246. if ( mChildGroup )
  247. {
  248. // Get a flat vector of all our children.
  249. Vector<SceneObject*> foundObjects;
  250. mChildGroup->findObjectByType( foundObjects );
  251. // Remove them all from the ChildToPrefabMap.
  252. for ( S32 i = 0; i < foundObjects.size(); i++ )
  253. smChildToPrefabMap.erase( foundObjects[i]->getId() );
  254. mChildGroup->deleteObject();
  255. mChildGroup = NULL;
  256. }
  257. if ( removeFileNotify )
  258. Torque::FS::RemoveChangeNotification( mFilename, this, &Prefab::_onFileChanged );
  259. // Back to a default bounding box size.
  260. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ), Point3F( 0.5f, 0.5f, 0.5f ) );
  261. resetWorldBox();
  262. }
  263. void Prefab::_loadFile( bool addFileNotify )
  264. {
  265. AssertFatal( isServerObject(), "Prefab-bad" );
  266. if ( mFilename == StringTable->EmptyString())
  267. return;
  268. if ( !Torque::FS::IsScriptFile( mFilename ) )
  269. {
  270. Con::errorf( "Prefab::_loadFile() - file %s was not found.", mFilename );
  271. return;
  272. }
  273. if ( sPrefabFileStack.contains(mFilename) )
  274. {
  275. Con::errorf(
  276. "Prefab::_loadFile - failed loading prefab file (%s). \n"
  277. "File was referenced recursively by both a Parent and Child prefab.", mFilename );
  278. return;
  279. }
  280. sPrefabFileStack.push_back(mFilename);
  281. String command = String::ToString( "exec( \"%s\" );", mFilename );
  282. Con::evaluate( command );
  283. SimGroup *group;
  284. if ( !Sim::findObject( Con::getVariable( "$ThisPrefab" ), group ) )
  285. {
  286. Con::errorf( "Prefab::_loadFile() - file %s did not create $ThisPrefab.", mFilename );
  287. return;
  288. }
  289. if ( addFileNotify )
  290. Torque::FS::AddChangeNotification( mFilename, this, &Prefab::_onFileChanged );
  291. mChildGroup = group;
  292. Vector<SceneObject*> foundObjects;
  293. mChildGroup->findObjectByType( foundObjects );
  294. if ( !foundObjects.empty() )
  295. {
  296. mWorldBox = Box3F::Invalid;
  297. for ( S32 i = 0; i < foundObjects.size(); i++ )
  298. {
  299. SceneObject *child = foundObjects[i];
  300. mChildMap.insert( child->getId(), Transform( child->getTransform(), child->getScale() ) );
  301. smChildToPrefabMap.insert( child->getId(), getId() );
  302. _updateChildTransform( child );
  303. mWorldBox.intersect( child->getWorldBox() );
  304. }
  305. resetObjectBox();
  306. }
  307. sPrefabFileStack.pop_back();
  308. onLoad_callback( mChildGroup );
  309. }
  310. void Prefab::_updateChildTransform( SceneObject* child )
  311. {
  312. ChildToMatMap::Iterator itr = mChildMap.find(child->getId());
  313. AssertFatal( itr != mChildMap.end(), "Prefab, mChildMap out of synch with mChildGroup." );
  314. MatrixF mat( itr->value.mat );
  315. Point3F pos = mat.getPosition();
  316. pos.convolve( mObjScale );
  317. mat.setPosition( pos );
  318. mat.mulL( mObjToWorld );
  319. child->setTransform( mat );
  320. child->setScale( itr->value.scale * mObjScale );
  321. // Hack for PhysicsShape... need to store the "editor" position to return to
  322. // when a physics reset event occurs. Normally this would be where it is
  323. // during onAdd, but in this case it is not because the prefab stores its
  324. // child objects in object space...
  325. PhysicsShape *childPS = dynamic_cast<PhysicsShape*>( child );
  326. if ( childPS )
  327. childPS->storeRestorePos();
  328. }
  329. void Prefab::_updateChildren()
  330. {
  331. if ( !mChildGroup )
  332. return;
  333. Vector<SceneObject*> foundObjects;
  334. mChildGroup->findObjectByType( foundObjects );
  335. for ( S32 i = 0; i < foundObjects.size(); i++ )
  336. {
  337. SceneObject *child = foundObjects[i];
  338. _updateChildTransform( child );
  339. if ( child->getClientObject() )
  340. {
  341. ((SceneObject*)child->getClientObject())->setTransform( child->getTransform() );
  342. ((SceneObject*)child->getClientObject())->setScale( child->getScale() );
  343. }
  344. }
  345. }
  346. void Prefab::_onFileChanged( const Torque::Path &path )
  347. {
  348. AssertFatal( path == mFilename, "Prefab::_onFileChanged - path does not match filename." );
  349. _closeFile(false);
  350. _loadFile(false);
  351. setMaskBits(U32_MAX);
  352. }
  353. Prefab* Prefab::getPrefabByChild( SimObject *child )
  354. {
  355. ChildToPrefabMap::Iterator itr = smChildToPrefabMap.find( child->getId() );
  356. if ( itr == smChildToPrefabMap.end() )
  357. return NULL;
  358. Prefab *prefab;
  359. if ( !Sim::findObject( itr->value, prefab ) )
  360. {
  361. Con::errorf( "Prefab::getPrefabByChild - child object mapped to a prefab that no longer exists." );
  362. return NULL;
  363. }
  364. return prefab;
  365. }
  366. bool Prefab::isValidChild( SimObject *simobj, bool logWarnings )
  367. {
  368. if ( simobj->getName() && simobj == Scene::getRootScene() )
  369. {
  370. if ( logWarnings )
  371. Con::warnf( "root Scene is not valid within a Prefab." );
  372. return false;
  373. }
  374. if ( simobj->getClassRep()->isClass( AbstractClassRep::findClassRep("LevelInfo") ) )
  375. {
  376. if ( logWarnings )
  377. Con::warnf( "LevelInfo objects are not valid within a Prefab" );
  378. return false;
  379. }
  380. if ( simobj->getClassRep()->isClass( AbstractClassRep::findClassRep("TimeOfDay") ) )
  381. {
  382. if ( logWarnings )
  383. Con::warnf( "TimeOfDay objects are not valid within a Prefab" );
  384. return false;
  385. }
  386. SceneObject *sceneobj = dynamic_cast<SceneObject*>(simobj);
  387. if ( !sceneobj )
  388. return false;
  389. if ( sceneobj->isGlobalBounds() )
  390. {
  391. if ( logWarnings )
  392. Con::warnf( "SceneObject's with global bounds are not valid within a Prefab." );
  393. return false;
  394. }
  395. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("TerrainBlock") ) )
  396. {
  397. if ( logWarnings )
  398. Con::warnf( "TerrainBlock objects are not valid within a Prefab" );
  399. return false;
  400. }
  401. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("Player") ) )
  402. {
  403. if ( logWarnings )
  404. Con::warnf( "Player objects are not valid within a Prefab" );
  405. return false;
  406. }
  407. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("DecalRoad") ) )
  408. {
  409. if ( logWarnings )
  410. Con::warnf( "DecalRoad objects are not valid within a Prefab" );
  411. return false;
  412. }
  413. return true;
  414. }
  415. bool Prefab::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF& sphere)
  416. {
  417. Vector<SceneObject*> foundObjects;
  418. if (mChildGroup.isNull() || mChildGroup->empty())
  419. {
  420. Con::warnf("Bad Prefab Config! %s has no valid entries!", getName());
  421. return false;
  422. }
  423. mChildGroup->findObjectByType(foundObjects);
  424. for (S32 i = 0; i < foundObjects.size(); i++)
  425. {
  426. foundObjects[i]->buildPolyList(context, polyList, box, sphere);
  427. }
  428. return true;
  429. }
  430. bool Prefab::buildExportPolyList(ColladaUtils::ExportData* exportData, const Box3F &box, const SphereF &sphere)
  431. {
  432. Vector<SceneObject*> foundObjects;
  433. mChildGroup->findObjectByType(foundObjects);
  434. for (S32 i = 0; i < foundObjects.size(); i++)
  435. {
  436. foundObjects[i]->buildExportPolyList(exportData, box, sphere);
  437. }
  438. return true;
  439. }
  440. void Prefab::getUtilizedAssets(Vector<StringTableEntry>* usedAssetsList)
  441. {
  442. if (!mChildGroup) return;
  443. Vector<SceneObject*> foundObjects;
  444. mChildGroup->findObjectByType(foundObjects);
  445. for (S32 i = 0; i < foundObjects.size(); i++)
  446. {
  447. SceneObject* child = foundObjects[i];
  448. child->getUtilizedAssets(usedAssetsList);
  449. }
  450. }
  451. ExplodePrefabUndoAction::ExplodePrefabUndoAction( Prefab *prefab )
  452. : UndoAction( "Explode Prefab" )
  453. {
  454. mPrefabId = prefab->getId();
  455. mGroup = NULL;
  456. // Do the action.
  457. redo();
  458. }
  459. void ExplodePrefabUndoAction::undo()
  460. {
  461. if ( !mGroup )
  462. {
  463. Con::errorf( "ExplodePrefabUndoAction::undo - NULL Group" );
  464. return;
  465. }
  466. mGroup->deleteObject();
  467. mGroup = NULL;
  468. }
  469. void ExplodePrefabUndoAction::redo()
  470. {
  471. Prefab *prefab;
  472. if ( !Sim::findObject( mPrefabId, prefab ) )
  473. {
  474. Con::errorf( "ExplodePrefabUndoAction::redo - Prefab (%i) not found.", mPrefabId );
  475. return;
  476. }
  477. mGroup = prefab->explode();
  478. String name;
  479. if ( prefab->getName() && prefab->getName()[0] != '\0' )
  480. name = prefab->getName();
  481. else
  482. name = "prefab";
  483. name += "_exploded";
  484. name = Sim::getUniqueName( name );
  485. mGroup->assignName( name );
  486. }
  487. DefineEngineMethod(Prefab, getChildGroup, S32, (),,
  488. "")
  489. {
  490. return object->getChildGroup();
  491. }