textureBlock.ts 17 KB

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