reflectionBlock.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import { NodeMaterialBlockConnectionPointTypes } from '../../Enums/nodeMaterialBlockConnectionPointTypes';
  2. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  3. import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointDirection } from '../../nodeMaterialBlockConnectionPoint';
  4. import { NodeMaterialBlockTargets } from '../../Enums/nodeMaterialBlockTargets';
  5. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  6. import { _TypeStore } from '../../../../Misc/typeStore';
  7. import { NodeMaterialConnectionPointCustomObject } from "../../nodeMaterialConnectionPointCustomObject";
  8. import { ReflectionTextureBaseBlock } from '../Dual/reflectionTextureBaseBlock';
  9. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  10. import { Nullable } from '../../../../types';
  11. import { Texture } from '../../../Textures/texture';
  12. import { BaseTexture } from '../../../Textures/baseTexture';
  13. import { Mesh } from '../../../../Meshes/mesh';
  14. import { SubMesh } from '../../../../Meshes/subMesh';
  15. import { Effect } from '../../../effect';
  16. import { editableInPropertyPage, PropertyTypeForEdition } from "../../nodeMaterialDecorator";
  17. import { Scene } from '../../../../scene';
  18. /**
  19. * Block used to implement the reflection module of the PBR material
  20. */
  21. export class ReflectionBlock extends ReflectionTextureBaseBlock {
  22. /** @hidden */
  23. public _defineLODReflectionAlpha: string;
  24. /** @hidden */
  25. public _defineLinearSpecularReflection: string;
  26. private _vEnvironmentIrradianceName: string;
  27. /** @hidden */
  28. public _vReflectionMicrosurfaceInfosName: string;
  29. /** @hidden */
  30. public _vReflectionInfosName: string;
  31. private _scene: Scene;
  32. /**
  33. * The three properties below are set by the main PBR block prior to calling methods of this class.
  34. * This is to avoid having to add them as inputs here whereas they are already inputs of the main block, so already known.
  35. * It's less burden on the user side in the editor part.
  36. */
  37. /** @hidden */
  38. public worldPositionConnectionPoint: NodeMaterialConnectionPoint;
  39. /** @hidden */
  40. public worldNormalConnectionPoint: NodeMaterialConnectionPoint;
  41. /** @hidden */
  42. public cameraPositionConnectionPoint: NodeMaterialConnectionPoint;
  43. /**
  44. * Defines if the material uses spherical harmonics vs spherical polynomials for the
  45. * diffuse part of the IBL.
  46. */
  47. @editableInPropertyPage("Spherical Harmonics", PropertyTypeForEdition.Boolean, "ADVANCED", { "notifiers": { "update": true }})
  48. public useSphericalHarmonics: boolean = true;
  49. /**
  50. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  51. */
  52. @editableInPropertyPage("Force irradiance in fragment", PropertyTypeForEdition.Boolean, "ADVANCED", { "notifiers": { "update": true }})
  53. public forceIrradianceInFragment: boolean = false;
  54. /**
  55. * Create a new ReflectionBlock
  56. * @param name defines the block name
  57. */
  58. public constructor(name: string) {
  59. super(name);
  60. this._isUnique = true;
  61. this.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Vertex);
  62. this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
  63. this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment);
  64. this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
  65. this.registerOutput("reflection", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment,
  66. new NodeMaterialConnectionPointCustomObject("reflection", this, NodeMaterialConnectionPointDirection.Output, ReflectionBlock, "ReflectionBlock"));
  67. }
  68. /**
  69. * Gets the current class name
  70. * @returns the class name
  71. */
  72. public getClassName() {
  73. return "ReflectionBlock";
  74. }
  75. /**
  76. * Gets the position input component
  77. */
  78. public get position(): NodeMaterialConnectionPoint {
  79. return this._inputs[0];
  80. }
  81. /**
  82. * Gets the world position input component
  83. */
  84. public get worldPosition(): NodeMaterialConnectionPoint {
  85. return this.worldPositionConnectionPoint;
  86. }
  87. /**
  88. * Gets the world normal input component
  89. */
  90. public get worldNormal(): NodeMaterialConnectionPoint {
  91. return this.worldNormalConnectionPoint;
  92. }
  93. /**
  94. * Gets the world input component
  95. */
  96. public get world(): NodeMaterialConnectionPoint {
  97. return this._inputs[1];
  98. }
  99. /**
  100. * Gets the camera (or eye) position component
  101. */
  102. public get cameraPosition(): NodeMaterialConnectionPoint {
  103. return this.cameraPositionConnectionPoint;
  104. }
  105. /**
  106. * Gets the view input component
  107. */
  108. public get view(): NodeMaterialConnectionPoint {
  109. return this._inputs[2];
  110. }
  111. /**
  112. * Gets the color input component
  113. */
  114. public get color(): NodeMaterialConnectionPoint {
  115. return this._inputs[3];
  116. }
  117. /**
  118. * Gets the reflection object output component
  119. */
  120. public get reflection(): NodeMaterialConnectionPoint {
  121. return this._outputs[0];
  122. }
  123. /**
  124. * Returns true if the block has a texture (either its own texture or the environment texture from the scene, if set)
  125. */
  126. public get hasTexture(): boolean {
  127. return !!this._getTexture();
  128. }
  129. /**
  130. * Gets the reflection color (either the name of the variable if the color input is connected, else a default value)
  131. */
  132. public get reflectionColor(): string {
  133. return this.color.isConnected ? this.color.associatedVariableName : "vec3(1., 1., 1.)";
  134. }
  135. protected _getTexture(): Nullable<BaseTexture> {
  136. if (this.texture) {
  137. return this.texture;
  138. }
  139. return this._scene.environmentTexture;
  140. }
  141. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  142. super.prepareDefines(mesh, nodeMaterial, defines);
  143. const reflectionTexture = this._getTexture();
  144. const reflection = reflectionTexture && reflectionTexture.getTextureMatrix;
  145. defines.setValue("REFLECTION", reflection, true);
  146. if (!reflection) {
  147. return;
  148. }
  149. defines.setValue(this._defineLODReflectionAlpha, reflectionTexture!.lodLevelInAlpha, true);
  150. defines.setValue(this._defineLinearSpecularReflection, reflectionTexture!.linearSpecularLOD, true);
  151. defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture!.invertZ : reflectionTexture!.invertZ, true);
  152. defines.setValue("SPHERICAL_HARMONICS", this.useSphericalHarmonics, true);
  153. defines.setValue("GAMMAREFLECTION", reflectionTexture!.gammaSpace, true);
  154. defines.setValue("RGBDREFLECTION", reflectionTexture!.isRGBD, true);
  155. if (reflectionTexture && reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {
  156. if (reflectionTexture.isCube) {
  157. defines.setValue("USESPHERICALFROMREFLECTIONMAP", true);
  158. defines.setValue("USEIRRADIANCEMAP", false);
  159. if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  160. defines.setValue("USESPHERICALINVERTEX", false);
  161. }
  162. else {
  163. defines.setValue("USESPHERICALINVERTEX", true);
  164. }
  165. }
  166. }
  167. }
  168. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh, subMesh?: SubMesh) {
  169. super.bind(effect, nodeMaterial, mesh);
  170. const reflectionTexture = this._getTexture();
  171. if (!reflectionTexture || !subMesh) {
  172. return;
  173. }
  174. if (reflectionTexture.isCube) {
  175. effect.setTexture(this._cubeSamplerName, reflectionTexture);
  176. } else {
  177. effect.setTexture(this._2DSamplerName, reflectionTexture);
  178. }
  179. effect.setFloat3(this._vReflectionMicrosurfaceInfosName, reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  180. const defines = subMesh._materialDefines as NodeMaterialDefines;
  181. const polynomials = reflectionTexture.sphericalPolynomial;
  182. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  183. if (defines.SPHERICAL_HARMONICS) {
  184. const preScaledHarmonics = polynomials.preScaledHarmonics;
  185. effect.setVector3("vSphericalL00", preScaledHarmonics.l00);
  186. effect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
  187. effect.setVector3("vSphericalL10", preScaledHarmonics.l10);
  188. effect.setVector3("vSphericalL11", preScaledHarmonics.l11);
  189. effect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
  190. effect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
  191. effect.setVector3("vSphericalL20", preScaledHarmonics.l20);
  192. effect.setVector3("vSphericalL21", preScaledHarmonics.l21);
  193. effect.setVector3("vSphericalL22", preScaledHarmonics.l22);
  194. }
  195. else {
  196. effect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  197. effect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  198. effect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  199. effect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x,
  200. polynomials.xx.y - polynomials.zz.y,
  201. polynomials.xx.z - polynomials.zz.z);
  202. effect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x,
  203. polynomials.yy.y - polynomials.zz.y,
  204. polynomials.yy.z - polynomials.zz.z);
  205. effect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  206. effect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  207. effect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  208. effect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  209. }
  210. }
  211. }
  212. /**
  213. * Gets the code to inject in the vertex shader
  214. * @param state current state of the node material building
  215. * @returns the shader code
  216. */
  217. public handleVertexSide(state: NodeMaterialBuildState): string {
  218. let code = super.handleVertexSide(state);
  219. state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, {
  220. replaceStrings: [
  221. { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" },
  222. { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" },
  223. ]
  224. });
  225. const reflectionVectorName = state._getFreeVariableName("reflectionVector");
  226. this._vEnvironmentIrradianceName = state._getFreeVariableName("vEnvironmentIrradiance");
  227. state._emitVaryingFromString(this._vEnvironmentIrradianceName, "vec3", "defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)");
  228. state._emitUniformFromString("vSphericalL00", "vec3", "SPHERICAL_HARMONICS");
  229. state._emitUniformFromString("vSphericalL1_1", "vec3", "SPHERICAL_HARMONICS");
  230. state._emitUniformFromString("vSphericalL10", "vec3", "SPHERICAL_HARMONICS");
  231. state._emitUniformFromString("vSphericalL11", "vec3", "SPHERICAL_HARMONICS");
  232. state._emitUniformFromString("vSphericalL2_2", "vec3", "SPHERICAL_HARMONICS");
  233. state._emitUniformFromString("vSphericalL2_1", "vec3", "SPHERICAL_HARMONICS");
  234. state._emitUniformFromString("vSphericalL20", "vec3", "SPHERICAL_HARMONICS");
  235. state._emitUniformFromString("vSphericalL21", "vec3", "SPHERICAL_HARMONICS");
  236. state._emitUniformFromString("vSphericalL22", "vec3", "SPHERICAL_HARMONICS");
  237. state._emitUniformFromString("vSphericalX", "vec3", "SPHERICAL_HARMONICS", true);
  238. state._emitUniformFromString("vSphericalY", "vec3", "SPHERICAL_HARMONICS", true);
  239. state._emitUniformFromString("vSphericalZ", "vec3", "SPHERICAL_HARMONICS", true);
  240. state._emitUniformFromString("vSphericalXX_ZZ", "vec3", "SPHERICAL_HARMONICS", true);
  241. state._emitUniformFromString("vSphericalYY_ZZ", "vec3", "SPHERICAL_HARMONICS", true);
  242. state._emitUniformFromString("vSphericalZZ", "vec3", "SPHERICAL_HARMONICS", true);
  243. state._emitUniformFromString("vSphericalXY", "vec3", "SPHERICAL_HARMONICS", true);
  244. state._emitUniformFromString("vSphericalYZ", "vec3", "SPHERICAL_HARMONICS", true);
  245. state._emitUniformFromString("vSphericalZX", "vec3", "SPHERICAL_HARMONICS", true);
  246. code +=
  247. `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
  248. vec3 ${reflectionVectorName} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz;
  249. #ifdef ${this._defineOppositeZ}
  250. ${reflectionVectorName}.z *= -1.0;
  251. #endif
  252. ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${reflectionVectorName});
  253. #endif\r\n`;
  254. return code;
  255. }
  256. /**
  257. * Gets the main code of the block (fragment side)
  258. * @param state current state of the node material building
  259. * @param normalVarName name of the existing variable corresponding to the normal
  260. * @returns the shader code
  261. */
  262. public getCode(state: NodeMaterialBuildState, normalVarName: string): string {
  263. let code = "";
  264. this.handleFragmentSideInits(state);
  265. state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, {
  266. replaceStrings: [
  267. { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" },
  268. { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" },
  269. ]
  270. });
  271. state._emitFunction("sampleReflection", `
  272. #ifdef ${this._define3DName}
  273. #define sampleReflection(s, c) textureCube(s, c)
  274. #else
  275. #define sampleReflection(s, c) texture2D(s, c)
  276. #endif\r\n`, `//${this.name}`);
  277. state._emitFunction("sampleReflectionLod", `
  278. #ifdef ${this._define3DName}
  279. #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)
  280. #else
  281. #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)
  282. #endif\r\n`, `//${this.name}`);
  283. const computeReflectionCoordsFunc = `
  284. vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {
  285. ${this.handleFragmentSideCodeReflectionCoords('worldNormal', 'worldPos', true)}
  286. return ${this._reflectionVectorName};
  287. }\r\n`;
  288. state._emitFunction("computeReflectionCoordsPBR", computeReflectionCoordsFunc, `//${this.name}`);
  289. this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName("vReflectionMicrosurfaceInfos");
  290. state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, "vec3");
  291. this._vReflectionInfosName = state._getFreeVariableName("vReflectionInfos");
  292. code += `#ifdef REFLECTION
  293. vec2 ${this._vReflectionInfosName} = vec2(1., 0.);
  294. reflectionOutParams reflectionOut;
  295. reflectionBlock(
  296. ${"v_" + this.worldPosition.associatedVariableName + ".xyz"},
  297. ${normalVarName},
  298. alphaG,
  299. ${this._vReflectionMicrosurfaceInfosName},
  300. ${this._vReflectionInfosName},
  301. ${this.reflectionColor},
  302. #ifdef ANISOTROPIC
  303. anisotropicOut,
  304. #endif
  305. #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})
  306. NdotVUnclamped,
  307. #endif
  308. #ifdef ${this._defineLinearSpecularReflection}
  309. roughness,
  310. #endif
  311. #ifdef ${this._define3DName}
  312. ${this._cubeSamplerName},
  313. #else
  314. ${this._2DSamplerName},
  315. #endif
  316. #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
  317. ${this._vEnvironmentIrradianceName},
  318. #endif
  319. #ifdef USESPHERICALFROMREFLECTIONMAP
  320. #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
  321. ${this._reflectionMatrixName},
  322. #endif
  323. #endif
  324. #ifdef USEIRRADIANCEMAP
  325. irradianceSampler, // ** not handled **
  326. #endif
  327. #ifndef LODBASEDMICROSFURACE
  328. #ifdef ${this._define3DName}
  329. ${this._cubeSamplerName},
  330. ${this._cubeSamplerName},
  331. #else
  332. ${this._2DSamplerName},
  333. ${this._2DSamplerName},
  334. #endif
  335. #endif
  336. reflectionOut
  337. );
  338. #endif\r\n`;
  339. return code;
  340. }
  341. protected _buildBlock(state: NodeMaterialBuildState) {
  342. this._scene = state.sharedData.scene;
  343. if (state.target !== NodeMaterialBlockTargets.Fragment) {
  344. this._defineLODReflectionAlpha = state._getFreeDefineName("LODINREFLECTIONALPHA");
  345. this._defineLinearSpecularReflection = state._getFreeDefineName("LINEARSPECULARREFLECTION");
  346. }
  347. return this;
  348. }
  349. protected _dumpPropertiesCode() {
  350. let codeString: string = super._dumpPropertiesCode();
  351. codeString += `${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\r\n`;
  352. codeString += `${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\r\n`;
  353. return codeString;
  354. }
  355. public serialize(): any {
  356. let serializationObject = super.serialize();
  357. serializationObject.useSphericalHarmonics = this.useSphericalHarmonics;
  358. serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment;
  359. return serializationObject;
  360. }
  361. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  362. super._deserialize(serializationObject, scene, rootUrl);
  363. this.useSphericalHarmonics = serializationObject.useSphericalHarmonics;
  364. this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment;
  365. }
  366. }
  367. _TypeStore.RegisteredTypes["BABYLON.ReflectionBlock"] = ReflectionBlock;