textureBlock.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import { NodeMaterialBlock } from '../../nodeMaterialBlock';
  2. import { NodeMaterialBlockConnectionPointTypes } from '../../Enums/nodeMaterialBlockConnectionPointTypes';
  3. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  4. import { NodeMaterialBlockTargets } from '../../Enums/nodeMaterialBlockTargets';
  5. import { NodeMaterialConnectionPoint } from '../../nodeMaterialBlockConnectionPoint';
  6. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  7. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  8. import { InputBlock } from '../Input/inputBlock';
  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 "../../../../Shaders/ShadersInclude/helperFunctions";
  16. /**
  17. * Block used to read a texture from a sampler
  18. */
  19. export class TextureBlock extends NodeMaterialBlock {
  20. private _defineName: string;
  21. private _linearDefineName: string;
  22. private _gammaDefineName: string;
  23. private _tempTextureRead: string;
  24. private _samplerName: string;
  25. private _transformedUVName: string;
  26. private _textureTransformName: string;
  27. private _textureInfoName: string;
  28. private _mainUVName: string;
  29. private _mainUVDefineName: string;
  30. /**
  31. * Gets or sets the texture associated with the node
  32. */
  33. public texture: Nullable<Texture>;
  34. /**
  35. * Gets or sets a boolean indicating if content needs to be converted to gamma space
  36. */
  37. public convertToGammaSpace = false;
  38. /**
  39. * Gets or sets a boolean indicating if content needs to be converted to linear space
  40. */
  41. public convertToLinearSpace = false;
  42. /**
  43. * Create a new TextureBlock
  44. * @param name defines the block name
  45. */
  46. public constructor(name: string) {
  47. super(name, NodeMaterialBlockTargets.VertexAndFragment);
  48. this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, false, NodeMaterialBlockTargets.VertexAndFragment);
  49. this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
  50. this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
  51. this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  52. this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  53. this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  54. this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  55. this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);
  56. this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4);
  57. this._inputs[0]._prioritizeVertex = true;
  58. }
  59. /**
  60. * Gets the current class name
  61. * @returns the class name
  62. */
  63. public getClassName() {
  64. return "TextureBlock";
  65. }
  66. /**
  67. * Gets the uv input component
  68. */
  69. public get uv(): NodeMaterialConnectionPoint {
  70. return this._inputs[0];
  71. }
  72. /**
  73. * Gets the rgba output component
  74. */
  75. public get rgba(): NodeMaterialConnectionPoint {
  76. return this._outputs[0];
  77. }
  78. /**
  79. * Gets the rgb output component
  80. */
  81. public get rgb(): NodeMaterialConnectionPoint {
  82. return this._outputs[1];
  83. }
  84. /**
  85. * Gets the r output component
  86. */
  87. public get r(): NodeMaterialConnectionPoint {
  88. return this._outputs[2];
  89. }
  90. /**
  91. * Gets the g output component
  92. */
  93. public get g(): NodeMaterialConnectionPoint {
  94. return this._outputs[3];
  95. }
  96. /**
  97. * Gets the b output component
  98. */
  99. public get b(): NodeMaterialConnectionPoint {
  100. return this._outputs[4];
  101. }
  102. /**
  103. * Gets the a output component
  104. */
  105. public get a(): NodeMaterialConnectionPoint {
  106. return this._outputs[5];
  107. }
  108. public get target() {
  109. // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.
  110. // But we need to detect uvs coming from fragment then
  111. if (!this.uv.isConnected) {
  112. return NodeMaterialBlockTargets.VertexAndFragment;
  113. }
  114. if (this.uv.sourceBlock!.isInput) {
  115. return NodeMaterialBlockTargets.VertexAndFragment;
  116. }
  117. let parent = this.uv.connectedPoint;
  118. while (parent) {
  119. if (parent.target === NodeMaterialBlockTargets.Fragment) {
  120. return NodeMaterialBlockTargets.Fragment;
  121. }
  122. if (parent.target === NodeMaterialBlockTargets.Vertex) {
  123. return NodeMaterialBlockTargets.VertexAndFragment;
  124. }
  125. if (parent.target === NodeMaterialBlockTargets.Neutral || parent.target === NodeMaterialBlockTargets.VertexAndFragment) {
  126. let parentBlock = parent.ownerBlock;
  127. parent = null;
  128. for (var input of parentBlock.inputs) {
  129. if (input.connectedPoint) {
  130. parent = input.connectedPoint;
  131. break;
  132. }
  133. }
  134. }
  135. }
  136. return NodeMaterialBlockTargets.VertexAndFragment;
  137. }
  138. public autoConfigure(material: NodeMaterial) {
  139. if (!this.uv.isConnected) {
  140. let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv");
  141. if (!uvInput) {
  142. uvInput = new InputBlock("uv");
  143. uvInput.setAsAttribute();
  144. }
  145. uvInput.output.connectTo(this.uv);
  146. }
  147. }
  148. public initializeDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  149. if (!defines._areTexturesDirty) {
  150. return;
  151. }
  152. defines.setValue(this._mainUVDefineName, false);
  153. }
  154. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  155. if (!defines._areTexturesDirty) {
  156. return;
  157. }
  158. if (!this.texture || !this.texture.getTextureMatrix) {
  159. defines.setValue(this._defineName, false);
  160. defines.setValue(this._mainUVDefineName, true);
  161. return;
  162. }
  163. defines.setValue(this._linearDefineName, this.convertToGammaSpace);
  164. defines.setValue(this._gammaDefineName, this.convertToLinearSpace);
  165. if (this._isMixed) {
  166. if (!this.texture.getTextureMatrix().isIdentityAs3x2()) {
  167. defines.setValue(this._defineName, true);
  168. } else {
  169. defines.setValue(this._defineName, false);
  170. defines.setValue(this._mainUVDefineName, true);
  171. }
  172. }
  173. }
  174. public isReady() {
  175. if (this.texture && !this.texture.isReadyOrNotBlocking()) {
  176. return false;
  177. }
  178. return true;
  179. }
  180. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  181. if (!mesh || !this.texture) {
  182. return;
  183. }
  184. if (this._isMixed) {
  185. effect.setFloat(this._textureInfoName, this.texture.level);
  186. effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix());
  187. }
  188. effect.setTexture(this._samplerName, this.texture);
  189. }
  190. private get _isMixed() {
  191. return this.target !== NodeMaterialBlockTargets.Fragment;
  192. }
  193. private _injectVertexCode(state: NodeMaterialBuildState) {
  194. let uvInput = this.uv;
  195. // Inject code in vertex
  196. this._defineName = state._getFreeDefineName("UVTRANSFORM");
  197. this._mainUVDefineName = "VMAIN" + uvInput.associatedVariableName.toUpperCase();
  198. if (uvInput.connectedPoint!.ownerBlock.isInput) {
  199. let uvInputOwnerBlock = uvInput.connectedPoint!.ownerBlock as InputBlock;
  200. if (!uvInputOwnerBlock.isAttribute) {
  201. state._emitUniformFromString(uvInput.associatedVariableName, "vec2");
  202. }
  203. }
  204. this._mainUVName = "vMain" + uvInput.associatedVariableName;
  205. this._transformedUVName = state._getFreeVariableName("transformedUV");
  206. this._textureTransformName = state._getFreeVariableName("textureTransform");
  207. this._textureInfoName = state._getFreeVariableName("textureInfoName");
  208. state._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName);
  209. state._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName);
  210. state._emitUniformFromString(this._textureTransformName, "mat4", this._defineName);
  211. state.compilationString += `#ifdef ${this._defineName}\r\n`;
  212. state.compilationString += `${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\r\n`;
  213. state.compilationString += `#elif defined(${this._mainUVDefineName})\r\n`;
  214. state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\r\n`;
  215. state.compilationString += `#endif\r\n`;
  216. if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {
  217. return;
  218. }
  219. this._writeTextureRead(state, true);
  220. for (var output of this._outputs) {
  221. if (output.hasEndpoints) {
  222. this._writeOutput(state, output, output.name, true);
  223. }
  224. }
  225. }
  226. private _writeTextureRead(state: NodeMaterialBuildState, vertexMode = false) {
  227. let uvInput = this.uv;
  228. if (vertexMode) {
  229. if (state.target === NodeMaterialBlockTargets.Fragment) {
  230. return;
  231. }
  232. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\r\n`;
  233. return;
  234. }
  235. if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
  236. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\r\n`;
  237. return;
  238. }
  239. state.compilationString += `#ifdef ${this._defineName}\r\n`;
  240. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._transformedUVName});\r\n`;
  241. state.compilationString += `#elif defined(${this._mainUVDefineName})\r\n`;
  242. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`;
  243. state.compilationString += `#endif\r\n`;
  244. }
  245. private _writeOutput(state: NodeMaterialBuildState, output: NodeMaterialConnectionPoint, swizzle: string, vertexMode = false) {
  246. if (vertexMode) {
  247. if (state.target === NodeMaterialBlockTargets.Fragment) {
  248. return;
  249. }
  250. state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\r\n`;
  251. return;
  252. }
  253. if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
  254. state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\r\n`;
  255. return;
  256. }
  257. const complement = ` * ${this._textureInfoName}`;
  258. state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\r\n`;
  259. state.compilationString += `#ifdef ${this._linearDefineName}\r\n`;
  260. state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\r\n`;
  261. state.compilationString += `#endif\r\n`;
  262. state.compilationString += `#ifdef ${this._gammaDefineName}\r\n`;
  263. state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\r\n`;
  264. state.compilationString += `#endif\r\n`;
  265. }
  266. protected _buildBlock(state: NodeMaterialBuildState) {
  267. super._buildBlock(state);
  268. if (state.target === NodeMaterialBlockTargets.Vertex) {
  269. this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
  270. }
  271. if (!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment || this._isMixed && state.target === NodeMaterialBlockTargets.Vertex) {
  272. this._samplerName = state._getFreeVariableName(this.name + "Sampler");
  273. state._emit2DSampler(this._samplerName);
  274. // Declarations
  275. state.sharedData.blockingBlocks.push(this);
  276. state.sharedData.textureBlocks.push(this);
  277. state.sharedData.blocksWithDefines.push(this);
  278. state.sharedData.bindableBlocks.push(this);
  279. }
  280. if (state.target !== NodeMaterialBlockTargets.Fragment) {
  281. // Vertex
  282. this._injectVertexCode(state);
  283. return;
  284. }
  285. // Fragment
  286. if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {
  287. return;
  288. }
  289. if (this._isMixed) {
  290. // Reexport the sampler
  291. state._emit2DSampler(this._samplerName);
  292. }
  293. this._linearDefineName = state._getFreeDefineName("ISLINEAR");
  294. this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
  295. let comments = `//${this.name}`;
  296. state._emitFunctionFromInclude("helperFunctions", comments);
  297. if (this._isMixed) {
  298. state._emitUniformFromString(this._textureInfoName, "float");
  299. }
  300. this._writeTextureRead(state);
  301. for (var output of this._outputs) {
  302. if (output.hasEndpoints) {
  303. this._writeOutput(state, output, output.name);
  304. }
  305. }
  306. return this;
  307. }
  308. protected _dumpPropertiesCode() {
  309. if (!this.texture) {
  310. return "";
  311. }
  312. var codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\r\n`;
  313. codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`;
  314. codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`;
  315. codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`;
  316. codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`;
  317. codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`;
  318. codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`;
  319. codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`;
  320. codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`;
  321. codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`;
  322. codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`;
  323. codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`;
  324. return codeString;
  325. }
  326. public serialize(): any {
  327. let serializationObject = super.serialize();
  328. serializationObject.convertToGammaSpace = this.convertToGammaSpace;
  329. serializationObject.convertToLinearSpace = this.convertToLinearSpace;
  330. if (this.texture) {
  331. serializationObject.texture = this.texture.serialize();
  332. }
  333. return serializationObject;
  334. }
  335. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  336. super._deserialize(serializationObject, scene, rootUrl);
  337. this.convertToGammaSpace = serializationObject.convertToGammaSpace;
  338. this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
  339. if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime) {
  340. rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
  341. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl) as Texture;
  342. }
  343. }
  344. }
  345. _TypeStore.RegisteredTypes["BABYLON.TextureBlock"] = TextureBlock;