WebGPURenderer.js 14 KB

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