ShaderFunction.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import DeveloperError from "../Core/DeveloperError.js";
  2. /**
  3. * A utility for dynamically-generating a GLSL function
  4. *
  5. * @alias ShaderFunction
  6. * @constructor
  7. *
  8. * @see {@link ShaderBuilder}
  9. * @param {string} signature The full signature of the function as it will appear in the shader. Do not include the curly braces.
  10. * @example
  11. * // generate the following function
  12. * //
  13. * // void assignVaryings(vec3 position)
  14. * // {
  15. * // v_positionEC = (czm_modelView * vec4(a_position, 1.0)).xyz;
  16. * // v_texCoord = a_texCoord;
  17. * // }
  18. * const signature = "void assignVaryings(vec3 position)";
  19. * const func = new ShaderFunction(signature);
  20. * func.addLine("v_positionEC = (czm_modelView * vec4(a_position, 1.0)).xyz;");
  21. * func.addLine("v_texCoord = a_texCoord;");
  22. * const generatedLines = func.generateGlslLines();
  23. *
  24. * @private
  25. */
  26. function ShaderFunction(signature) {
  27. this.signature = signature;
  28. this.body = [];
  29. }
  30. /**
  31. * Adds one or more lines to the body of the function
  32. * @param {string|string[]} lines One or more lines of GLSL code to add to the function body. Do not include any preceding or ending whitespace, but do include the semicolon for each line.
  33. */
  34. ShaderFunction.prototype.addLines = function (lines) {
  35. //>>includeStart('debug', pragmas.debug);
  36. if (typeof lines !== "string" && !Array.isArray(lines)) {
  37. throw new DeveloperError(
  38. `Expected lines to be a string or an array of strings, actual value was ${lines}`
  39. );
  40. }
  41. //>>includeEnd('debug');
  42. const body = this.body;
  43. // Indent the body of the function by 4 spaces
  44. if (Array.isArray(lines)) {
  45. const length = lines.length;
  46. for (let i = 0; i < length; i++) {
  47. body.push(` ${lines[i]}`);
  48. }
  49. } else {
  50. // Single string case
  51. body.push(` ${lines}`);
  52. }
  53. };
  54. /**
  55. * Generate lines of GLSL code for use with {@link ShaderBuilder}
  56. * @return {string[]}
  57. */
  58. ShaderFunction.prototype.generateGlslLines = function () {
  59. return [].concat(this.signature, "{", this.body, "}");
  60. };
  61. export default ShaderFunction;