ArrayNode.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import TempNode from './TempNode.js';
  2. import { addMethodChaining, nodeObject } from '../tsl/TSLCore.js';
  3. /** @module ArrayNode **/
  4. /**
  5. * ArrayNode represents a collection of nodes, typically created using the {@link module:TSL~array} function.
  6. * ```js
  7. * const colors = array( [
  8. * vec3( 1, 0, 0 ),
  9. * vec3( 0, 1, 0 ),
  10. * vec3( 0, 0, 1 )
  11. * ] );
  12. *
  13. * const redColor = tintColors.element( 0 );
  14. *
  15. * @augments Node
  16. */
  17. class ArrayNode extends TempNode {
  18. static get type() {
  19. return 'ArrayNode';
  20. }
  21. /**
  22. * Constructs a new array node.
  23. *
  24. * @param {String} [nodeType] - The data type of the elements.
  25. * @param {Number} [count] - Size of the array.
  26. * @param {Array<Node>?} [values=null] - Array default values.
  27. */
  28. constructor( nodeType, count, values = null ) {
  29. super( nodeType );
  30. /**
  31. * Array size.
  32. *
  33. * @type {Array<Node>}
  34. */
  35. this.count = count;
  36. /**
  37. * Array default values.
  38. *
  39. * @type {Array<Node>}
  40. */
  41. this.values = values;
  42. /**
  43. * This flag can be used for type testing.
  44. *
  45. * @type {Boolean}
  46. * @readonly
  47. * @default true
  48. */
  49. this.isArrayNode = true;
  50. }
  51. getNodeType( builder ) {
  52. if ( this.nodeType === null ) {
  53. this.nodeType = this.values[ 0 ].getNodeType( builder );
  54. }
  55. return this.nodeType;
  56. }
  57. getElementType( builder ) {
  58. return this.getNodeType( builder );
  59. }
  60. generate( builder ) {
  61. const type = this.getNodeType( builder );
  62. return builder.generateArray( type, this.count, this.values );
  63. }
  64. }
  65. export default ArrayNode;
  66. /**
  67. * TSL function for creating an array node.
  68. *
  69. * @function
  70. * @param {String|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  71. * or an array containing the default values (e.g., [ vec3() ]).
  72. * @param {Number?} [count] - Size of the array.
  73. * @returns {ArrayNode}
  74. */
  75. export const array = ( ...params ) => {
  76. let node;
  77. if ( params.length === 1 ) {
  78. const values = params[ 0 ];
  79. node = new ArrayNode( null, values.length, values );
  80. } else {
  81. const nodeType = params[ 0 ];
  82. const count = params[ 1 ];
  83. node = new ArrayNode( nodeType, count );
  84. }
  85. return nodeObject( node );
  86. };
  87. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
粤ICP备19079148号