textureBlock.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 { Constants } from '../../../../Engines/constants';
  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 _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. * Create a new TextureBlock
  36. * @param name defines the block name
  37. */
  38. public constructor(name: string) {
  39. super(name, NodeMaterialBlockTargets.VertexAndFragment);
  40. this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, false, NodeMaterialBlockTargets.VertexAndFragment);
  41. this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
  42. this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
  43. this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  44. this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  45. this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  46. this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  47. this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);
  48. this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4);
  49. this._inputs[0]._prioritizeVertex = true;
  50. }
  51. /**
  52. * Gets the current class name
  53. * @returns the class name
  54. */
  55. public getClassName() {
  56. return "TextureBlock";
  57. }
  58. /**
  59. * Gets the uv input component
  60. */
  61. public get uv(): NodeMaterialConnectionPoint {
  62. return this._inputs[0];
  63. }
  64. /**
  65. * Gets the rgba output component
  66. */
  67. public get rgba(): NodeMaterialConnectionPoint {
  68. return this._outputs[0];
  69. }
  70. /**
  71. * Gets the rgb output component
  72. */
  73. public get rgb(): NodeMaterialConnectionPoint {
  74. return this._outputs[1];
  75. }
  76. /**
  77. * Gets the r output component
  78. */
  79. public get r(): NodeMaterialConnectionPoint {
  80. return this._outputs[2];
  81. }
  82. /**
  83. * Gets the g output component
  84. */
  85. public get g(): NodeMaterialConnectionPoint {
  86. return this._outputs[3];
  87. }
  88. /**
  89. * Gets the b output component
  90. */
  91. public get b(): NodeMaterialConnectionPoint {
  92. return this._outputs[4];
  93. }
  94. /**
  95. * Gets the a output component
  96. */
  97. public get a(): NodeMaterialConnectionPoint {
  98. return this._outputs[5];
  99. }
  100. public get target() {
  101. // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.
  102. // But we need to detect uvs coming from fragment then
  103. if (!this.uv.isConnected) {
  104. return NodeMaterialBlockTargets.VertexAndFragment;
  105. }
  106. if (this.uv.sourceBlock!.isInput) {
  107. return NodeMaterialBlockTargets.VertexAndFragment;
  108. }
  109. let parent = this.uv.connectedPoint;
  110. while (parent) {
  111. if (parent.target === NodeMaterialBlockTargets.Fragment) {
  112. return NodeMaterialBlockTargets.Fragment;
  113. }
  114. if (parent.target === NodeMaterialBlockTargets.Vertex) {
  115. return NodeMaterialBlockTargets.VertexAndFragment;
  116. }
  117. if (parent.target === NodeMaterialBlockTargets.Neutral || parent.target === NodeMaterialBlockTargets.VertexAndFragment) {
  118. let parentBlock = parent.ownerBlock;
  119. parent = null;
  120. for (var input of parentBlock.inputs) {
  121. if (input.connectedPoint) {
  122. parent = input.connectedPoint;
  123. break;
  124. }
  125. }
  126. }
  127. }
  128. return NodeMaterialBlockTargets.VertexAndFragment;
  129. }
  130. public autoConfigure(material: NodeMaterial) {
  131. if (!this.uv.isConnected) {
  132. let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv");
  133. if (!uvInput) {
  134. uvInput = new InputBlock("uv");
  135. uvInput.setAsAttribute();
  136. }
  137. uvInput.output.connectTo(this.uv);
  138. }
  139. }
  140. public initializeDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  141. if (!defines._areTexturesDirty) {
  142. return;
  143. }
  144. defines.setValue(this._mainUVDefineName, false);
  145. }
  146. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  147. if (!defines._areTexturesDirty) {
  148. return;
  149. }
  150. if (!this.texture || !this.texture.getTextureMatrix) {
  151. defines.setValue(this._defineName, false);
  152. defines.setValue(this._mainUVDefineName, true);
  153. return;
  154. }
  155. defines.setValue(this._linearDefineName, !this.texture.gammaSpace);
  156. if (this._isMixed) {
  157. if (!this.texture.getTextureMatrix(this._getTextureBase(mesh as Mesh)).isIdentityAs3x2()) {
  158. defines.setValue(this._defineName, true);
  159. } else {
  160. defines.setValue(this._defineName, false);
  161. defines.setValue(this._mainUVDefineName, true);
  162. }
  163. }
  164. }
  165. private _getTextureBase(mesh?: Mesh) {
  166. let base = 1;
  167. // By default textures loaded by the node material are loaded with invertY set to false. But for regular meshes (created by the MeshBuilder) we need to switch it
  168. if (this.texture && mesh && (mesh.overrideMaterialSideOrientation === null || mesh.overrideMaterialSideOrientation === Constants.MATERIAL_CounterClockWiseSideOrientation)) {
  169. if (!this.texture.invertY) {
  170. base = -1;
  171. }
  172. }
  173. return base;
  174. }
  175. public isReady() {
  176. if (this.texture && !this.texture.isReadyOrNotBlocking()) {
  177. return false;
  178. }
  179. return true;
  180. }
  181. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  182. if (!mesh || !this.texture) {
  183. return;
  184. }
  185. if (this._isMixed) {
  186. effect.setFloat(this._textureInfoName, this.texture.level);
  187. effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix(this._getTextureBase(mesh)));
  188. }
  189. effect.setTexture(this._samplerName, this.texture);
  190. }
  191. private get _isMixed() {
  192. return this.target !== NodeMaterialBlockTargets.Fragment;
  193. }
  194. private _injectVertexCode(state: NodeMaterialBuildState) {
  195. let uvInput = this.uv;
  196. // Inject code in vertex
  197. this._defineName = state._getFreeDefineName("UVTRANSFORM");
  198. this._mainUVDefineName = "VMAIN" + uvInput.associatedVariableName.toUpperCase();
  199. if (uvInput.connectedPoint!.ownerBlock.isInput) {
  200. let uvInputOwnerBlock = uvInput.connectedPoint!.ownerBlock as InputBlock;
  201. if (!uvInputOwnerBlock.isAttribute) {
  202. state._emitUniformFromString(uvInput.associatedVariableName, "vec2");
  203. }
  204. }
  205. this._mainUVName = "vMain" + uvInput.associatedVariableName;
  206. this._transformedUVName = state._getFreeVariableName("transformedUV");
  207. this._textureTransformName = state._getFreeVariableName("textureTransform");
  208. this._textureInfoName = state._getFreeVariableName("textureInfoName");
  209. state._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName);
  210. state._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName);
  211. state._emitUniformFromString(this._textureTransformName, "mat4", this._defineName);
  212. state.compilationString += `#ifdef ${this._defineName}\r\n`;
  213. state.compilationString += `${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\r\n`;
  214. state.compilationString += `#endif\r\n`;
  215. state.compilationString += `#ifdef ${this._mainUVDefineName}\r\n`;
  216. state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\r\n`;
  217. state.compilationString += `#endif\r\n`;
  218. if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {
  219. return;
  220. }
  221. this._writeTextureRead(state, true);
  222. for (var output of this._outputs) {
  223. if (output.hasEndpoints) {
  224. this._writeOutput(state, output, output.name, true);
  225. }
  226. }
  227. }
  228. private _writeTextureRead(state: NodeMaterialBuildState, vertexMode = false) {
  229. let uvInput = this.uv;
  230. if (vertexMode) {
  231. if (state.target === NodeMaterialBlockTargets.Fragment) {
  232. return;
  233. }
  234. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\r\n`;
  235. return;
  236. }
  237. if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
  238. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\r\n`;
  239. return;
  240. }
  241. state.compilationString += `#ifdef ${this._defineName}\r\n`;
  242. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._transformedUVName});\r\n`;
  243. state.compilationString += `#endif\r\n`;
  244. state.compilationString += `#ifdef ${this._mainUVDefineName}\r\n`;
  245. state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`;
  246. state.compilationString += `#endif\r\n`;
  247. }
  248. private _writeOutput(state: NodeMaterialBuildState, output: NodeMaterialConnectionPoint, swizzle: string, vertexMode = false) {
  249. if (vertexMode) {
  250. if (state.target === NodeMaterialBlockTargets.Fragment) {
  251. return;
  252. }
  253. state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\r\n`;
  254. return;
  255. }
  256. if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
  257. state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\r\n`;
  258. return;
  259. }
  260. const complement = ` * ${this._textureInfoName}`;
  261. state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\r\n`;
  262. state.compilationString += `#ifdef ${this._linearDefineName}\r\n`;
  263. state.compilationString += `${output.associatedVariableName} = toGammaSpace(${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. let comments = `//${this.name}`;
  295. state._emitFunctionFromInclude("helperFunctions", comments);
  296. if (this._isMixed) {
  297. state._emitUniformFromString(this._textureInfoName, "float");
  298. }
  299. this._writeTextureRead(state);
  300. for (var output of this._outputs) {
  301. if (output.hasEndpoints) {
  302. this._writeOutput(state, output, output.name);
  303. }
  304. }
  305. return this;
  306. }
  307. protected _dumpPropertiesCode() {
  308. if (!this.texture) {
  309. return "";
  310. }
  311. var codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`;
  312. codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`;
  313. codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`;
  314. codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`;
  315. codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`;
  316. codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`;
  317. codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`;
  318. codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`;
  319. codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`;
  320. codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`;
  321. codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\r\n`;
  322. return codeString;
  323. }
  324. public serialize(): any {
  325. let serializationObject = super.serialize();
  326. if (this.texture) {
  327. serializationObject.texture = this.texture.serialize();
  328. }
  329. return serializationObject;
  330. }
  331. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  332. super._deserialize(serializationObject, scene, rootUrl);
  333. if (serializationObject.texture) {
  334. rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
  335. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl) as Texture;
  336. }
  337. }
  338. }
  339. _TypeStore.RegisteredTypes["BABYLON.TextureBlock"] = TextureBlock;