WebGPURenderer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. import { GPUIndexFormat, GPUTextureFormat, GPUStoreOp } from './constants.js';
  2. import WebGPUObjects from './WebGPUObjects.js';
  3. import WebGPUAttributes from './WebGPUAttributes.js';
  4. import WebGPUGeometries from './WebGPUGeometries.js';
  5. import WebGPUInfo from './WebGPUInfo.js';
  6. import WebGPUProperties from './WebGPUProperties.js';
  7. import WebGPURenderPipelines from './WebGPURenderPipelines.js';
  8. import WebGPUBindings from './WebGPUBindings.js';
  9. import WebGPURenderLists from './WebGPURenderLists.js';
  10. import WebGPUTextures from './WebGPUTextures.js';
  11. import WebGPUBackground from './WebGPUBackground.js';
  12. import { Frustum, Matrix4, Vector3, Color } from '../../../../build/three.module.js';
  13. const _frustum = new Frustum();
  14. const _projScreenMatrix = new Matrix4();
  15. const _vector3 = new Vector3();
  16. class WebGPURenderer {
  17. constructor( parameters = {} ) {
  18. // public
  19. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  20. this.parameters = parameters;
  21. this.autoClear = true;
  22. this.autoClearColor = true;
  23. this.autoClearDepth = true;
  24. this.autoClearStencil = true;
  25. this.sortObjects = true;
  26. // internals
  27. this._pixelRatio = 1;
  28. this._width = this.domElement.width;
  29. this._height = this.domElement.height;
  30. this._viewport = null;
  31. this._scissor = null;
  32. this._adapter = null;
  33. this._device = null;
  34. this._context = null;
  35. this._swapChain = null;
  36. this._depthBuffer = null;
  37. this._info = null;
  38. this._properties = null;
  39. this._attributes = null;
  40. this._geometries = null;
  41. this._bindings = null;
  42. this._objects = null;
  43. this._renderPipelines = null;
  44. this._renderLists = null;
  45. this._textures = null;
  46. this._background = null;
  47. this._renderPassDescriptor = null;
  48. this._currentRenderList = null;
  49. this._opaqueSort = null;
  50. this._transparentSort = null;
  51. this._clearAlpha = 1;
  52. this._clearColor = new Color( 0x000000 );
  53. this._clearDepth = 1;
  54. this._clearStencil = 0;
  55. this._renderTarget = null;
  56. }
  57. init() {
  58. return initWebGPU( this );
  59. }
  60. render( scene, camera ) {
  61. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  62. if ( camera.parent === null ) camera.updateMatrixWorld();
  63. if ( this._info.autoReset === true ) this._info.reset();
  64. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  65. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  66. this._currentRenderList = this._renderLists.get( scene, camera );
  67. this._currentRenderList.init();
  68. this._projectObject( scene, camera, 0 );
  69. this._currentRenderList.finish();
  70. if ( this.sortObjects === true ) {
  71. this._currentRenderList.sort( this._opaqueSort, this._transparentSort );
  72. }
  73. // prepare render pass descriptor
  74. const colorAttachment = this._renderPassDescriptor.colorAttachments[ 0 ];
  75. const depthStencilAttachment = this._renderPassDescriptor.depthStencilAttachment;
  76. const renderTarget = this._renderTarget;
  77. if ( renderTarget !== null ) {
  78. const renderTargetProperties = this._properties.get( renderTarget );
  79. colorAttachment.attachment = renderTargetProperties.colorTextureGPU.createView();
  80. depthStencilAttachment.attachment = renderTargetProperties.depthTextureGPU.createView();
  81. } else {
  82. colorAttachment.attachment = this._swapChain.getCurrentTexture().createView();
  83. depthStencilAttachment.attachment = this._depthBuffer.createView();
  84. }
  85. //
  86. this._background.update( scene );
  87. // start render pass
  88. const device = this._device;
  89. const cmdEncoder = device.createCommandEncoder( {} );
  90. const passEncoder = cmdEncoder.beginRenderPass( this._renderPassDescriptor );
  91. // global rasterization settings for all renderable objects
  92. const vp = this._viewport;
  93. if ( vp !== null ) {
  94. const width = Math.floor( vp.width * this._pixelRatio );
  95. const height = Math.floor( vp.height * this._pixelRatio );
  96. passEncoder.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  97. }
  98. const sc = this._scissor;
  99. if ( sc !== null ) {
  100. const width = Math.floor( sc.width * this._pixelRatio );
  101. const height = Math.floor( sc.height * this._pixelRatio );
  102. passEncoder.setScissorRect( sc.x, sc.y, width, height );
  103. }
  104. // process render lists
  105. const opaqueObjects = this._currentRenderList.opaque;
  106. const transparentObjects = this._currentRenderList.transparent;
  107. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, passEncoder );
  108. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, passEncoder );
  109. // finish render pass
  110. passEncoder.endPass();
  111. device.defaultQueue.submit( [ cmdEncoder.finish() ] );
  112. }
  113. getContext() {
  114. return this._context;
  115. }
  116. getPixelRatio() {
  117. return this._pixelRatio;
  118. }
  119. getDrawingBufferSize( target ) {
  120. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  121. }
  122. getSize( target ) {
  123. return target.set( this._width, this._height );
  124. }
  125. setPixelRatio( value = 1 ) {
  126. this._pixelRatio = value;
  127. this.setSize( this._width, this._height, false );
  128. }
  129. setDrawingBufferSize( width, height, pixelRatio ) {
  130. this._width = width;
  131. this._height = height;
  132. this._pixelRatio = pixelRatio;
  133. this.domElement.width = Math.floor( width * pixelRatio );
  134. this.domElement.height = Math.floor( height * pixelRatio );
  135. this._setupDepthBuffer();
  136. }
  137. setSize( width, height, updateStyle = true ) {
  138. this._width = width;
  139. this._height = height;
  140. this.domElement.width = Math.floor( width * this._pixelRatio );
  141. this.domElement.height = Math.floor( height * this._pixelRatio );
  142. if ( updateStyle === true ) {
  143. this.domElement.style.width = width + 'px';
  144. this.domElement.style.height = height + 'px';
  145. }
  146. this._setupDepthBuffer();
  147. }
  148. setOpaqueSort( method ) {
  149. this._opaqueSort = method;
  150. }
  151. setTransparentSort( method ) {
  152. this._transparentSort = method;
  153. }
  154. getScissor( target ) {
  155. const scissor = this._scissor;
  156. target.x = scissor.x;
  157. target.y = scissor.y;
  158. target.width = scissor.width;
  159. target.height = scissor.height;
  160. return target;
  161. }
  162. setScissor( x, y, width, height ) {
  163. if ( x === null ) {
  164. this._scissor = null;
  165. } else {
  166. this._scissor = {
  167. x: x,
  168. y: y,
  169. width: width,
  170. height: height
  171. };
  172. }
  173. }
  174. getViewport( target ) {
  175. const viewport = this._viewport;
  176. target.x = viewport.x;
  177. target.y = viewport.y;
  178. target.width = viewport.width;
  179. target.height = viewport.height;
  180. target.minDepth = viewport.minDepth;
  181. target.maxDepth = viewport.maxDepth;
  182. return target;
  183. }
  184. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  185. if ( x === null ) {
  186. this._viewport = null;
  187. } else {
  188. this._viewport = {
  189. x: x,
  190. y: y,
  191. width: width,
  192. height: height,
  193. minDepth: minDepth,
  194. maxDepth: maxDepth
  195. };
  196. }
  197. }
  198. getClearColor() {
  199. return this._clearColor;
  200. }
  201. setClearColor( color, alpha = 1 ) {
  202. this._clearColor.set( color );
  203. this._clearAlpha = alpha;
  204. }
  205. getClearAlpha() {
  206. return this._clearAlpha;
  207. }
  208. setClearAlpha( alpha ) {
  209. this._clearAlpha = alpha;
  210. }
  211. getClearDepth() {
  212. return this._clearDepth;
  213. }
  214. setClearDepth( depth ) {
  215. this._clearDepth = depth;
  216. }
  217. getClearStencil() {
  218. return this._clearStencil;
  219. }
  220. setClearStencil( stencil ) {
  221. this._clearStencil = stencil;
  222. }
  223. clear() {
  224. this._background.clear();
  225. }
  226. dispose() {
  227. this._objects.dispose();
  228. this._properties.dispose();
  229. this._renderPipelines.dispose();
  230. this._bindings.dispose();
  231. this._info.dispose();
  232. this._renderLists.dispose();
  233. this._textures.dispose();
  234. }
  235. setRenderTarget( renderTarget ) {
  236. this._renderTarget = renderTarget;
  237. if ( renderTarget !== null ) {
  238. this._textures.initRenderTarget( renderTarget );
  239. }
  240. }
  241. _projectObject( object, camera, groupOrder ) {
  242. const info = this._info;
  243. const currentRenderList = this._currentRenderList;
  244. if ( object.visible === false ) return;
  245. const visible = object.layers.test( camera.layers );
  246. if ( visible ) {
  247. if ( object.isGroup ) {
  248. groupOrder = object.renderOrder;
  249. } else if ( object.isLOD ) {
  250. if ( object.autoUpdate === true ) object.update( camera );
  251. } else if ( object.isLight ) {
  252. //currentRenderState.pushLight( object );
  253. if ( object.castShadow ) {
  254. //currentRenderState.pushShadow( object );
  255. }
  256. } else if ( object.isSprite ) {
  257. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  258. if ( this.sortObjects === true ) {
  259. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  260. }
  261. const geometry = object.geometry;
  262. const material = object.material;
  263. if ( material.visible ) {
  264. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  265. }
  266. }
  267. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  268. if ( object.isSkinnedMesh ) {
  269. // update skeleton only once in a frame
  270. if ( object.skeleton.frame !== info.render.frame ) {
  271. object.skeleton.update();
  272. object.skeleton.frame = info.render.frame;
  273. }
  274. }
  275. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  276. if ( this.sortObjects === true ) {
  277. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  278. }
  279. const geometry = object.geometry;
  280. const material = object.material;
  281. if ( Array.isArray( material ) ) {
  282. const groups = geometry.groups;
  283. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  284. const group = groups[ i ];
  285. const groupMaterial = material[ group.materialIndex ];
  286. if ( groupMaterial && groupMaterial.visible ) {
  287. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  288. }
  289. }
  290. } else if ( material.visible ) {
  291. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  292. }
  293. }
  294. }
  295. }
  296. const children = object.children;
  297. for ( let i = 0, l = children.length; i < l; i ++ ) {
  298. this._projectObject( children[ i ], camera, groupOrder );
  299. }
  300. }
  301. _renderObjects( renderList, camera, passEncoder ) {
  302. // process renderable objects
  303. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  304. const renderItem = renderList[ i ];
  305. const object = renderItem.object;
  306. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  307. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  308. this._objects.update( object );
  309. this._bindings.update( object, camera );
  310. this._renderObject( object, passEncoder );
  311. }
  312. }
  313. _renderObject( object, passEncoder ) {
  314. const info = this._info;
  315. // pipeline
  316. const pipeline = this._renderPipelines.get( object );
  317. passEncoder.setPipeline( pipeline );
  318. // bind group
  319. const bindGroup = this._bindings.get( object ).group;
  320. passEncoder.setBindGroup( 0, bindGroup );
  321. // index
  322. const geometry = object.geometry;
  323. const index = geometry.index;
  324. const hasIndex = ( index !== null );
  325. if ( hasIndex === true ) {
  326. this._setupIndexBuffer( passEncoder, index );
  327. }
  328. // vertex buffers
  329. this._setupVertexBuffers( passEncoder, geometry.attributes );
  330. // draw
  331. const drawRange = geometry.drawRange;
  332. const firstVertex = drawRange.start;
  333. if ( hasIndex === true ) {
  334. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  335. passEncoder.drawIndexed( indexCount, 1, firstVertex, 0, 0 );
  336. info.update( object, indexCount );
  337. } else {
  338. const positionAttribute = geometry.attributes.position;
  339. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  340. passEncoder.draw( vertexCount, 1, firstVertex, 0 );
  341. info.update( object, vertexCount );
  342. }
  343. }
  344. _setupIndexBuffer( encoder, index ) {
  345. const buffer = this._attributes.get( index ).buffer;
  346. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  347. encoder.setIndexBuffer( buffer, indexFormat );
  348. }
  349. _setupVertexBuffers( encoder, geometryAttributes ) {
  350. let slot = 0;
  351. for ( const name in geometryAttributes ) {
  352. const attribute = geometryAttributes[ name ];
  353. const buffer = this._attributes.get( attribute ).buffer;
  354. encoder.setVertexBuffer( slot, buffer );
  355. slot ++;
  356. }
  357. }
  358. _setupDepthBuffer() {
  359. const device = this._device;
  360. if ( device ) {
  361. if ( this._depthBuffer ) this._depthBuffer.destroy();
  362. this._depthBuffer = this._device.createTexture( {
  363. size: {
  364. width: this._width * this._pixelRatio,
  365. height: this._height * this._pixelRatio,
  366. depth: 1
  367. },
  368. format: GPUTextureFormat.Depth24PlusStencil8,
  369. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  370. } );
  371. }
  372. }
  373. }
  374. async function initWebGPU( scope ) {
  375. const parameters = scope.parameters;
  376. const adapterOptions = {
  377. powerPreference: ( parameters.powerPreference !== undefined ) ? parameters.powerPreference : undefined
  378. };
  379. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  380. const deviceDescriptor = {
  381. enabledExtensions: ( parameters.enabledExtensions !== undefined ) ? parameters.enabledExtensions : [],
  382. limits: ( parameters.limits !== undefined ) ? parameters.limits : {}
  383. };
  384. const device = await adapter.requestDevice( deviceDescriptor );
  385. const glslang = await import( 'https://cdn.jsdelivr.net/npm/@webgpu/[email protected]/dist/web-devel/glslang.js' );
  386. const compiler = await glslang.default();
  387. const context = ( parameters.context !== undefined ) ? parameters.context : scope.domElement.getContext( 'gpupresent' );
  388. const swapChain = context.configureSwapChain( {
  389. device: device,
  390. format: GPUTextureFormat.BRGA8Unorm
  391. } );
  392. scope._adapter = adapter;
  393. scope._device = device;
  394. scope._context = context;
  395. scope._swapChain = swapChain;
  396. scope._info = new WebGPUInfo();
  397. scope._properties = new WebGPUProperties();
  398. scope._attributes = new WebGPUAttributes( device );
  399. scope._geometries = new WebGPUGeometries( scope._attributes, scope._info );
  400. scope._textures = new WebGPUTextures( device, scope._properties, scope._info );
  401. scope._bindings = new WebGPUBindings( device, scope._info, scope._properties, scope._textures );
  402. scope._objects = new WebGPUObjects( scope._geometries, scope._info );
  403. scope._renderPipelines = new WebGPURenderPipelines( device, compiler, scope._bindings );
  404. scope._renderLists = new WebGPURenderLists();
  405. scope._background = new WebGPUBackground( scope );
  406. //
  407. scope._renderPassDescriptor = {
  408. colorAttachments: [ {
  409. attachment: null
  410. } ],
  411. depthStencilAttachment: {
  412. attachment: null,
  413. depthStoreOp: GPUStoreOp.Store,
  414. stencilStoreOp: GPUStoreOp.Store
  415. }
  416. };
  417. scope._setupDepthBuffer();
  418. }
  419. export default WebGPURenderer;