renderMeshExample.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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/examples/renderMeshExample.h"
  24. #include "math/mathIO.h"
  25. #include "scene/sceneRenderState.h"
  26. #include "console/consoleTypes.h"
  27. #include "core/stream/bitStream.h"
  28. #include "materials/materialManager.h"
  29. #include "materials/baseMatInstance.h"
  30. #include "renderInstance/renderPassManager.h"
  31. #include "lighting/lightQuery.h"
  32. #include "console/engineAPI.h"
  33. IMPLEMENT_CO_NETOBJECT_V1(RenderMeshExample);
  34. ConsoleDocClass( RenderMeshExample,
  35. "@brief An example scene object which renders a mesh.\n\n"
  36. "This class implements a basic SceneObject that can exist in the world at a "
  37. "3D position and render itself. There are several valid ways to render an "
  38. "object in Torque. This class implements the preferred rendering method which "
  39. "is to submit a MeshRenderInst along with a Material, vertex buffer, "
  40. "primitive buffer, and transform and allow the RenderMeshMgr handle the "
  41. "actual setup and rendering for you.\n\n"
  42. "See the C++ code for implementation details.\n\n"
  43. "@ingroup Examples\n" );
  44. //-----------------------------------------------------------------------------
  45. // Object setup and teardown
  46. //-----------------------------------------------------------------------------
  47. RenderMeshExample::RenderMeshExample()
  48. {
  49. // Flag this object so that it will always
  50. // be sent across the network to clients
  51. mNetFlags.set( Ghostable | ScopeAlways );
  52. // Set it as a "static" object that casts shadows
  53. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  54. INIT_ASSET(Material);
  55. }
  56. RenderMeshExample::~RenderMeshExample()
  57. {
  58. if ( mMaterialInst )
  59. SAFE_DELETE( mMaterialInst );
  60. }
  61. //-----------------------------------------------------------------------------
  62. // Object Editing
  63. //-----------------------------------------------------------------------------
  64. void RenderMeshExample::initPersistFields()
  65. {
  66. addGroup( "Rendering" );
  67. INITPERSISTFIELD_MATERIALASSET(Material, RenderMeshExample, "The material used to render the mesh.");
  68. endGroup( "Rendering" );
  69. // SceneObject already handles exposing the transform
  70. Parent::initPersistFields();
  71. }
  72. void RenderMeshExample::inspectPostApply()
  73. {
  74. Parent::inspectPostApply();
  75. // Flag the network mask to send the updates
  76. // to the client object
  77. setMaskBits( UpdateMask );
  78. }
  79. bool RenderMeshExample::onAdd()
  80. {
  81. if ( !Parent::onAdd() )
  82. return false;
  83. // Set up a 1x1x1 bounding box
  84. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ),
  85. Point3F( 0.5f, 0.5f, 0.5f ) );
  86. resetWorldBox();
  87. // Add this object to the scene
  88. addToScene();
  89. // Refresh this object's material (if any)
  90. updateMaterial();
  91. return true;
  92. }
  93. void RenderMeshExample::onRemove()
  94. {
  95. // Remove this object from the scene
  96. removeFromScene();
  97. Parent::onRemove();
  98. }
  99. void RenderMeshExample::setTransform(const MatrixF & mat)
  100. {
  101. // Let SceneObject handle all of the matrix manipulation
  102. Parent::setTransform( mat );
  103. // Dirty our network mask so that the new transform gets
  104. // transmitted to the client object
  105. setMaskBits( TransformMask );
  106. }
  107. U32 RenderMeshExample::packUpdate( NetConnection *conn, U32 mask, BitStream *stream )
  108. {
  109. // Allow the Parent to get a crack at writing its info
  110. U32 retMask = Parent::packUpdate( conn, mask, stream );
  111. // Write our transform information
  112. if ( stream->writeFlag( mask & TransformMask ) )
  113. {
  114. mathWrite(*stream, getTransform());
  115. mathWrite(*stream, getScale());
  116. }
  117. // Write out any of the updated editable properties
  118. if (stream->writeFlag(mask & UpdateMask))
  119. {
  120. PACK_ASSET(conn, Material);
  121. }
  122. return retMask;
  123. }
  124. void RenderMeshExample::unpackUpdate(NetConnection *conn, BitStream *stream)
  125. {
  126. // Let the Parent read any info it sent
  127. Parent::unpackUpdate(conn, stream);
  128. if ( stream->readFlag() ) // TransformMask
  129. {
  130. mathRead(*stream, &mObjToWorld);
  131. mathRead(*stream, &mObjScale);
  132. setTransform( mObjToWorld );
  133. }
  134. if ( stream->readFlag() ) // UpdateMask
  135. {
  136. UNPACK_ASSET(conn, Material);
  137. if ( isProperlyAdded() )
  138. updateMaterial();
  139. }
  140. }
  141. //-----------------------------------------------------------------------------
  142. // Object Rendering
  143. //-----------------------------------------------------------------------------
  144. void RenderMeshExample::createGeometry()
  145. {
  146. static const Point3F cubePoints[8] =
  147. {
  148. Point3F( 1, -1, -1), Point3F( 1, -1, 1), Point3F( 1, 1, -1), Point3F( 1, 1, 1),
  149. Point3F(-1, -1, -1), Point3F(-1, 1, -1), Point3F(-1, -1, 1), Point3F(-1, 1, 1)
  150. };
  151. static const Point3F cubeNormals[6] =
  152. {
  153. Point3F( 1, 0, 0), Point3F(-1, 0, 0), Point3F( 0, 1, 0),
  154. Point3F( 0, -1, 0), Point3F( 0, 0, 1), Point3F( 0, 0, -1)
  155. };
  156. static const Point2F cubeTexCoords[4] =
  157. {
  158. Point2F( 0, 0), Point2F( 0, -1),
  159. Point2F( 1, 0), Point2F( 1, -1)
  160. };
  161. static const U32 cubeFaces[36][3] =
  162. {
  163. { 3, 0, 3 }, { 0, 0, 0 }, { 1, 0, 1 },
  164. { 2, 0, 2 }, { 0, 0, 0 }, { 3, 0, 3 },
  165. { 7, 1, 1 }, { 4, 1, 2 }, { 5, 1, 0 },
  166. { 6, 1, 3 }, { 4, 1, 2 }, { 7, 1, 1 },
  167. { 3, 2, 1 }, { 5, 2, 2 }, { 2, 2, 0 },
  168. { 7, 2, 3 }, { 5, 2, 2 }, { 3, 2, 1 },
  169. { 1, 3, 3 }, { 4, 3, 0 }, { 6, 3, 1 },
  170. { 0, 3, 2 }, { 4, 3, 0 }, { 1, 3, 3 },
  171. { 3, 4, 3 }, { 6, 4, 0 }, { 7, 4, 1 },
  172. { 1, 4, 2 }, { 6, 4, 0 }, { 3, 4, 3 },
  173. { 2, 5, 1 }, { 4, 5, 2 }, { 0, 5, 0 },
  174. { 5, 5, 3 }, { 4, 5, 2 }, { 2, 5, 1 }
  175. };
  176. // Fill the vertex buffer
  177. VertexType *pVert = NULL;
  178. mVertexBuffer.set( GFX, 36, GFXBufferTypeStatic );
  179. pVert = mVertexBuffer.lock();
  180. Point3F halfSize = getObjBox().getExtents() * 0.5f;
  181. for (U32 i = 0; i < 36; i++)
  182. {
  183. const U32& vdx = cubeFaces[i][0];
  184. const U32& ndx = cubeFaces[i][1];
  185. const U32& tdx = cubeFaces[i][2];
  186. pVert[i].point = cubePoints[vdx] * halfSize;
  187. pVert[i].normal = cubeNormals[ndx];
  188. pVert[i].texCoord = cubeTexCoords[tdx];
  189. }
  190. mVertexBuffer.unlock();
  191. // Fill the primitive buffer
  192. U16 *pIdx = NULL;
  193. mPrimitiveBuffer.set( GFX, 36, 12, GFXBufferTypeStatic );
  194. mPrimitiveBuffer.lock(&pIdx);
  195. for (U16 i = 0; i < 36; i++)
  196. pIdx[i] = i;
  197. mPrimitiveBuffer.unlock();
  198. }
  199. void RenderMeshExample::updateMaterial()
  200. {
  201. if (mMaterialAsset.notNull())
  202. {
  203. if (mMaterialInst && String(mMaterialAsset->getMaterialDefinitionName()).equal(mMaterialInst->getMaterial()->getName(), String::NoCase))
  204. return;
  205. SAFE_DELETE(mMaterialInst);
  206. mMaterialInst = MATMGR->createMatInstance(mMaterialAsset->getMaterialDefinitionName(), getGFXVertexFormat< VertexType >());
  207. if (!mMaterialInst)
  208. Con::errorf("RenderMeshExample::updateMaterial - no Material called '%s'", mMaterialAsset->getMaterialDefinitionName());
  209. }
  210. }
  211. void RenderMeshExample::prepRenderImage( SceneRenderState *state )
  212. {
  213. // Do a little prep work if needed
  214. if ( mVertexBuffer.isNull() )
  215. createGeometry();
  216. // If we have no material then skip out.
  217. if ( !mMaterialInst || !state)
  218. return;
  219. // If we don't have a material instance after the override then
  220. // we can skip rendering all together.
  221. BaseMatInstance *matInst = state->getOverrideMaterial( mMaterialInst );
  222. if ( !matInst )
  223. return;
  224. // Get a handy pointer to our RenderPassmanager
  225. RenderPassManager *renderPass = state->getRenderPass();
  226. // Allocate an MeshRenderInst so that we can submit it to the RenderPassManager
  227. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  228. // Set our RenderInst as a standard mesh render
  229. ri->type = RenderPassManager::RIT_Mesh;
  230. //If our material has transparency set on this will redirect it to proper render bin
  231. if ( matInst->getMaterial()->isTranslucent() )
  232. {
  233. ri->type = RenderPassManager::RIT_Translucent;
  234. ri->translucentSort = true;
  235. }
  236. // Calculate our sorting point
  237. if ( state )
  238. {
  239. // Calculate our sort point manually.
  240. const Box3F& rBox = getRenderWorldBox();
  241. ri->sortDistSq = rBox.getSqDistanceToPoint( state->getCameraPosition() );
  242. }
  243. else
  244. ri->sortDistSq = 0.0f;
  245. // Set up our transforms
  246. MatrixF objectToWorld = getRenderTransform();
  247. objectToWorld.scale( getScale() );
  248. ri->objectToWorld = renderPass->allocUniqueXform( objectToWorld );
  249. ri->worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  250. ri->projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  251. // If our material needs lights then fill the RIs
  252. // light vector with the best lights.
  253. if ( matInst->isForwardLit() )
  254. {
  255. LightQuery query;
  256. query.init( getWorldSphere() );
  257. query.getLights( ri->lights, 8 );
  258. }
  259. // Make sure we have an up-to-date backbuffer in case
  260. // our Material would like to make use of it
  261. // NOTICE: SFXBB is removed and refraction is disabled!
  262. //ri->backBuffTex = GFX->getSfxBackBuffer();
  263. // Set our Material
  264. ri->matInst = matInst;
  265. // Set up our vertex buffer and primitive buffer
  266. ri->vertBuff = &mVertexBuffer;
  267. ri->primBuff = &mPrimitiveBuffer;
  268. ri->prim = renderPass->allocPrim();
  269. ri->prim->type = GFXTriangleList;
  270. ri->prim->minIndex = 0;
  271. ri->prim->startIndex = 0;
  272. ri->prim->numPrimitives = 12;
  273. ri->prim->startVertex = 0;
  274. ri->prim->numVertices = 36;
  275. // We sort by the material then vertex buffer
  276. ri->defaultKey = matInst->getStateHint();
  277. ri->defaultKey2 = (uintptr_t)ri->vertBuff; // Not 64bit safe!
  278. // Submit our RenderInst to the RenderPassManager
  279. state->getRenderPass()->addInst( ri );
  280. }
  281. DefineEngineMethod( RenderMeshExample, postApply, void, (),,
  282. "A utility method for forcing a network update.\n")
  283. {
  284. object->inspectPostApply();
  285. }