LightsNode.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import Node from '../core/Node.js';
  2. import LightingNode from './LightingNode.js';
  3. const references = new WeakMap();
  4. const sortLights = ( lights ) => {
  5. return lights.sort( ( a, b ) => a.id - b.id );
  6. };
  7. class LightsNode extends Node {
  8. constructor( lightNodes = [] ) {
  9. super( 'vec3' );
  10. this.lightNodes = lightNodes;
  11. this._hash = null;
  12. }
  13. get hasLight() {
  14. return this.lightNodes.length > 0;
  15. }
  16. construct( builder ) {
  17. const lightNodes = this.lightNodes;
  18. for ( const lightNode of lightNodes ) {
  19. lightNode.build( builder );
  20. }
  21. }
  22. getHash( builder ) {
  23. if ( this._hash === null ) {
  24. let hash = '';
  25. const lightNodes = this.lightNodes;
  26. for ( const lightNode of lightNodes ) {
  27. hash += lightNode.getHash( builder ) + ' ';
  28. }
  29. this._hash = hash;
  30. }
  31. return this._hash;
  32. }
  33. getLightNodeByHash( hash ) {
  34. const lightNodes = this.lightNodes;
  35. for ( const lightNode of lightNodes ) {
  36. if ( lightNode.light.uuid === hash ) {
  37. return lightNode;
  38. }
  39. }
  40. return null;
  41. }
  42. fromLights( lights ) {
  43. const lightNodes = [];
  44. lights = sortLights( lights );
  45. for ( const light of lights ) {
  46. let lightNode = this.getLightNodeByHash( light.uuid );
  47. if ( lightNode === null ) {
  48. const lightClass = light.constructor;
  49. const lightNodeClass = references.has( lightClass ) ? references.get( lightClass ) : LightingNode;
  50. lightNode = new lightNodeClass( light );
  51. }
  52. lightNodes.push( lightNode );
  53. }
  54. this.lightNodes = lightNodes;
  55. this._hash = null;
  56. return this;
  57. }
  58. static setReference( lightClass, lightNodeClass ) {
  59. references.set( lightClass, lightNodeClass );
  60. }
  61. }
  62. export default LightsNode;