WebGPURenderer.js 13 KB

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