portal.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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/portal.h"
  24. #include "core/stream/bitStream.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/engineAPI.h"
  27. #include "scene/sceneManager.h"
  28. #include "scene/sceneRenderState.h"
  29. #include "scene/zones/sceneRootZone.h"
  30. #include "scene/culling/sceneCullingState.h"
  31. #include "scene/zones/sceneTraversalState.h"
  32. #include "math/mPlaneSet.h"
  33. #include "gfx/gfxDrawUtil.h"
  34. #include "gfx/gfxTransformSaver.h"
  35. #include "scene/mixin/sceneAmbientSoundObject.impl.h"
  36. #include "scene/mixin/scenePolyhedralObject.impl.h"
  37. #include "math/mPolyhedron.impl.h"
  38. IMPLEMENT_CO_NETOBJECT_V1( Portal );
  39. ConsoleDocClass( Portal,
  40. "@brief An object that provides a \"window\" into a zone, allowing a viewer "
  41. "to see what's rendered in the zone.\n\n"
  42. "A portal is an object that connects zones such that the content of one zone becomes "
  43. "visible in the other when looking through the portal.\n\n"
  44. "Each portal is a full zone which is divided into two sides by the portal plane that "
  45. "intersects it. This intersection polygon is shown in red in the editor. Either of the "
  46. "sides of a portal can be connected to one or more zones.\n\n"
  47. "A connection from a specific portal side to a zone is made in either of two ways:\n\n"
  48. "<ol>\n"
  49. "<li>By moving a Zone object to intersect with the portal at the respective side. While usually it makes "
  50. "sense for this overlap to be small, the connection is established correctly as long as the center of the Zone "
  51. "object that should connect is on the correct side of the portal plane.</li>\n"
  52. "<li>By the respective side of the portal free of Zone objects that would connect to it. In this case, given "
  53. "that the other side is connected to one or more Zones, the portal will automatically connect itself to the "
  54. "outdoor \"zone\" which implicitly is present in any level.</li>\n"
  55. "</ol>\n\n"
  56. "From this, it follows that there are two types of portals:\n\n"
  57. "<dl>\n"
  58. "<dt>Exterior Portals</dt>"
  59. "<dd>An exterior portal is one that is connected to one or more Zone objects on one side and to the outdoor "
  60. "zone at the other side. This kind of portal is most useful for covering transitions from outdoor spaces to "
  61. "indoor spaces.</dd>"
  62. "<dt>Interior Portals</dt>"
  63. "<dd>An interior portal is one that is connected to one or more Zone objects on both sides. This kind of portal "
  64. "is most useful for covering transitions between indoor spaces./dd>"
  65. "</dl>\n\n"
  66. "Strictly speaking, there is a third type of portal called an \"invalid portal\". This is a portal that is not "
  67. "connected to a Zone object on either side in which case the portal serves no use.\n\n"
  68. "Portals in Torque are bidirectional meaning that they connect zones both ways and "
  69. "you can look through the portal's front side as well as through its back-side.\n\n"
  70. "Like Zones, Portals can either be box-shaped or use custom convex polyhedral shapes.\n\n"
  71. "Portals will usually be created in the editor but can, of course, also be created "
  72. "in script code as such:\n\n"
  73. "@tsexample\n"
  74. "// Example declaration of a Portal. This will create a box-shaped portal.\n"
  75. "new Portal( PortalToTestZone )\n"
  76. "{\n"
  77. " position = \"12.8467 -4.02246 14.8017\";\n"
  78. " rotation = \"0 0 -1 97.5085\";\n"
  79. " scale = \"1 0.25 1\";\n"
  80. " canSave = \"1\";\n"
  81. " canSaveDynamicFields = \"1\";\n"
  82. "};\n"
  83. "@endtsexample\n\n"
  84. "@note Keep in mind that zones and portals are more or less strictly a scene optimization mechanism meant to "
  85. "improve render times.\n\n"
  86. "@see Zone\n"
  87. "@ingroup enviroMisc\n"
  88. );
  89. // Notes:
  90. // - This class implements portal spaces as single zones. A different, interesting take
  91. // on this is to turn portal spaces into two zones with the portal plane acting as
  92. // the separator.
  93. // - One downside to our treatment of portals as full zones in their own right is that
  94. // in certain cases we end up including space in the traversal that is clearly not visible.
  95. // Take a situation where you are in the outside zone and you are looking straight into
  96. // the wall of a house. On the other side of that house is a portal leading into the house.
  97. // While the traversal will not step through that portal into the house since that would
  98. // be leading towards the camera rather than away from it, it will still add the frustum
  99. // to the visible space of the portal zone and thus make everything in the portal zone
  100. // visible. It has to do this since, while it can easily tell whether to step through the
  101. // portal or not, it cannot easily tell whether the whole portal zone is visible or not as
  102. // that depends on the occlusion situation in the outdoor zone.
  103. //-----------------------------------------------------------------------------
  104. Portal::Portal()
  105. : mClassification( InvalidPortal ),
  106. mIsGeometryDirty( true )
  107. {
  108. VECTOR_SET_ASSOCIATION( mPortalPolygonWS );
  109. mNetFlags.set( Ghostable | ScopeAlways );
  110. mTypeMask |= StaticObjectType;
  111. mPassableSides[ FrontSide ] = true;
  112. mPassableSides[ BackSide ] = true;
  113. mObjScale.set( 1.0f, 0.25f, 1.0f );
  114. // We're not closed off.
  115. mZoneFlags.clear( ZoneFlag_IsClosedOffSpace );
  116. }
  117. //-----------------------------------------------------------------------------
  118. void Portal::initPersistFields()
  119. {
  120. addGroup( "Zoning" );
  121. addProtectedField( "frontSidePassable", TypeBool, Offset( mPassableSides[ FrontSide ], Portal ),
  122. &_setFrontSidePassable, &defaultProtectedGetFn,
  123. "Whether one can view through the front-side of the portal." );
  124. addProtectedField( "backSidePassable", TypeBool, Offset( mPassableSides[ BackSide ], Portal ),
  125. &_setBackSidePassable, &defaultProtectedGetFn,
  126. "Whether one can view through the back-side of the portal." );
  127. endGroup( "Zoning" );
  128. Parent::initPersistFields();
  129. }
  130. //-----------------------------------------------------------------------------
  131. void Portal::consoleInit()
  132. {
  133. // Disable rendering of portals by default.
  134. getStaticClassRep()->mIsRenderEnabled = false;
  135. }
  136. //-----------------------------------------------------------------------------
  137. String Portal::describeSelf() const
  138. {
  139. String str = Parent::describeSelf();
  140. switch( getClassification() )
  141. {
  142. case InvalidPortal: str += "|InvalidPortal"; break;
  143. case ExteriorPortal: str += "|ExteriorPortal"; break;
  144. case InteriorPortal: str += "|InteriorPortal"; break;
  145. }
  146. return str;
  147. }
  148. //-----------------------------------------------------------------------------
  149. bool Portal::writeField( StringTableEntry fieldName, const char* value )
  150. {
  151. static StringTableEntry sFrontSidePassable = StringTable->insert( "frontSidePassable" );
  152. static StringTableEntry sBackSidePassable = StringTable->insert( "backSidePassable" );
  153. // Don't write passable flags if at default.
  154. if( ( fieldName == sFrontSidePassable || fieldName == sBackSidePassable ) &&
  155. dAtob( value ) )
  156. return false;
  157. return Parent::writeField( fieldName, value );
  158. }
  159. //-----------------------------------------------------------------------------
  160. void Portal::onSceneRemove()
  161. {
  162. // Disconnect from root zone, if it's an exterior portal.
  163. if( mClassification == ExteriorPortal )
  164. {
  165. AssertFatal( getSceneManager()->getZoneManager(), "Portal::onSceneRemove - Portal classified as exterior without having a zone manager!" );
  166. getSceneManager()->getZoneManager()->getRootZone()->disconnectZoneSpace( this );
  167. }
  168. Parent::onSceneRemove();
  169. }
  170. //-----------------------------------------------------------------------------
  171. void Portal::setTransform( const MatrixF& mat )
  172. {
  173. // Portal geometry needs updating. Set this before calling
  174. // parent because the transform change will cause an immediate
  175. // update of the portal's zoning state.
  176. mIsGeometryDirty = true;
  177. Parent::setTransform( mat );
  178. }
  179. //-----------------------------------------------------------------------------
  180. void Portal::setSidePassable( Side side, bool value )
  181. {
  182. if( mPassableSides[ side ] == value )
  183. return;
  184. mPassableSides[ side ] = value;
  185. if( isServerObject() )
  186. setMaskBits( PassableMask );
  187. }
  188. //-----------------------------------------------------------------------------
  189. U32 Portal::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  190. {
  191. U32 retMask = Parent::packUpdate( con, mask, stream );
  192. stream->writeFlag( mPassableSides[ FrontSide ] );
  193. stream->writeFlag( mPassableSides[ BackSide ] );
  194. return retMask;
  195. }
  196. //-----------------------------------------------------------------------------
  197. void Portal::unpackUpdate( NetConnection *con, BitStream *stream )
  198. {
  199. Parent::unpackUpdate( con, stream );
  200. mPassableSides[ FrontSide ] = stream->readFlag();
  201. mPassableSides[ BackSide ] = stream->readFlag();
  202. }
  203. //-----------------------------------------------------------------------------
  204. void Portal::_renderObject( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* overrideMat )
  205. {
  206. if( overrideMat )
  207. return;
  208. // Update geometry if necessary.
  209. if( mIsGeometryDirty )
  210. _updateGeometry();
  211. // Render portal polygon.
  212. GFXStateBlockDesc desc;
  213. desc.setBlend( true );
  214. desc.setZReadWrite( true, false );
  215. desc.setCullMode( GFXCullNone );
  216. PlaneF::Side viewSide = mPortalPlane.whichSide( state->getCameraPosition() );
  217. ColorI color;
  218. switch( mClassification )
  219. {
  220. case InvalidPortal: color = ColorI( 255, 255, 255, 45 ); break;
  221. case ExteriorPortal: color = viewSide == PlaneF::Front ? ColorI( 0, 128, 128, 45 ) : ColorI( 0, 255, 255, 45 ); break;
  222. case InteriorPortal: color = viewSide == PlaneF::Front ? ColorI( 128, 128, 0, 45 ) : ColorI( 255, 255, 0, 45 ); break;
  223. }
  224. GFX->getDrawUtil()->drawPolygon( desc, mPortalPolygonWS.address(), mPortalPolygonWS.size(), color );
  225. desc.setFillModeWireframe();
  226. GFX->getDrawUtil()->drawPolygon( desc, mPortalPolygonWS.address(), mPortalPolygonWS.size(), ColorI::RED );
  227. // Render rest.
  228. Parent::_renderObject( ri, state, overrideMat );
  229. }
  230. //-----------------------------------------------------------------------------
  231. void Portal::traverseZones( SceneTraversalState* state, U32 startZoneId )
  232. {
  233. // Check whether the portal is occluded.
  234. if( state->getTraversalDepth() > 0 &&
  235. state->getCullingState()->isOccluded( this ) )
  236. return;
  237. Parent::traverseZones( state, startZoneId );
  238. }
  239. //-----------------------------------------------------------------------------
  240. void Portal::_traverseConnectedZoneSpaces( SceneTraversalState* state )
  241. {
  242. PROFILE_SCOPE( Portal_traverseConnectedZoneSpaces );
  243. // Don't traverse out from the portal if it is invalid.
  244. if( mClassification == InvalidPortal )
  245. return;
  246. AssertFatal( !mIsGeometryDirty, "Portal::_traverseConnectedZoneSpaces - Geometry not up-to-date!" );
  247. // When starting traversal within a portal zone, we cannot really use the portal
  248. // plane itself to direct our visibility queries. For example, the camera might
  249. // actually be located in front of the portal plane and thus cannot actually look
  250. // through the portal, though it will still see what lies on front of where the
  251. // portal leads.
  252. //
  253. // So if we're the start of the traversal chain, i.e. the traversal has started
  254. // out in the portal zone, then just put the traversal through to SceneZoneSpace
  255. // so it can hand it over to all connected zone managers.
  256. //
  257. // Otherwise, just do a normal traversal by stepping through the portal.
  258. if( state->getTraversalDepth() == 1 )
  259. {
  260. Parent::_traverseConnectedZoneSpaces( state );
  261. return;
  262. }
  263. SceneCullingState* cullingState = state->getCullingState();
  264. const SceneCameraState& cameraState = cullingState->getCameraState();
  265. // Get the data of the zone we're coming from. Note that at this point
  266. // the portal zone itself is already on top of the traversal stack, so
  267. // we skip over the bottom-most entry.
  268. const U32 sourceZoneId = state->getZoneIdFromStack( 1 );
  269. const SceneZoneSpace* sourceZoneSpace = state->getZoneFromStack( 1 );
  270. // Find out which side of the portal we are on given the
  271. // source zone.
  272. const Portal::Side currentZoneSide =
  273. sourceZoneId == SceneZoneSpaceManager::RootZoneId
  274. ? ( getInteriorSideOfExteriorPortal() == FrontSide ? BackSide : FrontSide )
  275. : getSideRelativeToPortalPlane( sourceZoneSpace->getPosition() );
  276. // Don't step through portal if the side we're interested in isn't passable.
  277. if( !isSidePassable( currentZoneSide ) )
  278. return;
  279. // If the viewpoint isn't on the same side of the portal as the source zone,
  280. // then stepping through the portal would mean we are stepping back towards
  281. // the viewpoint which doesn't make sense; so, skip the portal.
  282. const Point3F& viewPos = cameraState.getViewPosition();
  283. const F32 viewPosDistToPortal = mFabs( getPortalPlane().distToPlane( viewPos ) );
  284. if( !mIsZero( viewPosDistToPortal ) && getSideRelativeToPortalPlane( viewPos ) != currentZoneSide )
  285. return;
  286. // Before we go ahead and do the real work, try to find out whether
  287. // the portal is at a perpendicular or near-perpendicular angle to the view
  288. // direction. If so, there's no point in going further since we can't really
  289. // see much through the portal anyway. It also prevents us from stepping
  290. // over front/back side ambiguities.
  291. Point3F viewDirection = cameraState.getViewDirection();
  292. const F32 dotProduct = mDot( viewDirection, getPortalPlane() );
  293. if( mIsZero( dotProduct ) )
  294. return;
  295. // Finally, if we have come through a portal to the current zone, check if the target
  296. // portal we are trying to step through now completely lies on the "backside"--i.e.
  297. // the side of portal on which our current zone lies--of the source portal. If so,
  298. // we can be sure this portal leads us in the wrong direction. This prevents the
  299. // outdoor zone from having just arrived through a window on one side of a house just
  300. // to go round the house and re-enter it from the other side.
  301. Portal* sourcePortal = state->getTraversalDepth() > 2 ? dynamic_cast< Portal* >( state->getZoneFromStack( 2 ) ) : NULL;
  302. if( sourcePortal != NULL )
  303. {
  304. const Side sourcePortalFrontSide =
  305. sourceZoneId == SceneZoneSpaceManager::RootZoneId
  306. ? sourcePortal->getInteriorSideOfExteriorPortal()
  307. : sourcePortal->getSideRelativeToPortalPlane( sourceZoneSpace->getPosition() );
  308. const PlaneF::Side sourcePortalPlaneFrontSide =
  309. sourcePortalFrontSide == FrontSide ? PlaneF::Front : PlaneF::Back;
  310. bool allPortalVerticesOnBackside = true;
  311. const U32 numVertices = mPortalPolygonWS.size();
  312. for( U32 i = 0; i < numVertices; ++ i )
  313. {
  314. // Not using getSideRelativeToPortalPlane here since we want PlaneF::On to be
  315. // counted as backside here.
  316. if( sourcePortal->mPortalPlane.whichSide( mPortalPolygonWS[ i ] ) == sourcePortalPlaneFrontSide )
  317. {
  318. allPortalVerticesOnBackside = false;
  319. break;
  320. }
  321. }
  322. if( allPortalVerticesOnBackside )
  323. return;
  324. }
  325. // If we come from the outdoor zone, then we don't want to step through any portal
  326. // where the interior zones are actually on the same side as our camera since that
  327. // would mean we are stepping into an interior through the backside of a portal.
  328. if( sourceZoneId == SceneZoneSpaceManager::RootZoneId )
  329. {
  330. const Portal::Side cameraSide = getSideRelativeToPortalPlane( viewPos );
  331. if( cameraSide == getInteriorSideOfExteriorPortal() )
  332. return;
  333. }
  334. // Clip the current culling volume against the portal's polygon. If the polygon
  335. // lies completely outside the volume or for some other reason there's no good resulting
  336. // volume, _generateCullingVolume() will return false and we terminate this portal sequence
  337. // here.
  338. //
  339. // However, don't attempt to clip the portal if we are standing really close to or
  340. // even below the near distance away from the portal plane. In that case, trying to
  341. // clip the portal will only result in trouble so we stick to the original culling volume
  342. // in that case.
  343. bool haveClipped = false;
  344. if( viewPosDistToPortal > ( cameraState.getFrustum().getNearDist() + 0.1f ) )
  345. {
  346. SceneCullingVolume volume;
  347. if( !_generateCullingVolume( state, volume ) )
  348. return;
  349. state->pushCullingVolume( volume );
  350. haveClipped = true;
  351. }
  352. // Short-circuit things if we are stepping from an interior zone outside. In this
  353. // case we know that the only zone we care about is the outdoor zone so head straight
  354. // into it.
  355. if( isExteriorPortal() && sourceZoneId != SceneZoneSpaceManager::RootZoneId )
  356. getSceneManager()->getZoneManager()->getRootZone()->traverseZones( state );
  357. else
  358. {
  359. // Go through the zones that the portal connects to and
  360. // traverse into them.
  361. for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext )
  362. {
  363. SceneZoneSpace* targetSpace = ref->mZoneSpace;
  364. if( targetSpace == sourceZoneSpace )
  365. continue; // Skip space we originated from.
  366. // We have handled the case of stepping into the outdoor zone above and
  367. // by skipping the zone we originated from, we have implicitly handled the
  368. // case of stepping out of the outdoor zone. Thus, we should not see the
  369. // outdoor zone here. Important as getPosition() is meaningless for it.
  370. AssertFatal( targetSpace->getZoneRangeStart() != SceneZoneSpaceManager::RootZoneId,
  371. "Portal::_traverseConnectedZoneSpaces - Outdoor zone must have been handled already" );
  372. // Skip zones that lie on the same side as the zone
  373. // we originated from.
  374. if( getSideRelativeToPortalPlane( targetSpace->getPosition() ) == currentZoneSide )
  375. continue;
  376. // Traverse into the space.
  377. targetSpace->traverseZones( state );
  378. }
  379. }
  380. // If we have pushed our own clipping volume,
  381. // remove that from the stack now.
  382. if( haveClipped )
  383. state->popCullingVolume();
  384. }
  385. //-----------------------------------------------------------------------------
  386. bool Portal::_generateCullingVolume( SceneTraversalState* state, SceneCullingVolume& outVolume ) const
  387. {
  388. PROFILE_SCOPE( Portal_generateCullingVolume );
  389. SceneCullingState* cullingState = state->getCullingState();
  390. const SceneCullingVolume& currentVolume = state->getCurrentCullingVolume();
  391. // Clip the portal polygon against the current culling volume.
  392. Point3F vertices[ 64 ];
  393. U32 numVertices = 0;
  394. numVertices = currentVolume.getPlanes().clipPolygon(
  395. mPortalPolygonWS.address(),
  396. mPortalPolygonWS.size(),
  397. vertices,
  398. sizeof( vertices ) /sizeof( vertices[ 0 ] )
  399. );
  400. AssertFatal( numVertices == 0 || numVertices >= 3,
  401. "Portal::_generateCullingVolume - Clipping produced degenerate polygon" );
  402. if( !numVertices )
  403. return false;
  404. // Create a culling volume.
  405. return cullingState->createCullingVolume(
  406. vertices, numVertices,
  407. SceneCullingVolume::Includer,
  408. outVolume
  409. );
  410. }
  411. //-----------------------------------------------------------------------------
  412. void Portal::connectZoneSpace( SceneZoneSpace* zoneSpace )
  413. {
  414. Parent::connectZoneSpace( zoneSpace );
  415. // Update portal state. Unfortunately, we can't do that on demand
  416. // easily since everything must be in place before a traversal starts.
  417. _update();
  418. }
  419. //-----------------------------------------------------------------------------
  420. void Portal::disconnectZoneSpace( SceneZoneSpace* zoneSpace )
  421. {
  422. Parent::disconnectZoneSpace( zoneSpace );
  423. // Update portal state.
  424. _update();
  425. }
  426. //-----------------------------------------------------------------------------
  427. void Portal::_disconnectAllZoneSpaces()
  428. {
  429. Parent::_disconnectAllZoneSpaces();
  430. // Update portal state.
  431. _update();
  432. }
  433. //-----------------------------------------------------------------------------
  434. void Portal::_update()
  435. {
  436. if( mIsGeometryDirty )
  437. _updateGeometry();
  438. _updateConnectivity();
  439. }
  440. //-----------------------------------------------------------------------------
  441. void Portal::_updateGeometry()
  442. {
  443. const F32 boxHalfWidth = getScale().x * 0.5f;
  444. const F32 boxHalfHeight = getScale().z * 0.5f;
  445. const Point3F center = getTransform().getPosition();
  446. const Point3F up = getTransform().getUpVector() * boxHalfHeight;
  447. const Point3F right = getTransform().getRightVector() * boxHalfWidth;
  448. // Update the portal polygon and plane.
  449. if( mIsBox )
  450. {
  451. // It's a box so the portal polygon is a rectangle.
  452. // Simply compute the corner points by stepping from the
  453. // center to the corners using the up and right vector.
  454. mPortalPolygonWS.setSize( 4 );
  455. mPortalPolygonWS[ 0 ] = center + right - up; // bottom right
  456. mPortalPolygonWS[ 1 ] = center - right - up; // bottom left
  457. mPortalPolygonWS[ 2 ] = center - right + up; // top left
  458. mPortalPolygonWS[ 3 ] = center + right + up; // top right
  459. // Update the plane by going through three of the points.
  460. mPortalPlane = PlaneF(
  461. mPortalPolygonWS[ 0 ],
  462. mPortalPolygonWS[ 1 ],
  463. mPortalPolygonWS[ 2 ]
  464. );
  465. }
  466. else
  467. {
  468. // It's not necessarily a box so we must use the general
  469. // routine.
  470. // Update the portal plane by building a plane that cuts the
  471. // OBB in half vertically along its Y axis.
  472. mPortalPlane = PlaneF(
  473. center + right - up,
  474. center - right - up,
  475. center - right + up
  476. );
  477. // Slice the polyhedron along the same plane in object space.
  478. const PlaneF slicePlane = PlaneF( Point3F::Zero, Point3F( 0.f, 1.f, 0.f ) );
  479. mPortalPolygonWS.setSize( mPolyhedron.getNumEdges() );
  480. U32 numPoints = mPolyhedron.constructIntersection( slicePlane, mPortalPolygonWS.address(), mPortalPolygonWS.size() );
  481. mPortalPolygonWS.setSize( numPoints );
  482. // Transform the polygon to world space.
  483. for( U32 i = 0; i < numPoints; ++ i )
  484. {
  485. mPortalPolygonWS[ i ].convolve( getScale() );
  486. mObjToWorld.mulP( mPortalPolygonWS[ i ] );
  487. }
  488. }
  489. mIsGeometryDirty = false;
  490. }
  491. //-----------------------------------------------------------------------------
  492. void Portal::_updateConnectivity()
  493. {
  494. SceneZoneSpaceManager* zoneManager = getSceneManager()->getZoneManager();
  495. if( !zoneManager )
  496. return;
  497. // Find out where our connected zones are in respect to the portal
  498. // plane.
  499. bool haveInteriorZonesOnFrontSide = false;
  500. bool haveInteriorZonesOnBackSide = false;
  501. bool isConnectedToRootZone = ( mClassification == ExteriorPortal );
  502. for( ZoneSpaceRef* ref = mConnectedZoneSpaces;
  503. ref != NULL; ref = ref->mNext )
  504. {
  505. SceneZoneSpace* zone = dynamic_cast< SceneZoneSpace* >( ref->mZoneSpace );
  506. if( !zone || zone->isRootZone() )
  507. continue;
  508. if( getSideRelativeToPortalPlane( zone->getPosition() ) == FrontSide )
  509. haveInteriorZonesOnFrontSide = true;
  510. else
  511. haveInteriorZonesOnBackSide = true;
  512. }
  513. // If we have zones connected to us on only one side, we are an exterior
  514. // portal. Otherwise, we're an interior portal.
  515. SceneRootZone* rootZone = zoneManager->getRootZone();
  516. if( haveInteriorZonesOnFrontSide && haveInteriorZonesOnBackSide )
  517. {
  518. mClassification = InteriorPortal;
  519. }
  520. else if( haveInteriorZonesOnFrontSide || haveInteriorZonesOnBackSide )
  521. {
  522. mClassification = ExteriorPortal;
  523. // Remember where our interior zones are.
  524. if( haveInteriorZonesOnBackSide )
  525. mInteriorSide = BackSide;
  526. else
  527. mInteriorSide = FrontSide;
  528. // If we aren't currently connected to the root zone,
  529. // establish the connection now.
  530. if( !isConnectedToRootZone )
  531. {
  532. Parent::connectZoneSpace( rootZone );
  533. rootZone->connectZoneSpace( this );
  534. }
  535. }
  536. else
  537. mClassification = InvalidPortal;
  538. // If we have been connected to the outdoor zone already but the
  539. // portal got classified as invalid or interior now, break the
  540. // connection to the outdoor zone.
  541. if( isConnectedToRootZone &&
  542. ( mClassification == InvalidPortal || mClassification == InteriorPortal ) )
  543. {
  544. Parent::disconnectZoneSpace( rootZone );
  545. rootZone->disconnectZoneSpace( this );
  546. }
  547. }
  548. //-----------------------------------------------------------------------------
  549. Portal::Side Portal::getSideRelativeToPortalPlane( const Point3F& point ) const
  550. {
  551. // For our purposes, we consider PlaneF::Front and PlaneF::On
  552. // placement as FrontSide.
  553. PlaneF::Side planeSide = getPortalPlane().whichSide( point );
  554. if( planeSide == PlaneF::Front || planeSide == PlaneF::On )
  555. return FrontSide;
  556. else
  557. return BackSide;
  558. }
  559. //-----------------------------------------------------------------------------
  560. bool Portal::_setFrontSidePassable( void* object, const char* index, const char* data )
  561. {
  562. Portal* portal = reinterpret_cast< Portal* >( object );
  563. portal->setSidePassable( Portal::FrontSide, EngineUnmarshallData< bool >()( data ) );
  564. return false;
  565. }
  566. //-----------------------------------------------------------------------------
  567. bool Portal::_setBackSidePassable( void* object, const char* index, const char* data )
  568. {
  569. Portal* portal = reinterpret_cast< Portal* >( object );
  570. portal->setSidePassable( Portal::BackSide, EngineUnmarshallData< bool >()( data ) );
  571. return false;
  572. }
  573. //=============================================================================
  574. // Console API.
  575. //=============================================================================
  576. // MARK: ---- Console API ----
  577. //-----------------------------------------------------------------------------
  578. DefineEngineMethod( Portal, isInteriorPortal, bool, (),,
  579. "Test whether the portal connects interior zones only.\n\n"
  580. "@return True if the portal is an interior portal." )
  581. {
  582. return object->isInteriorPortal();
  583. }
  584. //-----------------------------------------------------------------------------
  585. DefineEngineMethod( Portal, isExteriorPortal, bool, (),,
  586. "Test whether the portal connects interior zones to the outdoor zone.\n\n"
  587. "@return True if the portal is an exterior portal." )
  588. {
  589. return object->isExteriorPortal();
  590. }