entity.cpp 53 KB

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