reflectionBlock.ts 19 KB

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