groundPlane.cpp 17 KB

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