CustomShader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import Check from "../../Core/Check.js";
  2. import defaultValue from "../../Core/defaultValue.js";
  3. import defined from "../../Core/defined.js";
  4. import destroyObject from "../../Core/destroyObject.js";
  5. import DeveloperError from "../../Core/DeveloperError.js";
  6. import CustomShaderMode from "./CustomShaderMode.js";
  7. import UniformType from "./UniformType.js";
  8. import TextureManager from "./TextureManager.js";
  9. import CustomShaderTranslucencyMode from "./CustomShaderTranslucencyMode.js";
  10. /**
  11. * An object describing a uniform, its type, and an initial value
  12. *
  13. * @typedef {object} UniformSpecifier
  14. * @property {UniformType} type The Glsl type of the uniform.
  15. * @property {boolean|number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|TextureUniform} value The initial value of the uniform
  16. *
  17. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  18. */
  19. /**
  20. * A set of variables parsed from the user-defined shader code. These can be
  21. * used for optimizations when generating the overall shader. Though they are
  22. * represented as JS objects, the intended use is like a set, so only the
  23. * existence of keys matter. The values will always be <code>true</code> if
  24. * defined. This data structure is used because:
  25. * <ul>
  26. * <li>We cannot yet use ES6 Set objects</li>
  27. * <li>Using a dictionary automatically de-duplicates variable names</li>
  28. * <li>Queries such as <code>variableSet.hasOwnProperty("position")</code> are straightforward</li>
  29. * </ul>
  30. * @typedef {Object<string, boolean>} VariableSet
  31. * @private
  32. */
  33. /**
  34. * Variable sets parsed from the user-defined vertex shader text.
  35. * @typedef {object} VertexVariableSets
  36. * @property {VariableSet} attributeSet A set of all unique attributes used in the vertex shader via the <code>vsInput.attributes</code> struct.
  37. * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the vertex shader via the <code>vsInput.featureIds</code> struct.
  38. * @property {VariableSet} metadataSet A set of all unique metadata properties used in the vertex shader via the <code>vsInput.metadata</code> struct.
  39. * @private
  40. */
  41. /**
  42. * Variable sets parsed from the user-defined fragment shader text.
  43. * @typedef {object} FragmentVariableSets
  44. * @property {VariableSet} attributeSet A set of all unique attributes used in the fragment shader via the <code>fsInput.attributes</code> struct
  45. * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the fragment shader via the <code>fsInput.featureIds</code> struct.
  46. * @property {VariableSet} metadataSet A set of all unique metadata properties used in the fragment shader via the <code>fsInput.metadata</code> struct.
  47. * @property {VariableSet} materialSet A set of all material variables such as diffuse, specular or alpha that are used in the fragment shader via the <code>material</code> struct.
  48. * @private
  49. */
  50. /**
  51. * A user defined GLSL shader used with {@link Model} as well
  52. * as {@link Cesium3DTileset}.
  53. * <p>
  54. * If texture uniforms are used, additional resource management must be done:
  55. * </p>
  56. * <ul>
  57. * <li>
  58. * The <code>update</code> function must be called each frame. When a
  59. * custom shader is passed to a {@link Model} or a
  60. * {@link Cesium3DTileset}, this step is handled automaticaly
  61. * </li>
  62. * <li>
  63. * {@link CustomShader#destroy} must be called when the custom shader is
  64. * no longer needed to clean up GPU resources properly. The application
  65. * is responsible for calling this method.
  66. * </li>
  67. * </ul>
  68. * <p>
  69. * See the {@link https://github.com/CesiumGS/cesium/tree/main/Documentation/CustomShaderGuide|Custom Shader Guide} for more detailed documentation.
  70. * </p>
  71. *
  72. * @param {object} options An object with the following options
  73. * @param {CustomShaderMode} [options.mode=CustomShaderMode.MODIFY_MATERIAL] The custom shader mode, which determines how the custom shader code is inserted into the fragment shader.
  74. * @param {LightingModel} [options.lightingModel] The lighting model (e.g. PBR or unlit). If present, this overrides the default lighting for the model.
  75. * @param {CustomShaderTranslucencyMode} [options.translucencyMode=CustomShaderTranslucencyMode.INHERIT] The translucency mode, which determines how the custom shader will be applied. If the value is CustomShaderTransulcencyMode.OPAQUE or CustomShaderTransulcencyMode.TRANSLUCENT, the custom shader will override settings from the model's material. If the value is CustomShaderTransulcencyMode.INHERIT, the custom shader will render as either opaque or translucent depending on the primitive's material settings.
  76. * @param {Object<string, UniformSpecifier>} [options.uniforms] A dictionary for user-defined uniforms. The key is the uniform name that will appear in the GLSL code. The value is an object that describes the uniform type and initial value
  77. * @param {Object<string, VaryingType>} [options.varyings] A dictionary for declaring additional GLSL varyings used in the shader. The key is the varying name that will appear in the GLSL code. The value is the data type of the varying. For each varying, the declaration will be added to the top of the shader automatically. The caller is responsible for assigning a value in the vertex shader and using the value in the fragment shader.
  78. * @param {string} [options.vertexShaderText] The custom vertex shader as a string of GLSL code. It must include a GLSL function called vertexMain. See the example for the expected signature. If not specified, the custom vertex shader step will be skipped in the computed vertex shader.
  79. * @param {string} [options.fragmentShaderText] The custom fragment shader as a string of GLSL code. It must include a GLSL function called fragmentMain. See the example for the expected signature. If not specified, the custom fragment shader step will be skipped in the computed fragment shader.
  80. *
  81. * @alias CustomShader
  82. * @constructor
  83. *
  84. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  85. *
  86. * @example
  87. * const customShader = new CustomShader({
  88. * uniforms: {
  89. * u_colorIndex: {
  90. * type: Cesium.UniformType.FLOAT,
  91. * value: 1.0
  92. * },
  93. * u_normalMap: {
  94. * type: Cesium.UniformType.SAMPLER_2D,
  95. * value: new Cesium.TextureUniform({
  96. * url: "http://example.com/normal.png"
  97. * })
  98. * }
  99. * },
  100. * varyings: {
  101. * v_selectedColor: Cesium.VaryingType.VEC3
  102. * },
  103. * vertexShaderText: `
  104. * void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
  105. * v_selectedColor = mix(vsInput.attributes.color_0, vsInput.attributes.color_1, u_colorIndex);
  106. * vsOutput.positionMC += 0.1 * vsInput.attributes.normal;
  107. * }
  108. * `,
  109. * fragmentShaderText: `
  110. * void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
  111. * material.normal = texture(u_normalMap, fsInput.attributes.texCoord_0);
  112. * material.diffuse = v_selectedColor;
  113. * }
  114. * `
  115. * });
  116. */
  117. function CustomShader(options) {
  118. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  119. /**
  120. * A value determining how the custom shader interacts with the overall
  121. * fragment shader. This is used by {@link CustomShaderPipelineStage}
  122. *
  123. * @type {CustomShaderMode}
  124. * @readonly
  125. */
  126. this.mode = defaultValue(options.mode, CustomShaderMode.MODIFY_MATERIAL);
  127. /**
  128. * The lighting model to use when using the custom shader.
  129. * This is used by {@link CustomShaderPipelineStage}
  130. *
  131. * @type {LightingModel}
  132. * @readonly
  133. */
  134. this.lightingModel = options.lightingModel;
  135. /**
  136. * Additional uniforms as declared by the user.
  137. *
  138. * @type {Object<string, UniformSpecifier>}
  139. * @readonly
  140. */
  141. this.uniforms = defaultValue(options.uniforms, defaultValue.EMPTY_OBJECT);
  142. /**
  143. * Additional varyings as declared by the user.
  144. * This is used by {@link CustomShaderPipelineStage}
  145. *
  146. * @type {Object<string, VaryingType>}
  147. * @readonly
  148. */
  149. this.varyings = defaultValue(options.varyings, defaultValue.EMPTY_OBJECT);
  150. /**
  151. * The user-defined GLSL code for the vertex shader
  152. *
  153. * @type {string}
  154. * @readonly
  155. */
  156. this.vertexShaderText = options.vertexShaderText;
  157. /**
  158. * The user-defined GLSL code for the fragment shader
  159. *
  160. * @type {string}
  161. * @readonly
  162. */
  163. this.fragmentShaderText = options.fragmentShaderText;
  164. /**
  165. * The translucency mode, which determines how the custom shader will be applied. If the value is
  166. * CustomShaderTransulcencyMode.OPAQUE or CustomShaderTransulcencyMode.TRANSLUCENT, the custom shader
  167. * will override settings from the model's material. If the value isCustomShaderTransulcencyMode.INHERIT,
  168. * the custom shader will render as either opaque or translucent depending on the primitive's material settings.
  169. *
  170. * @type {CustomShaderTranslucencyMode}
  171. * @default CustomShaderTranslucencyMode.INHERIT
  172. * @readonly
  173. */
  174. this.translucencyMode = defaultValue(
  175. options.translucencyMode,
  176. CustomShaderTranslucencyMode.INHERIT
  177. );
  178. /**
  179. * texture uniforms require some asynchronous processing. This is delegated
  180. * to a texture manager.
  181. *
  182. * @type {TextureManager}
  183. * @readonly
  184. * @private
  185. */
  186. this._textureManager = new TextureManager();
  187. /**
  188. * The default texture (from the {@link Context}) to use while textures
  189. * are loading
  190. *
  191. * @type {Texture}
  192. * @readonly
  193. * @private
  194. */
  195. this._defaultTexture = undefined;
  196. /**
  197. * The map of uniform names to a function that returns a value. This map
  198. * is combined with the overall uniform map used by the {@link DrawCommand}
  199. *
  200. * @type {Object<string, Function>}
  201. * @readonly
  202. * @private
  203. */
  204. this.uniformMap = buildUniformMap(this);
  205. /**
  206. * A collection of variables used in <code>vertexShaderText</code>. This
  207. * is used only for optimizations in {@link CustomShaderPipelineStage}.
  208. * @type {VertexVariableSets}
  209. * @private
  210. */
  211. this.usedVariablesVertex = {
  212. attributeSet: {},
  213. featureIdSet: {},
  214. metadataSet: {},
  215. };
  216. /**
  217. * A collection of variables used in <code>fragmentShaderText</code>. This
  218. * is used only for optimizations in {@link CustomShaderPipelineStage}.
  219. * @type {FragmentVariableSets}
  220. * @private
  221. */
  222. this.usedVariablesFragment = {
  223. attributeSet: {},
  224. featureIdSet: {},
  225. metadataSet: {},
  226. materialSet: {},
  227. };
  228. findUsedVariables(this);
  229. validateBuiltinVariables(this);
  230. }
  231. function buildUniformMap(customShader) {
  232. const uniforms = customShader.uniforms;
  233. const uniformMap = {};
  234. for (const uniformName in uniforms) {
  235. if (uniforms.hasOwnProperty(uniformName)) {
  236. const uniform = uniforms[uniformName];
  237. const type = uniform.type;
  238. //>>includeStart('debug', pragmas.debug);
  239. if (type === UniformType.SAMPLER_CUBE) {
  240. throw new DeveloperError(
  241. "CustomShader does not support samplerCube uniforms"
  242. );
  243. }
  244. //>>includeEnd('debug');
  245. if (type === UniformType.SAMPLER_2D) {
  246. customShader._textureManager.loadTexture2D(uniformName, uniform.value);
  247. uniformMap[uniformName] = createUniformTexture2DFunction(
  248. customShader,
  249. uniformName
  250. );
  251. } else {
  252. uniformMap[uniformName] = createUniformFunction(
  253. customShader,
  254. uniformName
  255. );
  256. }
  257. }
  258. }
  259. return uniformMap;
  260. }
  261. function createUniformTexture2DFunction(customShader, uniformName) {
  262. return function () {
  263. return defaultValue(
  264. customShader._textureManager.getTexture(uniformName),
  265. customShader._defaultTexture
  266. );
  267. };
  268. }
  269. function createUniformFunction(customShader, uniformName) {
  270. return function () {
  271. return customShader.uniforms[uniformName].value;
  272. };
  273. }
  274. function getVariables(shaderText, regex, outputSet) {
  275. let match;
  276. while ((match = regex.exec(shaderText)) !== null) {
  277. const variableName = match[1];
  278. // Using a dictionary like a set. The value doesn't
  279. // matter, as this will only be used for queries such as
  280. // if (set.hasOwnProperty(variableName)) { ... }
  281. outputSet[variableName] = true;
  282. }
  283. }
  284. function findUsedVariables(customShader) {
  285. const attributeRegex = /[vf]sInput\.attributes\.(\w+)/g;
  286. const featureIdRegex = /[vf]sInput\.featureIds\.(\w+)/g;
  287. const metadataRegex = /[vf]sInput\.metadata.(\w+)/g;
  288. let attributeSet;
  289. const vertexShaderText = customShader.vertexShaderText;
  290. if (defined(vertexShaderText)) {
  291. attributeSet = customShader.usedVariablesVertex.attributeSet;
  292. getVariables(vertexShaderText, attributeRegex, attributeSet);
  293. attributeSet = customShader.usedVariablesVertex.featureIdSet;
  294. getVariables(vertexShaderText, featureIdRegex, attributeSet);
  295. attributeSet = customShader.usedVariablesVertex.metadataSet;
  296. getVariables(vertexShaderText, metadataRegex, attributeSet);
  297. }
  298. const fragmentShaderText = customShader.fragmentShaderText;
  299. if (defined(fragmentShaderText)) {
  300. attributeSet = customShader.usedVariablesFragment.attributeSet;
  301. getVariables(fragmentShaderText, attributeRegex, attributeSet);
  302. attributeSet = customShader.usedVariablesFragment.featureIdSet;
  303. getVariables(fragmentShaderText, featureIdRegex, attributeSet);
  304. attributeSet = customShader.usedVariablesFragment.metadataSet;
  305. getVariables(fragmentShaderText, metadataRegex, attributeSet);
  306. const materialRegex = /material\.(\w+)/g;
  307. const materialSet = customShader.usedVariablesFragment.materialSet;
  308. getVariables(fragmentShaderText, materialRegex, materialSet);
  309. }
  310. }
  311. function expandCoordinateAbbreviations(variableName) {
  312. const modelCoordinatesRegex = /^.*MC$/;
  313. const worldCoordinatesRegex = /^.*WC$/;
  314. const eyeCoordinatesRegex = /^.*EC$/;
  315. if (modelCoordinatesRegex.test(variableName)) {
  316. return `${variableName} (model coordinates)`;
  317. }
  318. if (worldCoordinatesRegex.test(variableName)) {
  319. return `${variableName} (Cartesian world coordinates)`;
  320. }
  321. if (eyeCoordinatesRegex.test(variableName)) {
  322. return `${variableName} (eye coordinates)`;
  323. }
  324. return variableName;
  325. }
  326. function validateVariableUsage(
  327. variableSet,
  328. incorrectVariable,
  329. correctVariable,
  330. vertexOrFragment
  331. ) {
  332. if (variableSet.hasOwnProperty(incorrectVariable)) {
  333. const message = `${expandCoordinateAbbreviations(
  334. incorrectVariable
  335. )} is not available in the ${vertexOrFragment} shader. Did you mean ${expandCoordinateAbbreviations(
  336. correctVariable
  337. )} instead?`;
  338. throw new DeveloperError(message);
  339. }
  340. }
  341. function validateBuiltinVariables(customShader) {
  342. const attributesVS = customShader.usedVariablesVertex.attributeSet;
  343. // names without MC/WC/EC are ambiguous
  344. validateVariableUsage(attributesVS, "position", "positionMC", "vertex");
  345. validateVariableUsage(attributesVS, "normal", "normalMC", "vertex");
  346. validateVariableUsage(attributesVS, "tangent", "tangentMC", "vertex");
  347. validateVariableUsage(attributesVS, "bitangent", "bitangentMC", "vertex");
  348. // world and eye coordinate positions are only available in the fragment shader.
  349. validateVariableUsage(attributesVS, "positionWC", "positionMC", "vertex");
  350. validateVariableUsage(attributesVS, "positionEC", "positionMC", "vertex");
  351. // normal, tangent and bitangent are in model coordinates in the vertex shader
  352. validateVariableUsage(attributesVS, "normalEC", "normalMC", "vertex");
  353. validateVariableUsage(attributesVS, "tangentEC", "tangentMC", "vertex");
  354. validateVariableUsage(attributesVS, "bitangentEC", "bitangentMC", "vertex");
  355. const attributesFS = customShader.usedVariablesFragment.attributeSet;
  356. // names without MC/WC/EC are ambiguous
  357. validateVariableUsage(attributesFS, "position", "positionEC", "fragment");
  358. validateVariableUsage(attributesFS, "normal", "normalEC", "fragment");
  359. validateVariableUsage(attributesFS, "tangent", "tangentEC", "fragment");
  360. validateVariableUsage(attributesFS, "bitangent", "bitangentEC", "fragment");
  361. // normal, tangent, and bitangent are in eye coordinates in the fragment
  362. // shader.
  363. validateVariableUsage(attributesFS, "normalMC", "normalEC", "fragment");
  364. validateVariableUsage(attributesFS, "tangentMC", "tangentEC", "fragment");
  365. validateVariableUsage(attributesFS, "bitangentMC", "bitangentEC", "fragment");
  366. }
  367. /**
  368. * Update the value of a uniform declared in the shader
  369. * @param {string} uniformName The GLSL name of the uniform. This must match one of the uniforms declared in the constructor
  370. * @param {boolean|number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|string|Resource} value The new value of the uniform.
  371. */
  372. CustomShader.prototype.setUniform = function (uniformName, value) {
  373. //>>includeStart('debug', pragmas.debug);
  374. Check.typeOf.string("uniformName", uniformName);
  375. Check.defined("value", value);
  376. if (!defined(this.uniforms[uniformName])) {
  377. throw new DeveloperError(
  378. `Uniform ${uniformName} must be declared in the CustomShader constructor.`
  379. );
  380. }
  381. //>>includeEnd('debug');
  382. const uniform = this.uniforms[uniformName];
  383. if (uniform.type === UniformType.SAMPLER_2D) {
  384. // Textures are loaded asynchronously
  385. this._textureManager.loadTexture2D(uniformName, value);
  386. } else if (defined(value.clone)) {
  387. // clone Cartesian and Matrix types.
  388. uniform.value = value.clone(uniform.value);
  389. } else {
  390. uniform.value = value;
  391. }
  392. };
  393. CustomShader.prototype.update = function (frameState) {
  394. this._defaultTexture = frameState.context.defaultTexture;
  395. this._textureManager.update(frameState);
  396. };
  397. /**
  398. * Returns true if this object was destroyed; otherwise, false.
  399. * <br /><br />
  400. * If this object was destroyed, it should not be used; calling any function other than
  401. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  402. *
  403. * @returns {boolean} True if this object was destroyed; otherwise, false.
  404. *
  405. * @see CustomShader#destroy
  406. * @private
  407. */
  408. CustomShader.prototype.isDestroyed = function () {
  409. return false;
  410. };
  411. /**
  412. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  413. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  414. * <br /><br />
  415. * Once an object is destroyed, it should not be used; calling any function other than
  416. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  417. * assign the return value (<code>undefined</code>) to the object as done in the example.
  418. *
  419. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  420. *
  421. * @example
  422. * customShader = customShader && customShader.destroy();
  423. *
  424. * @see CustomShader#isDestroyed
  425. * @private
  426. */
  427. CustomShader.prototype.destroy = function () {
  428. this._textureManager = this._textureManager && this._textureManager.destroy();
  429. destroyObject(this);
  430. };
  431. export default CustomShader;