trigger.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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/trigger.h"
  24. #include "scene/sceneRenderState.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/engineAPI.h"
  27. #include "collision/boxConvex.h"
  28. #include "core/stream/bitStream.h"
  29. #include "math/mathIO.h"
  30. #include "gfx/gfxTransformSaver.h"
  31. #include "renderInstance/renderPassManager.h"
  32. #include "gfx/gfxDrawUtil.h"
  33. #include "T3D/physics/physicsPlugin.h"
  34. #include "T3D/physics/physicsBody.h"
  35. #include "T3D/physics/physicsCollision.h"
  36. bool Trigger::smRenderTriggers = false;
  37. //-----------------------------------------------------------------------------
  38. //----------------------------------------------------------------------------
  39. IMPLEMENT_CO_DATABLOCK_V1(TriggerData);
  40. ConsoleDocClass( TriggerData,
  41. "@brief Defines shared properties for Trigger objects.\n\n"
  42. "The primary focus of the TriggerData datablock is the callbacks it provides when an object is "
  43. "within or leaves the Trigger bounds.\n"
  44. "@see Trigger.\n"
  45. "@ingroup gameObjects\n"
  46. "@ingroup Datablocks\n"
  47. );
  48. IMPLEMENT_CALLBACK( TriggerData, onEnterTrigger, void, ( Trigger* trigger, GameBase* obj ), ( trigger, obj ),
  49. "@brief Called when an object enters the volume of the Trigger instance using this TriggerData.\n\n"
  50. "@param trigger the Trigger instance whose volume the object entered\n"
  51. "@param obj the object that entered the volume of the Trigger instance\n" );
  52. IMPLEMENT_CALLBACK( TriggerData, onTickTrigger, void, ( Trigger* trigger ), ( trigger ),
  53. "@brief Called every tickPeriodMS number of milliseconds (as specified in the TriggerData) whenever "
  54. "one or more objects are inside the volume of the trigger.\n\n"
  55. "The Trigger has methods to retrieve the objects that are within the Trigger's bounds if you "
  56. "want to do something with them in this callback.\n"
  57. "@param trigger the Trigger instance whose volume the object is inside\n"
  58. "@see tickPeriodMS\n"
  59. "@see Trigger::getNumObjects()\n"
  60. "@see Trigger::getObject()\n");
  61. IMPLEMENT_CALLBACK( TriggerData, onLeaveTrigger, void, ( Trigger* trigger, GameBase* obj ), ( trigger, obj ),
  62. "@brief Called when an object leaves the volume of the Trigger instance using this TriggerData.\n\n"
  63. "@param trigger the Trigger instance whose volume the object left\n"
  64. "@param obj the object that left the volume of the Trigger instance\n" );
  65. TriggerData::TriggerData()
  66. {
  67. tickPeriodMS = 100;
  68. isClientSide = false;
  69. }
  70. bool TriggerData::onAdd()
  71. {
  72. if (!Parent::onAdd())
  73. return false;
  74. return true;
  75. }
  76. void TriggerData::initPersistFields()
  77. {
  78. addGroup("Callbacks");
  79. addField( "tickPeriodMS", TypeS32, Offset( tickPeriodMS, TriggerData ),
  80. "@brief Time in milliseconds between calls to onTickTrigger() while at least one object is within a Trigger's bounds.\n\n"
  81. "@see onTickTrigger()\n");
  82. addField( "clientSide", TypeBool, Offset( isClientSide, TriggerData ),
  83. "Forces Trigger callbacks to only be called on clients.");
  84. endGroup("Callbacks");
  85. Parent::initPersistFields();
  86. }
  87. //--------------------------------------------------------------------------
  88. void TriggerData::packData(BitStream* stream)
  89. {
  90. Parent::packData(stream);
  91. stream->write(tickPeriodMS);
  92. stream->write(isClientSide);
  93. }
  94. void TriggerData::unpackData(BitStream* stream)
  95. {
  96. Parent::unpackData(stream);
  97. stream->read(&tickPeriodMS);
  98. stream->read(&isClientSide);
  99. }
  100. //--------------------------------------------------------------------------
  101. IMPLEMENT_CO_NETOBJECT_V1(Trigger);
  102. ConsoleDocClass( Trigger,
  103. "@brief A Trigger is a volume of space that initiates script callbacks "
  104. "when objects pass through the Trigger.\n\n"
  105. "TriggerData provides the callbacks for the Trigger when an object enters, stays inside "
  106. "or leaves the Trigger's volume.\n\n"
  107. "@see TriggerData\n"
  108. "@ingroup gameObjects\n"
  109. );
  110. IMPLEMENT_CALLBACK( Trigger, onAdd, void, ( U32 objectId ), ( objectId ),
  111. "@brief Called when the Trigger is being created.\n\n"
  112. "@param objectId the object id of the Trigger being created\n" );
  113. IMPLEMENT_CALLBACK( Trigger, onRemove, void, ( U32 objectId ), ( objectId ),
  114. "@brief Called just before the Trigger is deleted.\n\n"
  115. "@param objectId the object id of the Trigger being deleted\n" );
  116. Trigger::Trigger()
  117. {
  118. // Don't ghost by default.
  119. mNetFlags.set(Ghostable | ScopeAlways);
  120. mTypeMask |= TriggerObjectType;
  121. mObjScale.set(1, 1, 1);
  122. mObjToWorld.identity();
  123. mWorldToObj.identity();
  124. mDataBlock = NULL;
  125. mLastThink = 0;
  126. mCurrTick = 0;
  127. mConvexList = new Convex;
  128. mPhysicsRep = NULL;
  129. mTripOnce = false;
  130. mTrippedBy = 0xFFFFFFFF;
  131. mTripCondition = "";
  132. //Default up a basic square
  133. Point3F vecs[3] = { Point3F(1.0, 0.0, 0.0),
  134. Point3F(0.0, -1.0, 0.0),
  135. Point3F(0.0, 0.0, 1.0) };
  136. mTriggerPolyhedron = Polyhedron(Point3F(-0.5, 0.5, 0.0), vecs);
  137. }
  138. Trigger::~Trigger()
  139. {
  140. delete mConvexList;
  141. mConvexList = NULL;
  142. SAFE_DELETE( mPhysicsRep );
  143. }
  144. bool Trigger::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  145. {
  146. // Collide against bounding box
  147. F32 st,et,fst = 0,fet = 1;
  148. F32 *bmin = &mObjBox.minExtents.x;
  149. F32 *bmax = &mObjBox.maxExtents.x;
  150. F32 const *si = &start.x;
  151. F32 const *ei = &end.x;
  152. for (S32 i = 0; i < 3; i++)
  153. {
  154. if (*si < *ei)
  155. {
  156. if (*si > *bmax || *ei < *bmin)
  157. return false;
  158. F32 di = *ei - *si;
  159. st = (*si < *bmin)? (*bmin - *si) / di: 0;
  160. et = (*ei > *bmax)? (*bmax - *si) / di: 1;
  161. }
  162. else
  163. {
  164. if (*ei > *bmax || *si < *bmin)
  165. return false;
  166. F32 di = *ei - *si;
  167. st = (*si > *bmax)? (*bmax - *si) / di: 0;
  168. et = (*ei < *bmin)? (*bmin - *si) / di: 1;
  169. }
  170. if (st > fst) fst = st;
  171. if (et < fet) fet = et;
  172. if (fet < fst)
  173. return false;
  174. bmin++; bmax++;
  175. si++; ei++;
  176. }
  177. info->normal = start - end;
  178. info->normal.normalizeSafe();
  179. getTransform().mulV( info->normal );
  180. info->t = fst;
  181. info->object = this;
  182. info->point.interpolate(start,end,fst);
  183. info->material = 0;
  184. return true;
  185. }
  186. //--------------------------------------------------------------------------
  187. /* Console polyhedron data type exporter
  188. The polyhedron type is really a quadrilateral and consists of a corner
  189. point follow by three vectors representing the edges extending from the
  190. corner.
  191. */
  192. DECLARE_STRUCT( Polyhedron );
  193. IMPLEMENT_STRUCT( Polyhedron, Polyhedron,,
  194. "" )
  195. FIELD(mPointList, pointList, 1, "")
  196. FIELD(mPlaneList, planeList, 1, "")
  197. FIELD(mEdgeList, edgeList, 1, "")
  198. END_IMPLEMENT_STRUCT;
  199. ConsoleType(floatList, TypeTriggerPolyhedron, Polyhedron, "")
  200. ConsoleGetType( TypeTriggerPolyhedron )
  201. {
  202. U32 i;
  203. Polyhedron* pPoly = reinterpret_cast<Polyhedron*>(dptr);
  204. // First point is corner, need to find the three vectors...`
  205. Point3F origin = pPoly->mPointList[0];
  206. U32 currVec = 0;
  207. Point3F vecs[3];
  208. for (i = 0; i < pPoly->mEdgeList.size(); i++) {
  209. const U32 *vertex = pPoly->mEdgeList[i].vertex;
  210. if (vertex[0] == 0)
  211. vecs[currVec++] = pPoly->mPointList[vertex[1]] - origin;
  212. else
  213. if (vertex[1] == 0)
  214. vecs[currVec++] = pPoly->mPointList[vertex[0]] - origin;
  215. }
  216. AssertFatal(currVec == 3, "Internal error: Bad trigger polyhedron");
  217. // Build output string.
  218. static const U32 bufSize = 1024;
  219. char* retBuf = Con::getReturnBuffer(bufSize);
  220. dSprintf(retBuf, bufSize, "%7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f",
  221. origin.x, origin.y, origin.z,
  222. vecs[0].x, vecs[0].y, vecs[0].z,
  223. vecs[2].x, vecs[2].y, vecs[2].z,
  224. vecs[1].x, vecs[1].y, vecs[1].z);
  225. return retBuf;
  226. }
  227. /* Console polyhedron data type loader
  228. The polyhedron type is really a quadrilateral and consists of an corner
  229. point follow by three vectors representing the edges extending from the
  230. corner.
  231. */
  232. ConsoleSetType( TypeTriggerPolyhedron )
  233. {
  234. if (argc != 1) {
  235. Con::printf("(TypeTriggerPolyhedron) multiple args not supported for polyhedra");
  236. return;
  237. }
  238. Point3F origin;
  239. Point3F vecs[3];
  240. U32 numArgs = dSscanf(argv[0], "%g %g %g %g %g %g %g %g %g %g %g %g",
  241. &origin.x, &origin.y, &origin.z,
  242. &vecs[0].x, &vecs[0].y, &vecs[0].z,
  243. &vecs[1].x, &vecs[1].y, &vecs[1].z,
  244. &vecs[2].x, &vecs[2].y, &vecs[2].z);
  245. if (numArgs != 12) {
  246. Con::printf("Bad polyhedron!");
  247. return;
  248. }
  249. Polyhedron* pPoly = reinterpret_cast<Polyhedron*>(dptr);
  250. // This setup goes against conventions for Polyhedrons in that it a) sets up
  251. // edges with CCW instead of CW order for face[0] and that it b) lets plane
  252. // normals face outwards rather than inwards.
  253. pPoly->mPointList.setSize(8);
  254. pPoly->mPointList[0] = origin;
  255. pPoly->mPointList[1] = origin + vecs[0];
  256. pPoly->mPointList[2] = origin + vecs[1];
  257. pPoly->mPointList[3] = origin + vecs[2];
  258. pPoly->mPointList[4] = origin + vecs[0] + vecs[1];
  259. pPoly->mPointList[5] = origin + vecs[0] + vecs[2];
  260. pPoly->mPointList[6] = origin + vecs[1] + vecs[2];
  261. pPoly->mPointList[7] = origin + vecs[0] + vecs[1] + vecs[2];
  262. Point3F normal;
  263. pPoly->mPlaneList.setSize(6);
  264. mCross(vecs[2], vecs[0], &normal);
  265. pPoly->mPlaneList[0].set(origin, normal);
  266. mCross(vecs[0], vecs[1], &normal);
  267. pPoly->mPlaneList[1].set(origin, normal);
  268. mCross(vecs[1], vecs[2], &normal);
  269. pPoly->mPlaneList[2].set(origin, normal);
  270. mCross(vecs[1], vecs[0], &normal);
  271. pPoly->mPlaneList[3].set(pPoly->mPointList[7], normal);
  272. mCross(vecs[2], vecs[1], &normal);
  273. pPoly->mPlaneList[4].set(pPoly->mPointList[7], normal);
  274. mCross(vecs[0], vecs[2], &normal);
  275. pPoly->mPlaneList[5].set(pPoly->mPointList[7], normal);
  276. pPoly->mEdgeList.setSize(12);
  277. pPoly->mEdgeList[0].vertex[0] = 0; pPoly->mEdgeList[0].vertex[1] = 1; pPoly->mEdgeList[0].face[0] = 0; pPoly->mEdgeList[0].face[1] = 1;
  278. pPoly->mEdgeList[1].vertex[0] = 1; pPoly->mEdgeList[1].vertex[1] = 5; pPoly->mEdgeList[1].face[0] = 0; pPoly->mEdgeList[1].face[1] = 4;
  279. pPoly->mEdgeList[2].vertex[0] = 5; pPoly->mEdgeList[2].vertex[1] = 3; pPoly->mEdgeList[2].face[0] = 0; pPoly->mEdgeList[2].face[1] = 3;
  280. pPoly->mEdgeList[3].vertex[0] = 3; pPoly->mEdgeList[3].vertex[1] = 0; pPoly->mEdgeList[3].face[0] = 0; pPoly->mEdgeList[3].face[1] = 2;
  281. pPoly->mEdgeList[4].vertex[0] = 3; pPoly->mEdgeList[4].vertex[1] = 6; pPoly->mEdgeList[4].face[0] = 3; pPoly->mEdgeList[4].face[1] = 2;
  282. pPoly->mEdgeList[5].vertex[0] = 6; pPoly->mEdgeList[5].vertex[1] = 2; pPoly->mEdgeList[5].face[0] = 2; pPoly->mEdgeList[5].face[1] = 5;
  283. pPoly->mEdgeList[6].vertex[0] = 2; pPoly->mEdgeList[6].vertex[1] = 0; pPoly->mEdgeList[6].face[0] = 2; pPoly->mEdgeList[6].face[1] = 1;
  284. pPoly->mEdgeList[7].vertex[0] = 1; pPoly->mEdgeList[7].vertex[1] = 4; pPoly->mEdgeList[7].face[0] = 4; pPoly->mEdgeList[7].face[1] = 1;
  285. pPoly->mEdgeList[8].vertex[0] = 4; pPoly->mEdgeList[8].vertex[1] = 2; pPoly->mEdgeList[8].face[0] = 1; pPoly->mEdgeList[8].face[1] = 5;
  286. pPoly->mEdgeList[9].vertex[0] = 4; pPoly->mEdgeList[9].vertex[1] = 7; pPoly->mEdgeList[9].face[0] = 4; pPoly->mEdgeList[9].face[1] = 5;
  287. pPoly->mEdgeList[10].vertex[0] = 5; pPoly->mEdgeList[10].vertex[1] = 7; pPoly->mEdgeList[10].face[0] = 3; pPoly->mEdgeList[10].face[1] = 4;
  288. pPoly->mEdgeList[11].vertex[0] = 7; pPoly->mEdgeList[11].vertex[1] = 6; pPoly->mEdgeList[11].face[0] = 3; pPoly->mEdgeList[11].face[1] = 5;
  289. }
  290. //-----------------------------------------------------------------------------
  291. void Trigger::consoleInit()
  292. {
  293. Con::addVariable( "$Trigger::renderTriggers", TypeBool, &smRenderTriggers,
  294. "@brief Forces all Trigger's to render.\n\n"
  295. "Used by the Tools and debug render modes.\n"
  296. "@ingroup gameObjects" );
  297. }
  298. void Trigger::initPersistFields()
  299. {
  300. addField("polyhedron", TypeTriggerPolyhedron, Offset(mTriggerPolyhedron, Trigger),
  301. "@brief Defines a non-rectangular area for the trigger.\n\n"
  302. "Rather than the standard rectangular bounds, this optional parameter defines a quadrilateral "
  303. "trigger area. The quadrilateral is defined as a corner point followed by three vectors "
  304. "representing the edges extending from the corner.\n");
  305. addField("TripOnce", TypeBool, Offset(mTripOnce, Trigger),"Do we trigger callacks just the once?");
  306. addField("TripCondition", TypeRealString, Offset(mTripCondition, Trigger),"evaluation condition to trip callbacks (true/false)");
  307. addField("TrippedBy", TypeS32, Offset(mTrippedBy, Trigger), "typemask filter");
  308. addProtectedField("enterCommand", TypeCommand, Offset(mEnterCommand, Trigger), &setEnterCmd, &defaultProtectedGetFn,
  309. "The command to execute when an object enters this trigger. Object id stored in %%obj. Maximum 1023 characters." );
  310. addProtectedField("leaveCommand", TypeCommand, Offset(mLeaveCommand, Trigger), &setLeaveCmd, &defaultProtectedGetFn,
  311. "The command to execute when an object leaves this trigger. Object id stored in %%obj. Maximum 1023 characters." );
  312. addProtectedField("tickCommand", TypeCommand, Offset(mTickCommand, Trigger), &setTickCmd, &defaultProtectedGetFn,
  313. "The command to execute while an object is inside this trigger. Maximum 1023 characters." );
  314. Parent::initPersistFields();
  315. }
  316. bool Trigger::setEnterCmd( void *object, const char *index, const char *data )
  317. {
  318. static_cast<Trigger*>(object)->setMaskBits(EnterCmdMask);
  319. return true; // to update the actual field
  320. }
  321. bool Trigger::setLeaveCmd(void *object, const char *index, const char *data)
  322. {
  323. static_cast<Trigger*>(object)->setMaskBits(LeaveCmdMask);
  324. return true; // to update the actual field
  325. }
  326. bool Trigger::setTickCmd(void *object, const char *index, const char *data)
  327. {
  328. static_cast<Trigger*>(object)->setMaskBits(TickCmdMask);
  329. return true; // to update the actual field
  330. }
  331. //------------------------------------------------------------------------------
  332. void Trigger::testObjects()
  333. {
  334. Vector<SceneObject*> foundobjs;
  335. foundobjs.clear();
  336. if (getSceneManager() && getSceneManager()->getContainer() && getSceneManager()->getZoneManager())
  337. getSceneManager()->getContainer()->findObjectList(getWorldBox(), mTrippedBy, &foundobjs);
  338. else return;
  339. for (S32 i = 0; i < foundobjs.size(); i++)
  340. {
  341. GameBase* so = dynamic_cast<GameBase*>(foundobjs[i]);
  342. if (so)
  343. potentialEnterObject(so);
  344. }
  345. }
  346. //--------------------------------------------------------------------------
  347. bool Trigger::onAdd()
  348. {
  349. if(!Parent::onAdd())
  350. return false;
  351. onAdd_callback( getId() );
  352. Polyhedron temp = mTriggerPolyhedron;
  353. setTriggerPolyhedron(temp);
  354. mTripped = false;
  355. addToScene();
  356. if (isServerObject())
  357. scriptOnAdd();
  358. testObjects();
  359. return true;
  360. }
  361. void Trigger::onRemove()
  362. {
  363. onRemove_callback( getId() );
  364. mConvexList->nukeList();
  365. removeFromScene();
  366. Parent::onRemove();
  367. }
  368. bool Trigger::onNewDataBlock( GameBaseData *dptr, bool reload )
  369. {
  370. mDataBlock = dynamic_cast<TriggerData*>( dptr );
  371. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  372. return false;
  373. scriptOnNewDataBlock();
  374. return true;
  375. }
  376. void Trigger::onDeleteNotify( SimObject *obj )
  377. {
  378. GameBase* pScene = dynamic_cast<GameBase*>( obj );
  379. if ( pScene != NULL && mDataBlock != NULL )
  380. {
  381. for ( U32 i = 0; i < mObjects.size(); i++ )
  382. {
  383. if ( pScene == mObjects[i] )
  384. {
  385. mObjects.erase(i);
  386. if (mDataBlock)
  387. mDataBlock->onLeaveTrigger_callback( this, NULL );
  388. break;
  389. }
  390. }
  391. }
  392. Parent::onDeleteNotify( obj );
  393. }
  394. void Trigger::inspectPostApply()
  395. {
  396. setTriggerPolyhedron(mTriggerPolyhedron);
  397. setMaskBits(PolyMask);
  398. Parent::inspectPostApply();
  399. }
  400. //--------------------------------------------------------------------------
  401. void Trigger::buildConvex(const Box3F& box, Convex* convex)
  402. {
  403. // These should really come out of a pool
  404. mConvexList->collectGarbage();
  405. Box3F realBox = box;
  406. mWorldToObj.mul(realBox);
  407. realBox.minExtents.convolveInverse(mObjScale);
  408. realBox.maxExtents.convolveInverse(mObjScale);
  409. if (realBox.isOverlapped(getObjBox()) == false)
  410. return;
  411. // Just return a box convex for the entire shape...
  412. Convex* cc = 0;
  413. CollisionWorkingList& wl = convex->getWorkingList();
  414. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
  415. if (itr->mConvex->getType() == BoxConvexType &&
  416. itr->mConvex->getObject() == this) {
  417. cc = itr->mConvex;
  418. break;
  419. }
  420. }
  421. if (cc)
  422. return;
  423. // Create a new convex.
  424. BoxConvex* cp = new BoxConvex;
  425. mConvexList->registerObject(cp);
  426. convex->addToWorkingList(cp);
  427. cp->init(this);
  428. mObjBox.getCenter(&cp->mCenter);
  429. cp->mSize.x = mObjBox.len_x() / 2.0f;
  430. cp->mSize.y = mObjBox.len_y() / 2.0f;
  431. cp->mSize.z = mObjBox.len_z() / 2.0f;
  432. }
  433. //------------------------------------------------------------------------------
  434. void Trigger::setTransform(const MatrixF & mat)
  435. {
  436. Parent::setTransform(mat);
  437. if ( mPhysicsRep )
  438. mPhysicsRep->setTransform( mat );
  439. if (isServerObject()) {
  440. MatrixF base(true);
  441. base.scale(Point3F(1.0/mObjScale.x,
  442. 1.0/mObjScale.y,
  443. 1.0/mObjScale.z));
  444. base.mul(mWorldToObj);
  445. mClippedList.setBaseTransform(base);
  446. setMaskBits(TransformMask | ScaleMask);
  447. }
  448. testObjects();
  449. }
  450. void Trigger::onUnmount( SceneObject *obj, S32 node )
  451. {
  452. Parent::onUnmount( obj, node );
  453. // Make sure the client get's the final server pos.
  454. setMaskBits(TransformMask | ScaleMask);
  455. }
  456. void Trigger::prepRenderImage( SceneRenderState *state )
  457. {
  458. // only render if selected or render flag is set
  459. if ( !smRenderTriggers && !isSelected() )
  460. return;
  461. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  462. ri->renderDelegate.bind( this, &Trigger::renderObject );
  463. ri->type = RenderPassManager::RIT_Editor;
  464. ri->translucentSort = true;
  465. ri->defaultKey = 1;
  466. state->getRenderPass()->addInst( ri );
  467. }
  468. void Trigger::renderObject( ObjectRenderInst *ri,
  469. SceneRenderState *state,
  470. BaseMatInstance *overrideMat )
  471. {
  472. if(overrideMat)
  473. return;
  474. GFXStateBlockDesc desc;
  475. desc.setZReadWrite( true, false );
  476. desc.setBlend( true );
  477. // Trigger polyhedrons are set up with outward facing normals and CCW ordering
  478. // so can't enable backface culling.
  479. desc.setCullMode( GFXCullNone );
  480. GFXTransformSaver saver;
  481. MatrixF mat = getRenderTransform();
  482. mat.scale( getScale() );
  483. GFX->multWorld( mat );
  484. GFXDrawUtil *drawer = GFX->getDrawUtil();
  485. drawer->drawPolyhedron( desc, mTriggerPolyhedron, ColorI( 255, 192, 0, 45 ) );
  486. // Render wireframe.
  487. desc.setFillModeWireframe();
  488. drawer->drawPolyhedron( desc, mTriggerPolyhedron, ColorI::BLACK );
  489. }
  490. void Trigger::setTriggerPolyhedron(const Polyhedron& rPolyhedron)
  491. {
  492. mTriggerPolyhedron = rPolyhedron;
  493. if (mTriggerPolyhedron.mPointList.size() != 0) {
  494. mObjBox.minExtents.set(1e10, 1e10, 1e10);
  495. mObjBox.maxExtents.set(-1e10, -1e10, -1e10);
  496. for (U32 i = 0; i < mTriggerPolyhedron.mPointList.size(); i++) {
  497. mObjBox.minExtents.setMin(mTriggerPolyhedron.mPointList[i]);
  498. mObjBox.maxExtents.setMax(mTriggerPolyhedron.mPointList[i]);
  499. }
  500. } else {
  501. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  502. mObjBox.maxExtents.set( 0.5, 0.5, 0.5);
  503. }
  504. MatrixF xform = getTransform();
  505. setTransform(xform);
  506. mClippedList.clear();
  507. mClippedList.mPlaneList = mTriggerPolyhedron.mPlaneList;
  508. // for (U32 i = 0; i < mClippedList.mPlaneList.size(); i++)
  509. // mClippedList.mPlaneList[i].neg();
  510. MatrixF base(true);
  511. base.scale(Point3F(1.0/mObjScale.x,
  512. 1.0/mObjScale.y,
  513. 1.0/mObjScale.z));
  514. base.mul(mWorldToObj);
  515. mClippedList.setBaseTransform(base);
  516. SAFE_DELETE( mPhysicsRep );
  517. if ( PHYSICSMGR )
  518. {
  519. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  520. MatrixF colMat( true );
  521. colMat.displace( Point3F( 0, 0, mObjBox.getExtents().z * 0.5f * mObjScale.z ) );
  522. colShape->addBox( mObjBox.getExtents() * 0.5f * mObjScale, colMat );
  523. //MatrixF colMat( true );
  524. //colMat.scale( mObjScale );
  525. //colShape->addConvex( mTriggerPolyhedron.pointList.address(), mTriggerPolyhedron.pointList.size(), colMat );
  526. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  527. mPhysicsRep = PHYSICSMGR->createBody();
  528. mPhysicsRep->init( colShape, 0, PhysicsBody::BF_TRIGGER | PhysicsBody::BF_KINEMATIC, this, world );
  529. mPhysicsRep->setTransform( getTransform() );
  530. }
  531. }
  532. //--------------------------------------------------------------------------
  533. bool Trigger::testObject(GameBase* enter)
  534. {
  535. if (mTriggerPolyhedron.mPointList.size() == 0)
  536. return false;
  537. if (!(enter->getTypeMask() & mTrippedBy))
  538. return false; //not the right type of object
  539. mClippedList.clear();
  540. SphereF sphere;
  541. sphere.center = (mWorldBox.minExtents + mWorldBox.maxExtents) * 0.5;
  542. VectorF bv = mWorldBox.maxExtents - sphere.center;
  543. sphere.radius = bv.len();
  544. enter->buildPolyList(PLC_Collision, &mClippedList, mWorldBox, sphere);
  545. return mClippedList.isEmpty() == false;
  546. }
  547. bool Trigger::testTrippable()
  548. {
  549. if ((mTripOnce == true) && (mTripped == true))
  550. return false; // we've already fired the once
  551. return true;
  552. }
  553. bool Trigger::testCondition()
  554. {
  555. if (mTripCondition.isEmpty())
  556. return true; //we've got no tests to run so just do it
  557. //test the mapper plugged in condition line
  558. String resVar = getIdString() + String(".result");
  559. Con::setBoolVariable(resVar.c_str(), false);
  560. String command = resVar + "=" + mTripCondition + ";";
  561. Con::evaluatef(command.c_str());
  562. if (Con::getBoolVariable(resVar.c_str()) == 1)
  563. {
  564. return true;
  565. }
  566. return false;
  567. }
  568. bool Trigger::evalCmD(String* cmd)
  569. {
  570. if (!testTrippable()) return false;
  571. if (cmd && cmd->isNotEmpty())//do we have a callback?
  572. {
  573. return testCondition();
  574. }
  575. return false;
  576. }
  577. void Trigger::potentialEnterObject(GameBase* enter)
  578. {
  579. if( (!mDataBlock || mDataBlock->isClientSide) && isServerObject() )
  580. return;
  581. if( (mDataBlock && !mDataBlock->isClientSide) && isGhost() )
  582. return;
  583. for (U32 i = 0; i < mObjects.size(); i++) {
  584. if (mObjects[i] == enter)
  585. return;
  586. }
  587. if (testObject(enter) == true) {
  588. mObjects.push_back(enter);
  589. deleteNotify(enter);
  590. if(evalCmD(&mEnterCommand))
  591. {
  592. String command = String("%obj = ") + enter->getIdString() + ";";
  593. command = command + String("%this = ") + getIdString() + ";" + mEnterCommand;
  594. Con::evaluate(command.c_str());
  595. }
  596. if( mDataBlock && testTrippable() && testCondition())
  597. mDataBlock->onEnterTrigger_callback( this, enter );
  598. mTripped = true;
  599. }
  600. }
  601. void Trigger::processTick(const Move* move)
  602. {
  603. Parent::processTick(move);
  604. if (!mDataBlock)
  605. return;
  606. if (mDataBlock->isClientSide && isServerObject())
  607. return;
  608. if (!mDataBlock->isClientSide && isClientObject())
  609. return;
  610. if (isMounted()) {
  611. MatrixF mat;
  612. mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat );
  613. setTransform(mat);
  614. setRenderTransform(mat);
  615. }
  616. //
  617. if (mObjects.size() == 0)
  618. return;
  619. if (mLastThink + mDataBlock->tickPeriodMS < mCurrTick)
  620. {
  621. mCurrTick = 0;
  622. mLastThink = 0;
  623. for (S32 i = S32(mObjects.size() - 1); i >= 0; i--)
  624. {
  625. if (testObject(mObjects[i]) == false)
  626. {
  627. GameBase* remove = mObjects[i];
  628. mObjects.erase(i);
  629. clearNotify(remove);
  630. if (evalCmD(&mLeaveCommand))
  631. {
  632. String command = String("%obj = ") + remove->getIdString() + ";";
  633. command = command + String("%this = ") + getIdString() + ";" + mLeaveCommand;
  634. Con::evaluate(command.c_str());
  635. }
  636. if (testTrippable() && testCondition())
  637. mDataBlock->onLeaveTrigger_callback( this, remove );
  638. mTripped = true;
  639. }
  640. }
  641. if (evalCmD(&mTickCommand))
  642. Con::evaluate(mTickCommand.c_str());
  643. if (mObjects.size() != 0 && testTrippable() && testCondition())
  644. mDataBlock->onTickTrigger_callback( this );
  645. }
  646. else
  647. {
  648. mCurrTick += TickMs;
  649. }
  650. }
  651. void Trigger::interpolateTick(F32 delta)
  652. {
  653. if (isMounted()) {
  654. MatrixF mat;
  655. mMount.object->getRenderMountTransform( delta, mMount.node, mMount.xfm, &mat );
  656. setRenderTransform(mat);
  657. }
  658. }
  659. //--------------------------------------------------------------------------
  660. U32 Trigger::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  661. {
  662. U32 i;
  663. U32 retMask = Parent::packUpdate(con, mask, stream);
  664. if( stream->writeFlag( mask & TransformMask ) )
  665. {
  666. stream->writeAffineTransform(mObjToWorld);
  667. }
  668. // Write the polyhedron
  669. if( stream->writeFlag( mask & PolyMask ) )
  670. {
  671. stream->write(mTriggerPolyhedron.mPointList.size());
  672. for (i = 0; i < mTriggerPolyhedron.mPointList.size(); i++)
  673. mathWrite(*stream, mTriggerPolyhedron.mPointList[i]);
  674. stream->write(mTriggerPolyhedron.mPlaneList.size());
  675. for (i = 0; i < mTriggerPolyhedron.mPlaneList.size(); i++)
  676. mathWrite(*stream, mTriggerPolyhedron.mPlaneList[i]);
  677. stream->write(mTriggerPolyhedron.mEdgeList.size());
  678. for (i = 0; i < mTriggerPolyhedron.mEdgeList.size(); i++) {
  679. const Polyhedron::Edge& rEdge = mTriggerPolyhedron.mEdgeList[i];
  680. stream->write(rEdge.face[0]);
  681. stream->write(rEdge.face[1]);
  682. stream->write(rEdge.vertex[0]);
  683. stream->write(rEdge.vertex[1]);
  684. }
  685. }
  686. if( stream->writeFlag( mask & EnterCmdMask ) )
  687. stream->writeLongString(CMD_SIZE-1, mEnterCommand.c_str());
  688. if( stream->writeFlag( mask & LeaveCmdMask ) )
  689. stream->writeLongString(CMD_SIZE-1, mLeaveCommand.c_str());
  690. if( stream->writeFlag( mask & TickCmdMask ) )
  691. stream->writeLongString(CMD_SIZE-1, mTickCommand.c_str());
  692. return retMask;
  693. }
  694. void Trigger::unpackUpdate(NetConnection* con, BitStream* stream)
  695. {
  696. Parent::unpackUpdate(con, stream);
  697. U32 i, size;
  698. // Transform
  699. if( stream->readFlag() )
  700. {
  701. MatrixF temp;
  702. stream->readAffineTransform(&temp);
  703. setTransform(temp);
  704. }
  705. // Read the polyhedron
  706. if( stream->readFlag() )
  707. {
  708. Polyhedron tempPH;
  709. stream->read(&size);
  710. tempPH.mPointList.setSize(size);
  711. for (i = 0; i < tempPH.mPointList.size(); i++)
  712. mathRead(*stream, &tempPH.mPointList[i]);
  713. stream->read(&size);
  714. tempPH.mPlaneList.setSize(size);
  715. for (i = 0; i < tempPH.mPlaneList.size(); i++)
  716. mathRead(*stream, &tempPH.mPlaneList[i]);
  717. stream->read(&size);
  718. tempPH.mEdgeList.setSize(size);
  719. for (i = 0; i < tempPH.mEdgeList.size(); i++) {
  720. Polyhedron::Edge& rEdge = tempPH.mEdgeList[i];
  721. stream->read(&rEdge.face[0]);
  722. stream->read(&rEdge.face[1]);
  723. stream->read(&rEdge.vertex[0]);
  724. stream->read(&rEdge.vertex[1]);
  725. }
  726. setTriggerPolyhedron(tempPH);
  727. }
  728. if( stream->readFlag() )
  729. {
  730. char buf[CMD_SIZE];
  731. stream->readLongString(CMD_SIZE-1, buf);
  732. mEnterCommand = buf;
  733. }
  734. if( stream->readFlag() )
  735. {
  736. char buf[CMD_SIZE];
  737. stream->readLongString(CMD_SIZE-1, buf);
  738. mLeaveCommand = buf;
  739. }
  740. if( stream->readFlag() )
  741. {
  742. char buf[CMD_SIZE];
  743. stream->readLongString(CMD_SIZE-1, buf);
  744. mTickCommand = buf;
  745. }
  746. }
  747. //ConsoleMethod( Trigger, getNumObjects, S32, 2, 2, "")
  748. DefineEngineMethod( Trigger, getNumObjects, S32, (),,
  749. "@brief Get the number of objects that are within the Trigger's bounds.\n\n"
  750. "@see getObject()\n")
  751. {
  752. return object->getNumTriggeringObjects();
  753. }
  754. //ConsoleMethod( Trigger, getObject, S32, 3, 3, "(int idx)")
  755. DefineEngineMethod( Trigger, getObject, S32, ( S32 index ),,
  756. "@brief Retrieve the requested object that is within the Trigger's bounds.\n\n"
  757. "@param index Index of the object to get (range is 0 to getNumObjects()-1)\n"
  758. "@returns The SimObjectID of the object, or -1 if the requested index is invalid.\n"
  759. "@see getNumObjects()\n")
  760. {
  761. if (index >= object->getNumTriggeringObjects() || index < 0)
  762. return -1;
  763. else
  764. return object->getObject(U32(index))->getId();
  765. }