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