| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629 |
- import { GLSLNodeParser, NodeBuilder, TextureNode, vectorComponents, CodeNode } from '../../../nodes/Nodes.js';
- import NodeUniformBuffer from '../../common/nodes/NodeUniformBuffer.js';
- import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
- import { NodeSampledTexture, NodeSampledCubeTexture, NodeSampledTexture3D } from '../../common/nodes/NodeSampledTexture.js';
- import { NoColorSpace, ByteType, ShortType, RGBAIntegerFormat, RGBIntegerFormat, RedIntegerFormat, RGIntegerFormat, UnsignedByteType, UnsignedIntType, UnsignedShortType, RedFormat, RGFormat, IntType, RGBFormat, RGBAFormat, FloatType } from '../../../constants.js';
- import { DataTexture } from '../../../textures/DataTexture.js';
- import { error } from '../../../utils.js';
- const glslPolyfills = {
- bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
- bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
- };
- const glslMethods = {
- textureDimensions: 'textureSize',
- equals: 'equal',
- bitcast_float_int: 'floatBitsToInt',
- bitcast_int_float: 'intBitsToFloat',
- bitcast_uint_float: 'uintBitsToFloat',
- bitcast_float_uint: 'floatBitsToUint',
- bitcast_uint_int: 'tsl_bitcast_uint_to_int',
- bitcast_int_uint: 'tsl_bitcast_int_to_uint',
- floatpack_snorm_2x16: 'packSnorm2x16',
- floatpack_unorm_2x16: 'packUnorm2x16',
- floatpack_float16_2x16: 'packHalf2x16',
- floatunpack_snorm_2x16: 'unpackSnorm2x16',
- floatunpack_unorm_2x16: 'unpackUnorm2x16',
- floatunpack_float16_2x16: 'unpackHalf2x16'
- };
- const precisionLib = {
- low: 'lowp',
- medium: 'mediump',
- high: 'highp'
- };
- const supports = {
- swizzleAssign: true,
- storageBuffer: false
- };
- const interpolationTypeMap = {
- perspective: 'smooth',
- linear: 'noperspective'
- };
- const interpolationModeMap = {
- 'centroid': 'centroid'
- };
- const defaultPrecisions = `
- precision highp float;
- precision highp int;
- precision highp sampler2D;
- precision highp sampler3D;
- precision highp samplerCube;
- precision highp sampler2DArray;
- precision highp usampler2D;
- precision highp usampler3D;
- precision highp usamplerCube;
- precision highp usampler2DArray;
- precision highp isampler2D;
- precision highp isampler3D;
- precision highp isamplerCube;
- precision highp isampler2DArray;
- precision lowp sampler2DShadow;
- precision lowp sampler2DArrayShadow;
- precision lowp samplerCubeShadow;
- `;
- /**
- * A node builder targeting GLSL.
- *
- * This module generates GLSL shader code from node materials and also
- * generates the respective bindings and vertex buffer definitions. These
- * data are later used by the renderer to create render and compute pipelines
- * for render objects.
- *
- * @augments NodeBuilder
- */
- class GLSLNodeBuilder extends NodeBuilder {
- /**
- * Constructs a new GLSL node builder renderer.
- *
- * @param {Object3D} object - The 3D object.
- * @param {Renderer} renderer - The renderer.
- */
- constructor( object, renderer ) {
- super( object, renderer, new GLSLNodeParser() );
- /**
- * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
- * another dictionary which manages UBOs per group ('render','frame','object').
- *
- * @type {Object<string,Object<string,NodeUniformsGroup>>}
- */
- this.uniformGroups = {};
- /**
- * An array that holds objects defining the varying and attribute data in
- * context of Transform Feedback.
- *
- * @type {Array<Object<string,AttributeNode|string>>}
- */
- this.transforms = [];
- /**
- * A dictionary that holds for each shader stage a Map of used extensions.
- *
- * @type {Object<string,Map<string,Object>>}
- */
- this.extensions = {};
- /**
- * A dictionary that holds for each shader stage an Array of used builtins.
- *
- * @type {Object<string,Array<string>>}
- */
- this.builtins = { vertex: [], fragment: [], compute: [] };
- }
- /**
- * Checks if the given texture requires a manual conversion to the working color space.
- *
- * @param {Texture} texture - The texture to check.
- * @return {boolean} Whether the given texture requires a conversion to working color space or not.
- */
- needsToWorkingColorSpace( texture ) {
- return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
- }
- /**
- * Includes the given method name into the current
- * function node.
- *
- * @private
- * @param {string} name - The method name to include.
- * @return {CodeNode} The respective code node.
- */
- _include( name ) {
- const codeNode = glslPolyfills[ name ];
- codeNode.build( this );
- this.addInclude( codeNode );
- return codeNode;
- }
- /**
- * Returns the native shader method name for a given generic name.
- *
- * @param {string} method - The method name to resolve.
- * @return {string} The resolved GLSL method name.
- */
- getMethod( method ) {
- if ( glslPolyfills[ method ] !== undefined ) {
- this._include( method );
- }
- return glslMethods[ method ] || method;
- }
- /**
- * Returns the bitcast method name for a given input and outputType.
- *
- * @param {string} type - The output type to bitcast to.
- * @param {string} inputType - The input type of the.
- * @return {string} The resolved WGSL bitcast invocation.
- */
- getBitcastMethod( type, inputType ) {
- return this.getMethod( `bitcast_${ inputType }_${ type }` );
- }
- /**
- * Returns the float packing method name for a given numeric encoding.
- *
- * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
- * @returns {string} The resolved GLSL float packing method name.
- */
- getFloatPackingMethod( encoding ) {
- return this.getMethod( `floatpack_${ encoding }_2x16` );
- }
- /**
- * Returns the float unpacking method name for a given numeric encoding.
- *
- * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
- * @returns {string} The resolved GLSL float unpacking method name.
- */
- getFloatUnpackingMethod( encoding ) {
- return this.getMethod( `floatunpack_${ encoding }_2x16` );
- }
- /**
- * Returns the native snippet for a ternary operation.
- *
- * @param {string} condSnippet - The condition determining which expression gets resolved.
- * @param {string} ifSnippet - The expression to resolve to if the condition is true.
- * @param {string} elseSnippet - The expression to resolve to if the condition is false.
- * @return {string} The resolved method name.
- */
- getTernary( condSnippet, ifSnippet, elseSnippet ) {
- return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
- }
- /**
- * Returns the output struct name. Not relevant for GLSL.
- *
- * @return {string}
- */
- getOutputStructName() {
- return '';
- }
- /**
- * Builds the given shader node.
- *
- * @param {ShaderNodeInternal} shaderNode - The shader node.
- * @return {string} The GLSL function code.
- */
- buildFunctionCode( shaderNode ) {
- const layout = shaderNode.layout;
- const flowData = this.flowShaderNode( shaderNode );
- const parameters = [];
- for ( const input of layout.inputs ) {
- parameters.push( this.getType( input.type ) + ' ' + input.name );
- }
- //
- const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
- ${ flowData.vars }
- ${ flowData.code }
- return ${ flowData.result };
- }`;
- //
- return code;
- }
- /**
- * Setups the Pixel Buffer Object (PBO) for the given storage
- * buffer node.
- *
- * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
- */
- setupPBO( storageBufferNode ) {
- const attribute = storageBufferNode.value;
- if ( attribute.pbo === undefined ) {
- const originalArray = attribute.array;
- const numElements = attribute.count * attribute.itemSize;
- const { itemSize } = attribute;
- const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
- let format = isInteger ? RedIntegerFormat : RedFormat;
- if ( itemSize === 2 ) {
- format = isInteger ? RGIntegerFormat : RGFormat;
- } else if ( itemSize === 3 ) {
- format = isInteger ? RGBIntegerFormat : RGBFormat;
- } else if ( itemSize === 4 ) {
- format = isInteger ? RGBAIntegerFormat : RGBAFormat;
- }
- const typeMap = {
- Float32Array: FloatType,
- Uint8Array: UnsignedByteType,
- Uint16Array: UnsignedShortType,
- Uint32Array: UnsignedIntType,
- Int8Array: ByteType,
- Int16Array: ShortType,
- Int32Array: IntType,
- Uint8ClampedArray: UnsignedByteType,
- };
- const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
- let height = Math.ceil( ( numElements / itemSize ) / width );
- if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
- const newSize = width * height * itemSize;
- const newArray = new originalArray.constructor( newSize );
- newArray.set( originalArray, 0 );
- attribute.array = newArray;
- const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
- pboTexture.needsUpdate = true;
- pboTexture.isPBOTexture = true;
- const pbo = new TextureNode( pboTexture, null, null );
- pbo.setPrecision( 'high' );
- attribute.pboNode = pbo;
- attribute.pbo = pbo.value;
- this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
- }
- }
- /**
- * Returns a GLSL snippet that represents the property name of the given node.
- *
- * @param {Node} node - The node.
- * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
- * @return {string} The property name.
- */
- getPropertyName( node, shaderStage = this.shaderStage ) {
- if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
- return shaderStage.charAt( 0 ) + '_' + node.name;
- }
- return super.getPropertyName( node, shaderStage );
- }
- /**
- * Setups the Pixel Buffer Object (PBO) for the given storage
- * buffer node.
- *
- * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
- * @return {string} The property name.
- */
- generatePBO( storageArrayElementNode ) {
- const { node, indexNode } = storageArrayElementNode;
- const attribute = node.value;
- if ( this.renderer.backend.has( attribute ) ) {
- const attributeData = this.renderer.backend.get( attribute );
- attributeData.pbo = attribute.pbo;
- }
- const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
- const textureName = this.getPropertyName( nodeUniform );
- this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
- const indexSnippet = indexNode.build( this, 'uint' );
- const elementNodeData = this.getDataFromNode( storageArrayElementNode );
- let propertyName = elementNodeData.propertyName;
- if ( propertyName === undefined ) {
- // property element
- const nodeVar = this.getVarFromNode( storageArrayElementNode );
- propertyName = this.getPropertyName( nodeVar );
- // property size
- const bufferNodeData = this.getDataFromNode( node );
- let propertySizeName = bufferNodeData.propertySizeName;
- if ( propertySizeName === undefined ) {
- propertySizeName = propertyName + 'Size';
- this.getVarFromNode( node, propertySizeName, 'uint' );
- this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
- bufferNodeData.propertySizeName = propertySizeName;
- }
- //
- const { itemSize } = attribute;
- const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
- const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
- const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
- //
- let prefix = 'vec4';
- if ( attribute.pbo.type === UnsignedIntType ) {
- prefix = 'uvec4';
- } else if ( attribute.pbo.type === IntType ) {
- prefix = 'ivec4';
- }
- this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
- elementNodeData.propertyName = propertyName;
- }
- return propertyName;
- }
- /**
- * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
- *
- * @param {?Texture} texture - The texture.
- * @param {string} textureProperty - The name of the texture uniform in the shader.
- * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
- * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
- * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
- * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
- * @return {string} The GLSL snippet.
- */
- generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
- if ( levelSnippet === null ) levelSnippet = '0';
- let snippet;
- if ( depthSnippet ) {
- if ( offsetSnippet ) {
- snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
- } else {
- snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
- }
- } else {
- if ( offsetSnippet ) {
- snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
- } else {
- snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
- }
- }
- if ( texture !== null && texture.isDepthTexture ) {
- snippet += '.x';
- }
- return snippet;
- }
- /**
- * Generates the GLSL snippet for sampling/loading the given texture.
- *
- * @param {Texture} texture - The texture.
- * @param {string} textureProperty - The name of the texture uniform in the shader.
- * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
- * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
- * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
- * @return {string} The GLSL snippet.
- */
- generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
- if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
- if ( texture.isDepthTexture ) {
- if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
- return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
- }
- if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
- return `texture( ${ textureProperty }, ${ uvSnippet } )`;
- }
- /**
- * Generates the GLSL snippet when sampling textures with explicit mip level.
- *
- * @param {Texture} texture - The texture.
- * @param {string} textureProperty - The name of the texture uniform in the shader.
- * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
- * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
- * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
- * @return {string} The GLSL snippet.
- */
- generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
- if ( offsetSnippet ) {
- return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
- }
- return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
- }
- /**
- * Generates the GLSL snippet when sampling textures with a bias to the mip level.
- *
- * @param {Texture} texture - The texture.
- * @param {string} textureProperty - The name of the texture uniform in the shader.
- * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
- * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
- * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
- * @return {string} The GLSL snippet.
- */
- generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
- if ( offsetSnippet ) {
- return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
- }
- return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
- }
- /**
- * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
- *
- * @param {Texture} texture - The texture.
- * @param {string} textureProperty - The name of the texture uniform in the shader.
- * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
- * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
- * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
- * @return {string} The GLSL snippet.
- */
- generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
- if ( offsetSnippet ) {
- return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
- }
- return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
- }
- /**
- * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
- * against a reference value.
- *
- * @param {Texture} texture - The texture.
- * @param {string} textureProperty - The name of the texture uniform in the shader.
- * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
- * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
- * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
- * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
- * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
- * @return {string} The GLSL snippet.
- */
- generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
- if ( shaderStage === 'fragment' ) {
- // Cube shadow maps use vec4(direction, compareValue)
- if ( texture.isCubeTexture ) {
- return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
- }
- if ( depthSnippet ) {
- if ( offsetSnippet ) {
- return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
- }
- return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
- }
- if ( offsetSnippet ) {
- return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
- }
- return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
- } else {
- error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
- }
- }
- /**
- * Returns the variables of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the variables.
- */
- getVars( shaderStage ) {
- const snippets = [];
- const vars = this.vars[ shaderStage ];
- if ( vars !== undefined ) {
- for ( const variable of vars ) {
- snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
- }
- }
- return snippets.join( '\n\t' );
- }
- /**
- * Returns the uniforms of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the uniforms.
- */
- getUniforms( shaderStage ) {
- const uniforms = this.uniforms[ shaderStage ];
- const bindingSnippets = [];
- const uniformGroups = {};
- for ( const uniform of uniforms ) {
- let snippet = null;
- let group = false;
- if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
- const texture = uniform.node.value;
- let typePrefix = '';
- if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
- if ( texture.type === UnsignedIntType ) {
- typePrefix = 'u';
- } else if ( texture.type === IntType ) {
- typePrefix = 'i';
- }
- }
- if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
- snippet = `${typePrefix}sampler3D ${ uniform.name };`;
- } else if ( texture.compareFunction ) {
- if ( texture.isArrayTexture === true ) {
- snippet = `sampler2DArrayShadow ${ uniform.name };`;
- } else {
- snippet = `sampler2DShadow ${ uniform.name };`;
- }
- } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
- snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
- } else {
- snippet = `${typePrefix}sampler2D ${ uniform.name };`;
- }
- } else if ( uniform.type === 'cubeTexture' ) {
- snippet = `samplerCube ${ uniform.name };`;
- } else if ( uniform.type === 'cubeDepthTexture' ) {
- snippet = `samplerCubeShadow ${ uniform.name };`;
- } else if ( uniform.type === 'buffer' ) {
- const bufferNode = uniform.node;
- const bufferType = this.getType( bufferNode.bufferType );
- const bufferCount = bufferNode.bufferCount;
- const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
- snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
- } else {
- const vectorType = this.getVectorType( uniform.type );
- snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
- group = true;
- }
- const precision = uniform.node.precision;
- if ( precision !== null ) {
- snippet = precisionLib[ precision ] + ' ' + snippet;
- }
- if ( group ) {
- snippet = '\t' + snippet;
- const groupName = uniform.groupNode.name;
- const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
- groupSnippets.push( snippet );
- } else {
- snippet = 'uniform ' + snippet;
- bindingSnippets.push( snippet );
- }
- }
- let output = '';
- for ( const name in uniformGroups ) {
- const groupSnippets = uniformGroups[ name ];
- output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
- }
- output += bindingSnippets.join( '\n' );
- return output;
- }
- /**
- * Returns the type for a given buffer attribute.
- *
- * @param {BufferAttribute} attribute - The buffer attribute.
- * @return {string} The type.
- */
- getTypeFromAttribute( attribute ) {
- let nodeType = super.getTypeFromAttribute( attribute );
- if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
- let dataAttribute = attribute;
- if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
- const array = dataAttribute.array;
- if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
- nodeType = nodeType.slice( 1 );
- }
- }
- return nodeType;
- }
- /**
- * Returns the shader attributes of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the shader attributes.
- */
- getAttributes( shaderStage ) {
- let snippet = '';
- if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
- const attributes = this.getAttributesArray();
- let location = 0;
- for ( const attribute of attributes ) {
- snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
- }
- }
- return snippet;
- }
- /**
- * Returns the members of the given struct type node as a GLSL string.
- *
- * @param {StructTypeNode} struct - The struct type node.
- * @return {string} The GLSL snippet that defines the struct members.
- */
- getStructMembers( struct ) {
- const snippets = [];
- for ( const member of struct.members ) {
- snippets.push( `\t${ member.type } ${ member.name };` );
- }
- return snippets.join( '\n' );
- }
- /**
- * Returns the structs of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the structs.
- */
- getStructs( shaderStage ) {
- const snippets = [];
- const structs = this.structs[ shaderStage ];
- const outputSnippet = [];
- for ( const struct of structs ) {
- if ( struct.output ) {
- for ( const member of struct.members ) {
- outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
- }
- } else {
- let snippet = 'struct ' + struct.name + ' {\n';
- snippet += this.getStructMembers( struct );
- snippet += '\n};\n';
- snippets.push( snippet );
- }
- }
- if ( outputSnippet.length === 0 ) {
- outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
- }
- return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
- }
- /**
- * Returns the varyings of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the varyings.
- */
- getVaryings( shaderStage ) {
- let snippet = '';
- const varyings = this.varyings;
- if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
- for ( const varying of varyings ) {
- if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
- const type = this.getType( varying.type );
- if ( varying.needsInterpolation ) {
- if ( varying.interpolationType ) {
- const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
- const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
- snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
- } else {
- const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
- snippet += `${ flat }out ${ type } ${ varying.name };\n`;
- }
- } else {
- snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
- }
- }
- } else if ( shaderStage === 'fragment' ) {
- for ( const varying of varyings ) {
- if ( varying.needsInterpolation ) {
- const type = this.getType( varying.type );
- if ( varying.interpolationType ) {
- const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
- const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
- snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
- } else {
- const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
- snippet += `${ flat }in ${ type } ${ varying.name };\n`;
- }
- }
- }
- }
- for ( const builtin of this.builtins[ shaderStage ] ) {
- snippet += `${builtin};\n`;
- }
- return snippet;
- }
- /**
- * Returns the vertex index builtin.
- *
- * @return {string} The vertex index.
- */
- getVertexIndex() {
- return 'uint( gl_VertexID )';
- }
- /**
- * Contextually returns either the vertex stage instance index builtin
- * or the linearized index of an compute invocation within a grid of workgroups.
- *
- * @return {string} The instance index.
- */
- getInstanceIndex() {
- return 'uint( gl_InstanceID )';
- }
- /**
- * Returns a builtin representing the index of an invocation within its workgroup.
- *
- * @return {string} The invocation local index.
- */
- getInvocationLocalIndex() {
- const workgroupSize = this.object.workgroupSize;
- const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
- return `uint( gl_InstanceID ) % ${size}u`;
- }
- /**
- * Returns a builtin representing the size of a subgroup within the current shader.
- */
- getSubgroupSize() {
- error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
- }
- /**
- * Returns a builtin representing the index of an invocation within its subgroup.
- */
- getInvocationSubgroupIndex() {
- error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
- }
- /**
- * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
- */
- getSubgroupIndex() {
- error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
- }
- /**
- * Returns the draw index builtin.
- *
- * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
- */
- getDrawIndex() {
- const extensions = this.renderer.backend.extensions;
- if ( extensions.has( 'WEBGL_multi_draw' ) ) {
- return 'uint( gl_DrawID )';
- }
- return null;
- }
- /**
- * Returns the front facing builtin.
- *
- * @return {string} The front facing builtin.
- */
- getFrontFacing() {
- return 'gl_FrontFacing';
- }
- /**
- * Returns the frag coord builtin.
- *
- * @return {string} The frag coord builtin.
- */
- getFragCoord() {
- return 'gl_FragCoord.xy';
- }
- /**
- * Returns the frag depth builtin.
- *
- * @return {string} The frag depth builtin.
- */
- getFragDepth() {
- return 'gl_FragDepth';
- }
- /**
- * Enables the given extension.
- *
- * @param {string} name - The extension name.
- * @param {string} behavior - The extension behavior.
- * @param {string} [shaderStage=this.shaderStage] - The shader stage.
- */
- enableExtension( name, behavior, shaderStage = this.shaderStage ) {
- const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
- if ( map.has( name ) === false ) {
- map.set( name, {
- name,
- behavior
- } );
- }
- }
- /**
- * Returns the enabled extensions of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the enabled extensions.
- */
- getExtensions( shaderStage ) {
- const snippets = [];
- if ( shaderStage === 'vertex' ) {
- const ext = this.renderer.backend.extensions;
- const isBatchedMesh = this.object.isBatchedMesh;
- if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
- this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
- }
- }
- const extensions = this.extensions[ shaderStage ];
- if ( extensions !== undefined ) {
- for ( const { name, behavior } of extensions.values() ) {
- snippets.push( `#extension ${name} : ${behavior}` );
- }
- }
- return snippets.join( '\n' );
- }
- /**
- * Returns the clip distances builtin.
- *
- * @return {string} The clip distances builtin.
- */
- getClipDistance() {
- return 'gl_ClipDistance';
- }
- /**
- * Whether the requested feature is available or not.
- *
- * @param {string} name - The requested feature.
- * @return {boolean} Whether the requested feature is supported or not.
- */
- isAvailable( name ) {
- let result = supports[ name ];
- if ( result === undefined ) {
- let extensionName;
- result = false;
- switch ( name ) {
- case 'float32Filterable':
- extensionName = 'OES_texture_float_linear';
- break;
- case 'clipDistance':
- extensionName = 'WEBGL_clip_cull_distance';
- break;
- }
- if ( extensionName !== undefined ) {
- const extensions = this.renderer.backend.extensions;
- if ( extensions.has( extensionName ) ) {
- extensions.get( extensionName );
- result = true;
- }
- }
- supports[ name ] = result;
- }
- return result;
- }
- /**
- * Whether to flip texture data along its vertical axis or not.
- *
- * @return {boolean} Returns always `true` in context of GLSL.
- */
- isFlipY() {
- return true;
- }
- /**
- * Enables hardware clipping.
- *
- * @param {string} planeCount - The clipping plane count.
- */
- enableHardwareClipping( planeCount ) {
- this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
- this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
- }
- /**
- * Enables multiview.
- */
- enableMultiview() {
- this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
- this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
- this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
- }
- /**
- * Registers a transform in context of Transform Feedback.
- *
- * @param {string} varyingName - The varying name.
- * @param {AttributeNode} attributeNode - The attribute node.
- */
- registerTransform( varyingName, attributeNode ) {
- this.transforms.push( { varyingName, attributeNode } );
- }
- /**
- * Returns the transforms of the given shader stage as a GLSL string.
- *
- * @param {string} shaderStage - The shader stage.
- * @return {string} The GLSL snippet that defines the transforms.
- */
- getTransforms( /* shaderStage */ ) {
- const transforms = this.transforms;
- let snippet = '';
- for ( let i = 0; i < transforms.length; i ++ ) {
- const transform = transforms[ i ];
- const attributeName = this.getPropertyName( transform.attributeNode );
- if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
- }
- return snippet;
- }
- /**
- * Returns a GLSL struct based on the given name and variables.
- *
- * @private
- * @param {string} name - The struct name.
- * @param {string} vars - The struct variables.
- * @return {string} The GLSL snippet representing a struct.
- */
- _getGLSLUniformStruct( name, vars ) {
- return `
- layout( std140 ) uniform ${name} {
- ${vars}
- };`;
- }
- /**
- * Returns a GLSL vertex shader based on the given shader data.
- *
- * @private
- * @param {Object} shaderData - The shader data.
- * @return {string} The vertex shader.
- */
- _getGLSLVertexCode( shaderData ) {
- return `#version 300 es
- ${ this.getSignature() }
- // extensions
- ${shaderData.extensions}
- // precision
- ${ defaultPrecisions }
- // uniforms
- ${shaderData.uniforms}
- // varyings
- ${shaderData.varyings}
- // attributes
- ${shaderData.attributes}
- // codes
- ${shaderData.codes}
- void main() {
- // vars
- ${shaderData.vars}
- // transforms
- ${shaderData.transforms}
- // flow
- ${shaderData.flow}
- gl_PointSize = 1.0;
- }
- `;
- }
- /**
- * Returns a GLSL fragment shader based on the given shader data.
- *
- * @private
- * @param {Object} shaderData - The shader data.
- * @return {string} The vertex shader.
- */
- _getGLSLFragmentCode( shaderData ) {
- return `#version 300 es
- ${ this.getSignature() }
- // extensions
- ${shaderData.extensions}
- // precision
- ${ defaultPrecisions }
- // structs
- ${shaderData.structs}
- // uniforms
- ${shaderData.uniforms}
- // varyings
- ${shaderData.varyings}
- // codes
- ${shaderData.codes}
- void main() {
- // vars
- ${shaderData.vars}
- // flow
- ${shaderData.flow}
- }
- `;
- }
- /**
- * Controls the code build of the shader stages.
- */
- buildCode() {
- const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
- this.sortBindingGroups();
- for ( const shaderStage in shadersData ) {
- let flow = '// code\n\n';
- flow += this.flowCode[ shaderStage ];
- const flowNodes = this.flowNodes[ shaderStage ];
- const mainNode = flowNodes[ flowNodes.length - 1 ];
- for ( const node of flowNodes ) {
- const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
- const slotName = node.name;
- if ( slotName ) {
- if ( flow.length > 0 ) flow += '\n';
- flow += `\t// flow -> ${ slotName }\n\t`;
- }
- flow += `${ flowSlotData.code }\n\t`;
- if ( node === mainNode && shaderStage !== 'compute' ) {
- flow += '// result\n\t';
- if ( shaderStage === 'vertex' ) {
- flow += 'gl_Position = ';
- flow += `${ flowSlotData.result };`;
- } else if ( shaderStage === 'fragment' ) {
- if ( ! node.outputNode.isOutputStructNode ) {
- flow += 'fragColor = ';
- flow += `${ flowSlotData.result };`;
- }
- }
- }
- }
- const stageData = shadersData[ shaderStage ];
- stageData.extensions = this.getExtensions( shaderStage );
- stageData.uniforms = this.getUniforms( shaderStage );
- stageData.attributes = this.getAttributes( shaderStage );
- stageData.varyings = this.getVaryings( shaderStage );
- stageData.vars = this.getVars( shaderStage );
- stageData.structs = this.getStructs( shaderStage );
- stageData.codes = this.getCodes( shaderStage );
- stageData.transforms = this.getTransforms( shaderStage );
- stageData.flow = flow;
- }
- if ( this.material !== null ) {
- this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
- this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
- } else {
- this.computeShader = this._getGLSLVertexCode( shadersData.compute );
- }
- }
- /**
- * This method is one of the more important ones since it's responsible
- * for generating a matching binding instance for the given uniform node.
- *
- * These bindings are later used in the renderer to create bind groups
- * and layouts.
- *
- * @param {UniformNode} node - The uniform node.
- * @param {string} type - The node data type.
- * @param {string} shaderStage - The shader stage.
- * @param {?string} [name=null] - An optional uniform name.
- * @return {NodeUniform} The node uniform object.
- */
- getUniformFromNode( node, type, shaderStage, name = null ) {
- const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
- const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
- let uniformGPU = nodeData.uniformGPU;
- if ( uniformGPU === undefined ) {
- const group = node.groupNode;
- const groupName = group.name;
- const bindings = this.getBindGroupArray( groupName, shaderStage );
- if ( type === 'texture' ) {
- uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
- bindings.push( uniformGPU );
- } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
- uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
- bindings.push( uniformGPU );
- } else if ( type === 'texture3D' ) {
- uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
- bindings.push( uniformGPU );
- } else if ( type === 'buffer' ) {
- uniformNode.name = `buffer${ node.id }`;
- const sharedData = this.getSharedDataFromNode( node );
- let buffer = sharedData.buffer;
- if ( buffer === undefined ) {
- node.name = `NodeBuffer_${ node.id }`;
- buffer = new NodeUniformBuffer( node, group );
- buffer.name = node.name;
- sharedData.buffer = buffer;
- }
- bindings.push( buffer );
- uniformGPU = buffer;
- } else {
- const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
- let uniformsGroup = uniformsStage[ groupName ];
- if ( uniformsGroup === undefined ) {
- uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
- //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
- uniformsStage[ groupName ] = uniformsGroup;
- bindings.push( uniformsGroup );
- }
- uniformGPU = this.getNodeUniform( uniformNode, type );
- uniformsGroup.addUniform( uniformGPU );
- }
- nodeData.uniformGPU = uniformGPU;
- }
- return uniformNode;
- }
- }
- export default GLSLNodeBuilder;
|