reflectionTextureBlock.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { NodeMaterialBlock } from '../../nodeMaterialBlock';
  2. import { NodeMaterialBlockConnectionPointTypes } from '../../nodeMaterialBlockConnectionPointTypes';
  3. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  4. import { NodeMaterialBlockTargets } from '../../nodeMaterialBlockTargets';
  5. import { NodeMaterialConnectionPoint } from '../../nodeMaterialBlockConnectionPoint';
  6. import { BaseTexture } from '../../../Textures/baseTexture';
  7. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  8. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  9. import { Effect } from '../../../effect';
  10. import { Mesh } from '../../../../Meshes/mesh';
  11. import { Nullable } from '../../../../types';
  12. import { _TypeStore } from '../../../../Misc/typeStore';
  13. import { Texture } from '../../../Textures/texture';
  14. import { Scene } from '../../../../scene';
  15. import { InputBlock } from '../Input/inputBlock';
  16. import { NodeMaterialWellKnownValues } from '../../nodeMaterialWellKnownValues';
  17. import { Constants } from '../../../../Engines/constants';
  18. /**
  19. * Block used to read a reflection texture from a sampler
  20. */
  21. export class ReflectionTextureBlock extends NodeMaterialBlock {
  22. private _define3DName: string;
  23. private _defineCubicName: string;
  24. private _defineExplicitName: string;
  25. private _defineProjectionName: string;
  26. private _defineLocalCubicName: string;
  27. private _defineSphericalName: string;
  28. private _definePlanarName: string;
  29. private _defineEquirectangularName: string;
  30. private _defineMirroredEquirectangularFixedName: string;
  31. private _defineEquirectangularFixedName: string;
  32. private _defineSkyboxName: string;
  33. private _cubeSamplerName: string;
  34. private _2DSamplerName: string;
  35. private _positionUVWName: string;
  36. private _directionWName: string;
  37. private _reflectionCoordsName: string;
  38. private _reflection2DCoordsName: string;
  39. private _reflectionColorName: string;
  40. private _reflectionMatrixName: string;
  41. /**
  42. * Gets or sets the texture associated with the node
  43. */
  44. public texture: Nullable<BaseTexture>;
  45. /**
  46. * Create a new TextureBlock
  47. * @param name defines the block name
  48. */
  49. public constructor(name: string) {
  50. super(name, NodeMaterialBlockTargets.VertexAndFragment);
  51. this.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Vertex);
  52. this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
  53. this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
  54. this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
  55. this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);
  56. this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment);
  57. this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
  58. this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  59. this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  60. this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  61. }
  62. /**
  63. * Gets the current class name
  64. * @returns the class name
  65. */
  66. public getClassName() {
  67. return "ReflectionTextureBlock";
  68. }
  69. /**
  70. * Gets the world position input component
  71. */
  72. public get position(): NodeMaterialConnectionPoint {
  73. return this._inputs[0];
  74. }
  75. /**
  76. * Gets the world position input component
  77. */
  78. public get worldPosition(): NodeMaterialConnectionPoint {
  79. return this._inputs[1];
  80. }
  81. /**
  82. * Gets the world normal input component
  83. */
  84. public get worldNormal(): NodeMaterialConnectionPoint {
  85. return this._inputs[2];
  86. }
  87. /**
  88. * Gets the world input component
  89. */
  90. public get world(): NodeMaterialConnectionPoint {
  91. return this._inputs[3];
  92. }
  93. /**
  94. * Gets the camera (or eye) position component
  95. */
  96. public get cameraPosition(): NodeMaterialConnectionPoint {
  97. return this._inputs[4];
  98. }
  99. /**
  100. * Gets the view input component
  101. */
  102. public get view(): NodeMaterialConnectionPoint {
  103. return this._inputs[5];
  104. }
  105. /**
  106. * Gets the rgb output component
  107. */
  108. public get rgb(): NodeMaterialConnectionPoint {
  109. return this._outputs[0];
  110. }
  111. /**
  112. * Gets the r output component
  113. */
  114. public get r(): NodeMaterialConnectionPoint {
  115. return this._outputs[1];
  116. }
  117. /**
  118. * Gets the g output component
  119. */
  120. public get g(): NodeMaterialConnectionPoint {
  121. return this._outputs[2];
  122. }
  123. /**
  124. * Gets the b output component
  125. */
  126. public get b(): NodeMaterialConnectionPoint {
  127. return this._outputs[3];
  128. }
  129. public autoConfigure() {
  130. if (!this.position.isConnected) {
  131. let positionInput = new InputBlock("position");
  132. positionInput.setAsAttribute();
  133. positionInput.output.connectTo(this.position);
  134. }
  135. if (!this.world.isConnected) {
  136. let worldInput = new InputBlock("world");
  137. worldInput.setAsWellKnownValue(NodeMaterialWellKnownValues.World);
  138. worldInput.output.connectTo(this.world);
  139. }
  140. if (!this.cameraPosition.isConnected) {
  141. let cameraPositionInput = new InputBlock("cameraPosition");
  142. cameraPositionInput.setAsWellKnownValue(NodeMaterialWellKnownValues.CameraPosition);
  143. cameraPositionInput.output.connectTo(this.cameraPosition);
  144. }
  145. if (!this.view.isConnected) {
  146. let viewInput = new InputBlock("view");
  147. viewInput.setAsWellKnownValue(NodeMaterialWellKnownValues.View);
  148. viewInput.output.connectTo(this.view);
  149. }
  150. }
  151. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  152. if (!defines._areTexturesDirty) {
  153. return;
  154. }
  155. if (!this.texture || !this.texture.getTextureMatrix) {
  156. return;
  157. }
  158. defines.setValue(this._define3DName, this.texture.isCube);
  159. defines.setValue(this._defineLocalCubicName, (<any>this.texture).boundingBoxSize ? true : false);
  160. defines.setValue(this._defineExplicitName, this.texture.coordinatesMode === Constants.TEXTURE_EXPLICIT_MODE);
  161. defines.setValue(this._defineSkyboxName, this.texture.coordinatesMode === Constants.TEXTURE_SKYBOX_MODE);
  162. defines.setValue(this._defineCubicName, this.texture.coordinatesMode === Constants.TEXTURE_CUBIC_MODE);
  163. defines.setValue(this._defineSphericalName, this.texture.coordinatesMode === Constants.TEXTURE_SPHERICAL_MODE);
  164. defines.setValue(this._definePlanarName, this.texture.coordinatesMode === Constants.TEXTURE_PLANAR_MODE);
  165. defines.setValue(this._defineProjectionName, this.texture.coordinatesMode === Constants.TEXTURE_PROJECTION_MODE);
  166. defines.setValue(this._defineEquirectangularName, this.texture.coordinatesMode === Constants.TEXTURE_EQUIRECTANGULAR_MODE);
  167. defines.setValue(this._defineEquirectangularFixedName, this.texture.coordinatesMode === Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE);
  168. defines.setValue(this._defineMirroredEquirectangularFixedName, this.texture.coordinatesMode === Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE);
  169. }
  170. public isReady() {
  171. if (this.texture && !this.texture.isReadyOrNotBlocking()) {
  172. return false;
  173. }
  174. return true;
  175. }
  176. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  177. if (!mesh || !this.texture) {
  178. return;
  179. }
  180. effect.setMatrix(this._reflectionMatrixName, this.texture.getReflectionTextureMatrix());
  181. if (this.texture.isCube) {
  182. effect.setTexture(this._cubeSamplerName, this.texture);
  183. } else {
  184. effect.setTexture(this._2DSamplerName, this.texture);
  185. }
  186. }
  187. private _injectVertexCode(state: NodeMaterialBuildState) {
  188. let worldPosVaryingName = "v_" + this.worldPosition.associatedVariableName;
  189. if (state._emitVaryingFromString(worldPosVaryingName, "vec3")) {
  190. state.compilationString += `${worldPosVaryingName} = ${this.worldPosition.associatedVariableName}.xyz;\r\n`;
  191. }
  192. let worldNormalVaryingName = "v_" + this.worldNormal.associatedVariableName;
  193. if (state._emitVaryingFromString(worldNormalVaryingName, "vec3")) {
  194. state.compilationString += `${worldNormalVaryingName} = ${this.worldNormal.associatedVariableName}.xyz;\r\n`;
  195. }
  196. this._positionUVWName = state._getFreeVariableName("positionUVW");
  197. this._directionWName = state._getFreeVariableName("directionW");
  198. if (state._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName)) {
  199. state.compilationString += `#ifdef ${this._defineSkyboxName}\r\n`;
  200. state.compilationString += `${this._positionUVWName} = ${this.position.associatedVariableName};\r\n`;
  201. state.compilationString += `#endif\r\n`;
  202. }
  203. if (state._emitVaryingFromString(this._directionWName, "vec3", `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) {
  204. state.compilationString += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\r\n`;
  205. state.compilationString += `${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}, 0.0)));\r\n`;
  206. state.compilationString += `#endif\r\n`;
  207. }
  208. }
  209. private _writeOutput(state: NodeMaterialBuildState, output: NodeMaterialConnectionPoint, swizzle: string) {
  210. state.compilationString += `${this._declareOutput(output, state)} = ${this._reflectionColorName}.${swizzle};\r\n`;
  211. }
  212. protected _buildBlock(state: NodeMaterialBuildState) {
  213. super._buildBlock(state);
  214. if (state.target !== NodeMaterialBlockTargets.Fragment) {
  215. this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D");
  216. this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC");
  217. this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL");
  218. this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR");
  219. this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION");
  220. this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT");
  221. this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR");
  222. this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC");
  223. this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  224. this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  225. this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX");
  226. // Vertex
  227. this._injectVertexCode(state);
  228. return;
  229. }
  230. state.sharedData.blockingBlocks.push(this);
  231. state.sharedData.textureBlocks.push(this);
  232. // Samplers
  233. this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
  234. state.samplers.push(this._cubeSamplerName);
  235. this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
  236. state.samplers.push(this._2DSamplerName);
  237. state._samplerDeclaration += `#ifdef ${this._define3DName}\r\n`;
  238. state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\r\n`;
  239. state._samplerDeclaration += `#else\r\n`;
  240. state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\r\n`;
  241. state._samplerDeclaration += `#endif\r\n`;
  242. // Fragment
  243. state.sharedData.blocksWithDefines.push(this);
  244. state.sharedData.bindableBlocks.push(this);
  245. let comments = `//${this.name}`;
  246. state._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", "");
  247. state._emitFunctionFromInclude("reflectionFunction", comments);
  248. this._reflectionColorName = state._getFreeVariableName("reflectionColor");
  249. this._reflectionCoordsName = state._getFreeVariableName("reflectionUVW");
  250. this._reflection2DCoordsName = state._getFreeVariableName("reflectionUV");
  251. this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix");
  252. state._emitUniformFromString(this._reflectionMatrixName, "mat4");
  253. // Code
  254. let worldPos = `vec4(v_${this.worldPosition.associatedVariableName}, 1.0)`;
  255. let worldNormal = "v_" + this.worldNormal.associatedVariableName + ".xyz";
  256. let reflectionMatrix = this._reflectionMatrixName;
  257. let direction = `normalize(${this._directionWName})`;
  258. let positionUVW = `${this._positionUVWName}`;
  259. let vEyePosition = `${this.cameraPosition.associatedVariableName}`;
  260. let view = `${this.view.associatedVariableName}`;
  261. state.compilationString += `vec3 ${this._reflectionColorName};\r\n`;
  262. state.compilationString += `#ifdef ${this._define3DName}\r\n`;
  263. state.compilationString += `#ifdef ${this._defineMirroredEquirectangularFixedName}\r\n`;
  264. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormal}, ${direction});\r\n`;
  265. state.compilationString += `#endif\r\n`;
  266. state.compilationString += `#ifdef ${this._defineEquirectangularFixedName}\r\n`;
  267. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormal}, ${direction});\r\n`;
  268. state.compilationString += `#endif\r\n`;
  269. state.compilationString += `#ifdef ${this._defineEquirectangularName}\r\n`;
  270. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeEquirectangularCoords(${worldPos}, ${worldNormal}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n`;
  271. state.compilationString += ` #endif\r\n`;
  272. state.compilationString += `#ifdef ${this._defineSphericalName}\r\n`;
  273. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeSphericalCoords(${worldPos}, ${worldNormal}, ${view}, ${reflectionMatrix});\r\n`;
  274. state.compilationString += `#endif\r\n`;
  275. state.compilationString += `#ifdef ${this._definePlanarName}\r\n`;
  276. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computePlanarCoords(${worldPos}, ${worldNormal}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n`;
  277. state.compilationString += `#endif\r\n`;
  278. state.compilationString += `#ifdef ${this._defineCubicName}\r\n`;
  279. state.compilationString += ` #ifdef ${this._defineLocalCubicName}\r\n`;
  280. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeCubicLocalCoords(${worldPos}, ${worldNormal}, ${vEyePosition}.xyz, ${reflectionMatrix}, vReflectionSize, vReflectionPosition);\r\n`;
  281. state.compilationString += ` #else\r\n`;
  282. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeCubicCoords(${worldPos}, ${worldNormal}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n`;
  283. state.compilationString += ` #endif\r\n`;
  284. state.compilationString += `#endif\r\n`;
  285. state.compilationString += `#ifdef ${this._defineProjectionName}\r\n`;
  286. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix});\r\n`;
  287. state.compilationString += `#endif\r\n`;
  288. state.compilationString += `#ifdef ${this._defineSkyboxName}\r\n`;
  289. state.compilationString += ` vec3 ${this._reflectionCoordsName} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix});\r\n`;
  290. state.compilationString += `#endif\r\n`;
  291. state.compilationString += `#ifdef ${this._defineExplicitName}\r\n`;
  292. state.compilationString += ` vec3 ${this._reflectionCoordsName} = vec3(0, 0, 0);\r\n`;
  293. state.compilationString += `#endif\r\n`;
  294. state.compilationString += `${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionCoordsName}).rgb;\r\n`;
  295. state.compilationString += `#else\r\n`;
  296. state.compilationString += `vec2 ${this._reflection2DCoordsName} = ${this._reflectionCoordsName}.xy;\r\n`;
  297. state.compilationString += `#ifdef ${this._defineProjectionName}\r\n`;
  298. state.compilationString += `${this._reflection2DCoordsName} /= ${this._reflectionCoordsName}.z;\r\n`;
  299. state.compilationString += `#endif\r\n`;
  300. state.compilationString += `${this._reflection2DCoordsName}.y = 1.0 - ${this._reflection2DCoordsName}.y;\r\n`;
  301. state.compilationString += `${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflection2DCoordsName}).rgb;\r\n`;
  302. state.compilationString += `#endif\r\n`;
  303. for (var output of this._outputs) {
  304. if (output.connectedBlocks.length) {
  305. this._writeOutput(state, output, output.name);
  306. }
  307. }
  308. return this;
  309. }
  310. public serialize(): any {
  311. let serializationObject = super.serialize();
  312. if (this.texture) {
  313. serializationObject.texture = this.texture.serialize();
  314. }
  315. return serializationObject;
  316. }
  317. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  318. super._deserialize(serializationObject, scene, rootUrl);
  319. if (serializationObject.texture) {
  320. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
  321. }
  322. }
  323. }
  324. _TypeStore.RegisteredTypes["BABYLON.ReflectionTextureBlock"] = ReflectionTextureBlock;