puppeteer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. import puppeteer from 'puppeteer';
  2. import express from 'express';
  3. import path from 'path';
  4. import pixelmatch from 'pixelmatch';
  5. import { Jimp } from 'jimp';
  6. import * as fs from 'fs/promises';
  7. class PromiseQueue {
  8. constructor( func, ...args ) {
  9. this.func = func.bind( this, ...args );
  10. this.promises = [];
  11. }
  12. add( ...args ) {
  13. const promise = this.func( ...args );
  14. this.promises.push( promise );
  15. promise.then( () => this.promises.splice( this.promises.indexOf( promise ), 1 ) );
  16. }
  17. async waitForAll() {
  18. while ( this.promises.length > 0 ) {
  19. await Promise.all( this.promises );
  20. }
  21. }
  22. }
  23. /* CONFIG VARIABLES START */
  24. const idleTime = 12; // 9 seconds - for how long there should be no network requests
  25. const parseTime = 6; // 6 seconds per megabyte
  26. const exceptionList = [
  27. // tiles not loaded in time for screenshot
  28. 'webgl_loader_3dtiles',
  29. // video tag isn't deterministic enough?
  30. 'css3d_youtube',
  31. 'webgl_materials_video',
  32. 'webgl_video_kinect',
  33. 'webgl_video_panorama_equirectangular',
  34. 'webgpu_video_frame',
  35. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  36. // WebXR also isn't deterministic enough?
  37. 'webxr_ar_lighting',
  38. 'webxr_vr_sandbox',
  39. 'webxr_vr_video',
  40. 'webxr_xr_ballshooter',
  41. 'webxr_xr_dragging_custom_depth',
  42. 'webgl_worker_offscreencanvas', // in a worker, not robust
  43. // Windows-Linux text rendering differences
  44. // TODO: Fix these by e.g. disabling text rendering altogether -- this can also fix a bunch of 0.1%-0.2% examples
  45. 'css3d_periodictable',
  46. 'misc_controls_pointerlock',
  47. 'misc_uv_tests',
  48. 'webgl_camera_logarithmicdepthbuffer',
  49. 'webgl_effects_ascii',
  50. 'webgl_geometry_extrude_shapes',
  51. 'webgl_interactive_lines',
  52. 'webgl_loader_collada_kinematics',
  53. 'webgl_loader_ldraw',
  54. 'webgl_loader_texture_ktx2',
  55. 'webgl_loader_pdb',
  56. 'webgl_modifier_simplifier',
  57. 'webgl_multiple_canvases_circle',
  58. 'webgl_multiple_elements_text',
  59. // Unknown
  60. // TODO: most of these can be fixed just by increasing idleTime and parseTime
  61. 'physics_rapier_basic',
  62. 'webgl_animation_skinning_blending',
  63. 'webgl_animation_skinning_additive_blending',
  64. 'webgl_buffergeometry_glbufferattribute',
  65. 'webgl_interactive_cubes_gpu',
  66. 'webgl_clipping_advanced',
  67. 'webgl_lensflares',
  68. 'webgl_lights_spotlights',
  69. 'webgl_loader_imagebitmap',
  70. 'webgl_loader_texture_ktx',
  71. 'webgl_loader_texture_lottie',
  72. 'webgl_loader_texture_pvrtc',
  73. 'webgl_materials_alphahash',
  74. 'webgpu_materials_alphahash',
  75. 'webgl_materials_blending',
  76. 'webgl_mirror',
  77. 'webgl_morphtargets_face',
  78. 'webgl_postprocessing_transition',
  79. 'webgl_postprocessing_glitch',
  80. 'webgl_postprocessing_dof2',
  81. 'webgl_renderer_pathtracer',
  82. 'webgl_shadowmap',
  83. 'webgl_shadowmap_progressive',
  84. 'webgpu_shadowmap_progressive',
  85. 'webgl_test_memory2',
  86. 'webgl_points_dynamic',
  87. 'webgpu_multisampled_renderbuffers',
  88. 'webgl_test_wide_gamut',
  89. 'webgl_volume_instancing',
  90. 'webgl_buffergeometry',
  91. 'webgl_buffergeometry_attributes_integer',
  92. 'webgl_buffergeometry_attributes_none',
  93. 'webgl_buffergeometry_custom_attributes_particles',
  94. 'webgl_batch_lod_bvh',
  95. // Intentional z-fighting in this demo makes it non-deterministic
  96. 'webgl_reversed_depth_buffer',
  97. // TODO: implement determinism for setTimeout and setInterval
  98. // could it fix some examples from above?
  99. 'physics_rapier_instancing',
  100. 'physics_jolt_instancing',
  101. // Awaiting for WebGL backend support
  102. 'webgpu_compute_audio',
  103. 'webgpu_compute_birds',
  104. 'webgpu_compute_texture',
  105. 'webgpu_compute_texture_3d',
  106. 'webgpu_compute_texture_pingpong',
  107. 'webgpu_compute_water',
  108. 'webgpu_materials',
  109. 'webgpu_multiple_canvas',
  110. 'webgpu_video_panorama',
  111. 'webgpu_postprocessing_bloom_emissive',
  112. 'webgpu_lights_tiled',
  113. 'webgpu_postprocessing_traa',
  114. 'webgpu_tsl_wood',
  115. // Awaiting for WebGPU Backend support in Puppeteer
  116. 'webgpu_storage_buffer',
  117. 'webgpu_compute_sort_bitonic',
  118. 'webgpu_compute_reduce',
  119. 'webgpu_struct_drawindirect',
  120. 'webgpu_hdr',
  121. // WebGPURenderer: Unknown problem
  122. 'webgpu_backdrop_water',
  123. "webgpu_centroid_sampling",
  124. 'webgpu_camera_logarithmicdepthbuffer',
  125. 'webgpu_lightprobe_cubecamera',
  126. 'webgpu_loader_materialx',
  127. 'webgpu_materials_basic',
  128. 'webgpu_materials_video',
  129. 'webgpu_materialx_noise',
  130. 'webgpu_morphtargets_face',
  131. 'webgpu_occlusion',
  132. 'webgpu_particles',
  133. 'webgpu_shadertoy',
  134. 'webgpu_shadowmap',
  135. 'webgpu_shadowmap_array',
  136. 'webgpu_tsl_editor',
  137. 'webgpu_tsl_transpiler',
  138. 'webgpu_tsl_interoperability',
  139. 'webgpu_portal',
  140. 'webgpu_custom_fog',
  141. 'webgpu_instancing_morph',
  142. 'webgpu_texturegrad',
  143. 'webgpu_performance_renderbundle',
  144. 'webgpu_lights_rectarealight',
  145. 'webgpu_tsl_vfx_flames',
  146. 'webgpu_tsl_halftone',
  147. 'webgpu_tsl_vfx_linkedparticles',
  148. 'webgpu_textures_anisotropy',
  149. 'webgpu_textures_2d-array_compressed',
  150. 'webgpu_rendertarget_2d-array_3d',
  151. 'webgpu_materials_envmaps_bpcem',
  152. 'webgpu_postprocessing_ao',
  153. 'webgpu_postprocessing_difference',
  154. 'webgpu_postprocessing_dof',
  155. 'webgpu_postprocessing_sobel',
  156. 'webgpu_postprocessing_3dlut',
  157. 'webgpu_postprocessing_fxaa',
  158. 'webgpu_postprocessing_afterimage',
  159. 'webgpu_postprocessing_ca',
  160. 'webgpu_postprocessing_ssgi',
  161. 'webgpu_postprocessing_sss',
  162. 'webgpu_xr_native_layers',
  163. 'webgpu_volume_caustics',
  164. 'webgpu_volume_lighting',
  165. 'webgpu_volume_lighting_rectarea',
  166. 'webgpu_reflection',
  167. 'webgpu_ocean',
  168. // WebGPU idleTime and parseTime too low
  169. 'webgpu_compute_cloth',
  170. 'webgpu_compute_particles',
  171. 'webgpu_compute_particles_fluid',
  172. 'webgpu_compute_particles_rain',
  173. 'webgpu_compute_particles_snow',
  174. 'webgpu_compute_points'
  175. ];
  176. /* CONFIG VARIABLES END */
  177. const port = 1234;
  178. const pixelThreshold = 0.1; // threshold error in one pixel
  179. const maxDifferentPixels = 0.3; // at most 0.3% different pixels
  180. const networkTimeout = 5; // 5 minutes, set to 0 to disable
  181. const renderTimeout = 5; // 5 seconds, set to 0 to disable
  182. const numAttempts = 2; // perform 2 attempts before failing
  183. const numPages = 8; // use 8 browser pages
  184. const numCIJobs = 4; // GitHub Actions run the script in 4 threads
  185. const width = 400;
  186. const height = 250;
  187. const viewScale = 2;
  188. const jpgQuality = 95;
  189. console.red = msg => console.log( `\x1b[31m${msg}\x1b[39m` );
  190. console.green = msg => console.log( `\x1b[32m${msg}\x1b[39m` );
  191. console.yellow = msg => console.log( `\x1b[33m${msg}\x1b[39m` );
  192. let browser;
  193. /* Launch server */
  194. const app = express();
  195. app.use( express.static( path.resolve() ) );
  196. const server = app.listen( port, main );
  197. process.on( 'SIGINT', () => close() );
  198. async function main() {
  199. /* Create output directory */
  200. try { await fs.rm( 'test/e2e/output-screenshots', { recursive: true, force: true } ); } catch {}
  201. try { await fs.mkdir( 'test/e2e/output-screenshots' ); } catch {}
  202. /* Find files */
  203. let isMakeScreenshot = false;
  204. let isWebGPU = false;
  205. let argvIndex = 2;
  206. if ( process.argv[ argvIndex ] === '--webgpu' ) {
  207. isWebGPU = true;
  208. argvIndex ++;
  209. }
  210. if ( process.argv[ argvIndex ] === '--make' ) {
  211. isMakeScreenshot = true;
  212. argvIndex ++;
  213. }
  214. const exactList = process.argv.slice( argvIndex )
  215. .map( f => f.replace( '.html', '' ) );
  216. const isExactList = exactList.length !== 0;
  217. let files = ( await fs.readdir( 'examples' ) )
  218. .filter( s => s.slice( - 5 ) === '.html' && s !== 'index.html' )
  219. .map( s => s.slice( 0, s.length - 5 ) )
  220. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  221. if ( isExactList ) {
  222. for ( const file of exactList ) {
  223. if ( ! files.includes( file ) ) {
  224. console.log( `Warning! Unrecognised example name: ${ file }` );
  225. }
  226. }
  227. }
  228. if ( isWebGPU ) files = files.filter( f => f.includes( 'webgpu_' ) );
  229. /* CI parallelism */
  230. if ( 'CI' in process.env ) {
  231. const CI = parseInt( process.env.CI );
  232. files = files.slice(
  233. Math.floor( CI * files.length / numCIJobs ),
  234. Math.floor( ( CI + 1 ) * files.length / numCIJobs )
  235. );
  236. }
  237. /* Launch browser */
  238. const flags = [ '--hide-scrollbars', '--enable-gpu' ];
  239. // flags.push( '--enable-unsafe-webgpu', '--enable-features=Vulkan', '--use-gl=swiftshader', '--use-angle=swiftshader', '--use-vulkan=swiftshader', '--use-webgpu-adapter=swiftshader' );
  240. // if ( process.platform === 'linux' ) flags.push( '--enable-features=Vulkan,UseSkiaRenderer', '--use-vulkan=native', '--disable-vulkan-surface', '--disable-features=VaapiVideoDecoder', '--ignore-gpu-blocklist', '--use-angle=vulkan' );
  241. const viewport = { width: width * viewScale, height: height * viewScale };
  242. browser = await puppeteer.launch( {
  243. headless: process.env.VISIBLE ? false : 'new',
  244. args: flags,
  245. defaultViewport: viewport,
  246. handleSIGINT: false,
  247. protocolTimeout: 0
  248. } );
  249. // this line is intended to stop the script if the browser (in headful mode) is closed by user (while debugging)
  250. // browser.on( 'targetdestroyed', target => ( target.type() === 'other' ) ? close() : null );
  251. // for some reason it randomly stops the script after about ~30 screenshots processed
  252. /* Prepare injections */
  253. const buildInjection = ( code ) => code.replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  254. const cleanPage = await fs.readFile( 'test/e2e/clean-page.js', 'utf8' );
  255. const injection = await fs.readFile( 'test/e2e/deterministic-injection.js', 'utf8' );
  256. const builds = {
  257. 'three.core.js': buildInjection( await fs.readFile( 'build/three.core.js', 'utf8' ) ),
  258. 'three.module.js': buildInjection( await fs.readFile( 'build/three.module.js', 'utf8' ) ),
  259. 'three.webgpu.js': buildInjection( await fs.readFile( 'build/three.webgpu.js', 'utf8' ) )
  260. };
  261. /* Prepare pages */
  262. const errorMessagesCache = [];
  263. const pages = await browser.pages();
  264. while ( pages.length < numPages && pages.length < files.length ) pages.push( await browser.newPage() );
  265. for ( const page of pages ) await preparePage( page, injection, builds, errorMessagesCache );
  266. /* Loop for each file */
  267. const failedScreenshots = [];
  268. const queue = new PromiseQueue( makeAttempt, pages, failedScreenshots, cleanPage, isMakeScreenshot );
  269. for ( const file of files ) queue.add( file );
  270. await queue.waitForAll();
  271. /* Finish */
  272. failedScreenshots.sort();
  273. const list = failedScreenshots.join( ' ' );
  274. if ( isMakeScreenshot && failedScreenshots.length ) {
  275. console.red( 'List of failed screenshots: ' + list );
  276. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, try increasing idleTime and parseTime variables in /test/e2e/puppeteer.js file. If this also does not help, add remaining screenshots to the exception list.` );
  277. console.red( `${ failedScreenshots.length } from ${ files.length } screenshots have not generated successfully.` );
  278. } else if ( isMakeScreenshot && ! failedScreenshots.length ) {
  279. console.green( `${ files.length } screenshots successfully generated.` );
  280. } else if ( failedScreenshots.length ) {
  281. console.red( 'List of failed screenshots: ' + list );
  282. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, try increasing idleTime and parseTime variables in /test/e2e/puppeteer.js file. If this also does not help, add remaining screenshots to the exception list.` );
  283. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ files.length } screenshots have not rendered correctly.` );
  284. } else {
  285. console.green( `TEST PASSED! ${ files.length } screenshots rendered correctly.` );
  286. }
  287. setTimeout( close, 300, failedScreenshots.length );
  288. }
  289. async function preparePage( page, injection, builds, errorMessages ) {
  290. /* let page.file, page.pageSize, page.error */
  291. await page.evaluateOnNewDocument( injection );
  292. await page.setRequestInterception( true );
  293. page.on( 'console', async msg => {
  294. const type = msg.type();
  295. if ( type !== 'warning' && type !== 'error' ) {
  296. return;
  297. }
  298. const file = page.file;
  299. if ( file === undefined ) {
  300. return;
  301. }
  302. const args = await Promise.all( msg.args().map( async arg => {
  303. try {
  304. return await arg.executionContext().evaluate( arg => arg instanceof Error ? arg.message : arg, arg );
  305. } catch ( e ) { // Execution context might have been already destroyed
  306. return arg;
  307. }
  308. } ) );
  309. let text = args.join( ' ' ); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
  310. text = text.trim();
  311. if ( text === '' ) return;
  312. text = file + ': ' + text.replace( /\[\.WebGL-(.+?)\] /g, '' );
  313. if ( text === `${ file }: JSHandle@error` ) {
  314. text = `${ file }: Unknown error`;
  315. }
  316. if ( text.includes( 'Unable to access the camera/webcam' ) ) {
  317. return;
  318. }
  319. if ( errorMessages.includes( text ) ) {
  320. return;
  321. }
  322. errorMessages.push( text );
  323. if ( type === 'warning' ) {
  324. console.yellow( text );
  325. } else {
  326. page.error = text;
  327. }
  328. } );
  329. page.on( 'response', async ( response ) => {
  330. try {
  331. if ( response.status === 200 ) {
  332. await response.buffer().then( buffer => page.pageSize += buffer.length );
  333. }
  334. } catch {}
  335. } );
  336. page.on( 'request', async ( request ) => {
  337. const url = request.url();
  338. for ( const build in builds ) {
  339. if ( url === `http://localhost:${ port }/build/${ build }` ) {
  340. await request.respond( {
  341. status: 200,
  342. contentType: 'application/javascript; charset=utf-8',
  343. body: builds[ build ]
  344. } );
  345. return;
  346. }
  347. }
  348. await request.continue();
  349. } );
  350. }
  351. async function makeAttempt( pages, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID = 0 ) {
  352. const page = await new Promise( ( resolve, reject ) => {
  353. const interval = setInterval( () => {
  354. for ( const page of pages ) {
  355. if ( page.file === undefined ) {
  356. page.file = file; // acquire lock
  357. clearInterval( interval );
  358. resolve( page );
  359. break;
  360. }
  361. }
  362. }, 100 );
  363. } );
  364. try {
  365. page.pageSize = 0;
  366. page.error = undefined;
  367. /* Load target page */
  368. try {
  369. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  370. waitUntil: 'networkidle0',
  371. timeout: networkTimeout * 60000
  372. } );
  373. } catch ( e ) {
  374. throw new Error( `Error happened while loading file ${ file }: ${ e }` );
  375. }
  376. try {
  377. /* Render page */
  378. await page.evaluate( cleanPage );
  379. await page.waitForNetworkIdle( {
  380. timeout: networkTimeout * 60000,
  381. idleTime: idleTime * 1000
  382. } );
  383. await page.evaluate( async ( renderTimeout, parseTime ) => {
  384. await new Promise( resolve => setTimeout( resolve, parseTime ) );
  385. /* Resolve render promise */
  386. window._renderStarted = true;
  387. await new Promise( function ( resolve, reject ) {
  388. const renderStart = performance._now();
  389. const waitingLoop = setInterval( function () {
  390. const renderTimeoutExceeded = ( renderTimeout > 0 ) && ( performance._now() - renderStart > 1000 * renderTimeout );
  391. if ( renderTimeoutExceeded ) {
  392. clearInterval( waitingLoop );
  393. reject( 'Render timeout exceeded' );
  394. } else if ( window._renderFinished ) {
  395. clearInterval( waitingLoop );
  396. resolve();
  397. }
  398. }, 10 );
  399. } );
  400. }, renderTimeout, page.pageSize / 1024 / 1024 * parseTime * 1000 );
  401. } catch ( e ) {
  402. if ( e.includes && e.includes( 'Render timeout exceeded' ) === false ) {
  403. throw new Error( `Error happened while rendering file ${ file }: ${ e }` );
  404. } /* else { // This can mean that the example doesn't use requestAnimationFrame loop
  405. console.yellow( `Render timeout exceeded in file ${ file }` );
  406. } */ // TODO: fix this
  407. }
  408. const screenshot = ( await Jimp.read( await page.screenshot(), { quality: jpgQuality } ) ).scale( 1 / viewScale );
  409. if ( page.error !== undefined ) throw new Error( page.error );
  410. if ( isMakeScreenshot ) {
  411. /* Make screenshots */
  412. await screenshot.write( `examples/screenshots/${ file }.jpg` );
  413. console.green( `Screenshot generated for file ${ file }` );
  414. } else {
  415. /* Diff screenshots */
  416. let expected;
  417. try {
  418. expected = ( await Jimp.read( `examples/screenshots/${ file }.jpg`, { quality: jpgQuality } ) );
  419. } catch {
  420. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  421. throw new Error( `Screenshot does not exist: ${ file }` );
  422. }
  423. const actual = screenshot.bitmap;
  424. const diff = screenshot.clone();
  425. let numDifferentPixels;
  426. try {
  427. numDifferentPixels = pixelmatch( expected.bitmap.data, actual.data, diff.bitmap.data, actual.width, actual.height, {
  428. threshold: pixelThreshold,
  429. alpha: 0.2
  430. } );
  431. } catch {
  432. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  433. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  434. throw new Error( `Image sizes does not match in file: ${ file }` );
  435. }
  436. /* Print results */
  437. const differentPixels = numDifferentPixels / ( actual.width * actual.height ) * 100;
  438. if ( differentPixels < maxDifferentPixels ) {
  439. console.green( `Diff ${ differentPixels.toFixed( 1 ) }% in file: ${ file }` );
  440. } else {
  441. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  442. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  443. await diff.write( `test/e2e/output-screenshots/${ file }-diff.jpg` );
  444. throw new Error( `Diff wrong in ${ differentPixels.toFixed( 1 ) }% of pixels in file: ${ file }` );
  445. }
  446. }
  447. } catch ( e ) {
  448. if ( attemptID === numAttempts - 1 ) {
  449. console.red( e );
  450. failedScreenshots.push( file );
  451. } else {
  452. console.yellow( `${ e }, another attempt...` );
  453. this.add( file, attemptID + 1 );
  454. }
  455. }
  456. page.file = undefined; // release lock
  457. }
  458. function close( exitCode = 1 ) {
  459. console.log( 'Closing...' );
  460. browser.close();
  461. server.close();
  462. process.exit( exitCode );
  463. }
粤ICP备19079148号