groundPlane.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/groundPlane.h"
  28. #include "renderInstance/renderPassManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "materials/sceneData.h"
  31. #include "materials/materialDefinition.h"
  32. #include "materials/materialManager.h"
  33. #include "materials/baseMatInstance.h"
  34. #include "math/util/frustum.h"
  35. #include "math/mPlane.h"
  36. #include "console/consoleTypes.h"
  37. #include "console/engineAPI.h"
  38. #include "core/stream/bitStream.h"
  39. #include "collision/boxConvex.h"
  40. #include "collision/abstractPolyList.h"
  41. #include "T3D/physics/physicsPlugin.h"
  42. #include "T3D/physics/physicsBody.h"
  43. #include "T3D/physics/physicsCollision.h"
  44. #ifdef TORQUE_AFX_ENABLED
  45. #include "afx/ce/afxZodiacMgr.h"
  46. #endif
  47. /// Minimum square size allowed. This is a cheap way to limit the amount
  48. /// of geometry possibly generated by the GroundPlane (vertex buffers have a
  49. /// limit, too). Dynamically clipping extents into range is a problem since the
  50. /// location of the horizon depends on the camera orientation. Just shifting
  51. /// squareSize as needed also doesn't work as that causes different geometry to
  52. /// be generated depending on the viewpoint and orientation which affects the
  53. /// texturing.
  54. static const F32 sMIN_SQUARE_SIZE = 16;
  55. IMPLEMENT_CO_NETOBJECT_V1( GroundPlane );
  56. ConsoleDocClass( GroundPlane,
  57. "@brief An infinite plane extending in all direction.\n\n"
  58. "%GroundPlane is useful for setting up simple testing scenes, or it can be "
  59. "placed under an existing scene to keep objects from falling into 'nothing'.\n\n"
  60. "%GroundPlane may not be moved or rotated, it is always at the world origin.\n\n"
  61. "@ingroup Terrain"
  62. );
  63. GroundPlane::GroundPlane()
  64. : mSquareSize( 128.0f ),
  65. mScaleU( 1.0f ),
  66. mScaleV( 1.0f ),
  67. mMaterial( NULL ),
  68. mPhysicsRep( NULL ),
  69. mMin( 0.0f, 0.0f ),
  70. mMax( 0.0f, 0.0f )
  71. {
  72. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  73. mNetFlags.set( Ghostable | ScopeAlways );
  74. mConvexList = new Convex;
  75. mTypeMask |= TerrainLikeObjectType;
  76. }
  77. GroundPlane::~GroundPlane()
  78. {
  79. if( mMaterial )
  80. SAFE_DELETE( mMaterial );
  81. mConvexList->nukeList();
  82. SAFE_DELETE( mConvexList );
  83. }
  84. void GroundPlane::initPersistFields()
  85. {
  86. addGroup( "Plane" );
  87. addField( "squareSize", TypeF32, Offset( mSquareSize, GroundPlane ), "Square size in meters to which %GroundPlane subdivides its geometry." );
  88. addField( "scaleU", TypeF32, Offset( mScaleU, GroundPlane ), "Scale of texture repeat in the U direction." );
  89. addField( "scaleV", TypeF32, Offset( mScaleV, GroundPlane ), "Scale of texture repeat in the V direction." );
  90. addField( "material", TypeMaterialName, Offset( mMaterialName, GroundPlane ), "Name of Material used to render %GroundPlane's surface." );
  91. endGroup( "Plane" );
  92. Parent::initPersistFields();
  93. removeField( "scale" );
  94. removeField( "position" );
  95. removeField( "rotation" );
  96. }
  97. bool GroundPlane::onAdd()
  98. {
  99. if( !Parent::onAdd() )
  100. return false;
  101. if( isClientObject() )
  102. _updateMaterial();
  103. if( mSquareSize < sMIN_SQUARE_SIZE )
  104. {
  105. Con::errorf( "GroundPlane - squareSize below threshold; re-setting to %.02f", sMIN_SQUARE_SIZE );
  106. mSquareSize = sMIN_SQUARE_SIZE;
  107. }
  108. Parent::setScale( VectorF( 1.0f, 1.0f, 1.0f ) );
  109. Parent::setTransform( MatrixF::Identity );
  110. setGlobalBounds();
  111. resetWorldBox();
  112. addToScene();
  113. if ( PHYSICSMGR )
  114. {
  115. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  116. colShape->addPlane( PlaneF( Point3F::Zero, Point3F( 0, 0, 1 ) ) );
  117. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  118. mPhysicsRep = PHYSICSMGR->createBody();
  119. mPhysicsRep->init( colShape, 0, 0, this, world );
  120. }
  121. return true;
  122. }
  123. void GroundPlane::onRemove()
  124. {
  125. SAFE_DELETE( mPhysicsRep );
  126. removeFromScene();
  127. Parent::onRemove();
  128. }
  129. void GroundPlane::inspectPostApply()
  130. {
  131. Parent::inspectPostApply();
  132. setMaskBits( U32( -1 ) );
  133. if( mSquareSize < sMIN_SQUARE_SIZE )
  134. {
  135. Con::errorf( "GroundPlane - squareSize below threshold; re-setting to %.02f", sMIN_SQUARE_SIZE );
  136. mSquareSize = sMIN_SQUARE_SIZE;
  137. }
  138. setScale( VectorF( 1.0f, 1.0f, 1.0f ) );
  139. }
  140. void GroundPlane::setTransform( const MatrixF &mat )
  141. {
  142. // Ignore.
  143. }
  144. void GroundPlane::setScale( const Point3F& scale )
  145. {
  146. // Ignore.
  147. }
  148. U32 GroundPlane::packUpdate( NetConnection* connection, U32 mask, BitStream* stream )
  149. {
  150. U32 retMask = Parent::packUpdate( connection, mask, stream );
  151. stream->write( mSquareSize );
  152. stream->write( mScaleU );
  153. stream->write( mScaleV );
  154. stream->write( mMaterialName );
  155. return retMask;
  156. }
  157. void GroundPlane::unpackUpdate( NetConnection* connection, BitStream* stream )
  158. {
  159. Parent::unpackUpdate( connection, stream );
  160. stream->read( &mSquareSize );
  161. stream->read( &mScaleU );
  162. stream->read( &mScaleV );
  163. stream->read( &mMaterialName );
  164. // If we're added then something possibly changed in
  165. // the editor... do an update of the material and the
  166. // geometry.
  167. if ( isProperlyAdded() )
  168. {
  169. _updateMaterial();
  170. mVertexBuffer = NULL;
  171. }
  172. }
  173. void GroundPlane::_updateMaterial()
  174. {
  175. if( mMaterialName.isEmpty() )
  176. {
  177. Con::warnf( "GroundPlane::_updateMaterial - no material set; defaulting to 'WarningMaterial'" );
  178. mMaterialName = "WarningMaterial";
  179. }
  180. // If the material name matches then don't
  181. // bother updating it.
  182. if ( mMaterial &&
  183. mMaterialName.compare( mMaterial->getMaterial()->getName() ) == 0 )
  184. return;
  185. SAFE_DELETE( mMaterial );
  186. mMaterial = MATMGR->createMatInstance( mMaterialName, getGFXVertexFormat< VertexType >() );
  187. if ( !mMaterial )
  188. Con::errorf( "GroundPlane::_updateMaterial - no material called '%s'", mMaterialName.c_str() );
  189. }
  190. bool GroundPlane::castRay( const Point3F& start, const Point3F& end, RayInfo* info )
  191. {
  192. PlaneF plane( Point3F( 0.0f, 0.0f, 0.0f ), Point3F( 0.0f, 0.0f, 1.0f ) );
  193. F32 t = plane.intersect( start, end );
  194. if( t >= 0.0 && t <= 1.0 )
  195. {
  196. info->t = t;
  197. info->setContactPoint( start, end );
  198. info->normal.set( 0, 0, 1 );
  199. info->material = mMaterial;
  200. info->object = this;
  201. info->distance = 0;
  202. info->faceDot = 0;
  203. info->texCoord.set( 0, 0 );
  204. return true;
  205. }
  206. return false;
  207. }
  208. void GroundPlane::buildConvex( const Box3F& box, Convex* convex )
  209. {
  210. mConvexList->collectGarbage();
  211. Box3F planeBox = getPlaneBox();
  212. if ( !box.isOverlapped( planeBox ) )
  213. return;
  214. // See if we already have a convex in the working set.
  215. BoxConvex *boxConvex = NULL;
  216. CollisionWorkingList &wl = convex->getWorkingList();
  217. CollisionWorkingList *itr = wl.wLink.mNext;
  218. for ( ; itr != &wl; itr = itr->wLink.mNext )
  219. {
  220. if ( itr->mConvex->getType() == BoxConvexType &&
  221. itr->mConvex->getObject() == this )
  222. {
  223. boxConvex = (BoxConvex*)itr->mConvex;
  224. break;
  225. }
  226. }
  227. if ( !boxConvex )
  228. {
  229. boxConvex = new BoxConvex;
  230. mConvexList->registerObject( boxConvex );
  231. boxConvex->init( this );
  232. convex->addToWorkingList( boxConvex );
  233. }
  234. // Update our convex to best match the queried box
  235. if ( boxConvex )
  236. {
  237. Point3F queryCenter = box.getCenter();
  238. boxConvex->mCenter = Point3F( queryCenter.x, queryCenter.y, -GROUND_PLANE_BOX_HEIGHT_HALF );
  239. boxConvex->mSize = Point3F( box.getExtents().x,
  240. box.getExtents().y,
  241. GROUND_PLANE_BOX_HEIGHT_HALF );
  242. }
  243. }
  244. bool GroundPlane::buildPolyList( PolyListContext context, AbstractPolyList* polyList, const Box3F& box, const SphereF& )
  245. {
  246. polyList->setObject( this );
  247. polyList->setTransform( &MatrixF::Identity, Point3F( 1.0f, 1.0f, 1.0f ) );
  248. if(context == PLC_Navigation)
  249. {
  250. F32 z = getPosition().z;
  251. Point3F
  252. p0(box.minExtents.x, box.maxExtents.y, z),
  253. p1(box.maxExtents.x, box.maxExtents.y, z),
  254. p2(box.maxExtents.x, box.minExtents.y, z),
  255. p3(box.minExtents.x, box.minExtents.y, z);
  256. // Add vertices to poly list.
  257. U32 v0 = polyList->addPoint(p0);
  258. polyList->addPoint(p1);
  259. polyList->addPoint(p2);
  260. polyList->addPoint(p3);
  261. // Add plane between first three vertices.
  262. polyList->begin(0, 0);
  263. polyList->vertex(v0);
  264. polyList->vertex(v0+1);
  265. polyList->vertex(v0+2);
  266. polyList->plane(v0, v0+1, v0+2);
  267. polyList->end();
  268. // Add plane between last three vertices.
  269. polyList->begin(0, 1);
  270. polyList->vertex(v0+2);
  271. polyList->vertex(v0+3);
  272. polyList->vertex(v0);
  273. polyList->plane(v0+2, v0+3, v0);
  274. polyList->end();
  275. return true;
  276. }
  277. Box3F planeBox = getPlaneBox();
  278. polyList->addBox( planeBox, mMaterial );
  279. return true;
  280. }
  281. void GroundPlane::prepRenderImage( SceneRenderState* state )
  282. {
  283. PROFILE_SCOPE( GroundPlane_prepRenderImage );
  284. // TODO: Should we skip rendering the ground plane into
  285. // the shadows? Its not like you can ever get under it.
  286. if ( !mMaterial )
  287. return;
  288. // If we don't have a material instance after the override then
  289. // we can skip rendering all together.
  290. BaseMatInstance *matInst = state->getOverrideMaterial( mMaterial );
  291. if ( !matInst )
  292. return;
  293. PROFILE_SCOPE( GroundPlane_prepRender );
  294. // Update the geometry.
  295. createGeometry( state->getCullingFrustum() );
  296. if( mVertexBuffer.isNull() )
  297. return;
  298. #ifdef TORQUE_AFX_ENABLED
  299. afxZodiacMgr::renderGroundPlaneZodiacs(state, this);
  300. #endif
  301. // Add a render instance.
  302. RenderPassManager* pass = state->getRenderPass();
  303. MeshRenderInst* ri = pass->allocInst< MeshRenderInst >();
  304. ri->type = RenderPassManager::RIT_Mesh;
  305. ri->vertBuff = &mVertexBuffer;
  306. ri->primBuff = &mPrimitiveBuffer;
  307. ri->prim = &mPrimitive;
  308. ri->matInst = matInst;
  309. ri->objectToWorld = pass->allocUniqueXform( MatrixF::Identity );
  310. ri->worldToCamera = pass->allocSharedXform( RenderPassManager::View );
  311. ri->projection = pass->allocSharedXform( RenderPassManager::Projection );
  312. ri->visibility = 1.0f;
  313. ri->translucentSort = matInst->getMaterial()->isTranslucent();
  314. ri->defaultKey = matInst->getStateHint();
  315. if( ri->translucentSort )
  316. ri->type = RenderPassManager::RIT_Translucent;
  317. // If we need lights then set them up.
  318. if ( matInst->isForwardLit() )
  319. {
  320. LightQuery query;
  321. query.init( getWorldSphere() );
  322. query.getLights( ri->lights, 8 );
  323. }
  324. pass->addInst( ri );
  325. }
  326. /// Generate a subset of the ground plane matching the given frustum.
  327. void GroundPlane::createGeometry( const Frustum& frustum )
  328. {
  329. PROFILE_SCOPE( GroundPlane_createGeometry );
  330. enum { MAX_WIDTH = 256, MAX_HEIGHT = 256 };
  331. // Project the frustum onto the XY grid.
  332. Point2F min;
  333. Point2F max;
  334. projectFrustum( frustum, mSquareSize, min, max );
  335. // Early out if the grid projection hasn't changed.
  336. if( mVertexBuffer.isValid() &&
  337. min == mMin &&
  338. max == mMax )
  339. return;
  340. mMin = min;
  341. mMax = max;
  342. // Determine the grid extents and allocate the buffers.
  343. // Adjust square size permanently if with the given frustum,
  344. // we end up producing more than a certain limit of geometry.
  345. // This is to prevent this code from causing trouble with
  346. // long viewing distances.
  347. // This only affects the client object, of course, and thus
  348. // has no permanent effect.
  349. U32 width = mCeil( ( max.x - min.x ) / mSquareSize );
  350. if( width > MAX_WIDTH )
  351. {
  352. mSquareSize = mCeil( ( max.x - min.x ) / MAX_WIDTH );
  353. width = MAX_WIDTH;
  354. }
  355. else if( !width )
  356. width = 1;
  357. U32 height = mCeil( ( max.y - min.y ) / mSquareSize );
  358. if( height > MAX_HEIGHT )
  359. {
  360. mSquareSize = mCeil( ( max.y - min.y ) / MAX_HEIGHT );
  361. height = MAX_HEIGHT;
  362. }
  363. else if( !height )
  364. height = 1;
  365. const U32 numVertices = ( width + 1 ) * ( height + 1 );
  366. const U32 numTriangles = width * height * 2;
  367. // Only reallocate if the buffers are too small.
  368. if ( mVertexBuffer.isNull() || numVertices > mVertexBuffer->mNumVerts )
  369. {
  370. mVertexBuffer.set( GFX, numVertices, GFXBufferTypeDynamic );
  371. }
  372. if ( mPrimitiveBuffer.isNull() || numTriangles > mPrimitiveBuffer->mPrimitiveCount )
  373. {
  374. mPrimitiveBuffer.set( GFX, numTriangles*3, numTriangles, GFXBufferTypeDynamic );
  375. }
  376. // Generate the grid.
  377. generateGrid( width, height, mSquareSize, min, max, mVertexBuffer, mPrimitiveBuffer );
  378. // Set up GFX primitive.
  379. mPrimitive.type = GFXTriangleList;
  380. mPrimitive.numPrimitives = numTriangles;
  381. mPrimitive.numVertices = numVertices;
  382. }
  383. /// Project the given frustum onto the ground plane and return the XY bounds in world space.
  384. void GroundPlane::projectFrustum( const Frustum& frustum, F32 squareSize, Point2F& outMin, Point2F& outMax )
  385. {
  386. // Get the frustum's min and max XY coordinates.
  387. const Box3F bounds = frustum.getBounds();
  388. Point2F minPt( bounds.minExtents.x, bounds.minExtents.y );
  389. Point2F maxPt( bounds.maxExtents.x, bounds.maxExtents.y );
  390. // Round the min and max coordinates so they align on the grid.
  391. minPt.x -= mFmod( minPt.x, squareSize );
  392. minPt.y -= mFmod( minPt.y, squareSize );
  393. F32 maxDeltaX = mFmod( maxPt.x, squareSize );
  394. F32 maxDeltaY = mFmod( maxPt.y, squareSize );
  395. if( maxDeltaX != 0.0f )
  396. maxPt.x += ( squareSize - maxDeltaX );
  397. if( maxDeltaY != 0.0f )
  398. maxPt.y += ( squareSize - maxDeltaY );
  399. // Add a safezone, so we don't touch the clipping planes.
  400. minPt.x -= squareSize; minPt.y -= squareSize;
  401. maxPt.x += squareSize; maxPt.y += squareSize;
  402. outMin = minPt;
  403. outMax = maxPt;
  404. }
  405. /// Generate a triangulated grid spanning the given bounds into the given buffers.
  406. void GroundPlane::generateGrid( U32 width, U32 height, F32 squareSize,
  407. const Point2F& min, const Point2F& max,
  408. GFXVertexBufferHandle< VertexType >& outVertices,
  409. GFXPrimitiveBufferHandle& outPrimitives )
  410. {
  411. // Generate the vertices.
  412. VertexType* vertices = outVertices.lock();
  413. for( F32 y = min.y; y <= max.y; y += squareSize )
  414. for( F32 x = min.x; x <= max.x; x += squareSize )
  415. {
  416. vertices->point.x = x;
  417. vertices->point.y = y;
  418. vertices->point.z = 0.0;
  419. vertices->texCoord.x = ( x / squareSize ) * mScaleU;
  420. vertices->texCoord.y = ( y / squareSize ) * -mScaleV;
  421. vertices->normal.x = 0.0f;
  422. vertices->normal.y = 0.0f;
  423. vertices->normal.z = 1.0f;
  424. vertices->tangent.x = 1.0f;
  425. vertices->tangent.y = 0.0f;
  426. vertices->tangent.z = 0.0f;
  427. vertices->binormal.x = 0.0f;
  428. vertices->binormal.y = 1.0f;
  429. vertices->binormal.z = 0.0f;
  430. vertices++;
  431. }
  432. outVertices.unlock();
  433. // Generate the indices.
  434. U16* indices;
  435. outPrimitives.lock( &indices );
  436. U16 corner1 = 0;
  437. U16 corner2 = 1;
  438. U16 corner3 = width + 1;
  439. U16 corner4 = width + 2;
  440. for( U32 y = 0; y < height; ++ y )
  441. {
  442. for( U32 x = 0; x < width; ++ x )
  443. {
  444. indices[ 0 ] = corner3;
  445. indices[ 1 ] = corner2;
  446. indices[ 2 ] = corner1;
  447. indices += 3;
  448. indices[ 0 ] = corner3;
  449. indices[ 1 ] = corner4;
  450. indices[ 2 ] = corner2;
  451. indices += 3;
  452. corner1 ++;
  453. corner2 ++;
  454. corner3 ++;
  455. corner4 ++;
  456. }
  457. corner1 ++;
  458. corner2 ++;
  459. corner3 ++;
  460. corner4 ++;
  461. }
  462. outPrimitives.unlock();
  463. }
  464. DefineEngineMethod( GroundPlane, postApply, void, (),,
  465. "Intended as a helper to developers and editor scripts.\n"
  466. "Force trigger an inspectPostApply. This will transmit "
  467. "material and other fields to client objects."
  468. )
  469. {
  470. object->inspectPostApply();
  471. }