puppeteer.js 16 KB

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