puppeteer.js 17 KB

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