Renderer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. import Animation from './Animation.js';
  2. import RenderObjects from './RenderObjects.js';
  3. import Attributes from './Attributes.js';
  4. import Geometries from './Geometries.js';
  5. import Info from './Info.js';
  6. import Pipelines from './Pipelines.js';
  7. import Bindings from './Bindings.js';
  8. import RenderLists from './RenderLists.js';
  9. import RenderContexts from './RenderContexts.js';
  10. import Textures from './Textures.js';
  11. import Background from './Background.js';
  12. import Nodes from './nodes/Nodes.js';
  13. import { Scene, Frustum, Matrix4, Vector2, Vector3, Vector4, Color, DoubleSide, BackSide, FrontSide, SRGBColorSpace, NoToneMapping } from 'three';
  14. const _scene = new Scene();
  15. const _drawingBufferSize = new Vector2();
  16. const _screen = new Vector4();
  17. const _frustum = new Frustum();
  18. const _projScreenMatrix = new Matrix4();
  19. const _vector3 = new Vector3();
  20. class Renderer {
  21. constructor( backend ) {
  22. this.isRenderer = true;
  23. // public
  24. this.domElement = backend.getDomElement();
  25. this.backend = backend;
  26. this.autoClear = true;
  27. this.autoClearColor = true;
  28. this.autoClearDepth = true;
  29. this.autoClearStencil = true;
  30. this.outputColorSpace = SRGBColorSpace;
  31. this.toneMapping = NoToneMapping;
  32. this.toneMappingExposure = 1.0;
  33. this.sortObjects = true;
  34. this.depth = true;
  35. this.stencil = true;
  36. // internals
  37. this._pixelRatio = 1;
  38. this._width = this.domElement.width;
  39. this._height = this.domElement.height;
  40. this._viewport = new Vector4( 0, 0, this._width, this._height );
  41. this._scissor = new Vector4( 0, 0, this._width, this._height );
  42. this._scissorTest = false;
  43. this._info = null;
  44. this._properties = null;
  45. this._attributes = null;
  46. this._geometries = null;
  47. this._nodes = null;
  48. this._bindings = null;
  49. this._objects = null;
  50. this._pipelines = null;
  51. this._renderLists = null;
  52. this._renderContexts = null;
  53. this._textures = null;
  54. this._background = null;
  55. this._animation = new Animation();
  56. this._currentRenderContext = null;
  57. this._lastRenderContext = null;
  58. this._opaqueSort = null;
  59. this._transparentSort = null;
  60. this._clearAlpha = 1;
  61. this._clearColor = new Color( 0x000000 );
  62. this._clearDepth = 1;
  63. this._clearStencil = 0;
  64. this._renderTarget = null;
  65. this._currentActiveCubeFace = 0;
  66. this._initialized = false;
  67. this._initPromise = null;
  68. // backwards compatibility
  69. this.shadowMap = {
  70. enabled: false,
  71. type: null
  72. };
  73. this.xr = {
  74. enabled: false
  75. };
  76. }
  77. async init() {
  78. if ( this._initialized ) {
  79. throw new Error( 'Renderer: Backend has already been initialized.' );
  80. }
  81. if ( this._initPromise !== null ) {
  82. return this._initPromise;
  83. }
  84. this._initPromise = new Promise( async ( resolve, reject ) => {
  85. const backend = this.backend;
  86. try {
  87. await backend.init( this );
  88. } catch ( error ) {
  89. reject( error );
  90. return;
  91. }
  92. this._info = new Info();
  93. this._nodes = new Nodes( this, backend );
  94. this._attributes = new Attributes( backend );
  95. this._background = new Background( this, this._nodes );
  96. this._geometries = new Geometries( this._attributes, this._info );
  97. this._textures = new Textures( backend, this._info );
  98. this._pipelines = new Pipelines( backend, this._nodes );
  99. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this._info );
  100. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this._info );
  101. this._renderLists = new RenderLists();
  102. this._renderContexts = new RenderContexts();
  103. //
  104. this._animation.setNodes( this._nodes );
  105. this._animation.start();
  106. this._initialized = true;
  107. resolve();
  108. } );
  109. return this._initPromise;
  110. }
  111. get coordinateSystem() {
  112. return this.backend.coordinateSystem;
  113. }
  114. async compile( /*scene, camera*/ ) {
  115. console.warn( 'THREE.Renderer: .compile() is not implemented yet.' );
  116. }
  117. async render( scene, camera ) {
  118. if ( this._initialized === false ) await this.init();
  119. // preserve render tree
  120. const nodeFrame = this._nodes.nodeFrame;
  121. const previousRenderId = nodeFrame.renderId;
  122. const previousRenderState = this._currentRenderContext;
  123. //
  124. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  125. const renderTarget = this._renderTarget;
  126. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  127. const activeCubeFace = this._activeCubeFace;
  128. this._currentRenderContext = renderContext;
  129. nodeFrame.renderId ++;
  130. //
  131. const coordinateSystem = this.coordinateSystem;
  132. if ( camera.coordinateSystem !== coordinateSystem ) {
  133. camera.coordinateSystem = coordinateSystem;
  134. camera.updateProjectionMatrix();
  135. }
  136. //
  137. if ( this._animation.isAnimating === false ) nodeFrame.update();
  138. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  139. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  140. if ( this._info.autoReset === true ) this._info.reset();
  141. this._info.render.frame ++;
  142. //
  143. let viewport = this._viewport;
  144. let scissor = this._scissor;
  145. let pixelRatio = this._pixelRatio;
  146. if ( renderTarget !== null ) {
  147. viewport = renderTarget.viewport;
  148. scissor = renderTarget.scissor;
  149. pixelRatio = 1;
  150. }
  151. this.getDrawingBufferSize( _drawingBufferSize );
  152. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  153. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  154. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  155. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  156. renderContext.viewportValue.minDepth = minDepth;
  157. renderContext.viewportValue.maxDepth = maxDepth;
  158. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  159. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  160. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  161. renderContext.depth = this.depth;
  162. renderContext.stencil = this.stencil;
  163. //
  164. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  165. //
  166. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  167. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  168. const renderList = this._renderLists.get( scene, camera );
  169. renderList.begin();
  170. this._projectObject( scene, camera, 0, renderList );
  171. renderList.finish();
  172. if ( this.sortObjects === true ) {
  173. renderList.sort( this._opaqueSort, this._transparentSort );
  174. }
  175. //
  176. if ( renderTarget !== null ) {
  177. this._textures.updateRenderTarget( renderTarget );
  178. const renderTargetData = this._textures.get( renderTarget );
  179. renderContext.textures = renderTargetData.textures;
  180. renderContext.depthTexture = renderTargetData.depthTexture;
  181. } else {
  182. renderContext.textures = null;
  183. renderContext.depthTexture = null;
  184. }
  185. renderContext.activeCubeFace = activeCubeFace;
  186. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  187. //
  188. this._nodes.updateScene( sceneRef );
  189. //
  190. this._background.update( sceneRef, renderList, renderContext );
  191. //
  192. this.backend.beginRender( renderContext );
  193. // process render lists
  194. const opaqueObjects = renderList.opaque;
  195. const transparentObjects = renderList.transparent;
  196. const lightsNode = renderList.lightsNode;
  197. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  198. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  199. // finish render pass
  200. this.backend.finishRender( renderContext );
  201. // restore render tree
  202. nodeFrame.renderId = previousRenderId;
  203. this._currentRenderContext = previousRenderState;
  204. this._lastRenderContext = renderContext;
  205. //
  206. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  207. }
  208. setAnimationLoop( callback ) {
  209. if ( this._initialized === false ) this.init();
  210. const animation = this._animation;
  211. animation.setAnimationLoop( callback );
  212. ( callback === null ) ? animation.stop() : animation.start();
  213. }
  214. getArrayBuffer( attribute ) { // @deprecated, r155
  215. console.warn( 'THREE.Renderer: getArrayBuffer() is deprecated. Use getArrayBufferAsync() instead.' );
  216. return this.getArrayBufferAsync( attribute );
  217. }
  218. async getArrayBufferAsync( attribute ) {
  219. return await this.backend.getArrayBufferAsync( attribute );
  220. }
  221. getContext() {
  222. return this._context;
  223. }
  224. getPixelRatio() {
  225. return this._pixelRatio;
  226. }
  227. getDrawingBufferSize( target ) {
  228. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  229. }
  230. getSize( target ) {
  231. return target.set( this._width, this._height );
  232. }
  233. setPixelRatio( value = 1 ) {
  234. this._pixelRatio = value;
  235. this.setSize( this._width, this._height, false );
  236. }
  237. setDrawingBufferSize( width, height, pixelRatio ) {
  238. this._width = width;
  239. this._height = height;
  240. this._pixelRatio = pixelRatio;
  241. this.domElement.width = Math.floor( width * pixelRatio );
  242. this.domElement.height = Math.floor( height * pixelRatio );
  243. this.setViewport( 0, 0, width, height );
  244. if ( this._initialized ) this.backend.updateSize();
  245. }
  246. setSize( width, height, updateStyle = true ) {
  247. this._width = width;
  248. this._height = height;
  249. this.domElement.width = Math.floor( width * this._pixelRatio );
  250. this.domElement.height = Math.floor( height * this._pixelRatio );
  251. if ( updateStyle === true ) {
  252. this.domElement.style.width = width + 'px';
  253. this.domElement.style.height = height + 'px';
  254. }
  255. this.setViewport( 0, 0, width, height );
  256. if ( this._initialized ) this.backend.updateSize();
  257. }
  258. setOpaqueSort( method ) {
  259. this._opaqueSort = method;
  260. }
  261. setTransparentSort( method ) {
  262. this._transparentSort = method;
  263. }
  264. getScissor( target ) {
  265. const scissor = this._scissor;
  266. target.x = scissor.x;
  267. target.y = scissor.y;
  268. target.width = scissor.width;
  269. target.height = scissor.height;
  270. return target;
  271. }
  272. setScissor( x, y, width, height ) {
  273. const scissor = this._scissor;
  274. if ( x.isVector4 ) {
  275. scissor.copy( x );
  276. } else {
  277. scissor.set( x, y, width, height );
  278. }
  279. }
  280. getScissorTest() {
  281. return this._scissorTest;
  282. }
  283. setScissorTest( boolean ) {
  284. this._scissorTest = boolean;
  285. }
  286. getViewport( target ) {
  287. return target.copy( this._viewport );
  288. }
  289. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  290. const viewport = this._viewport;
  291. if ( x.isVector4 ) {
  292. viewport.copy( x );
  293. } else {
  294. viewport.set( x, y, width, height );
  295. }
  296. viewport.minDepth = minDepth;
  297. viewport.maxDepth = maxDepth;
  298. }
  299. getClearColor( target ) {
  300. return target.copy( this._clearColor );
  301. }
  302. setClearColor( color, alpha = 1 ) {
  303. this._clearColor.set( color );
  304. this._clearAlpha = alpha;
  305. }
  306. getClearAlpha() {
  307. return this._clearAlpha;
  308. }
  309. setClearAlpha( alpha ) {
  310. this._clearAlpha = alpha;
  311. }
  312. getClearDepth() {
  313. return this._clearDepth;
  314. }
  315. setClearDepth( depth ) {
  316. this._clearDepth = depth;
  317. }
  318. getClearStencil() {
  319. return this._clearStencil;
  320. }
  321. setClearStencil( stencil ) {
  322. this._clearStencil = stencil;
  323. }
  324. isOccluded( object ) {
  325. const renderContext = this._currentRenderContext || this._lastRenderContext;
  326. return renderContext && this.backend.isOccluded( renderContext, object );
  327. }
  328. clear( color = true, depth = true, stencil = true ) {
  329. const renderContext = this._currentRenderContext || this._lastRenderContext;
  330. if ( renderContext ) this.backend.clear( renderContext, color, depth, stencil );
  331. }
  332. clearColor() {
  333. this.clear( true, false, false );
  334. }
  335. clearDepth() {
  336. this.clear( false, true, false );
  337. }
  338. clearStencil() {
  339. this.clear( false, false, true );
  340. }
  341. dispose() {
  342. this._objects.dispose();
  343. this._properties.dispose();
  344. this._pipelines.dispose();
  345. this._nodes.dispose();
  346. this._bindings.dispose();
  347. this._info.dispose();
  348. this._renderLists.dispose();
  349. this._renderContexts.dispose();
  350. this._textures.dispose();
  351. this.setRenderTarget( null );
  352. this.setAnimationLoop( null );
  353. }
  354. setRenderTarget( renderTarget, activeCubeFace = 0 ) {
  355. this._renderTarget = renderTarget;
  356. this._activeCubeFace = activeCubeFace;
  357. }
  358. getRenderTarget() {
  359. return this._renderTarget;
  360. }
  361. async compute( computeNodes ) {
  362. if ( this._initialized === false ) await this.init();
  363. const backend = this.backend;
  364. const pipelines = this._pipelines;
  365. const bindings = this._bindings;
  366. const nodes = this._nodes;
  367. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  368. backend.beginCompute( computeNodes );
  369. for ( const computeNode of computeList ) {
  370. // onInit
  371. if ( pipelines.has( computeNode ) === false ) {
  372. const dispose = () => {
  373. computeNode.removeEventListener( 'dispose', dispose );
  374. pipelines.delete( computeNode );
  375. bindings.delete( computeNode );
  376. nodes.delete( computeNode );
  377. };
  378. computeNode.addEventListener( 'dispose', dispose );
  379. //
  380. computeNode.onInit( { renderer: this } );
  381. }
  382. nodes.updateForCompute( computeNode );
  383. bindings.updateForCompute( computeNode );
  384. const computeBindings = bindings.getForCompute( computeNode );
  385. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  386. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  387. }
  388. backend.finishCompute( computeNodes );
  389. }
  390. hasFeature( name ) {
  391. return this.backend.hasFeature( name );
  392. }
  393. copyFramebufferToTexture( framebufferTexture ) {
  394. const renderContext = this._currentRenderContext || this._lastRenderContext;
  395. this._textures.updateTexture( framebufferTexture );
  396. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  397. }
  398. readRenderTargetPixelsAsync( renderTarget, x, y, width, height ) {
  399. return this.backend.copyTextureToBuffer( renderTarget.texture, x, y, width, height );
  400. }
  401. _projectObject( object, camera, groupOrder, renderList ) {
  402. if ( object.visible === false ) return;
  403. const visible = object.layers.test( camera.layers );
  404. if ( visible ) {
  405. if ( object.isGroup ) {
  406. groupOrder = object.renderOrder;
  407. } else if ( object.isLOD ) {
  408. if ( object.autoUpdate === true ) object.update( camera );
  409. } else if ( object.isLight ) {
  410. renderList.pushLight( object );
  411. } else if ( object.isSprite ) {
  412. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  413. if ( this.sortObjects === true ) {
  414. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  415. }
  416. const geometry = object.geometry;
  417. const material = object.material;
  418. if ( material.visible ) {
  419. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  420. }
  421. }
  422. } else if ( object.isLineLoop ) {
  423. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  424. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  425. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  426. const geometry = object.geometry;
  427. const material = object.material;
  428. if ( this.sortObjects === true ) {
  429. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  430. _vector3
  431. .copy( geometry.boundingSphere.center )
  432. .applyMatrix4( object.matrixWorld )
  433. .applyMatrix4( _projScreenMatrix );
  434. }
  435. if ( Array.isArray( material ) ) {
  436. const groups = geometry.groups;
  437. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  438. const group = groups[ i ];
  439. const groupMaterial = material[ group.materialIndex ];
  440. if ( groupMaterial && groupMaterial.visible ) {
  441. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  442. }
  443. }
  444. } else if ( material.visible ) {
  445. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  446. }
  447. }
  448. }
  449. }
  450. const children = object.children;
  451. for ( let i = 0, l = children.length; i < l; i ++ ) {
  452. this._projectObject( children[ i ], camera, groupOrder, renderList );
  453. }
  454. }
  455. _renderObjects( renderList, camera, scene, lightsNode ) {
  456. // process renderable objects
  457. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  458. const renderItem = renderList[ i ];
  459. // @TODO: Add support for multiple materials per object. This will require to extract
  460. // the material from the renderItem object and pass it with its group data to _renderObject().
  461. const { object, geometry, material, group } = renderItem;
  462. if ( camera.isArrayCamera ) {
  463. const cameras = camera.cameras;
  464. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  465. const camera2 = cameras[ j ];
  466. if ( object.layers.test( camera2.layers ) ) {
  467. const vp = camera2.viewport;
  468. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  469. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  470. const viewportValue = this._currentRenderContext.viewportValue;
  471. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  472. viewportValue.minDepth = minDepth;
  473. viewportValue.maxDepth = maxDepth;
  474. this.backend.updateViewport( this._currentRenderContext );
  475. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  476. }
  477. }
  478. } else {
  479. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  480. }
  481. }
  482. }
  483. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  484. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  485. //
  486. object.onBeforeRender( this, scene, camera, geometry, material, group );
  487. material.onBeforeRender( this, scene, camera, geometry, material, group );
  488. //
  489. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  490. material.side = BackSide;
  491. this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id
  492. material.side = FrontSide;
  493. this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id
  494. material.side = DoubleSide;
  495. } else {
  496. this._renderObjectDirect( object, material, scene, camera, lightsNode );
  497. }
  498. //
  499. object.onAfterRender( this, scene, camera, geometry, material, group );
  500. }
  501. _renderObjectDirect( object, material, scene, camera, lightsNode, passId ) {
  502. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  503. //
  504. this._nodes.updateBefore( renderObject );
  505. //
  506. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  507. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  508. //
  509. this._nodes.updateForRender( renderObject );
  510. this._geometries.updateForRender( renderObject );
  511. this._bindings.updateForRender( renderObject );
  512. this._pipelines.updateForRender( renderObject );
  513. //
  514. this.backend.draw( renderObject, this._info );
  515. }
  516. }
  517. export default Renderer;