TSLGraphLoader.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import { FileLoader, error } from 'three';
  2. import * as THREE from 'three';
  3. import * as TSL from 'three/tsl';
  4. const _library = {
  5. 'three/tsl': { ...TSL }
  6. };
  7. const STORAGE_PREFIX = 'tsl-graph';
  8. const STORAGE_CODE = 'tsl-graph-code';
  9. function _storageKey( graphId ) {
  10. return `${STORAGE_PREFIX}:${graphId}`;
  11. }
  12. class TSLGraphLoaderApplier {
  13. constructor( tslGraphFns ) {
  14. this.tslGraphFns = tslGraphFns;
  15. }
  16. apply( scene ) {
  17. const tslGraphFns = this.tslGraphFns;
  18. scene.traverse( ( object ) => {
  19. if ( object.material && object.material.userData.graphId ) {
  20. if ( tslGraphFns[ object.material.userData.graphId ] ) {
  21. tslGraphFns[ object.material.userData.graphId ]( object.material );
  22. object.material.needsUpdate = true;
  23. }
  24. }
  25. } );
  26. }
  27. }
  28. export class TSLGraphLoader extends FileLoader {
  29. constructor( manager ) {
  30. super( manager );
  31. }
  32. load( url, onLoad, onProgress, onError ) {
  33. super.load( url, ( text ) => {
  34. let json;
  35. try {
  36. json = JSON.parse( text );
  37. } catch ( e ) {
  38. if ( onError ) onError( e );
  39. return;
  40. }
  41. const applier = this.parse( json );
  42. if ( onLoad ) onLoad( applier );
  43. }, onProgress, onError );
  44. }
  45. parseMaterial( json ) {
  46. const baseFn = 'tslGraph';
  47. const imports = {};
  48. const materials = [ this._generateMaterialCode( json, baseFn, imports ) ];
  49. const code = this._generateCode( materials, imports );
  50. const tslFunction = new Function( code )()( THREE, imports );
  51. return tslFunction;
  52. }
  53. parseMaterials( json ) {
  54. const imports = {};
  55. const materials = [];
  56. for ( const [ name, material ] of Object.entries( json ) ) {
  57. materials.push( this._generateMaterialCode( material, name, imports ) );
  58. }
  59. const code = this._generateCode( materials, imports );
  60. const tslFunction = new Function( code )()( THREE, imports );
  61. return tslFunction;
  62. }
  63. parse( json ) {
  64. let result;
  65. if ( json.material && json.material.code ) {
  66. result = this.parseMaterial( json.material );
  67. } else if ( json.materials ) {
  68. result = this.parseMaterials( json.materials );
  69. } else if ( json.codes && json.graphs ) {
  70. result = this.parseMaterials( json.codes.materials );
  71. TSLGraphLoader.setGraphs( json );
  72. }
  73. return new TSLGraphLoaderApplier( result );
  74. }
  75. _generateMaterialCode( json, name = 'tslGraph', imports = {} ) {
  76. const code = json.code.replace( 'function tslGraph', `materials[ '${ name }' ] = function` ).replace( /\n|^/g, '\n\t' );
  77. for ( const importData of json.imports ) {
  78. if ( _library[ importData.from ] ) {
  79. for ( const importName of importData.imports ) {
  80. if ( _library[ importData.from ][ importName ] ) {
  81. imports[ importName ] = _library[ importData.from ][ importName ];
  82. } else {
  83. error( `TSLGraph: Import ${ importName } not found in ${ importData.from }.` );
  84. }
  85. }
  86. } else {
  87. error( `TSLGraph: Library ${ importData.from } not found.` );
  88. }
  89. }
  90. return code;
  91. }
  92. _generateCode( materials, imports ) {
  93. const fnCode = `return ( THREE, { ${ Object.keys( imports ).join( ', ' ) } } ) => {\n\n\tconst materials = {};\n${ materials.join( '\n' ) }\n\n\treturn materials;\n\n}`;
  94. return fnCode;
  95. }
  96. static get hasGraphs() {
  97. return Object.keys( TSLGraphLoader.getCodes().materials ).length > 0;
  98. }
  99. static getCodes() {
  100. const code = window.localStorage.getItem( STORAGE_CODE );
  101. return code ? JSON.parse( code ) : { materials: {} };
  102. }
  103. static setCodes( codes ) {
  104. window.localStorage.setItem( STORAGE_CODE, JSON.stringify( codes ) );
  105. }
  106. static setGraph( graphId, graphData ) {
  107. window.localStorage.setItem( _storageKey( graphId ), JSON.stringify( graphData ) );
  108. }
  109. static getGraph( graphId ) {
  110. const raw = window.localStorage.getItem( _storageKey( graphId ) );
  111. if ( ! raw ) return null;
  112. try {
  113. return JSON.parse( raw );
  114. } catch ( e ) {
  115. error( 'TSLGraph: Invalid graph JSON in localStorage, ignoring.', e );
  116. return null;
  117. }
  118. }
  119. static deleteGraph( graphId ) {
  120. window.localStorage.removeItem( _storageKey( graphId ) );
  121. }
  122. static setGraphs( json ) {
  123. if ( ! json.codes || ! json.graphs ) {
  124. throw new Error( 'TSLGraph: Invalid import file structure.' );
  125. }
  126. TSLGraphLoader.clearGraphs();
  127. // Save imported graph visualizations
  128. for ( const [ id, graphData ] of Object.entries( json.graphs ) ) {
  129. TSLGraphLoader.setGraph( id, graphData );
  130. }
  131. // Fully overwrite codes
  132. TSLGraphLoader.setCodes( json.codes );
  133. return json;
  134. }
  135. static clearGraphs() {
  136. const keysToRemove = [];
  137. for ( let i = 0; i < window.localStorage.length; i ++ ) {
  138. const key = window.localStorage.key( i );
  139. if ( key.startsWith( STORAGE_PREFIX ) ) {
  140. keysToRemove.push( key );
  141. }
  142. }
  143. for ( const key of keysToRemove ) {
  144. window.localStorage.removeItem( key );
  145. }
  146. }
  147. }
粤ICP备19079148号