reflectionTextureBaseBlock.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { NodeMaterialBlock } from '../../nodeMaterialBlock';
  2. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  3. import { NodeMaterialBlockTargets } from '../../Enums/nodeMaterialBlockTargets';
  4. import { NodeMaterialConnectionPoint } from '../../nodeMaterialBlockConnectionPoint';
  5. import { BaseTexture } from '../../../Textures/baseTexture';
  6. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  7. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  8. import { Effect } from '../../../effect';
  9. import { Mesh } from '../../../../Meshes/mesh';
  10. import { Nullable } from '../../../../types';
  11. import { _TypeStore } from '../../../../Misc/typeStore';
  12. import { Scene } from '../../../../scene';
  13. import { InputBlock } from '../Input/inputBlock';
  14. import { NodeMaterialSystemValues } from '../../Enums/nodeMaterialSystemValues';
  15. import { Constants } from '../../../../Engines/constants';
  16. import "../../../../Shaders/ShadersInclude/reflectionFunction";
  17. import { CubeTexture } from '../../../Textures/cubeTexture';
  18. import { Texture } from '../../../Textures/texture';
  19. /**
  20. * Base block used to read a reflection texture from a sampler
  21. */
  22. export abstract class ReflectionTextureBaseBlock extends NodeMaterialBlock {
  23. /** @hidden */
  24. public _define3DName: string;
  25. /** @hidden */
  26. public _defineCubicName: string;
  27. /** @hidden */
  28. public _defineExplicitName: string;
  29. /** @hidden */
  30. public _defineProjectionName: string;
  31. /** @hidden */
  32. public _defineLocalCubicName: string;
  33. /** @hidden */
  34. public _defineSphericalName: string;
  35. /** @hidden */
  36. public _definePlanarName: string;
  37. /** @hidden */
  38. public _defineEquirectangularName: string;
  39. /** @hidden */
  40. public _defineMirroredEquirectangularFixedName: string;
  41. /** @hidden */
  42. public _defineEquirectangularFixedName: string;
  43. /** @hidden */
  44. public _defineSkyboxName: string;
  45. /** @hidden */
  46. public _defineOppositeZ: string;
  47. /** @hidden */
  48. public _cubeSamplerName: string;
  49. /** @hidden */
  50. public _2DSamplerName: string;
  51. protected _positionUVWName: string;
  52. protected _directionWName: string;
  53. protected _reflectionVectorName: string;
  54. /** @hidden */
  55. public _reflectionCoordsName: string;
  56. /** @hidden */
  57. public _reflectionMatrixName: string;
  58. protected _reflectionColorName: string;
  59. /**
  60. * Gets or sets the texture associated with the node
  61. */
  62. public texture: Nullable<BaseTexture>;
  63. /**
  64. * Create a new ReflectionTextureBaseBlock
  65. * @param name defines the block name
  66. */
  67. public constructor(name: string) {
  68. super(name, NodeMaterialBlockTargets.VertexAndFragment);
  69. }
  70. /**
  71. * Gets the current class name
  72. * @returns the class name
  73. */
  74. public getClassName() {
  75. return "ReflectionTextureBaseBlock";
  76. }
  77. /**
  78. * Gets the world position input component
  79. */
  80. public abstract get position(): NodeMaterialConnectionPoint;
  81. /**
  82. * Gets the world position input component
  83. */
  84. public abstract get worldPosition(): NodeMaterialConnectionPoint;
  85. /**
  86. * Gets the world normal input component
  87. */
  88. public abstract get worldNormal(): NodeMaterialConnectionPoint;
  89. /**
  90. * Gets the world input component
  91. */
  92. public abstract get world(): NodeMaterialConnectionPoint;
  93. /**
  94. * Gets the camera (or eye) position component
  95. */
  96. public abstract get cameraPosition(): NodeMaterialConnectionPoint;
  97. /**
  98. * Gets the view input component
  99. */
  100. public abstract get view(): NodeMaterialConnectionPoint;
  101. protected _getTexture(): Nullable<BaseTexture> {
  102. return this.texture;
  103. }
  104. public autoConfigure(material: NodeMaterial) {
  105. if (!this.position.isConnected) {
  106. let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position");
  107. if (!positionInput) {
  108. positionInput = new InputBlock("position");
  109. positionInput.setAsAttribute();
  110. }
  111. positionInput.output.connectTo(this.position);
  112. }
  113. if (!this.world.isConnected) {
  114. let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World);
  115. if (!worldInput) {
  116. worldInput = new InputBlock("world");
  117. worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
  118. }
  119. worldInput.output.connectTo(this.world);
  120. }
  121. if (this.view && !this.view.isConnected) {
  122. let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);
  123. if (!viewInput) {
  124. viewInput = new InputBlock("view");
  125. viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
  126. }
  127. viewInput.output.connectTo(this.view);
  128. }
  129. }
  130. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  131. if (!defines._areTexturesDirty) {
  132. return;
  133. }
  134. const texture = this._getTexture();
  135. if (!texture || !texture.getTextureMatrix) {
  136. return;
  137. }
  138. defines.setValue(this._define3DName, texture.isCube, true);
  139. defines.setValue(this._defineLocalCubicName, (<any>texture).boundingBoxSize ? true : false, true);
  140. defines.setValue(this._defineExplicitName, texture.coordinatesMode === Constants.TEXTURE_EXPLICIT_MODE, true);
  141. defines.setValue(this._defineSkyboxName, texture.coordinatesMode === Constants.TEXTURE_SKYBOX_MODE, true);
  142. defines.setValue(this._defineCubicName, texture.coordinatesMode === Constants.TEXTURE_CUBIC_MODE || texture.coordinatesMode === Constants.TEXTURE_INVCUBIC_MODE, true);
  143. defines.setValue("INVERTCUBICMAP", texture.coordinatesMode === Constants.TEXTURE_INVCUBIC_MODE, true);
  144. defines.setValue(this._defineSphericalName, texture.coordinatesMode === Constants.TEXTURE_SPHERICAL_MODE, true);
  145. defines.setValue(this._definePlanarName, texture.coordinatesMode === Constants.TEXTURE_PLANAR_MODE, true);
  146. defines.setValue(this._defineProjectionName, texture.coordinatesMode === Constants.TEXTURE_PROJECTION_MODE, true);
  147. defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === Constants.TEXTURE_EQUIRECTANGULAR_MODE, true);
  148. defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE, true);
  149. defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE, true);
  150. }
  151. public isReady() {
  152. const texture = this._getTexture();
  153. if (texture && !texture.isReadyOrNotBlocking()) {
  154. return false;
  155. }
  156. return true;
  157. }
  158. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  159. const texture = this._getTexture();
  160. if (!mesh || !texture) {
  161. return;
  162. }
  163. effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix());
  164. if (texture.isCube) {
  165. effect.setTexture(this._cubeSamplerName, texture);
  166. } else {
  167. effect.setTexture(this._2DSamplerName, texture);
  168. }
  169. }
  170. /**
  171. * Gets the code to inject in the vertex shader
  172. * @param state current state of the node material building
  173. * @returns the shader code
  174. */
  175. public handleVertexSide(state: NodeMaterialBuildState): string {
  176. this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D");
  177. this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC");
  178. this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL");
  179. this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR");
  180. this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION");
  181. this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT");
  182. this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR");
  183. this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC");
  184. this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  185. this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  186. this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX");
  187. this._defineOppositeZ = state._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ");
  188. this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix");
  189. state._emitUniformFromString(this._reflectionMatrixName, "mat4");
  190. let code = "";
  191. let worldPosVaryingName = "v_" + this.worldPosition.associatedVariableName;
  192. if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
  193. code += `${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};\r\n`;
  194. }
  195. this._positionUVWName = state._getFreeVariableName("positionUVW");
  196. this._directionWName = state._getFreeVariableName("directionW");
  197. if (state._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName)) {
  198. code += `#ifdef ${this._defineSkyboxName}\r\n`;
  199. code += `${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\r\n`;
  200. code += `#endif\r\n`;
  201. }
  202. if (state._emitVaryingFromString(this._directionWName, "vec3", `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) {
  203. code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\r\n`;
  204. code += `${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\r\n`;
  205. code += `#endif\r\n`;
  206. }
  207. return code;
  208. }
  209. /**
  210. * Handles the inits for the fragment code path
  211. * @param state node material build state
  212. */
  213. public handleFragmentSideInits(state: NodeMaterialBuildState) {
  214. state.sharedData.blockingBlocks.push(this);
  215. state.sharedData.textureBlocks.push(this);
  216. // Samplers
  217. this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
  218. state.samplers.push(this._cubeSamplerName);
  219. this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
  220. state.samplers.push(this._2DSamplerName);
  221. state._samplerDeclaration += `#ifdef ${this._define3DName}\r\n`;
  222. state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\r\n`;
  223. state._samplerDeclaration += `#else\r\n`;
  224. state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\r\n`;
  225. state._samplerDeclaration += `#endif\r\n`;
  226. // Fragment
  227. state.sharedData.blocksWithDefines.push(this);
  228. state.sharedData.bindableBlocks.push(this);
  229. let comments = `//${this.name}`;
  230. state._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", "");
  231. state._emitFunctionFromInclude("reflectionFunction", comments, {
  232. replaceStrings: [
  233. { search: /vec3 computeReflectionCoords/g, replace: "void DUMMYFUNC" }
  234. ]
  235. });
  236. this._reflectionColorName = state._getFreeVariableName("reflectionColor");
  237. this._reflectionVectorName = state._getFreeVariableName("reflectionUVW");
  238. this._reflectionCoordsName = state._getFreeVariableName("reflectionCoords");
  239. }
  240. /**
  241. * Generates the reflection coords code for the fragment code path
  242. * @param worldNormalVarName name of the world normal variable
  243. * @param worldPos name of the world position variable. If not provided, will use the world position connected to this block
  244. * @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates
  245. * @returns the shader code
  246. */
  247. public handleFragmentSideCodeReflectionCoords(worldNormalVarName: string, worldPos?: string, onlyReflectionVector = false): string {
  248. if (!worldPos) {
  249. worldPos = `v_${this.worldPosition.associatedVariableName}`;
  250. }
  251. let reflectionMatrix = this._reflectionMatrixName;
  252. let direction = `normalize(${this._directionWName})`;
  253. let positionUVW = `${this._positionUVWName}`;
  254. let vEyePosition = `${this.cameraPosition.associatedVariableName}`;
  255. let view = `${this.view.associatedVariableName}`;
  256. worldNormalVarName += ".xyz";
  257. let code = `
  258. #ifdef ${this._defineMirroredEquirectangularFixedName}
  259. vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});
  260. #endif
  261. #ifdef ${this._defineEquirectangularFixedName}
  262. vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});
  263. #endif
  264. #ifdef ${this._defineEquirectangularName}
  265. vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
  266. #endif
  267. #ifdef ${this._defineSphericalName}
  268. vec3 ${this._reflectionVectorName} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix});
  269. #endif
  270. #ifdef ${this._definePlanarName}
  271. vec3 ${this._reflectionVectorName} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
  272. #endif
  273. #ifdef ${this._defineCubicName}
  274. #ifdef ${this._defineLocalCubicName}
  275. vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, vReflectionSize, vReflectionPosition);
  276. #else
  277. vec3 ${this._reflectionVectorName} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
  278. #endif
  279. #endif
  280. #ifdef ${this._defineProjectionName}
  281. vec3 ${this._reflectionVectorName} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix});
  282. #endif
  283. #ifdef ${this._defineSkyboxName}
  284. vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix});
  285. #endif
  286. #ifdef ${this._defineExplicitName}
  287. vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);
  288. #endif
  289. #ifdef ${this._defineOppositeZ}
  290. ${this._reflectionVectorName}.z *= -1.0;
  291. #endif\r\n`;
  292. if (!onlyReflectionVector) {
  293. code += `
  294. #ifdef ${this._define3DName}
  295. vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};
  296. #else
  297. vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;
  298. #ifdef ${this._defineProjectionName}
  299. ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;
  300. #endif
  301. ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;
  302. #endif\r\n`;
  303. }
  304. return code;
  305. }
  306. /**
  307. * Generates the reflection color code for the fragment code path
  308. * @param lodVarName name of the lod variable
  309. * @param swizzleLookupTexture swizzle to use for the final color variable
  310. * @returns the shader code
  311. */
  312. public handleFragmentSideCodeReflectionColor(lodVarName?: string, swizzleLookupTexture = ".rgb"): string {
  313. const colorType = "vec" + (swizzleLookupTexture.length === 0 ? "4" : (swizzleLookupTexture.length - 1));
  314. let code = `${colorType} ${this._reflectionColorName};
  315. #ifdef ${this._define3DName}\r\n`;
  316. if (lodVarName) {
  317. code += `${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${lodVarName})${swizzleLookupTexture};\r\n`;
  318. } else {
  319. code += `${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${swizzleLookupTexture};\r\n`;
  320. }
  321. code += `
  322. #else\r\n`;
  323. if (lodVarName) {
  324. code += `${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${lodVarName})${swizzleLookupTexture};\r\n`;
  325. } else {
  326. code += `${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${swizzleLookupTexture};\r\n`;
  327. }
  328. code += `#endif\r\n`;
  329. return code;
  330. }
  331. /**
  332. * Generates the code corresponding to the connected output points
  333. * @param state node material build state
  334. * @param varName name of the variable to output
  335. * @returns the shader code
  336. */
  337. public writeOutputs(state: NodeMaterialBuildState, varName: string): string {
  338. let code = "";
  339. if (state.target === NodeMaterialBlockTargets.Fragment) {
  340. for (var output of this._outputs) {
  341. if (output.hasEndpoints) {
  342. code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\r\n`;
  343. }
  344. }
  345. }
  346. return code;
  347. }
  348. protected _buildBlock(state: NodeMaterialBuildState) {
  349. super._buildBlock(state);
  350. return this;
  351. }
  352. protected _dumpPropertiesCode() {
  353. if (!this.texture) {
  354. return "";
  355. }
  356. let codeString: string;
  357. if (this.texture.isCube) {
  358. codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\r\n`;
  359. } else {
  360. codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`;
  361. }
  362. codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`;
  363. return codeString;
  364. }
  365. public serialize(): any {
  366. let serializationObject = super.serialize();
  367. if (this.texture && !this.texture.isRenderTarget) {
  368. serializationObject.texture = this.texture.serialize();
  369. }
  370. return serializationObject;
  371. }
  372. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  373. super._deserialize(serializationObject, scene, rootUrl);
  374. if (serializationObject.texture) {
  375. rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
  376. if (serializationObject.texture.isCube) {
  377. this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);
  378. } else {
  379. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
  380. }
  381. }
  382. }
  383. public dispose() {
  384. super.dispose();
  385. this.texture?.dispose();
  386. }
  387. }
  388. _TypeStore.RegisteredTypes["BABYLON.ReflectionTextureBaseBlock"] = ReflectionTextureBaseBlock;