geometryBufferRenderer.ts 22 KB

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