trigger.cpp 29 KB

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