geometryBufferRenderer.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import { Matrix } from "../Maths/math.vector";
  2. import { VertexBuffer } from "../Meshes/buffer";
  3. import { SubMesh } from "../Meshes/subMesh";
  4. import { Mesh } from "../Meshes/mesh";
  5. import { Constants } from "../Engines/constants";
  6. import { SmartArray } from "../Misc/smartArray";
  7. import { Texture } from "../Materials/Textures/texture";
  8. import { MultiRenderTarget } from "../Materials/Textures/multiRenderTarget";
  9. import { Effect } from "../Materials/effect";
  10. import { MaterialHelper } from "../Materials/materialHelper";
  11. import { Scene } from "../scene";
  12. import { AbstractMesh } from "../Meshes/abstractMesh";
  13. import { Color4 } from '../Maths/math.color';
  14. import { StandardMaterial } from '../Materials/standardMaterial';
  15. import { PBRMaterial } from '../Materials/PBR/pbrMaterial';
  16. import "../Shaders/geometry.fragment";
  17. import "../Shaders/geometry.vertex";
  18. import { _DevTools } from '../Misc/devTools';
  19. /** @hidden */
  20. interface ISavedTransformationMatrix {
  21. world: Matrix;
  22. viewProjection: Matrix;
  23. }
  24. /**
  25. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  26. */
  27. export class GeometryBufferRenderer {
  28. /**
  29. * Constant used to retrieve the position texture index in the G-Buffer textures array
  30. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  31. */
  32. public static readonly POSITION_TEXTURE_TYPE = 1;
  33. /**
  34. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  35. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  36. */
  37. public static readonly VELOCITY_TEXTURE_TYPE = 2;
  38. /**
  39. * Constant used to retrieve the reflectivity texture index in the G-Buffer textures array
  40. * using the getIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE)
  41. */
  42. public static readonly REFLECTIVITY_TEXTURE_TYPE = 3;
  43. /**
  44. * Dictionary used to store the previous transformation matrices of each rendered mesh
  45. * in order to compute objects velocities when enableVelocity is set to "true"
  46. * @hidden
  47. */
  48. public _previousTransformationMatrices: { [index: number]: ISavedTransformationMatrix } = {};
  49. /**
  50. * Dictionary used to store the previous bones transformation matrices of each rendered mesh
  51. * in order to compute objects velocities when enableVelocity is set to "true"
  52. * @hidden
  53. */
  54. public _previousBonesTransformationMatrices: { [index: number]: Float32Array } = {};
  55. /**
  56. * Array used to store the ignored skinned meshes while computing velocity map (typically used by the motion blur post-process).
  57. * Avoids computing bones velocities and computes only mesh's velocity itself (position, rotation, scaling).
  58. */
  59. public excludedSkinnedMeshesFromVelocity: AbstractMesh[] = [];
  60. /** Gets or sets a boolean indicating if transparent meshes should be rendered */
  61. public renderTransparentMeshes = true;
  62. private _scene: Scene;
  63. private _multiRenderTarget: MultiRenderTarget;
  64. private _ratio: number;
  65. private _enablePosition: boolean = false;
  66. private _enableVelocity: boolean = false;
  67. private _enableReflectivity: boolean = false;
  68. private _positionIndex: number = -1;
  69. private _velocityIndex: number = -1;
  70. private _reflectivityIndex: number = -1;
  71. protected _effect: Effect;
  72. protected _cachedDefines: string;
  73. /**
  74. * Set the render list (meshes to be rendered) used in the G buffer.
  75. */
  76. public set renderList(meshes: Mesh[]) {
  77. this._multiRenderTarget.renderList = meshes;
  78. }
  79. /**
  80. * Gets wether or not G buffer are supported by the running hardware.
  81. * This requires draw buffer supports
  82. */
  83. public get isSupported(): boolean {
  84. return this._multiRenderTarget.isSupported;
  85. }
  86. /**
  87. * Returns the index of the given texture type in the G-Buffer textures array
  88. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  89. * @returns the index of the given texture type in the G-Buffer textures array
  90. */
  91. public getTextureIndex(textureType: number): number {
  92. switch (textureType) {
  93. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  94. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  95. case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE: return this._reflectivityIndex;
  96. default: return -1;
  97. }
  98. }
  99. /**
  100. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  101. */
  102. public get enablePosition(): boolean {
  103. return this._enablePosition;
  104. }
  105. /**
  106. * Sets whether or not objects positions are enabled for the G buffer.
  107. */
  108. public set enablePosition(enable: boolean) {
  109. this._enablePosition = enable;
  110. this.dispose();
  111. this._createRenderTargets();
  112. }
  113. /**
  114. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  115. */
  116. public get enableVelocity(): boolean {
  117. return this._enableVelocity;
  118. }
  119. /**
  120. * Sets wether or not objects velocities are enabled for the G buffer.
  121. */
  122. public set enableVelocity(enable: boolean) {
  123. this._enableVelocity = enable;
  124. if (!enable) {
  125. this._previousTransformationMatrices = {};
  126. }
  127. this.dispose();
  128. this._createRenderTargets();
  129. }
  130. /**
  131. * Gets a boolean indicating if objects roughness are enabled in the G buffer.
  132. */
  133. public get enableReflectivity(): boolean {
  134. return this._enableReflectivity;
  135. }
  136. /**
  137. * Sets wether or not objects roughness are enabled for the G buffer.
  138. */
  139. public set enableReflectivity(enable: boolean) {
  140. this._enableReflectivity = enable;
  141. this.dispose();
  142. this._createRenderTargets();
  143. }
  144. /**
  145. * Gets the scene associated with the buffer.
  146. */
  147. public get scene(): Scene {
  148. return this._scene;
  149. }
  150. /**
  151. * Gets the ratio used by the buffer during its creation.
  152. * How big is the buffer related to the main canvas.
  153. */
  154. public get ratio(): number {
  155. return this._ratio;
  156. }
  157. /** @hidden */
  158. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  159. throw _DevTools.WarnImport("GeometryBufferRendererSceneComponent");
  160. }
  161. /**
  162. * Creates a new G Buffer for the scene
  163. * @param scene The scene the buffer belongs to
  164. * @param ratio How big is the buffer related to the main canvas.
  165. */
  166. constructor(scene: Scene, ratio: number = 1) {
  167. this._scene = scene;
  168. this._ratio = ratio;
  169. GeometryBufferRenderer._SceneComponentInitialization(this._scene);
  170. // Render target
  171. this._createRenderTargets();
  172. }
  173. /**
  174. * Checks wether everything is ready to render a submesh to the G buffer.
  175. * @param subMesh the submesh to check readiness for
  176. * @param useInstances is the mesh drawn using instance or not
  177. * @returns true if ready otherwise false
  178. */
  179. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  180. var material = <any> subMesh.getMaterial();
  181. if (material && material.disableDepthWrite) {
  182. return false;
  183. }
  184. var defines = [];
  185. var attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
  186. var mesh = subMesh.getMesh();
  187. // Alpha test
  188. if (material) {
  189. let needUv = false;
  190. if (material.needAlphaTesting()) {
  191. defines.push("#define ALPHATEST");
  192. needUv = true;
  193. }
  194. if (material.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  195. defines.push("#define BUMP");
  196. needUv = true;
  197. }
  198. if (this._enableReflectivity) {
  199. if (material instanceof StandardMaterial && material.specularTexture) {
  200. defines.push("#define HAS_SPECULAR");
  201. needUv = true;
  202. } else if (material instanceof PBRMaterial && material.reflectivityTexture) {
  203. defines.push("#define HAS_REFLECTIVITY");
  204. needUv = true;
  205. }
  206. }
  207. if (needUv) {
  208. defines.push("#define NEED_UV");
  209. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  210. attribs.push(VertexBuffer.UVKind);
  211. defines.push("#define UV1");
  212. }
  213. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  214. attribs.push(VertexBuffer.UV2Kind);
  215. defines.push("#define UV2");
  216. }
  217. }
  218. }
  219. // Buffers
  220. if (this._enablePosition) {
  221. defines.push("#define POSITION");
  222. defines.push("#define POSITION_INDEX " + this._positionIndex);
  223. }
  224. if (this._enableVelocity) {
  225. defines.push("#define VELOCITY");
  226. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  227. if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) {
  228. defines.push("#define BONES_VELOCITY_ENABLED");
  229. }
  230. }
  231. if (this._enableReflectivity) {
  232. defines.push("#define REFLECTIVITY");
  233. defines.push("#define REFLECTIVITY_INDEX " + this._reflectivityIndex);
  234. }
  235. // Bones
  236. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  237. attribs.push(VertexBuffer.MatricesIndicesKind);
  238. attribs.push(VertexBuffer.MatricesWeightsKind);
  239. if (mesh.numBoneInfluencers > 4) {
  240. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  241. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  242. }
  243. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  244. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  245. } else {
  246. defines.push("#define NUM_BONE_INFLUENCERS 0");
  247. }
  248. // Morph targets
  249. const morphTargetManager = (mesh as Mesh).morphTargetManager;
  250. let numMorphInfluencers = 0;
  251. if (morphTargetManager) {
  252. if (morphTargetManager.numInfluencers > 0) {
  253. numMorphInfluencers = morphTargetManager.numInfluencers;
  254. defines.push("#define MORPHTARGETS");
  255. defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers);
  256. MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);
  257. }
  258. }
  259. // Instances
  260. if (useInstances) {
  261. defines.push("#define INSTANCES");
  262. MaterialHelper.PushAttributesForInstances(attribs);
  263. if (subMesh.getRenderingMesh().hasInstances) {
  264. defines.push("#define THIN_INSTANCES");
  265. }
  266. }
  267. // Setup textures count
  268. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  269. // Get correct effect
  270. var join = defines.join("\n");
  271. if (this._cachedDefines !== join) {
  272. this._cachedDefines = join;
  273. this._effect = this._scene.getEngine().createEffect("geometry",
  274. attribs,
  275. [
  276. "world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorld", "previousViewProjection", "mPreviousBones",
  277. "morphTargetInfluences", "bumpMatrix", "reflectivityMatrix", "vTangentSpaceParams", "vBumpInfos"
  278. ],
  279. ["diffuseSampler", "bumpSampler", "reflectivitySampler"], join,
  280. undefined, undefined, undefined,
  281. { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers });
  282. }
  283. return this._effect.isReady();
  284. }
  285. /**
  286. * Gets the current underlying G Buffer.
  287. * @returns the buffer
  288. */
  289. public getGBuffer(): MultiRenderTarget {
  290. return this._multiRenderTarget;
  291. }
  292. /**
  293. * Gets the number of samples used to render the buffer (anti aliasing).
  294. */
  295. public get samples(): number {
  296. return this._multiRenderTarget.samples;
  297. }
  298. /**
  299. * Sets the number of samples used to render the buffer (anti aliasing).
  300. */
  301. public set samples(value: number) {
  302. this._multiRenderTarget.samples = value;
  303. }
  304. /**
  305. * Disposes the renderer and frees up associated resources.
  306. */
  307. public dispose(): void {
  308. this.getGBuffer().dispose();
  309. }
  310. protected _createRenderTargets(): void {
  311. var engine = this._scene.getEngine();
  312. var count = 2;
  313. if (this._enablePosition) {
  314. this._positionIndex = count;
  315. count++;
  316. }
  317. if (this._enableVelocity) {
  318. this._velocityIndex = count;
  319. count++;
  320. }
  321. if (this._enableReflectivity) {
  322. this._reflectivityIndex = count;
  323. count++;
  324. }
  325. this._multiRenderTarget = new MultiRenderTarget("gBuffer",
  326. { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene,
  327. { generateMipMaps: false, generateDepthTexture: true, defaultType: Constants.TEXTURETYPE_FLOAT });
  328. if (!this.isSupported) {
  329. return;
  330. }
  331. this._multiRenderTarget.wrapU = Texture.CLAMP_ADDRESSMODE;
  332. this._multiRenderTarget.wrapV = Texture.CLAMP_ADDRESSMODE;
  333. this._multiRenderTarget.refreshRate = 1;
  334. this._multiRenderTarget.renderParticles = false;
  335. this._multiRenderTarget.renderList = null;
  336. // set default depth value to 1.0 (far away)
  337. this._multiRenderTarget.onClearObservable.add((engine) => {
  338. engine.clear(new Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  339. });
  340. // Custom render function
  341. var renderSubMesh = (subMesh: SubMesh): void => {
  342. var renderingMesh = subMesh.getRenderingMesh();
  343. var effectiveMesh = subMesh.getEffectiveMesh();
  344. var scene = this._scene;
  345. var engine = scene.getEngine();
  346. let material = <any> subMesh.getMaterial();
  347. if (!material) {
  348. return;
  349. }
  350. effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
  351. // Velocity
  352. if (this._enableVelocity && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) {
  353. this._previousTransformationMatrices[effectiveMesh.uniqueId] = {
  354. world: Matrix.Identity(),
  355. viewProjection: scene.getTransformMatrix()
  356. };
  357. if (renderingMesh.skeleton) {
  358. const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh);
  359. this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length));
  360. }
  361. }
  362. // Culling
  363. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  364. // Managing instances
  365. var batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
  366. if (batch.mustReturn) {
  367. return;
  368. }
  369. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);
  370. var world = effectiveMesh.getWorldMatrix();
  371. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  372. engine.enableEffect(this._effect);
  373. renderingMesh._bind(subMesh, this._effect, material.fillMode);
  374. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  375. this._effect.setMatrix("view", scene.getViewMatrix());
  376. if (material) {
  377. // Alpha test
  378. if (material.needAlphaTesting()) {
  379. var alphaTexture = material.getAlphaTestTexture();
  380. if (alphaTexture) {
  381. this._effect.setTexture("diffuseSampler", alphaTexture);
  382. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  383. }
  384. }
  385. // Bump
  386. if (material.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  387. this._effect.setFloat3("vBumpInfos", material.bumpTexture.coordinatesIndex, 1.0 / material.bumpTexture.level, material.parallaxScaleBias);
  388. this._effect.setMatrix("bumpMatrix", material.bumpTexture.getTextureMatrix());
  389. this._effect.setTexture("bumpSampler", material.bumpTexture);
  390. this._effect.setFloat2("vTangentSpaceParams", material.invertNormalMapX ? -1.0 : 1.0, material.invertNormalMapY ? -1.0 : 1.0);
  391. }
  392. // Roughness
  393. if (this._enableReflectivity) {
  394. if (material instanceof StandardMaterial && material.specularTexture) {
  395. this._effect.setMatrix("reflectivityMatrix", material.specularTexture.getTextureMatrix());
  396. this._effect.setTexture("reflectivitySampler", material.specularTexture);
  397. } else if (material instanceof PBRMaterial && material.reflectivityTexture) {
  398. this._effect.setMatrix("reflectivityMatrix", material.reflectivityTexture.getTextureMatrix());
  399. this._effect.setTexture("reflectivitySampler", material.reflectivityTexture);
  400. }
  401. }
  402. }
  403. // Bones
  404. if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
  405. this._effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh));
  406. if (this._enableVelocity) {
  407. this._effect.setMatrices("mPreviousBones", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]);
  408. }
  409. }
  410. // Morph targets
  411. MaterialHelper.BindMorphTargetParameters(renderingMesh, this._effect);
  412. // Velocity
  413. if (this._enableVelocity) {
  414. this._effect.setMatrix("previousWorld", this._previousTransformationMatrices[effectiveMesh.uniqueId].world);
  415. this._effect.setMatrix("previousViewProjection", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection);
  416. }
  417. // Draw
  418. renderingMesh._processRendering(effectiveMesh, subMesh, this._effect, material.fillMode, batch, hardwareInstancedRendering,
  419. (isInstance, w) => this._effect.setMatrix("world", w));
  420. }
  421. // Velocity
  422. if (this._enableVelocity) {
  423. this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone();
  424. this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone();
  425. if (renderingMesh.skeleton) {
  426. this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]);
  427. }
  428. }
  429. };
  430. this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  431. var index;
  432. if (depthOnlySubMeshes.length) {
  433. engine.setColorWrite(false);
  434. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  435. renderSubMesh(depthOnlySubMeshes.data[index]);
  436. }
  437. engine.setColorWrite(true);
  438. }
  439. for (index = 0; index < opaqueSubMeshes.length; index++) {
  440. renderSubMesh(opaqueSubMeshes.data[index]);
  441. }
  442. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  443. renderSubMesh(alphaTestSubMeshes.data[index]);
  444. }
  445. if (this.renderTransparentMeshes) {
  446. for (index = 0; index < transparentSubMeshes.length; index++) {
  447. renderSubMesh(transparentSubMeshes.data[index]);
  448. }
  449. }
  450. };
  451. }
  452. // Copies the bones transformation matrices into the target array and returns the target's reference
  453. private _copyBonesTransformationMatrices(source: Float32Array, target: Float32Array): Float32Array {
  454. for (let i = 0; i < source.length; i++) {
  455. target[i] = source[i];
  456. }
  457. return target;
  458. }
  459. }