Renderer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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. renderContext.width = renderTargetData.width;
  182. renderContext.height = renderTargetData.height;
  183. } else {
  184. renderContext.textures = null;
  185. renderContext.depthTexture = null;
  186. renderContext.width = this.domElement.width;
  187. renderContext.height = this.domElement.height;
  188. }
  189. renderContext.activeCubeFace = activeCubeFace;
  190. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  191. //
  192. this._nodes.updateScene( sceneRef );
  193. //
  194. this._background.update( sceneRef, renderList, renderContext );
  195. //
  196. this.backend.beginRender( renderContext );
  197. // process render lists
  198. const opaqueObjects = renderList.opaque;
  199. const transparentObjects = renderList.transparent;
  200. const lightsNode = renderList.lightsNode;
  201. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  202. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  203. // finish render pass
  204. this.backend.finishRender( renderContext );
  205. // restore render tree
  206. nodeFrame.renderId = previousRenderId;
  207. this._currentRenderContext = previousRenderState;
  208. this._lastRenderContext = renderContext;
  209. //
  210. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  211. }
  212. setAnimationLoop( callback ) {
  213. if ( this._initialized === false ) this.init();
  214. const animation = this._animation;
  215. animation.setAnimationLoop( callback );
  216. ( callback === null ) ? animation.stop() : animation.start();
  217. }
  218. getArrayBuffer( attribute ) { // @deprecated, r155
  219. console.warn( 'THREE.Renderer: getArrayBuffer() is deprecated. Use getArrayBufferAsync() instead.' );
  220. return this.getArrayBufferAsync( attribute );
  221. }
  222. async getArrayBufferAsync( attribute ) {
  223. return await this.backend.getArrayBufferAsync( attribute );
  224. }
  225. getContext() {
  226. return this._context;
  227. }
  228. getPixelRatio() {
  229. return this._pixelRatio;
  230. }
  231. getDrawingBufferSize( target ) {
  232. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  233. }
  234. getSize( target ) {
  235. return target.set( this._width, this._height );
  236. }
  237. setPixelRatio( value = 1 ) {
  238. this._pixelRatio = value;
  239. this.setSize( this._width, this._height, false );
  240. }
  241. setDrawingBufferSize( width, height, pixelRatio ) {
  242. this._width = width;
  243. this._height = height;
  244. this._pixelRatio = pixelRatio;
  245. this.domElement.width = Math.floor( width * pixelRatio );
  246. this.domElement.height = Math.floor( height * pixelRatio );
  247. this.setViewport( 0, 0, width, height );
  248. if ( this._initialized ) this.backend.updateSize();
  249. }
  250. setSize( width, height, updateStyle = true ) {
  251. this._width = width;
  252. this._height = height;
  253. this.domElement.width = Math.floor( width * this._pixelRatio );
  254. this.domElement.height = Math.floor( height * this._pixelRatio );
  255. if ( updateStyle === true ) {
  256. this.domElement.style.width = width + 'px';
  257. this.domElement.style.height = height + 'px';
  258. }
  259. this.setViewport( 0, 0, width, height );
  260. if ( this._initialized ) this.backend.updateSize();
  261. }
  262. setOpaqueSort( method ) {
  263. this._opaqueSort = method;
  264. }
  265. setTransparentSort( method ) {
  266. this._transparentSort = method;
  267. }
  268. getScissor( target ) {
  269. const scissor = this._scissor;
  270. target.x = scissor.x;
  271. target.y = scissor.y;
  272. target.width = scissor.width;
  273. target.height = scissor.height;
  274. return target;
  275. }
  276. setScissor( x, y, width, height ) {
  277. const scissor = this._scissor;
  278. if ( x.isVector4 ) {
  279. scissor.copy( x );
  280. } else {
  281. scissor.set( x, y, width, height );
  282. }
  283. }
  284. getScissorTest() {
  285. return this._scissorTest;
  286. }
  287. setScissorTest( boolean ) {
  288. this._scissorTest = boolean;
  289. }
  290. getViewport( target ) {
  291. return target.copy( this._viewport );
  292. }
  293. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  294. const viewport = this._viewport;
  295. if ( x.isVector4 ) {
  296. viewport.copy( x );
  297. } else {
  298. viewport.set( x, y, width, height );
  299. }
  300. viewport.minDepth = minDepth;
  301. viewport.maxDepth = maxDepth;
  302. }
  303. getClearColor( target ) {
  304. return target.copy( this._clearColor );
  305. }
  306. setClearColor( color, alpha = 1 ) {
  307. this._clearColor.set( color );
  308. this._clearAlpha = alpha;
  309. }
  310. getClearAlpha() {
  311. return this._clearAlpha;
  312. }
  313. setClearAlpha( alpha ) {
  314. this._clearAlpha = alpha;
  315. }
  316. getClearDepth() {
  317. return this._clearDepth;
  318. }
  319. setClearDepth( depth ) {
  320. this._clearDepth = depth;
  321. }
  322. getClearStencil() {
  323. return this._clearStencil;
  324. }
  325. setClearStencil( stencil ) {
  326. this._clearStencil = stencil;
  327. }
  328. isOccluded( object ) {
  329. const renderContext = this._currentRenderContext || this._lastRenderContext;
  330. return renderContext && this.backend.isOccluded( renderContext, object );
  331. }
  332. clear( color = true, depth = true, stencil = true ) {
  333. const renderContext = this._currentRenderContext || this._lastRenderContext;
  334. if ( renderContext ) this.backend.clear( renderContext, color, depth, stencil );
  335. }
  336. clearColor() {
  337. this.clear( true, false, false );
  338. }
  339. clearDepth() {
  340. this.clear( false, true, false );
  341. }
  342. clearStencil() {
  343. this.clear( false, false, true );
  344. }
  345. dispose() {
  346. this._objects.dispose();
  347. this._properties.dispose();
  348. this._pipelines.dispose();
  349. this._nodes.dispose();
  350. this._bindings.dispose();
  351. this._info.dispose();
  352. this._renderLists.dispose();
  353. this._renderContexts.dispose();
  354. this._textures.dispose();
  355. this.setRenderTarget( null );
  356. this.setAnimationLoop( null );
  357. }
  358. setRenderTarget( renderTarget, activeCubeFace = 0 ) {
  359. this._renderTarget = renderTarget;
  360. this._activeCubeFace = activeCubeFace;
  361. }
  362. getRenderTarget() {
  363. return this._renderTarget;
  364. }
  365. async compute( computeNodes ) {
  366. if ( this._initialized === false ) await this.init();
  367. const backend = this.backend;
  368. const pipelines = this._pipelines;
  369. const bindings = this._bindings;
  370. const nodes = this._nodes;
  371. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  372. backend.beginCompute( computeNodes );
  373. for ( const computeNode of computeList ) {
  374. // onInit
  375. if ( pipelines.has( computeNode ) === false ) {
  376. const dispose = () => {
  377. computeNode.removeEventListener( 'dispose', dispose );
  378. pipelines.delete( computeNode );
  379. bindings.delete( computeNode );
  380. nodes.delete( computeNode );
  381. };
  382. computeNode.addEventListener( 'dispose', dispose );
  383. //
  384. computeNode.onInit( { renderer: this } );
  385. }
  386. nodes.updateForCompute( computeNode );
  387. bindings.updateForCompute( computeNode );
  388. const computeBindings = bindings.getForCompute( computeNode );
  389. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  390. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  391. }
  392. backend.finishCompute( computeNodes );
  393. }
  394. hasFeature( name ) {
  395. return this.backend.hasFeature( name );
  396. }
  397. copyFramebufferToTexture( framebufferTexture ) {
  398. const renderContext = this._currentRenderContext || this._lastRenderContext;
  399. this._textures.updateTexture( framebufferTexture );
  400. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  401. }
  402. readRenderTargetPixelsAsync( renderTarget, x, y, width, height ) {
  403. return this.backend.copyTextureToBuffer( renderTarget.texture, x, y, width, height );
  404. }
  405. _projectObject( object, camera, groupOrder, renderList ) {
  406. if ( object.visible === false ) return;
  407. const visible = object.layers.test( camera.layers );
  408. if ( visible ) {
  409. if ( object.isGroup ) {
  410. groupOrder = object.renderOrder;
  411. } else if ( object.isLOD ) {
  412. if ( object.autoUpdate === true ) object.update( camera );
  413. } else if ( object.isLight ) {
  414. renderList.pushLight( object );
  415. } else if ( object.isSprite ) {
  416. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  417. if ( this.sortObjects === true ) {
  418. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  419. }
  420. const geometry = object.geometry;
  421. const material = object.material;
  422. if ( material.visible ) {
  423. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  424. }
  425. }
  426. } else if ( object.isLineLoop ) {
  427. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  428. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  429. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  430. const geometry = object.geometry;
  431. const material = object.material;
  432. if ( this.sortObjects === true ) {
  433. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  434. _vector3
  435. .copy( geometry.boundingSphere.center )
  436. .applyMatrix4( object.matrixWorld )
  437. .applyMatrix4( _projScreenMatrix );
  438. }
  439. if ( Array.isArray( material ) ) {
  440. const groups = geometry.groups;
  441. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  442. const group = groups[ i ];
  443. const groupMaterial = material[ group.materialIndex ];
  444. if ( groupMaterial && groupMaterial.visible ) {
  445. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  446. }
  447. }
  448. } else if ( material.visible ) {
  449. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  450. }
  451. }
  452. }
  453. }
  454. const children = object.children;
  455. for ( let i = 0, l = children.length; i < l; i ++ ) {
  456. this._projectObject( children[ i ], camera, groupOrder, renderList );
  457. }
  458. }
  459. _renderObjects( renderList, camera, scene, lightsNode ) {
  460. // process renderable objects
  461. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  462. const renderItem = renderList[ i ];
  463. // @TODO: Add support for multiple materials per object. This will require to extract
  464. // the material from the renderItem object and pass it with its group data to _renderObject().
  465. const { object, geometry, material, group } = renderItem;
  466. if ( camera.isArrayCamera ) {
  467. const cameras = camera.cameras;
  468. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  469. const camera2 = cameras[ j ];
  470. if ( object.layers.test( camera2.layers ) ) {
  471. const vp = camera2.viewport;
  472. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  473. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  474. const viewportValue = this._currentRenderContext.viewportValue;
  475. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  476. viewportValue.minDepth = minDepth;
  477. viewportValue.maxDepth = maxDepth;
  478. this.backend.updateViewport( this._currentRenderContext );
  479. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  480. }
  481. }
  482. } else {
  483. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  484. }
  485. }
  486. }
  487. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  488. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  489. //
  490. object.onBeforeRender( this, scene, camera, geometry, material, group );
  491. material.onBeforeRender( this, scene, camera, geometry, material, group );
  492. //
  493. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  494. material.side = BackSide;
  495. this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id
  496. material.side = FrontSide;
  497. this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id
  498. material.side = DoubleSide;
  499. } else {
  500. this._renderObjectDirect( object, material, scene, camera, lightsNode );
  501. }
  502. //
  503. object.onAfterRender( this, scene, camera, geometry, material, group );
  504. }
  505. _renderObjectDirect( object, material, scene, camera, lightsNode, passId ) {
  506. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  507. //
  508. this._nodes.updateBefore( renderObject );
  509. //
  510. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  511. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  512. //
  513. this._nodes.updateForRender( renderObject );
  514. this._geometries.updateForRender( renderObject );
  515. this._bindings.updateForRender( renderObject );
  516. this._pipelines.updateForRender( renderObject );
  517. //
  518. this.backend.draw( renderObject, this._info );
  519. }
  520. }
  521. export default Renderer;