prefab.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. }
  62. Prefab::~Prefab()
  63. {
  64. }
  65. void Prefab::initPersistFields()
  66. {
  67. addGroup( "Prefab" );
  68. addProtectedField( "filename", TypePrefabFilename, Offset( mFilename, Prefab ),
  69. &protectedSetFile, &defaultProtectedGetFn,
  70. "(.prefab) File describing objects within this prefab." );
  71. endGroup( "Prefab" );
  72. Parent::initPersistFields();
  73. }
  74. extern bool gEditingMission;
  75. bool Prefab::onAdd()
  76. {
  77. if ( !Parent::onAdd() )
  78. return false;
  79. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ),
  80. Point3F( 0.5f, 0.5f, 0.5f ) );
  81. resetWorldBox();
  82. // Not added to the scene unless we are editing.
  83. if ( gEditingMission )
  84. onEditorEnable();
  85. // Only the server-side prefab needs to create/update child objects.
  86. // We rely on regular Torque ghosting of the individual child objects
  87. // to take care of the rest.
  88. if ( isServerObject() )
  89. {
  90. _loadFile( true );
  91. _updateChildren();
  92. }
  93. return true;
  94. }
  95. void Prefab::onRemove()
  96. {
  97. if ( isServerObject() )
  98. _closeFile( true );
  99. removeFromScene();
  100. Parent::onRemove();
  101. }
  102. void Prefab::onEditorEnable()
  103. {
  104. if ( isClientObject() )
  105. return;
  106. // Just in case we are already in the scene, lets not cause an assert.
  107. if ( mContainer != NULL )
  108. return;
  109. // Enable ghosting so we can see this on the client.
  110. mNetFlags.set(Ghostable);
  111. setScopeAlways();
  112. addToScene();
  113. Parent::onEditorEnable();
  114. }
  115. void Prefab::onEditorDisable()
  116. {
  117. if ( isClientObject() )
  118. return;
  119. // Just in case we are not in the scene, lets not cause an assert.
  120. if ( mContainer == NULL )
  121. return;
  122. // Do not need this on the client if we are not editing.
  123. removeFromScene();
  124. mNetFlags.clear(Ghostable);
  125. clearScopeAlways();
  126. Parent::onEditorDisable();
  127. }
  128. void Prefab::inspectPostApply()
  129. {
  130. Parent::inspectPostApply();
  131. }
  132. void Prefab::setTransform(const MatrixF & mat)
  133. {
  134. Parent::setTransform( mat );
  135. if ( isServerObject() )
  136. {
  137. setMaskBits( TransformMask );
  138. _updateChildren();
  139. }
  140. }
  141. void Prefab::setScale(const VectorF & scale)
  142. {
  143. Parent::setScale( scale );
  144. if ( isServerObject() )
  145. {
  146. setMaskBits( TransformMask );
  147. _updateChildren();
  148. }
  149. }
  150. U32 Prefab::packUpdate( NetConnection *conn, U32 mask, BitStream *stream )
  151. {
  152. U32 retMask = Parent::packUpdate( conn, mask, stream );
  153. mathWrite(*stream,mObjBox);
  154. if ( stream->writeFlag( mask & FileMask ) )
  155. {
  156. stream->write( mFilename );
  157. }
  158. if ( stream->writeFlag( mask & TransformMask ) )
  159. {
  160. mathWrite(*stream, getTransform());
  161. mathWrite(*stream, getScale());
  162. }
  163. return retMask;
  164. }
  165. void Prefab::unpackUpdate(NetConnection *conn, BitStream *stream)
  166. {
  167. Parent::unpackUpdate(conn, stream);
  168. mathRead(*stream, &mObjBox);
  169. resetWorldBox();
  170. // FileMask
  171. if ( stream->readFlag() )
  172. {
  173. stream->read( &mFilename );
  174. }
  175. // TransformMask
  176. if ( stream->readFlag() )
  177. {
  178. mathRead(*stream, &mObjToWorld);
  179. mathRead(*stream, &mObjScale);
  180. setTransform( mObjToWorld );
  181. }
  182. }
  183. bool Prefab::protectedSetFile( void *object, const char *index, const char *data )
  184. {
  185. Prefab *prefab = static_cast<Prefab*>(object);
  186. String file = String( Platform::makeRelativePathName(data, Platform::getMainDotCsDir()) );
  187. prefab->setFile( file );
  188. return false;
  189. }
  190. void Prefab::setFile( String file )
  191. {
  192. AssertFatal( isServerObject(), "Prefab-bad" );
  193. if ( !isProperlyAdded() )
  194. {
  195. mFilename = file;
  196. return;
  197. }
  198. // Client-side Prefab(s) do not create/update/reference children, everything
  199. // is handled on the server-side. In normal usage this will never actually
  200. // be called for the client-side prefab but maybe the user did so accidentally.
  201. if ( isClientObject() )
  202. {
  203. Con::errorf( "Prefab::setFile( %s ) - Should not be called on a client-side Prefab.", file.c_str() );
  204. return;
  205. }
  206. _closeFile( true );
  207. mFilename = file;
  208. if ( isProperlyAdded() )
  209. _loadFile( true );
  210. }
  211. SimGroup* Prefab::explode()
  212. {
  213. Scene* scene = Scene::getRootScene();
  214. if ( !scene)
  215. {
  216. Con::errorf( "Prefab::explode, Scene was not found." );
  217. return NULL;
  218. }
  219. if ( !mChildGroup )
  220. return NULL;
  221. SimGroup *group = mChildGroup;
  222. Vector<SceneObject*> foundObjects;
  223. group->findObjectByType( foundObjects );
  224. if ( foundObjects.empty() )
  225. return NULL;
  226. for ( S32 i = 0; i < foundObjects.size(); i++ )
  227. {
  228. SceneObject *child = foundObjects[i];
  229. _updateChildTransform( child );
  230. smChildToPrefabMap.erase( child->getId() );
  231. }
  232. scene->addObject(group);
  233. mChildGroup = NULL;
  234. mChildMap.clear();
  235. return group;
  236. }
  237. void Prefab::_closeFile( bool removeFileNotify )
  238. {
  239. AssertFatal( isServerObject(), "Prefab-bad" );
  240. mChildMap.clear();
  241. if ( mChildGroup )
  242. {
  243. // Get a flat vector of all our children.
  244. Vector<SceneObject*> foundObjects;
  245. mChildGroup->findObjectByType( foundObjects );
  246. // Remove them all from the ChildToPrefabMap.
  247. for ( S32 i = 0; i < foundObjects.size(); i++ )
  248. smChildToPrefabMap.erase( foundObjects[i]->getId() );
  249. mChildGroup->deleteObject();
  250. mChildGroup = NULL;
  251. }
  252. if ( removeFileNotify )
  253. Torque::FS::RemoveChangeNotification( mFilename, this, &Prefab::_onFileChanged );
  254. // Back to a default bounding box size.
  255. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ), Point3F( 0.5f, 0.5f, 0.5f ) );
  256. resetWorldBox();
  257. }
  258. void Prefab::_loadFile( bool addFileNotify )
  259. {
  260. AssertFatal( isServerObject(), "Prefab-bad" );
  261. if ( mFilename.isEmpty() )
  262. return;
  263. if ( !Platform::isFile( mFilename ) )
  264. {
  265. Con::errorf( "Prefab::_loadFile() - file %s was not found.", mFilename.c_str() );
  266. return;
  267. }
  268. if ( sPrefabFileStack.contains(mFilename) )
  269. {
  270. Con::errorf(
  271. "Prefab::_loadFile - failed loading prefab file (%s). \n"
  272. "File was referenced recursively by both a Parent and Child prefab.", mFilename.c_str() );
  273. return;
  274. }
  275. sPrefabFileStack.push_back(mFilename);
  276. String command = String::ToString( "exec( \"%s\" );", mFilename.c_str() );
  277. Con::evaluate( command );
  278. SimGroup *group;
  279. if ( !Sim::findObject( Con::getVariable( "$ThisPrefab" ), group ) )
  280. {
  281. Con::errorf( "Prefab::_loadFile() - file %s did not create $ThisPrefab.", mFilename.c_str() );
  282. return;
  283. }
  284. if ( addFileNotify )
  285. Torque::FS::AddChangeNotification( mFilename, this, &Prefab::_onFileChanged );
  286. mChildGroup = group;
  287. Vector<SceneObject*> foundObjects;
  288. mChildGroup->findObjectByType( foundObjects );
  289. if ( !foundObjects.empty() )
  290. {
  291. mWorldBox = Box3F::Invalid;
  292. for ( S32 i = 0; i < foundObjects.size(); i++ )
  293. {
  294. SceneObject *child = foundObjects[i];
  295. mChildMap.insert( child->getId(), Transform( child->getTransform(), child->getScale() ) );
  296. smChildToPrefabMap.insert( child->getId(), getId() );
  297. _updateChildTransform( child );
  298. mWorldBox.intersect( child->getWorldBox() );
  299. }
  300. resetObjectBox();
  301. }
  302. sPrefabFileStack.pop_back();
  303. onLoad_callback( mChildGroup );
  304. }
  305. void Prefab::_updateChildTransform( SceneObject* child )
  306. {
  307. ChildToMatMap::Iterator itr = mChildMap.find(child->getId());
  308. AssertFatal( itr != mChildMap.end(), "Prefab, mChildMap out of synch with mChildGroup." );
  309. MatrixF mat( itr->value.mat );
  310. Point3F pos = mat.getPosition();
  311. pos.convolve( mObjScale );
  312. mat.setPosition( pos );
  313. mat.mulL( mObjToWorld );
  314. child->setTransform( mat );
  315. child->setScale( itr->value.scale * mObjScale );
  316. // Hack for PhysicsShape... need to store the "editor" position to return to
  317. // when a physics reset event occurs. Normally this would be where it is
  318. // during onAdd, but in this case it is not because the prefab stores its
  319. // child objects in object space...
  320. PhysicsShape *childPS = dynamic_cast<PhysicsShape*>( child );
  321. if ( childPS )
  322. childPS->storeRestorePos();
  323. }
  324. void Prefab::_updateChildren()
  325. {
  326. if ( !mChildGroup )
  327. return;
  328. Vector<SceneObject*> foundObjects;
  329. mChildGroup->findObjectByType( foundObjects );
  330. for ( S32 i = 0; i < foundObjects.size(); i++ )
  331. {
  332. SceneObject *child = foundObjects[i];
  333. _updateChildTransform( child );
  334. if ( child->getClientObject() )
  335. {
  336. ((SceneObject*)child->getClientObject())->setTransform( child->getTransform() );
  337. ((SceneObject*)child->getClientObject())->setScale( child->getScale() );
  338. }
  339. }
  340. }
  341. void Prefab::_onFileChanged( const Torque::Path &path )
  342. {
  343. AssertFatal( path == mFilename, "Prefab::_onFileChanged - path does not match filename." );
  344. _closeFile(false);
  345. _loadFile(false);
  346. setMaskBits(U32_MAX);
  347. }
  348. Prefab* Prefab::getPrefabByChild( SimObject *child )
  349. {
  350. ChildToPrefabMap::Iterator itr = smChildToPrefabMap.find( child->getId() );
  351. if ( itr == smChildToPrefabMap.end() )
  352. return NULL;
  353. Prefab *prefab;
  354. if ( !Sim::findObject( itr->value, prefab ) )
  355. {
  356. Con::errorf( "Prefab::getPrefabByChild - child object mapped to a prefab that no longer exists." );
  357. return NULL;
  358. }
  359. return prefab;
  360. }
  361. bool Prefab::isValidChild( SimObject *simobj, bool logWarnings )
  362. {
  363. if ( simobj->getName() && simobj == Scene::getRootScene() )
  364. {
  365. if ( logWarnings )
  366. Con::warnf( "root Scene is not valid within a Prefab." );
  367. return false;
  368. }
  369. if ( simobj->getClassRep()->isClass( AbstractClassRep::findClassRep("LevelInfo") ) )
  370. {
  371. if ( logWarnings )
  372. Con::warnf( "LevelInfo objects are not valid within a Prefab" );
  373. return false;
  374. }
  375. if ( simobj->getClassRep()->isClass( AbstractClassRep::findClassRep("TimeOfDay") ) )
  376. {
  377. if ( logWarnings )
  378. Con::warnf( "TimeOfDay objects are not valid within a Prefab" );
  379. return false;
  380. }
  381. SceneObject *sceneobj = dynamic_cast<SceneObject*>(simobj);
  382. if ( !sceneobj )
  383. return false;
  384. if ( sceneobj->isGlobalBounds() )
  385. {
  386. if ( logWarnings )
  387. Con::warnf( "SceneObject's with global bounds are not valid within a Prefab." );
  388. return false;
  389. }
  390. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("TerrainBlock") ) )
  391. {
  392. if ( logWarnings )
  393. Con::warnf( "TerrainBlock objects are not valid within a Prefab" );
  394. return false;
  395. }
  396. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("Player") ) )
  397. {
  398. if ( logWarnings )
  399. Con::warnf( "Player objects are not valid within a Prefab" );
  400. return false;
  401. }
  402. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("DecalRoad") ) )
  403. {
  404. if ( logWarnings )
  405. Con::warnf( "DecalRoad objects are not valid within a Prefab" );
  406. return false;
  407. }
  408. return true;
  409. }
  410. bool Prefab::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF& sphere)
  411. {
  412. Vector<SceneObject*> foundObjects;
  413. if (mChildGroup.isNull() || mChildGroup->empty())
  414. {
  415. Con::warnf("Bad Prefab Config! %s has no valid entries!", getName());
  416. return false;
  417. }
  418. mChildGroup->findObjectByType(foundObjects);
  419. for (S32 i = 0; i < foundObjects.size(); i++)
  420. {
  421. foundObjects[i]->buildPolyList(context, polyList, box, sphere);
  422. }
  423. return true;
  424. }
  425. bool Prefab::buildExportPolyList(ColladaUtils::ExportData* exportData, const Box3F &box, const SphereF &sphere)
  426. {
  427. Vector<SceneObject*> foundObjects;
  428. mChildGroup->findObjectByType(foundObjects);
  429. for (S32 i = 0; i < foundObjects.size(); i++)
  430. {
  431. foundObjects[i]->buildExportPolyList(exportData, box, sphere);
  432. }
  433. return true;
  434. }
  435. ExplodePrefabUndoAction::ExplodePrefabUndoAction( Prefab *prefab )
  436. : UndoAction( "Explode Prefab" )
  437. {
  438. mPrefabId = prefab->getId();
  439. mGroup = NULL;
  440. // Do the action.
  441. redo();
  442. }
  443. void ExplodePrefabUndoAction::undo()
  444. {
  445. if ( !mGroup )
  446. {
  447. Con::errorf( "ExplodePrefabUndoAction::undo - NULL Group" );
  448. return;
  449. }
  450. mGroup->deleteObject();
  451. mGroup = NULL;
  452. }
  453. void ExplodePrefabUndoAction::redo()
  454. {
  455. Prefab *prefab;
  456. if ( !Sim::findObject( mPrefabId, prefab ) )
  457. {
  458. Con::errorf( "ExplodePrefabUndoAction::redo - Prefab (%i) not found.", mPrefabId );
  459. return;
  460. }
  461. mGroup = prefab->explode();
  462. String name;
  463. if ( prefab->getName() && prefab->getName()[0] != '\0' )
  464. name = prefab->getName();
  465. else
  466. name = "prefab";
  467. name += "_exploded";
  468. name = Sim::getUniqueName( name );
  469. mGroup->assignName( name );
  470. }