entity.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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/entity.h"
  24. #include "core/stream/bitStream.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/consoleObject.h"
  27. #include "sim/netConnection.h"
  28. #include "scene/sceneRenderState.h"
  29. #include "scene/sceneManager.h"
  30. #include "T3D/gameBase/gameProcess.h"
  31. #include "console/engineAPI.h"
  32. #include "T3D/gameBase/gameConnection.h"
  33. #include "math/mathIO.h"
  34. #include "math/mTransform.h"
  35. #include "T3D/components/coreInterfaces.h"
  36. #include "T3D/components/render/renderComponentInterface.h"
  37. #include "T3D/components/collision/collisionInterfaces.h"
  38. #include "gui/controls/guiTreeViewCtrl.h"
  39. #include "assets/assetManager.h"
  40. #include "assets/assetQuery.h"
  41. #include "T3D/assets/ComponentAsset.h"
  42. #include "console/consoleInternal.h"
  43. #include "T3D/gameBase/std/stdMoveList.h"
  44. #include "T3D/prefab.h"
  45. //
  46. #include "gfx/sim/debugDraw.h"
  47. //
  48. #include "T3D/sfx/sfx3DWorld.h"
  49. extern bool gEditingMission;
  50. // Client prediction
  51. static F32 sMinWarpTicks = 0.5f; // Fraction of tick at which instant warp occurs
  52. static S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  53. static S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  54. IMPLEMENT_CO_NETOBJECT_V1(Entity);
  55. ConsoleDocClass(Entity,
  56. "@brief Base Entity class.\n\n"
  57. "Entity is typically made up of a shape and up to two particle emitters. In most cases Entity objects are "
  58. "not created directly. They are usually produced automatically by other means, such as through the Explosion "
  59. "class. When an explosion goes off, its ExplosionData datablock determines what Entity to emit.\n"
  60. "@tsexample\n"
  61. "datablock ExplosionData(GrenadeLauncherExplosion)\n"
  62. "{\n"
  63. " // Assiging Entity data\n"
  64. " Entity = GrenadeEntity;\n\n"
  65. " // Adjust how Entity is ejected\n"
  66. " EntityThetaMin = 10;\n"
  67. " EntityThetaMax = 60;\n"
  68. " EntityNum = 4;\n"
  69. " EntityNumVariance = 2;\n"
  70. " EntityVelocity = 25;\n"
  71. " EntityVelocityVariance = 5;\n\n"
  72. " // Note: other ExplosionData properties are not listed for this example\n"
  73. "};\n"
  74. "@endtsexample\n\n"
  75. "@note Entity are client side only objects.\n"
  76. "@see EntityData\n"
  77. "@see ExplosionData\n"
  78. "@see Explosion\n"
  79. "@ingroup FX\n"
  80. );
  81. Entity::Entity()
  82. {
  83. //mTypeMask |= DynamicShapeObjectType | StaticObjectType | ;
  84. mTypeMask |= EntityObjectType;
  85. mNetFlags.set(Ghostable | ScopeAlways);
  86. mPos = Point3F(0, 0, 0);
  87. mRot = Point3F(0, 0, 0);
  88. mDelta.pos = mDelta.posVec = Point3F::Zero;
  89. mDelta.rot[0].identity();
  90. mDelta.rot[1].identity();
  91. mDelta.warpOffset.set(0.0f, 0.0f, 0.0f);
  92. mDelta.warpTicks = mDelta.warpCount = 0;
  93. mDelta.dt = 1.0f;
  94. mDelta.move = NullMove;
  95. mComponents.clear();
  96. mStartComponentUpdate = false;
  97. mInitialized = false;
  98. mGameObjectAssetId = StringTable->insert("");
  99. }
  100. Entity::~Entity()
  101. {
  102. }
  103. void Entity::initPersistFields()
  104. {
  105. Parent::initPersistFields();
  106. removeField("DataBlock");
  107. addGroup("Transform");
  108. removeField("Position");
  109. addProtectedField("Position", TypePoint3F, Offset(mPos, Entity), &_setPosition, &_getPosition, "Object world orientation.");
  110. removeField("Rotation");
  111. addProtectedField("Rotation", TypeRotationF, Offset(mRot, Entity), &_setRotation, &_getRotation, "Object world orientation.");
  112. //These are basically renamed mountPos/Rot. pretty much there for conveinence
  113. addField("LocalPosition", TypeMatrixPosition, Offset(mMount.xfm, Entity), "Position we are mounted at ( object space of our mount object ).");
  114. addField("LocalRotation", TypeMatrixRotation, Offset(mMount.xfm, Entity), "Rotation we are mounted at ( object space of our mount object ).");
  115. endGroup("Transform");
  116. addGroup("GameObject");
  117. addProtectedField("gameObjectName", TypeGameObjectAssetPtr, Offset(mGameObjectAsset, Entity), &_setGameObject, &defaultProtectedGetFn,
  118. "The asset Id used for the game object this entity is based on.");
  119. endGroup("GameObject");
  120. }
  121. //
  122. bool Entity::_setPosition(void *object, const char *index, const char *data)
  123. {
  124. Entity* so = static_cast<Entity*>(object);
  125. if (so)
  126. {
  127. Point3F pos;
  128. if (!dStrcmp(data, ""))
  129. pos = Point3F(0, 0, 0);
  130. else
  131. Con::setData(TypePoint3F, &pos, 0, 1, &data);
  132. so->setTransform(pos, so->mRot);
  133. }
  134. return false;
  135. }
  136. const char * Entity::_getPosition(void* obj, const char* data)
  137. {
  138. Entity* so = static_cast<Entity*>(obj);
  139. if (so)
  140. {
  141. Point3F pos = so->getPosition();
  142. static const U32 bufSize = 256;
  143. char* returnBuffer = Con::getReturnBuffer(bufSize);
  144. dSprintf(returnBuffer, bufSize, "%g %g %g", pos.x, pos.y, pos.z);
  145. return returnBuffer;
  146. }
  147. return "0 0 0";
  148. }
  149. bool Entity::_setRotation(void *object, const char *index, const char *data)
  150. {
  151. Entity* so = static_cast<Entity*>(object);
  152. if (so)
  153. {
  154. RotationF rot;
  155. Con::setData(TypeRotationF, &rot, 0, 1, &data);
  156. //so->mRot = rot;
  157. //MatrixF mat = rot.asMatrixF();
  158. //mat.setPosition(so->getPosition());
  159. //so->setTransform(mat);
  160. so->setTransform(so->getPosition(), rot);
  161. }
  162. return false;
  163. }
  164. const char * Entity::_getRotation(void* obj, const char* data)
  165. {
  166. Entity* so = static_cast<Entity*>(obj);
  167. if (so)
  168. {
  169. EulerF eulRot = so->mRot.asEulerF();
  170. static const U32 bufSize = 256;
  171. char* returnBuffer = Con::getReturnBuffer(bufSize);
  172. dSprintf(returnBuffer, bufSize, "%g %g %g", mRadToDeg(eulRot.x), mRadToDeg(eulRot.y), mRadToDeg(eulRot.z));
  173. return returnBuffer;
  174. }
  175. return "0 0 0";
  176. }
  177. bool Entity::onAdd()
  178. {
  179. if (!Parent::onAdd())
  180. return false;
  181. mObjBox = Box3F(Point3F(-0.5, -0.5, -0.5), Point3F(0.5, 0.5, 0.5));
  182. resetWorldBox();
  183. setObjectBox(mObjBox);
  184. addToScene();
  185. //Make sure we get positioned
  186. setMaskBits(TransformMask);
  187. setMaskBits(NamespaceMask);
  188. return true;
  189. }
  190. void Entity::onRemove()
  191. {
  192. clearComponents(true);
  193. removeFromScene();
  194. onDataSet.removeAll();
  195. Parent::onRemove();
  196. }
  197. void Entity::onPostAdd()
  198. {
  199. mInitialized = true;
  200. //everything's done and added. go ahead and initialize the components
  201. for (U32 i = 0; i < mComponents.size(); i++)
  202. {
  203. mComponents[i]->onComponentAdd();
  204. }
  205. if (isMethod("onAdd"))
  206. Con::executef(this, "onAdd");
  207. }
  208. bool Entity::_setGameObject(void *object, const char *index, const char *data)
  209. {
  210. Entity *e = static_cast<Entity*>(object);
  211. // Sanity!
  212. AssertFatal(data != NULL, "Cannot use a NULL asset Id.");
  213. return true; //rbI->setMeshAsset(data);
  214. }
  215. void Entity::setDataField(StringTableEntry slotName, const char *array, const char *value)
  216. {
  217. Parent::setDataField(slotName, array, value);
  218. onDataSet.trigger(this, slotName, value);
  219. }
  220. void Entity::onStaticModified(const char* slotName, const char* newValue)
  221. {
  222. Parent::onStaticModified(slotName, newValue);
  223. onDataSet.trigger(this, slotName, newValue);
  224. }
  225. //Updating
  226. void Entity::processTick(const Move* move)
  227. {
  228. if (!isHidden())
  229. {
  230. if (mDelta.warpCount < mDelta.warpTicks)
  231. {
  232. mDelta.warpCount++;
  233. // Set new pos.
  234. mObjToWorld.getColumn(3, &mDelta.pos);
  235. mDelta.pos += mDelta.warpOffset;
  236. mDelta.rot[0] = mDelta.rot[1];
  237. mDelta.rot[1].interpolate(mDelta.warpRot[0], mDelta.warpRot[1], F32(mDelta.warpCount) / mDelta.warpTicks);
  238. setTransform(mDelta.pos, mDelta.rot[1]);
  239. // Pos backstepping
  240. mDelta.posVec.x = -mDelta.warpOffset.x;
  241. mDelta.posVec.y = -mDelta.warpOffset.y;
  242. mDelta.posVec.z = -mDelta.warpOffset.z;
  243. }
  244. else
  245. {
  246. if (isMounted())
  247. {
  248. MatrixF mat;
  249. mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat);
  250. Parent::setTransform(mat);
  251. Parent::setRenderTransform(mat);
  252. }
  253. else
  254. {
  255. if (!move)
  256. {
  257. if (isGhost())
  258. {
  259. // If we haven't run out of prediction time,
  260. // predict using the last known move.
  261. if (mPredictionCount-- <= 0)
  262. return;
  263. move = &mDelta.move;
  264. }
  265. else
  266. {
  267. move = &NullMove;
  268. }
  269. }
  270. }
  271. }
  272. Move prevMove = lastMove;
  273. if (move != NULL)
  274. lastMove = *move;
  275. else
  276. lastMove = NullMove;
  277. if (move && isServerObject())
  278. {
  279. if ((move->y != 0 || prevMove.y != 0)
  280. || (move->x != 0 || prevMove.x != 0)
  281. || (move->z != 0 || prevMove.x != 0))
  282. {
  283. if (isMethod("moveVectorEvent"))
  284. Con::executef(this, "moveVectorEvent", move->x, move->y, move->z);
  285. }
  286. if (move->yaw != 0)
  287. {
  288. if (isMethod("moveYawEvent"))
  289. Con::executef(this, "moveYawEvent", move->yaw);
  290. }
  291. if (move->pitch != 0)
  292. {
  293. if (isMethod("movePitchEvent"))
  294. Con::executef(this, "movePitchEvent", move->pitch);
  295. }
  296. if (move->roll != 0)
  297. {
  298. if (isMethod("moveRollEvent"))
  299. Con::executef(this, "moveRollEvent", move->roll);
  300. }
  301. for (U32 i = 0; i < MaxTriggerKeys; i++)
  302. {
  303. if (move->trigger[i] != prevMove.trigger[i])
  304. {
  305. if (isMethod("moveTriggerEvent"))
  306. Con::executef(this, "moveTriggerEvent", i, move->trigger[i]);
  307. }
  308. }
  309. }
  310. // Save current rigid state interpolation
  311. mDelta.posVec = getPosition();
  312. mDelta.rot[0] = mRot.asQuatF();
  313. //Handle any script updates, which can include physics stuff
  314. if (isServerObject() && isMethod("processTick"))
  315. Con::executef(this, "processTick");
  316. // Wrap up interpolation info
  317. mDelta.pos = getPosition();
  318. mDelta.posVec -= getPosition();
  319. mDelta.rot[1] = mRot.asQuatF();
  320. setTransform(getPosition(), mRot);
  321. }
  322. }
  323. void Entity::advanceTime(F32 dt)
  324. {
  325. }
  326. void Entity::interpolateTick(F32 dt)
  327. {
  328. if (dt == 0.0f)
  329. {
  330. setRenderTransform(mDelta.pos, mDelta.rot[1]);
  331. }
  332. else
  333. {
  334. QuatF rot;
  335. rot.interpolate(mDelta.rot[1], mDelta.rot[0], dt);
  336. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  337. setRenderTransform(pos, rot);
  338. }
  339. mDelta.dt = dt;
  340. }
  341. //Render
  342. void Entity::prepRenderImage(SceneRenderState *state)
  343. {
  344. }
  345. //Networking
  346. U32 Entity::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  347. {
  348. U32 retMask = Parent::packUpdate(con, mask, stream);
  349. if (stream->writeFlag(mask & TransformMask))
  350. {
  351. stream->writeCompressedPoint(mPos);
  352. mathWrite(*stream, getRotation());
  353. mDelta.move.pack(stream);
  354. stream->writeFlag(!(mask & NoWarpMask));
  355. }
  356. if (stream->writeFlag(mask & BoundsMask))
  357. {
  358. mathWrite(*stream, mObjBox);
  359. }
  360. //pass our behaviors around
  361. if (mask & ComponentsMask || mask & InitialUpdateMask)
  362. {
  363. stream->writeFlag(true);
  364. //now, we run through a list of our to-be-sent behaviors and begin sending them
  365. //if any fail, we keep our list and re-queue the mask
  366. S32 componentCount = mToLoadComponents.size();
  367. //build our 'ready' list
  368. //This requires both the instance and the instances' template to be prepped(if the template hasn't been ghosted,
  369. //then we know we shouldn't be passing the instance's ghosts around yet)
  370. U32 ghostedCompCnt = 0;
  371. for (U32 i = 0; i < componentCount; i++)
  372. {
  373. if (con->getGhostIndex(mToLoadComponents[i]) != -1)
  374. ghostedCompCnt++;
  375. }
  376. if (ghostedCompCnt != 0)
  377. {
  378. stream->writeFlag(true);
  379. stream->writeFlag(mStartComponentUpdate);
  380. //if not all the behaviors have been ghosted, we'll need another pass
  381. if (ghostedCompCnt != componentCount)
  382. retMask |= ComponentsMask;
  383. //write the currently ghosted behavior count
  384. stream->writeInt(ghostedCompCnt, 16);
  385. for (U32 i = 0; i < mToLoadComponents.size(); i++)
  386. {
  387. //now fetch them and pass the ghost
  388. S32 ghostIndex = con->getGhostIndex(mToLoadComponents[i]);
  389. if (ghostIndex != -1)
  390. {
  391. stream->writeInt(ghostIndex, NetConnection::GhostIdBitSize);
  392. mToLoadComponents.erase(i);
  393. i--;
  394. mStartComponentUpdate = false;
  395. }
  396. }
  397. }
  398. else if (componentCount)
  399. {
  400. //on the odd chance we have behaviors to ghost, but NONE of them have been yet, just set the flag now
  401. stream->writeFlag(false);
  402. retMask |= ComponentsMask;
  403. }
  404. else
  405. stream->writeFlag(false);
  406. }
  407. else
  408. stream->writeFlag(false);
  409. /*if (stream->writeFlag(mask & NamespaceMask))
  410. {
  411. const char* name = getName();
  412. if (stream->writeFlag(name && name[0]))
  413. stream->writeString(String(name));
  414. if (stream->writeFlag(mSuperClassName && mSuperClassName[0]))
  415. stream->writeString(String(mSuperClassName));
  416. if (stream->writeFlag(mClassName && mClassName[0]))
  417. stream->writeString(String(mClassName));
  418. }*/
  419. return retMask;
  420. }
  421. void Entity::unpackUpdate(NetConnection *con, BitStream *stream)
  422. {
  423. Parent::unpackUpdate(con, stream);
  424. if (stream->readFlag())
  425. {
  426. Point3F pos;
  427. stream->readCompressedPoint(&pos);
  428. RotationF rot;
  429. mathRead(*stream, &rot);
  430. mDelta.move.unpack(stream);
  431. if (stream->readFlag() && isProperlyAdded())
  432. {
  433. // Determine number of ticks to warp based on the average
  434. // of the client and server velocities.
  435. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  436. mDelta.warpOffset = pos - cp;
  437. // Calc the distance covered in one tick as the average of
  438. // the old speed and the new speed from the server.
  439. VectorF vel = pos - mDelta.pos;
  440. F32 dt, as = vel.len() * 0.5 * TickSec;
  441. // Cal how many ticks it will take to cover the warp offset.
  442. // If it's less than what's left in the current tick, we'll just
  443. // warp in the remaining time.
  444. if (!as || (dt = mDelta.warpOffset.len() / as) > sMaxWarpTicks)
  445. dt = mDelta.dt + sMaxWarpTicks;
  446. else
  447. dt = (dt <= mDelta.dt) ? mDelta.dt : mCeil(dt - mDelta.dt) + mDelta.dt;
  448. // Adjust current frame interpolation
  449. if (mDelta.dt)
  450. {
  451. mDelta.pos = cp + (mDelta.warpOffset * (mDelta.dt / dt));
  452. mDelta.posVec = (cp - mDelta.pos) / mDelta.dt;
  453. QuatF cr;
  454. cr.interpolate(mDelta.rot[1], mDelta.rot[0], mDelta.dt);
  455. mDelta.rot[1].interpolate(cr, rot.asQuatF(), mDelta.dt / dt);
  456. mDelta.rot[0].extrapolate(mDelta.rot[1], cr, mDelta.dt);
  457. }
  458. // Calculated multi-tick warp
  459. mDelta.warpCount = 0;
  460. mDelta.warpTicks = (S32)(mFloor(dt));
  461. if (mDelta.warpTicks)
  462. {
  463. mDelta.warpOffset = pos - mDelta.pos;
  464. mDelta.warpOffset /= mDelta.warpTicks;
  465. mDelta.warpRot[0] = mDelta.rot[1];
  466. mDelta.warpRot[1] = rot.asQuatF();
  467. }
  468. }
  469. else
  470. {
  471. // Set the entity to the server position
  472. mDelta.dt = 0;
  473. mDelta.pos = pos;
  474. mDelta.posVec.set(0, 0, 0);
  475. mDelta.rot[1] = mDelta.rot[0] = rot.asQuatF();
  476. mDelta.warpCount = mDelta.warpTicks = 0;
  477. setTransform(pos, rot);
  478. }
  479. }
  480. if (stream->readFlag())
  481. {
  482. mathRead(*stream, &mObjBox);
  483. resetWorldBox();
  484. }
  485. if (stream->readFlag())
  486. {
  487. //are we passing any behaviors currently?
  488. if (stream->readFlag())
  489. {
  490. //if we've just started the update, clear our behaviors
  491. if (stream->readFlag())
  492. clearComponents(false);
  493. S32 componentCount = stream->readInt(16);
  494. for (U32 i = 0; i < componentCount; i++)
  495. {
  496. S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize);
  497. addComponent(dynamic_cast<Component*>(con->resolveGhost(gIndex)));
  498. }
  499. }
  500. }
  501. /*if (stream->readFlag())
  502. {
  503. if (stream->readFlag())
  504. {
  505. char name[256];
  506. stream->readString(name);
  507. assignName(name);
  508. }
  509. if (stream->readFlag())
  510. {
  511. char superClassname[256];
  512. stream->readString(superClassname);
  513. mSuperClassName = superClassname;
  514. }
  515. if (stream->readFlag())
  516. {
  517. char classname[256];
  518. stream->readString(classname);
  519. mClassName = classname;
  520. }
  521. linkNamespaces();
  522. }*/
  523. }
  524. //Manipulation
  525. void Entity::setTransform(const MatrixF &mat)
  526. {
  527. MatrixF oldTransform = getTransform();
  528. if (isMounted())
  529. {
  530. // Use transform from mounted object
  531. Point3F newPos = mat.getPosition();
  532. Point3F parentPos = mMount.object->getTransform().getPosition();
  533. Point3F newOffset = newPos - parentPos;
  534. if (!newOffset.isZero())
  535. {
  536. mPos = newOffset;
  537. }
  538. Point3F matEul = mat.toEuler();
  539. if (matEul != Point3F(0, 0, 0))
  540. {
  541. Point3F mountEul = mMount.object->getTransform().toEuler();
  542. Point3F diff = matEul - mountEul;
  543. mRot = diff;
  544. }
  545. else
  546. {
  547. mRot = Point3F(0, 0, 0);
  548. }
  549. RotationF addRot = mRot + RotationF(mMount.object->getTransform());
  550. MatrixF transf = addRot.asMatrixF();
  551. transf.setPosition(mPos + mMount.object->getPosition());
  552. Parent::setTransform(transf);
  553. if (transf != oldTransform)
  554. setMaskBits(TransformMask);
  555. }
  556. else
  557. {
  558. //Are we part of a prefab?
  559. /*Prefab* p = Prefab::getPrefabByChild(this);
  560. if (p)
  561. {
  562. //just let our prefab know we moved
  563. p->childTransformUpdated(this, mat);
  564. }*/
  565. //else
  566. {
  567. //mRot.set(mat);
  568. //Parent::setTransform(mat);
  569. RotationF rot = RotationF(mat);
  570. EulerF tempRot = rot.asEulerF(RotationF::Degrees);
  571. Point3F pos;
  572. mat.getColumn(3,&pos);
  573. setTransform(pos, rot);
  574. }
  575. }
  576. }
  577. void Entity::setTransform(Point3F position, RotationF rotation)
  578. {
  579. MatrixF oldTransform = getTransform();
  580. if (isMounted())
  581. {
  582. mPos = position;
  583. mRot = rotation;
  584. RotationF addRot = mRot + RotationF(mMount.object->getTransform());
  585. MatrixF transf = addRot.asMatrixF();
  586. transf.setPosition(mPos + mMount.object->getPosition());
  587. Parent::setTransform(transf);
  588. if (transf != oldTransform)
  589. setMaskBits(TransformMask);
  590. }
  591. else
  592. {
  593. /*MatrixF newMat, imat, xmat, ymat, zmat;
  594. Point3F radRot = Point3F(mDegToRad(rotation.x), mDegToRad(rotation.y), mDegToRad(rotation.z));
  595. xmat.set(EulerF(radRot.x, 0, 0));
  596. ymat.set(EulerF(0.0f, radRot.y, 0.0f));
  597. zmat.set(EulerF(0, 0, radRot.z));
  598. imat.mul(zmat, xmat);
  599. newMat.mul(imat, ymat);*/
  600. MatrixF newMat = rotation.asMatrixF();
  601. newMat.setColumn(3, position);
  602. mPos = position;
  603. mRot = rotation;
  604. //if (isServerObject())
  605. // setMaskBits(TransformMask);
  606. //setTransform(temp);
  607. // This test is a bit expensive so turn it off in release.
  608. #ifdef TORQUE_DEBUG
  609. //AssertFatal( mat.isAffine(), "SceneObject::setTransform() - Bad transform (non affine)!" );
  610. #endif
  611. //PROFILE_SCOPE(Entity_setTransform);
  612. // Update the transforms.
  613. Parent::setTransform(newMat);
  614. onTransformSet.trigger(&newMat);
  615. Point3F newPos = newMat.getPosition();
  616. RotationF newRot = newMat;
  617. Point3F oldPos = oldTransform.getPosition();
  618. RotationF oldRot = oldTransform;
  619. if (newPos != oldPos || newRot != oldRot)
  620. setMaskBits(TransformMask);
  621. }
  622. }
  623. void Entity::setRenderTransform(const MatrixF &mat)
  624. {
  625. Parent::setRenderTransform(mat);
  626. }
  627. void Entity::setRenderTransform(Point3F position, RotationF rotation)
  628. {
  629. if (isMounted())
  630. {
  631. mPos = position;
  632. mRot = rotation;
  633. RotationF addRot = mRot + RotationF(mMount.object->getTransform());
  634. MatrixF transf = addRot.asMatrixF();
  635. transf.setPosition(mPos + mMount.object->getPosition());
  636. Parent::setRenderTransform(transf);
  637. }
  638. else
  639. {
  640. MatrixF newMat = rotation.asMatrixF();
  641. newMat.setColumn(3, position);
  642. mPos = position;
  643. mRot = rotation;
  644. Parent::setRenderTransform(newMat);
  645. onTransformSet.trigger(&newMat);
  646. }
  647. }
  648. MatrixF Entity::getTransform()
  649. {
  650. if (isMounted())
  651. {
  652. MatrixF mat;
  653. //Use transform from mount
  654. mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat);
  655. Point3F transPos = mat.getPosition() + mPos;
  656. mat.mul(mRot.asMatrixF());
  657. mat.setPosition(transPos);
  658. return mat;
  659. }
  660. else
  661. {
  662. return Parent::getTransform();
  663. }
  664. }
  665. void Entity::setMountOffset(Point3F posOffset)
  666. {
  667. if (isMounted())
  668. {
  669. mMount.xfm.setColumn(3, posOffset);
  670. //mPos = posOffset;
  671. setMaskBits(MountedMask);
  672. }
  673. }
  674. void Entity::setMountRotation(EulerF rotOffset)
  675. {
  676. if (isMounted())
  677. {
  678. MatrixF temp, imat, xmat, ymat, zmat;
  679. Point3F radRot = Point3F(mDegToRad(rotOffset.x), mDegToRad(rotOffset.y), mDegToRad(rotOffset.z));
  680. xmat.set(EulerF(radRot.x, 0, 0));
  681. ymat.set(EulerF(0.0f, radRot.y, 0.0f));
  682. zmat.set(EulerF(0, 0, radRot.z));
  683. imat.mul(zmat, xmat);
  684. temp.mul(imat, ymat);
  685. temp.setColumn(3, mMount.xfm.getPosition());
  686. mMount.xfm = temp;
  687. setMaskBits(MountedMask);
  688. }
  689. }
  690. //
  691. void Entity::getCameraTransform(F32* pos, MatrixF* mat)
  692. {
  693. Vector<CameraInterface*> updaters = getComponents<CameraInterface>();
  694. for (Vector<CameraInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  695. {
  696. if ((*it)->getCameraTransform(pos, mat))
  697. {
  698. return;
  699. }
  700. }
  701. }
  702. void Entity::getMountTransform(S32 index, const MatrixF &xfm, MatrixF *outMat)
  703. {
  704. RenderComponentInterface* renderInterface = getComponent<RenderComponentInterface>();
  705. if (renderInterface)
  706. {
  707. renderInterface->getShapeInstance()->animate();
  708. S32 nodeCount = renderInterface->getShapeInstance()->getShape()->nodes.size();
  709. if (index >= 0 && index < nodeCount)
  710. {
  711. MatrixF mountTransform = renderInterface->getShapeInstance()->mNodeTransforms[index];
  712. mountTransform.mul(xfm);
  713. const Point3F& scale = getScale();
  714. // The position of the mount point needs to be scaled.
  715. Point3F position = mountTransform.getPosition();
  716. position.convolve(scale);
  717. mountTransform.setPosition(position);
  718. // Also we would like the object to be scaled to the model.
  719. outMat->mul(mObjToWorld, mountTransform);
  720. return;
  721. }
  722. }
  723. // Then let SceneObject handle it.
  724. Parent::getMountTransform(index, xfm, outMat);
  725. }
  726. void Entity::getRenderMountTransform(F32 delta, S32 index, const MatrixF &xfm, MatrixF *outMat)
  727. {
  728. RenderComponentInterface* renderInterface = getComponent<RenderComponentInterface>();
  729. if (renderInterface && renderInterface->getShapeInstance())
  730. {
  731. renderInterface->getShapeInstance()->animate();
  732. S32 nodeCount = renderInterface->getShapeInstance()->getShape()->nodes.size();
  733. if (index >= 0 && index < nodeCount)
  734. {
  735. MatrixF mountTransform = renderInterface->getShapeInstance()->mNodeTransforms[index];
  736. mountTransform.mul(xfm);
  737. const Point3F& scale = getScale();
  738. // The position of the mount point needs to be scaled.
  739. Point3F position = mountTransform.getPosition();
  740. position.convolve(scale);
  741. mountTransform.setPosition(position);
  742. // Also we would like the object to be scaled to the model.
  743. outMat->mul(getRenderTransform(), mountTransform);
  744. return;
  745. }
  746. }
  747. // Then let SceneObject handle it.
  748. Parent::getMountTransform(index, xfm, outMat);
  749. }
  750. //
  751. //These basically just redirect to any collision behaviors we have
  752. bool Entity::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  753. {
  754. Vector<CastRayInterface*> updaters = getComponents<CastRayInterface>();
  755. for (Vector<CastRayInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  756. {
  757. if ((*it)->castRay(start, end, info))
  758. {
  759. return true;
  760. }
  761. }
  762. return false;
  763. }
  764. bool Entity::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  765. {
  766. Vector<CastRayRenderedInterface*> updaters = getComponents<CastRayRenderedInterface>();
  767. for (Vector<CastRayRenderedInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  768. {
  769. if ((*it)->castRayRendered(start, end, info))
  770. {
  771. return true;
  772. }
  773. }
  774. return false;
  775. }
  776. bool Entity::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &sphere)
  777. {
  778. Vector<BuildPolyListInterface*> updaters = getComponents<BuildPolyListInterface>();
  779. for (Vector<BuildPolyListInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  780. {
  781. return (*it)->buildPolyList(context, polyList, box, sphere);
  782. }
  783. return false;
  784. }
  785. void Entity::buildConvex(const Box3F& box, Convex* convex)
  786. {
  787. Vector<BuildConvexInterface*> updaters = getComponents<BuildConvexInterface>();
  788. for (Vector<BuildConvexInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  789. {
  790. (*it)->buildConvex(box, convex);
  791. }
  792. }
  793. //
  794. // Mounting and heirarchy manipulation
  795. void Entity::mountObject(SceneObject* objB, MatrixF txfm)
  796. {
  797. Parent::mountObject(objB, -1, txfm);
  798. Parent::addObject(objB);
  799. }
  800. void Entity::mountObject(SceneObject *obj, S32 node, const MatrixF &xfm)
  801. {
  802. Parent::mountObject(obj, node, xfm);
  803. }
  804. void Entity::onMount(SceneObject *obj, S32 node)
  805. {
  806. deleteNotify(obj);
  807. // Are we mounting to a GameBase object?
  808. Entity *entityObj = dynamic_cast<Entity*>(obj);
  809. if (entityObj && entityObj->getControlObject() != this)
  810. processAfter(entityObj);
  811. if (!isGhost()) {
  812. setMaskBits(MountedMask);
  813. //TODO implement this callback
  814. //onMount_callback( this, obj, node );
  815. }
  816. }
  817. void Entity::onUnmount(SceneObject *obj, S32 node)
  818. {
  819. clearNotify(obj);
  820. Entity *entityObj = dynamic_cast<Entity*>(obj);
  821. if (entityObj && entityObj->getControlObject() != this)
  822. clearProcessAfter();
  823. if (!isGhost()) {
  824. setMaskBits(MountedMask);
  825. //TODO implement this callback
  826. //onUnmount_callback( this, obj, node );
  827. }
  828. }
  829. void Entity::setControllingClient(GameConnection* client)
  830. {
  831. if (isGhost() && gSFX3DWorld)
  832. {
  833. if (gSFX3DWorld->getListener() == this && !client && getControllingClient() && getControllingClient()->isConnectionToServer())
  834. {
  835. // We are the current listener and are no longer a controller object on the
  836. // connection, so clear our listener status.
  837. gSFX3DWorld->setListener(NULL);
  838. }
  839. else if (client && client->isConnectionToServer() && !getControllingObject())
  840. {
  841. // We're on the local client and not controlled by another object, so make
  842. // us the current SFX listener.
  843. gSFX3DWorld->setListener(this);
  844. }
  845. }
  846. Parent::setControllingClient(client);
  847. }
  848. //Heirarchy stuff
  849. void Entity::addObject(SimObject* object)
  850. {
  851. Component* component = dynamic_cast<Component*>(object);
  852. if (component)
  853. {
  854. addComponent(component);
  855. return;
  856. }
  857. Entity* e = dynamic_cast<Entity*>(object);
  858. if (e)
  859. {
  860. MatrixF offset;
  861. //offset.mul(getWorldTransform(), e->getWorldTransform());
  862. //check if we're mounting to a node on a shape we have
  863. String node = e->getDataField("mountNode", NULL);
  864. if (!node.isEmpty())
  865. {
  866. RenderComponentInterface *renderInterface = getComponent<RenderComponentInterface>();
  867. if (renderInterface)
  868. {
  869. TSShape* shape = renderInterface->getShape();
  870. S32 nodeIdx = shape->findNode(node);
  871. mountObject(e, nodeIdx, MatrixF::Identity);
  872. }
  873. else
  874. {
  875. mountObject(e, MatrixF::Identity);
  876. }
  877. }
  878. else
  879. {
  880. /*Point3F posOffset = mPos - e->getPosition();
  881. mPos = posOffset;
  882. RotationF rotOffset = mRot - e->getRotation();
  883. mRot = rotOffset;
  884. setMaskBits(TransformMask);
  885. mountObject(e, MatrixF::Identity);*/
  886. mountObject(e, MatrixF::Identity);
  887. }
  888. //e->setMountOffset(e->getPosition() - getPosition());
  889. //Point3F diff = getWorldTransform().toEuler() - e->getWorldTransform().toEuler();
  890. //e->setMountRotation(Point3F(mRadToDeg(diff.x),mRadToDeg(diff.y),mRadToDeg(diff.z)));
  891. //mountObject(e, offset);
  892. }
  893. else
  894. {
  895. SceneObject* so = dynamic_cast<SceneObject*>(object);
  896. if (so)
  897. {
  898. //get the difference and build it as our offset!
  899. Point3F posOffset = so->getPosition() - mPos;
  900. RotationF rotOffset = RotationF(so->getTransform()) - mRot;
  901. MatrixF offset = rotOffset.asMatrixF();
  902. offset.setPosition(posOffset);
  903. mountObject(so, offset);
  904. return;
  905. }
  906. }
  907. Parent::addObject(object);
  908. }
  909. void Entity::removeObject(SimObject* object)
  910. {
  911. Entity* e = dynamic_cast<Entity*>(object);
  912. if (e)
  913. {
  914. mPos = mPos + e->getPosition();
  915. mRot = mRot + e->getRotation();
  916. unmountObject(e);
  917. setMaskBits(TransformMask);
  918. }
  919. else
  920. {
  921. SceneObject* so = dynamic_cast<SceneObject*>(object);
  922. if (so)
  923. unmountObject(so);
  924. }
  925. Parent::removeObject(object);
  926. }
  927. bool Entity::addComponent(Component *comp)
  928. {
  929. if (comp == NULL)
  930. return false;
  931. //double-check were not re-adding anything
  932. mComponents.push_back(comp);
  933. // Register the component with this owner.
  934. comp->setOwner(this);
  935. //if we've already been added and this is being added after the fact(at runtime),
  936. //then just go ahead and call it's onComponentAdd so it can get to work
  937. if (mInitialized)
  938. comp->onComponentAdd();
  939. onComponentAdded.trigger(comp);
  940. return true;
  941. }
  942. SimObject* Entity::findObjectByInternalName(StringTableEntry internalName, bool searchChildren)
  943. {
  944. for (U32 i = 0; i < mComponents.size(); i++)
  945. {
  946. if (mComponents[i]->getInternalName() == internalName)
  947. {
  948. return mComponents[i];
  949. }
  950. }
  951. return Parent::findObjectByInternalName(internalName, searchChildren);
  952. }
  953. //////////////////////////////////////////////////////////////////////////
  954. bool Entity::removeComponent(Component *comp, bool deleteComponent)
  955. {
  956. if (comp == NULL)
  957. return false;
  958. if(mComponents.remove(comp))
  959. {
  960. AssertFatal(comp->isProperlyAdded(), "Don't know how but a component is not registered w/ the sim");
  961. //setComponentsDirty();
  962. onComponentRemoved.trigger(comp);
  963. comp->onComponentRemove(); //in case the behavior needs to do cleanup on the owner
  964. comp->setOwner(NULL);
  965. if (deleteComponent)
  966. comp->safeDeleteObject();
  967. return true;
  968. }
  969. return false;
  970. }
  971. //////////////////////////////////////////////////////////////////////////
  972. //NOTE:
  973. //The actor class calls this and flags the deletion of the behaviors to false so that behaviors that should no longer be attached during
  974. //a network update will indeed be removed from the object. The reason it doesn't delete them is because when clearing the local behavior
  975. //list, it would delete them, purging the ghost, and causing a crash when the unpack update tried to fetch any existing behaviors' ghosts
  976. //to re-add them. Need to implement a clean clear function that will clear the local list, and only delete unused behaviors during an update.
  977. void Entity::clearComponents(bool deleteComponents)
  978. {
  979. bool srv = isServerObject();
  980. if (!deleteComponents)
  981. {
  982. while (mComponents.size() > 0)
  983. {
  984. removeComponent(mComponents.first(), deleteComponents);
  985. }
  986. }
  987. else
  988. {
  989. while (mComponents.size() > 0)
  990. {
  991. Component* comp = mComponents.first();
  992. if (comp)
  993. {
  994. comp->onComponentRemove(); //in case the behavior needs to do cleanup on the owner
  995. bool removed = mComponents.remove(comp);
  996. //we only need to delete them on the server side. they'll be cleaned up on the client side
  997. //via the ghosting system for us
  998. if (isServerObject())
  999. comp->deleteObject();
  1000. }
  1001. }
  1002. }
  1003. }
  1004. //////////////////////////////////////////////////////////////////////////
  1005. Component *Entity::getComponent(const U32 index) const
  1006. {
  1007. if (index < mComponents.size())
  1008. return mComponents[index];
  1009. return NULL;
  1010. }
  1011. Component *Entity::getComponent(String componentType)
  1012. {
  1013. for (U32 i = 0; i < mComponents.size(); i++)
  1014. {
  1015. Component* comp = mComponents[i];
  1016. /*String namespaceName = comp->getNamespace()->mName;
  1017. //check our namespace first
  1018. if (namespaceName == componentType)
  1019. {
  1020. return comp;
  1021. }
  1022. else
  1023. {*/
  1024. //lets scan up, just to be sure
  1025. Namespace *NS = comp->getNamespace();
  1026. //we shouldn't ever go past Component into net object, as we're no longer dealing with component classes
  1027. while (dStrcmp(NS->getName(), "NetObject"))
  1028. {
  1029. String namespaceName = NS->getName();
  1030. if (namespaceName == componentType)
  1031. {
  1032. return comp;
  1033. }
  1034. else
  1035. {
  1036. NS = NS->getParent();
  1037. }
  1038. }
  1039. //}
  1040. }
  1041. return NULL;
  1042. }
  1043. void Entity::onInspect()
  1044. {
  1045. Vector<EditorInspectInterface*> updaters = getComponents<EditorInspectInterface>();
  1046. for (Vector<EditorInspectInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  1047. {
  1048. (*it)->onInspect();
  1049. }
  1050. }
  1051. void Entity::onEndInspect()
  1052. {
  1053. Vector<EditorInspectInterface*> updaters = getComponents<EditorInspectInterface>();
  1054. for (Vector<EditorInspectInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++) {
  1055. (*it)->onEndInspect();
  1056. }
  1057. GuiTreeViewCtrl *editorTree = dynamic_cast<GuiTreeViewCtrl*>(Sim::findObject("EditorTree"));
  1058. if (!editorTree)
  1059. return;
  1060. S32 componentItemIdx = editorTree->findItemByName("Components");
  1061. editorTree->removeItem(componentItemIdx, false);
  1062. }
  1063. static void writeTabs(Stream &stream, U32 count)
  1064. {
  1065. char tab[] = " ";
  1066. while (count--)
  1067. stream.write(3, (void*)tab);
  1068. }
  1069. void Entity::write(Stream &stream, U32 tabStop, U32 flags)
  1070. {
  1071. // Do *not* call parent on this
  1072. /*VectorPtr<ComponentObject *> &componentList = lockComponentList();
  1073. // export selected only?
  1074. if( ( flags & SelectedOnly ) && !isSelected() )
  1075. {
  1076. for( BehaviorObjectIterator i = componentList.begin(); i != componentList.end(); i++ )
  1077. (*i)->write(stream, tabStop, flags);
  1078. goto write_end;
  1079. }*/
  1080. //catch if we have any written behavior fields already in the file, and clear them. We don't need to double-up
  1081. //the entries for no reason.
  1082. /*if(getFieldDictionary())
  1083. {
  1084. //get our dynamic field count, then parse through them to see if they're a behavior or not
  1085. //reset it
  1086. SimFieldDictionary* fieldDictionary = getFieldDictionary();
  1087. SimFieldDictionaryIterator itr(fieldDictionary);
  1088. for (S32 i = 0; i < fieldDictionary->getNumFields(); i++)
  1089. {
  1090. if (!(*itr))
  1091. break;
  1092. SimFieldDictionary::Entry* entry = *itr;
  1093. if(strstr(entry->slotName, "_behavior"))
  1094. {
  1095. entry->slotName = "";
  1096. entry->value = "";
  1097. }
  1098. ++itr;
  1099. }
  1100. }*/
  1101. //all existing written behavior fields should be cleared. now write the object block
  1102. writeTabs(stream, tabStop);
  1103. char buffer[1024];
  1104. dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() ? getName() : "");
  1105. stream.write(dStrlen(buffer), buffer);
  1106. writeFields(stream, tabStop + 1);
  1107. stream.write(1, "\n");
  1108. ////first, write out our behavior objects
  1109. // NOW we write the behavior fields proper
  1110. if (mComponents.size() > 0)
  1111. {
  1112. // Pack out the behaviors into fields
  1113. U32 i = 0;
  1114. for (U32 i = 0; i < mComponents.size(); i++)
  1115. {
  1116. writeTabs(stream, tabStop + 1);
  1117. char buffer[1024];
  1118. dSprintf(buffer, sizeof(buffer), "new %s() {\r\n", mComponents[i]->getClassName());
  1119. stream.write(dStrlen(buffer), buffer);
  1120. //bi->writeFields( stream, tabStop + 2 );
  1121. mComponents[i]->packToStream(stream, tabStop + 2, i - 1, flags);
  1122. writeTabs(stream, tabStop + 1);
  1123. stream.write(4, "};\r\n");
  1124. }
  1125. }
  1126. //
  1127. //if (size() > 0)
  1128. // stream.write(2, "\r\n");
  1129. for (U32 i = 0; i < size(); i++)
  1130. {
  1131. SimObject* child = (*this)[i];
  1132. if (child->getCanSave())
  1133. child->write(stream, tabStop + 1, flags);
  1134. }
  1135. //stream.write(2, "\r\n");
  1136. writeTabs(stream, tabStop);
  1137. stream.write(4, "};\r\n");
  1138. //write_end:
  1139. //unlockComponentList();
  1140. }
  1141. SimObject* Entity::getTamlChild(const U32 childIndex) const
  1142. {
  1143. // Sanity!
  1144. AssertFatal(childIndex < getTamlChildCount(), "SimSet::getTamlChild() - Child index is out of range.");
  1145. // For when the assert is not used.
  1146. if (childIndex >= getTamlChildCount())
  1147. return NULL;
  1148. //we always order components first, child objects second
  1149. if (childIndex >= getComponentCount())
  1150. return at(childIndex - getComponentCount());
  1151. else
  1152. return getComponent(childIndex);
  1153. }
  1154. //
  1155. void Entity::onCameraScopeQuery(NetConnection* connection, CameraScopeQuery* query)
  1156. {
  1157. // Object itself is in scope.
  1158. Parent::onCameraScopeQuery(connection, query);
  1159. if (CameraInterface* cI = getComponent<CameraInterface>())
  1160. {
  1161. cI->onCameraScopeQuery(connection, query);
  1162. }
  1163. }
  1164. //
  1165. void Entity::setObjectBox(Box3F objBox)
  1166. {
  1167. mObjBox = objBox;
  1168. resetWorldBox();
  1169. if (isServerObject())
  1170. setMaskBits(BoundsMask);
  1171. }
  1172. void Entity::updateContainer()
  1173. {
  1174. PROFILE_SCOPE(Entity_updateContainer);
  1175. // Update container drag and buoyancy properties
  1176. containerInfo.box = getWorldBox();
  1177. //containerInfo.mass = mMass;
  1178. getContainer()->findObjects(containerInfo.box, WaterObjectType | PhysicalZoneObjectType, findRouter, &containerInfo);
  1179. //mWaterCoverage = info.waterCoverage;
  1180. //mLiquidType = info.liquidType;
  1181. //mLiquidHeight = info.waterHeight;
  1182. //setCurrentWaterObject( info.waterObject );
  1183. // This value might be useful as a datablock value,
  1184. // This is what allows the player to stand in shallow water (below this coverage)
  1185. // without jiggling from buoyancy
  1186. /*if (info.waterCoverage >= 0.25f)
  1187. {
  1188. // water viscosity is used as drag for in water.
  1189. // ShapeBaseData drag is used for drag outside of water.
  1190. // Combine these two components to calculate this ShapeBase object's
  1191. // current drag.
  1192. mDrag = (info.waterCoverage * info.waterViscosity) +
  1193. (1.0f - info.waterCoverage) * mDrag;
  1194. //mBuoyancy = (info.waterDensity / mDataBlock->density) * info.waterCoverage;
  1195. }
  1196. //mAppliedForce = info.appliedForce;
  1197. mGravityMod = info.gravityScale;*/
  1198. }
  1199. //
  1200. void Entity::notifyComponents(String signalFunction, String argA, String argB, String argC, String argD, String argE)
  1201. {
  1202. for (U32 i = 0; i < mComponents.size(); i++)
  1203. {
  1204. // We can do this because both are in the string table
  1205. Component *comp = mComponents[i];
  1206. if (comp->isActive())
  1207. {
  1208. if (comp->isMethod(signalFunction))
  1209. Con::executef(comp, signalFunction, argA, argB, argC, argD, argE);
  1210. }
  1211. }
  1212. }
  1213. void Entity::setComponentsDirty()
  1214. {
  1215. if (mToLoadComponents.empty())
  1216. mStartComponentUpdate = true;
  1217. //we need to build a list of behaviors that need to be pushed across the network
  1218. for (U32 i = 0; i < mComponents.size(); i++)
  1219. {
  1220. // We can do this because both are in the string table
  1221. Component *comp = mComponents[i];
  1222. if (comp->isNetworked())
  1223. {
  1224. bool unique = true;
  1225. for (U32 i = 0; i < mToLoadComponents.size(); i++)
  1226. {
  1227. if (mToLoadComponents[i]->getId() == comp->getId())
  1228. {
  1229. unique = false;
  1230. break;
  1231. }
  1232. }
  1233. if (unique)
  1234. mToLoadComponents.push_back(comp);
  1235. }
  1236. }
  1237. setMaskBits(ComponentsMask);
  1238. }
  1239. void Entity::setComponentDirty(Component *comp, bool forceUpdate)
  1240. {
  1241. bool found = false;
  1242. for (U32 i = 0; i < mComponents.size(); i++)
  1243. {
  1244. if (mComponents[i]->getId() == comp->getId())
  1245. {
  1246. mComponents[i]->setOwner(this);
  1247. return;
  1248. }
  1249. }
  1250. if (!found)
  1251. return;
  1252. //if(mToLoadComponents.empty())
  1253. // mStartComponentUpdate = true;
  1254. /*if (comp->isNetworked() || forceUpdate)
  1255. {
  1256. bool unique = true;
  1257. for (U32 i = 0; i < mToLoadComponents.size(); i++)
  1258. {
  1259. if (mToLoadComponents[i]->getId() == comp->getId())
  1260. {
  1261. unique = false;
  1262. break;
  1263. }
  1264. }
  1265. if (unique)
  1266. mToLoadComponents.push_back(comp);
  1267. }
  1268. setMaskBits(ComponentsMask);*/
  1269. }
  1270. DefineEngineMethod(Entity, mountObject, bool,
  1271. (SceneObject* objB, TransformF txfm), (MatrixF::Identity),
  1272. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1273. "@param objB Object to mount onto us\n"
  1274. "@param slot Mount slot ID\n"
  1275. "@param txfm (optional) mount offset transform\n"
  1276. "@return true if successful, false if failed (objB is not valid)")
  1277. {
  1278. if (objB)
  1279. {
  1280. //BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
  1281. //for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
  1282. object->mountObject(objB, /*MatrixF::Identity*/txfm.getMatrix());
  1283. return true;
  1284. }
  1285. return false;
  1286. }
  1287. DefineEngineMethod(Entity, setMountOffset, void,
  1288. (Point3F posOffset), (Point3F(0, 0, 0)),
  1289. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1290. "@param objB Object to mount onto us\n"
  1291. "@param slot Mount slot ID\n"
  1292. "@param txfm (optional) mount offset transform\n"
  1293. "@return true if successful, false if failed (objB is not valid)")
  1294. {
  1295. object->setMountOffset(posOffset);
  1296. }
  1297. DefineEngineMethod(Entity, setMountRotation, void,
  1298. (EulerF rotOffset), (EulerF(0, 0, 0)),
  1299. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1300. "@param objB Object to mount onto us\n"
  1301. "@param slot Mount slot ID\n"
  1302. "@param txfm (optional) mount offset transform\n"
  1303. "@return true if successful, false if failed (objB is not valid)")
  1304. {
  1305. object->setMountRotation(rotOffset);
  1306. }
  1307. DefineEngineMethod(Entity, getMountTransform, TransformF, (), ,
  1308. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1309. "@param objB Object to mount onto us\n"
  1310. "@param slot Mount slot ID\n"
  1311. "@param txfm (optional) mount offset transform\n"
  1312. "@return true if successful, false if failed (objB is not valid)")
  1313. {
  1314. MatrixF mat;
  1315. object->getMountTransform(0, MatrixF::Identity, &mat);
  1316. return mat;
  1317. }
  1318. DefineEngineMethod(Entity, setBox, void,
  1319. (Point3F box), (Point3F(1, 1, 1)),
  1320. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1321. "@param objB Object to mount onto us\n"
  1322. "@param slot Mount slot ID\n"
  1323. "@param txfm (optional) mount offset transform\n"
  1324. "@return true if successful, false if failed (objB is not valid)")
  1325. {
  1326. object->setObjectBox(Box3F(-box, box));
  1327. }
  1328. /*DefineConsoleMethod(Entity, callOnComponents, void, (const char* functionName), ,
  1329. "Get the number of static fields on the object.\n"
  1330. "@return The number of static fields defined on the object.")
  1331. {
  1332. object->callOnComponents(functionName);
  1333. }
  1334. ConsoleMethod(Entity, callMethod, void, 3, 64, "(methodName, argi) Calls script defined method\n"
  1335. "@param methodName The method's name as a string\n"
  1336. "@param argi Any arguments to pass to the method\n"
  1337. "@return No return value"
  1338. "@note %obj.callMethod( %methodName, %arg1, %arg2, ... );\n")
  1339. {
  1340. object->callMethodArgList(argc - 1, argv + 2);
  1341. }
  1342. ConsoleMethod(Entity, addComponents, void, 2, 2, "() - Add all fielded behaviors\n"
  1343. "@return No return value")
  1344. {
  1345. object->addComponents();
  1346. }*/
  1347. ConsoleMethod(Entity, addComponent, bool, 3, 3, "(Component* bi) - Add a behavior to the object\n"
  1348. "@param bi The behavior instance to add"
  1349. "@return (bool success) Whether or not the behavior was successfully added")
  1350. {
  1351. Component *comp = dynamic_cast<Component *>(Sim::findObject(argv[2]));
  1352. if (comp != NULL)
  1353. {
  1354. bool success = object->addComponent(comp);
  1355. if (success)
  1356. {
  1357. //Placed here so we can differentiate against adding a new behavior during runtime, or when we load all
  1358. //fielded behaviors on mission load. This way, we can ensure that we only call the callback
  1359. //once everything is loaded. This avoids any problems with looking for behaviors that haven't been added yet, etc.
  1360. if (comp->isMethod("onBehaviorAdd"))
  1361. Con::executef(comp, "onBehaviorAdd");
  1362. return true;
  1363. }
  1364. }
  1365. return false;
  1366. }
  1367. ConsoleMethod(Entity, removeComponent, bool, 3, 4, "(Component* bi, [bool deleteBehavior = true])\n"
  1368. "@param bi The behavior instance to remove\n"
  1369. "@param deleteBehavior Whether or not to delete the behavior\n"
  1370. "@return (bool success) Whether the behavior was successfully removed")
  1371. {
  1372. bool deleteComponent = true;
  1373. if (argc > 3)
  1374. deleteComponent = dAtob(argv[3]);
  1375. return object->removeComponent(dynamic_cast<Component *>(Sim::findObject(argv[2])), deleteComponent);
  1376. }
  1377. ConsoleMethod(Entity, clearComponents, void, 2, 2, "() - Clear all behavior instances\n"
  1378. "@return No return value")
  1379. {
  1380. object->clearComponents();
  1381. }
  1382. ConsoleMethod(Entity, getComponentByIndex, S32, 3, 3, "(int index) - Gets a particular behavior\n"
  1383. "@param index The index of the behavior to get\n"
  1384. "@return (ComponentInstance bi) The behavior instance you requested")
  1385. {
  1386. Component *comp = object->getComponent(dAtoi(argv[2]));
  1387. return (comp != NULL) ? comp->getId() : 0;
  1388. }
  1389. DefineConsoleMethod(Entity, getComponent, S32, (String componentName), (""),
  1390. "Get the number of static fields on the object.\n"
  1391. "@return The number of static fields defined on the object.")
  1392. {
  1393. Component *comp = object->getComponent(componentName);
  1394. return (comp != NULL) ? comp->getId() : 0;
  1395. }
  1396. /*ConsoleMethod(Entity, getBehaviorByType, S32, 3, 3, "(string BehaviorTemplateName) - gets a behavior\n"
  1397. "@param BehaviorTemplateName The name of the template of the behavior instance you want\n"
  1398. "@return (ComponentInstance bi) The behavior instance you requested")
  1399. {
  1400. ComponentInstance *bInstance = object->getComponentByType(StringTable->insert(argv[2]));
  1401. return (bInstance != NULL) ? bInstance->getId() : 0;
  1402. }*/
  1403. /*ConsoleMethod(Entity, reOrder, bool, 3, 3, "(ComponentInstance inst, [int desiredIndex = 0])\n"
  1404. "@param inst The behavior instance you want to reorder\n"
  1405. "@param desiredIndex The index you want the behavior instance to be reordered to\n"
  1406. "@return (bool success) Whether or not the behavior instance was successfully reordered")
  1407. {
  1408. Component *inst = dynamic_cast<Component *>(Sim::findObject(argv[1]));
  1409. if (inst == NULL)
  1410. return false;
  1411. U32 idx = 0;
  1412. if (argc > 2)
  1413. idx = dAtoi(argv[2]);
  1414. return object->reOrder(inst, idx);
  1415. }*/
  1416. ConsoleMethod(Entity, getComponentCount, S32, 2, 2, "() - Get the count of behaviors on an object\n"
  1417. "@return (int count) The number of behaviors on an object")
  1418. {
  1419. return object->getComponentCount();
  1420. }
  1421. DefineConsoleMethod(Entity, setComponentDirty, void, (S32 componentID, bool forceUpdate), (0, false),
  1422. "Get the number of static fields on the object.\n"
  1423. "@return The number of static fields defined on the object.")
  1424. {
  1425. /*Component* comp;
  1426. if (Sim::findObject(componentID, comp))
  1427. object->setComponentDirty(comp, forceUpdate);*/
  1428. }
  1429. DefineConsoleMethod(Entity, getMoveVector, VectorF, (),,
  1430. "Get the number of static fields on the object.\n"
  1431. "@return The number of static fields defined on the object.")
  1432. {
  1433. if (object->getControllingClient() != NULL)
  1434. {
  1435. //fetch our last move
  1436. if (object->lastMove.x != 0 || object->lastMove.y != 0 || object->lastMove.z != 0)
  1437. return VectorF(object->lastMove.x, object->lastMove.y, object->lastMove.z);
  1438. }
  1439. return VectorF::Zero;
  1440. }
  1441. DefineConsoleMethod(Entity, getMoveRotation, VectorF, (), ,
  1442. "Get the number of static fields on the object.\n"
  1443. "@return The number of static fields defined on the object.")
  1444. {
  1445. if(object->getControllingClient() != NULL)
  1446. {
  1447. //fetch our last move
  1448. if (object->lastMove.pitch != 0 || object->lastMove.roll != 0 || object->lastMove.yaw != 0)
  1449. return VectorF(object->lastMove.pitch, object->lastMove.roll, object->lastMove.yaw);
  1450. }
  1451. return VectorF::Zero;
  1452. }
  1453. DefineConsoleMethod(Entity, getMoveTrigger, bool, (S32 triggerNum), (0),
  1454. "Get the number of static fields on the object.\n"
  1455. "@return The number of static fields defined on the object.")
  1456. {
  1457. if (object->getControllingClient() != NULL && triggerNum < MaxTriggerKeys)
  1458. {
  1459. return object->lastMove.trigger[triggerNum];
  1460. }
  1461. return false;
  1462. }
  1463. DefineEngineMethod(Entity, getForwardVector, VectorF, (), ,
  1464. "Get the direction this object is facing.\n"
  1465. "@return a vector indicating the direction this object is facing.\n"
  1466. "@note This is the object's y axis.")
  1467. {
  1468. VectorF forVec = object->getTransform().getForwardVector();
  1469. return forVec;
  1470. }
  1471. DefineConsoleMethod(Entity, setForwardVector, void, (VectorF newForward), (VectorF(0,0,0)),
  1472. "Get the number of static fields on the object.\n"
  1473. "@return The number of static fields defined on the object.")
  1474. {
  1475. object->setForwardVector(newForward);
  1476. }
  1477. DefineConsoleMethod(Entity, lookAt, void, (Point3F lookPosition),,
  1478. "Get the number of static fields on the object.\n"
  1479. "@return The number of static fields defined on the object.")
  1480. {
  1481. //object->setForwardVector(newForward);
  1482. }
  1483. DefineConsoleMethod(Entity, rotateTo, void, (Point3F lookPosition, F32 degreePerSecond), (1.0),
  1484. "Get the number of static fields on the object.\n"
  1485. "@return The number of static fields defined on the object.")
  1486. {
  1487. //object->setForwardVector(newForward);
  1488. }
  1489. DefineConsoleMethod(Entity, notify, void, (String signalFunction, String argA, String argB, String argC, String argD, String argE),
  1490. ("", "", "", "", "", ""),
  1491. "Triggers a signal call to all components for a certain function.")
  1492. {
  1493. if (signalFunction == String(""))
  1494. return;
  1495. object->notifyComponents(signalFunction, argA, argB, argC, argD, argE);
  1496. }