ShaderStruct.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * A utility for dynamically-generating a GLSL struct.
  3. *
  4. * @alias ShaderStruct
  5. * @constructor
  6. *
  7. * @see {@link ShaderBuilder}
  8. * @param {string} name The name of the struct as it will appear in the shader.
  9. * @example
  10. * // Generate the struct:
  11. * //
  12. * // struct Attributes
  13. * // {
  14. * // vec3 position;
  15. * // vec3 normal;
  16. * // vec2 texCoord;
  17. * // };
  18. * const struct = new ShaderStruct("Attributes");
  19. * struct.addField("vec3", "position");
  20. * struct.addField("vec3", "normal");
  21. * struct.addField("vec2", "texCoord");
  22. * const generatedLines = struct.generateGlslLines();
  23. *
  24. * @private
  25. */
  26. function ShaderStruct(name) {
  27. this.name = name;
  28. this.fields = [];
  29. }
  30. /**
  31. * Add a field to the struct
  32. * @param {string} type The type of the struct field
  33. * @param {string} identifier The identifier of the struct field
  34. */
  35. ShaderStruct.prototype.addField = function (type, identifier) {
  36. const field = ` ${type} ${identifier};`;
  37. this.fields.push(field);
  38. };
  39. /**
  40. * Generate a list of lines of GLSL code for use with {@link ShaderBuilder}
  41. * @return {string[]} The generated GLSL code.
  42. */
  43. ShaderStruct.prototype.generateGlslLines = function () {
  44. let fields = this.fields;
  45. if (fields.length === 0) {
  46. // GLSL requires structs to have at least one field
  47. fields = [" float _empty;"];
  48. }
  49. return [].concat(`struct ${this.name}`, "{", fields, "};");
  50. };
  51. export default ShaderStruct;