Best JavaScript code snippet using testcafe
assertion-helper.js
Source:assertion-helper.js
...42 });43 return results;44}45function checkScreenshotFileCropped (filePath) {46 return readPngFile(filePath)47 .then(function (png) {48 const width = png.width;49 const height = png.height;50 // NOTE: sometimes an appearing dialog can cover an edge of the browser. Try to check all edges51 return hasPixel(png, RED_PIXEL, 0, 0) && hasPixel(png, RED_PIXEL, 49, 49) && hasPixel(png, GREEN_PIXEL, 50, 50) ||52 hasPixel(png, RED_PIXEL, width - 1, height - 1) && hasPixel(png, RED_PIXEL, width - 50, height - 50) && hasPixel(png, GREEN_PIXEL, width - 51, height - 51) ||53 hasPixel(png, RED_PIXEL, width - 1, 0) && hasPixel(png, RED_PIXEL, width - 50, 49) && hasPixel(png, GREEN_PIXEL, width - 51, 50) ||54 hasPixel(png, RED_PIXEL, 0, height - 1) && hasPixel(png, RED_PIXEL, 49, height - 50) && hasPixel(png, GREEN_PIXEL, 50, height - 51);55 });56}57function checkScreenshotFileFullPage (filePath) {58 return readPngFile(filePath)59 .then(function (png) {60 const width = png.width;61 const height = png.height;62 const expectedHeight = 5000;63 return height === expectedHeight &&64 hasPixel(png, RED_PIXEL, 0, 0) &&65 hasPixel(png, RED_PIXEL, width - 1, height - 1) &&66 hasPixel(png, GREEN_PIXEL, 0, height - 1) &&67 hasPixel(png, GREEN_PIXEL, width - 1, 0);68 });69}70function checkScreenshotFileIsNotWhite (filePath) {71 return readPngFile(filePath)72 .then(function (png) {73 return png.data.indexOf(Buffer.from(RED_PIXEL)) > -1 && png.data.indexOf(Buffer.from(GREEN_PIXEL)) > -1;74 });75}76function isDirExists (folderPath) {77 let exists = false;78 try {79 exists = fs.statSync(folderPath).isDirectory();80 }81 catch (e) {82 exists = false;83 }84 return exists;85}86function checkTestDir (testDirPath, forError, expectedSubDirCount, expectedScreenshotCount) {87 const subDirs = fs88 .readdirSync(testDirPath)89 .filter(function (file) {90 return isDirExists(path.join(testDirPath, file));91 });92 if (subDirs.length !== expectedSubDirCount)93 return false;94 let dirPath = null;95 return subDirs.every(function (dir) {96 dirPath = forError ? path.join(testDirPath, dir, ERRORS_DIR_NAME) : path.join(testDirPath, dir);97 return getScreenshotFilesCount(dirPath) === expectedScreenshotCount;98 });99}100function checkScreenshotImages (forError, customPath, predicate, expectedScreenshotsCount = config.browsers.length) {101 if (!isDirExists(SCREENSHOTS_PATH))102 return false;103 const taskDirs = fs.readdirSync(SCREENSHOTS_PATH);104 if (!taskDirs || !taskDirs[0] || taskDirs.length !== 1)105 return false;106 const taskDirPath = path.join(SCREENSHOTS_PATH, taskDirs[0]);107 let list = [];108 if (forError) {109 const testDirs = fs.readdirSync(taskDirPath);110 if (!testDirs || !testDirs[0] || testDirs.length !== 1)111 return false;112 const testDirPath = path.join(taskDirPath, testDirs[0]);113 const browserDirs = fs.readdirSync(testDirPath);114 browserDirs.forEach(function (browserDir) {115 const errorDirPath = path.join(testDirPath, browserDir, 'errors');116 const screenshotFiles = fs.readdirSync(errorDirPath);117 const screenshotPaths = screenshotFiles.map(function (screenshotFile) {118 return path.join(errorDirPath, screenshotFile);119 });120 list = list.concat(screenshotPaths);121 });122 }123 else {124 if (taskDirPath.indexOf(customPath) < 0)125 return false;126 list = fs.readdirSync(taskDirPath).map(function (screenshotFile) {127 return path.join(taskDirPath, screenshotFile);128 });129 }130 if (list.length < config.browsers.length)131 return false;132 list = list.filter(function (filePath) {133 return filePath.match(CUSTOM_SCREENSHOT_FILE_NAME_RE);134 });135 return Promise136 .all(list.map(function (filePath) {137 return predicate(filePath);138 }))139 .then(function (checkResults) {140 let actualScreenshotsCount = 0;141 for (let i = 0; i < checkResults.length; i++)142 actualScreenshotsCount += checkResults[i] ? 1 : 0;143 return actualScreenshotsCount === expectedScreenshotsCount;144 });145}146exports.errorInEachBrowserContains = function errorInEachBrowserContains (testErrors, message, errorIndex) {147 if (testErrors instanceof Error)148 throw testErrors;149 // NOTE: if errors are the same in different browsers150 if (Array.isArray(testErrors))151 expect(testErrors[errorIndex]).contains(message);152 //NOTE: if they are different153 else {154 Object.keys(testErrors).forEach(function (key) {155 expect(testErrors[key][errorIndex]).contains(message);156 });157 }158};159exports.errorInEachBrowserContainsRegExp = function errorInEachBrowserContains (testErrors, messageRE, errorIndex) {160 if (testErrors instanceof Error)161 throw testErrors;162 // NOTE: if errors are the same in different browsers163 if (Array.isArray(testErrors))164 expect(messageRE.test(testErrors[errorIndex])).equals(true);165 //NOTE: if they are different166 else {167 Object.keys(testErrors).forEach(function (key) {168 expect(messageRE.test(testErrors[key][errorIndex])).equals(true);169 });170 }171};172exports.errorInEachBrowserNotContains = function errorInEachBrowserNotContains (testErrors, message, errorIndex) {173 if (testErrors instanceof Error)174 throw testErrors;175 // NOTE: if errors are the same in different browsers176 if (Array.isArray(testErrors))177 expect(testErrors[errorIndex]).not.contains(message);178 //NOTE: if the are different179 else {180 Object.keys(testErrors).forEach(function (key) {181 expect(testErrors[key][errorIndex]).not.contains(message);182 });183 }184};185exports.isScreenshotDirExists = function () {186 return isDirExists(SCREENSHOTS_PATH);187};188exports.checkScreenshotsCreated = function ({ forError, customPath, screenshotsCount, runDirCount, browsersCount, baseDir }) {189 const expectedSubDirCount = browsersCount || config.browsers.length;190 const expectedScreenshotCount = screenshotsCount || 2;191 baseDir = baseDir || SCREENSHOTS_PATH;192 if (!isDirExists(baseDir))193 return false;194 const taskDirs = fs.readdirSync(baseDir);195 if (!taskDirs || !taskDirs[0] || taskDirs.length !== 1)196 return false;197 const taskDirPath = path.join(baseDir, taskDirs[0]);198 if (customPath) {199 const customDirExists = taskDirPath.includes(customPath);200 const hasScreenshots = getScreenshotFilesCount(taskDirPath, customPath) ===201 expectedScreenshotCount * expectedSubDirCount;202 return customDirExists && hasScreenshots;203 }204 if (!TASK_DIR_RE.test(taskDirs[0]))205 return false;206 const testDirs = fs.readdirSync(taskDirPath);207 if (!testDirs || !testDirs.length || testDirs.length !== 1)208 return false;209 let basePath = null;210 let dirs = null;211 let dirNameRE = null;212 let dirPath = null;213 if (runDirCount) {214 basePath = path.join(taskDirPath, testDirs[0]);215 dirs = fs.readdirSync(basePath);216 dirNameRE = RUN_DIR_NAME_RE;217 if (!dirs || !dirs.length || dirs.length !== runDirCount)218 return false;219 }220 else {221 basePath = taskDirPath;222 dirs = testDirs;223 dirNameRE = TEST_DIR_NAME_RE;224 }225 return dirs.every(function (dir) {226 if (!dirNameRE.test(dir))227 return false;228 dirPath = path.join(basePath, dir);229 return checkTestDir(dirPath, forError, expectedSubDirCount, expectedScreenshotCount);230 });231};232exports.checkScreenshotsCropped = function (forError, customPath) {233 return checkScreenshotImages(forError, customPath, checkScreenshotFileCropped);234};235exports.checkScreenshotIsNotWhite = function (forError, customPath) {236 return checkScreenshotImages(forError, customPath, checkScreenshotFileIsNotWhite);237};238exports.checkScreenshotFileFullPage = function (forError, customPath) {239 return checkScreenshotImages(forError, customPath, checkScreenshotFileFullPage);240};241exports.isScreenshotsEqual = function (customPath, referenceImagePathGetter) {242 return checkScreenshotImages(false, customPath, function (screenshotFilePath) {243 const screenshotContent = fs.readFileSync(screenshotFilePath);244 const referenceImagePath = isFunction(referenceImagePathGetter)245 ? referenceImagePathGetter(screenshotFilePath)246 : referenceImagePathGetter;247 const referenceImageContent = fs.readFileSync(referenceImagePath);248 return screenshotContent.equals(referenceImageContent);249 });250};251exports.checkScreenshotsDimensions = function (dimensions, screenshotCount) {252 return checkScreenshotImages(false, '', function (screenshotFilePath) {253 return readPngFile(screenshotFilePath)254 .then(png => {255 return dimensions.width === png.width && dimensions.height === png.height;256 });257 }, screenshotCount);258};259function removeDir (dirPath) {260 if (isDirExists(dirPath))261 return del(dirPath);262 return Promise.resolve();263}264exports.removeScreenshotDir = (dir = SCREENSHOTS_PATH) => removeDir(dir);265exports.removeVideosDir = () => removeDir(VIDEOS_PATH);266exports.getVideoFilesList = () => {267 return globby(VIDEO_FILES_GLOB, { nodir: true });...
PNG160.js
Source:PNG160.js
1let pako = require("pako");2class CRC {3 static createTable32() {4 CRC.TABLE32 = new Uint32Array(256);5 for (let i = 256; i--; ) {6 let tmp = i;7 for (let k = 8; k--; ) {8 tmp = tmp & 1 ? 3988292384 ^ (tmp >>> 1) : tmp >>> 1;9 }10 CRC.TABLE32[i] = tmp;11 }12 }13 static crc32(data) {14 if (!CRC.TABLE32) {15 CRC.createTable32();16 }17 let crc = -1; // Begin with all bits set ( 0xffffffff )18 for (let i = 0, l = data.length; i < l; i++) {19 crc = (crc >>> 8) ^ CRC.TABLE32[(crc & 255) ^ data[i]];20 }21 return (crc ^ -1) >>> 0; // Apply binary NOT22 }23}24class PNG160 {25 //VERY LIKELY TO HAVE PROBLEMS WITH THIRD PARTY IMAGES!26 //TODO: change IDAT size after edit27 static readPNGFile(data, metaDataSet, read) {28 if (isPng(data)) {29 let index = PNG160.PNG_HEADER.length;30 //PNG properties from IHDR:31 let width, height, bitdepth, colortype, filterType;32 let alldata = new Uint8Array();33 let earlyStop = false;34 //Read file35 while (index < data.length && !earlyStop) {36 let dataLength = bytesToInt32(data, index, index + 4);37 let chunktype = bytesToInt32(data, index + 4, index + 8);38 let nextIndex = index + 12 + dataLength;39 if (bitdepth && bitdepth != 16 && colortype != 0) {40 console.log("INCORRECT FORMAT");41 break;42 }43 switch (chunktype) {44 case bytesToInt32(PNG160.IHDR):45 width = bytesToInt32(data, index + 8, index + 12);46 height = bytesToInt32(data, index + 12, index + 16);47 bitdepth = data[index + 16];48 colortype = data[index + 17];49 filterType = data[index + 19];50 metaDataSet({ width: width, height: height, bitdepth: bitdepth, colortype: colortype, filterType: filterType });51 //If read not set, no reason to continue52 if (read == null) {53 earlyStop = true;54 }55 break;56 case bytesToInt32(PNG160.IDAT):57 let nextChunktype = bytesToInt32(data, nextIndex + 4, nextIndex + 8);58 let chunkdata = data.subarray(index + 8, index + 8 + dataLength);59 let temp = new Uint8Array(alldata.length + chunkdata.length);60 temp.set(alldata);61 temp.set(chunkdata, alldata.length);62 alldata = temp;63 if (nextChunktype != bytesToInt32(PNG160.IDAT)) {64 let imagedata = pako.inflate(alldata);65 let filter = new Filters(imagedata, width);66 //Undo existing filters:67 let linefilter = 0,68 imageIndex = 0;69 for (let i = 0; i < (height + 1) * width; i++) {70 if (i % (1 + width)) {71 switch (linefilter) {72 case 0: //Nothing filter73 break;74 case 1: // Sub75 imagedata[imageIndex] += filter.raw(imageIndex); //First byte76 imagedata[imageIndex + 1] += filter.raw(imageIndex + 1); //Second byte77 break;78 case 2: // Up79 imagedata[imageIndex] += filter.prior(imageIndex);80 imagedata[imageIndex + 1] += filter.prior(imageIndex + 1);81 break;82 case 3: //Average83 imagedata[imageIndex] += filter.average(imageIndex);84 imagedata[imageIndex + 1] += filter.average(imageIndex + 1);85 break;86 case 4: //Paeth87 imagedata[imageIndex] += filter.paeth(imageIndex);88 imagedata[imageIndex + 1] += filter.paeth(imageIndex + 1);89 break;90 }91 read(width, i - 1 - ((i / (width + 1)) >> 0), bytesToInt16(imagedata, imageIndex));92 imageIndex += 2;93 filter.xindex++;94 } else {95 linefilter = imagedata[imageIndex];96 imagedata[imageIndex] = 0x00;97 imageIndex++;98 filter.xindex = 0;99 }100 }101 }102 break;103 case bytesToInt32(PNG160.IEND):104 break;105 default:106 let charcode = new TextDecoder("utf-8").decode(getInt32Bytes(chunktype).buffer);107 let hexcode = tohex(getInt32Bytes(chunktype));108 console.log("Unprocced chunk -> charcode: " + charcode + " hexcode: " + hexcode);109 break;110 }111 index += 12 + dataLength; //Move on to next block112 }113 }114 }115 static getRawImage(pngfile, dataconverter) {116 dataconverter = dataconverter117 ? dataconverter118 : value => {119 return value;120 };121 let image = {};122 PNG160.readPNGFile(123 pngfile,124 metadata => {125 image.data = new Uint16Array(metadata.width * metadata.height);126 image.height = metadata.height;127 image.width = metadata.width;128 },129 (width, i, value) => {130 image.data[i] = dataconverter(value);131 }132 );133 return image;134 }135 static getImageHeader(pngfile) {136 let header;137 PNG160.readPNGFile(pngfile, metadata => {138 header = metadata;139 });140 return header;141 }142 static createPNG(height, width, dataputter) {143 //Add png header144 let tempdata = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];145 tempdata.pushAll = (array, values) => {146 values.forEach(v => {147 array.push(v);148 });149 };150 //--------------------------------------------151 //-----------------IHDR-----------------------152 //--------------------------------------------153 tempdata.pushAll(tempdata, getInt32Bytes(13)); //Length154 tempdata.pushAll(tempdata, PNG160.IHDR); //Chunk type155 tempdata.pushAll(tempdata, getInt32Bytes(width));156 tempdata.pushAll(tempdata, getInt32Bytes(height));157 tempdata.push(0x10); // bit depth158 tempdata.push(0x0); // color type159 tempdata.push(0x0); // compression method160 tempdata.push(0x0); // filter method161 tempdata.push(0x0); // interlace method162 tempdata.pushAll(tempdata, getInt32Bytes(CRC.crc32(tempdata.slice(12, 29)))); //CRC163 //--------------------------------------------164 //-----------------IDAT-----------------------165 //--------------------------------------------166 //Create data167 let imagedata = new Uint8Array(height * width * 2 + height);168 let imageindex = 0;169 for (let i = 0; i < (height + 1) * width; i++) {170 if (i % (1 + width)) {171 let value = getInt16Bytes(dataputter(width, height, i - 1 - ((i / (width + 1)) >> 0)));172 imagedata[imageindex++] = value[0];173 imagedata[imageindex++] = value[1];174 } else {175 imagedata[imageindex++] = 0;176 }177 }178 let compressed = pako.deflate(imagedata, { level: 9, windowBits: 8, strategy: 1 });179 //Create chunk180 tempdata.pushAll(tempdata, getInt32Bytes(compressed.length)); //Length181 tempdata.pushAll(tempdata, PNG160.IDAT); //Chunk type182 tempdata.pushAll(tempdata, compressed); //Data183 tempdata.pushAll(tempdata, getInt32Bytes(CRC.crc32(tempdata.slice(37, 41 + compressed.length)))); //CRC184 //--------------------------------------------185 //-----------------IEND-----------------------186 //--------------------------------------------187 tempdata.pushAll(tempdata, getInt32Bytes(0)); //Length188 tempdata.pushAll(tempdata, PNG160.IEND); //Chunk type189 tempdata.pushAll(tempdata, [0xae, 0x42, 0x60, 0x82]); //CRC190 return new Uint8Array(tempdata);191 }192 static get IHDR() {193 return new Uint8Array([0x49, 0x48, 0x44, 0x52]);194 }195 static get IDAT() {196 return new Uint8Array([0x49, 0x44, 0x41, 0x54]);197 }198 static get IEND() {199 return new Uint8Array([0x49, 0x45, 0x4e, 0x44]);200 }201 static get PNG_HEADER() {202 return new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);203 }204}205//Filter functions206class Filters {207 constructor(array, width) {208 this.array = array;209 this.width = width;210 this.xindex = 0;211 }212 paethPredictor(a, b, c) {213 let p = a + b - c;214 let pa = Math.abs(p - a);215 let pb = Math.abs(p - b);216 let pc = Math.abs(p - c);217 if (pa <= pb && pa <= pc) return a;218 else if (pb <= pc) return b;219 else return c;220 }221 paeth(x) {222 let upperleft = 0;223 if (this.xindex != 0) {224 upperleft = this.prior(x - 2);225 }226 return this.paethPredictor(this.raw(x), this.prior(x), upperleft);227 }228 raw(x) {229 if (this.xindex != 0) {230 return this.array[x - 2];231 } else {232 return 0;233 }234 }235 prior(x) {236 return this.array[x - (this.width * 2 + 1)];237 }238 average(x) {239 return Math.floor((this.raw(x) + this.prior(x)) / 2);240 }241}242function isPng(data) {243 let ispng = true;244 data.subarray(0, 8).forEach((byte, i) => {245 ispng = byte == PNG160.PNG_HEADER[i] ? ispng : false;246 });247 return ispng;248}249//Helper methods250function getInt32Bytes(x) {251 var bytes = [];252 for (let i = 3; i >= 0; i--) {253 bytes[i] = x & 255;254 x = x >> 8;255 }256 return new Uint8Array(bytes);257}258function bytesToInt32(data, start, end) {259 var dataView = new DataView(data.buffer.slice(start, end));260 return dataView.getUint32(0);261}262function tohex(input) {263 let temp = "";264 input.forEach(element => {265 let hex = element.toString(16);266 if (hex.length == 1) {267 hex = "0" + hex;268 }269 temp += hex + " ";270 });271 temp.trim();272 return temp;273}274function bytesToInt16(data, start) {275 return data[start] * 256 + data[start + 1];276}277function getInt16Bytes(x) {278 var bytes = [];279 for (let i = 1; i >= 0; i--) {280 bytes[i] = x & 255;281 x = x >> 8;282 }283 return new Uint8Array(bytes);284}...
crop-test.js
Source:crop-test.js
...154 err = e;155 }156 finally {157 expect(err.message).contains('Unable to locate the page area in the browser window screenshot');158 const file = await readPngFile(screenshotPath);159 expect(file).is.not.null;160 await deleteFile(screenshotPath);161 }162 });...
index.mjs
Source:index.mjs
1import nvk from "nvk";2import tolw from "tolw";3import glMatrix from "gl-matrix";4import { performance } from "perf_hooks";5import { LOG } from "./utils.mjs";6import { dirname, readPNGFile, readObjectFile } from "./utils.mjs";7import RayTracer from "./RayTracer/index.mjs";8import VulkanApplication from "./VulkanApplication.mjs";9Object.assign(global, nvk);10Object.assign(global, glMatrix);11// input flags12global.VERBOSE = !!(13 process.env.npm_config_verbose_log ||14 process.argv.filter(v => v.match("--verbose-log"))[0]15);16// prefer to use diescrete gpu over integrated gpu17global.PREFER_DISCRETE_GPU = !!(18 process.env.npm_config_prefer_discrete_gpu ||19 process.argv.filter(v => v.match("--prefer-discrete-gpu"))[0]20);21// material models22const MATERIAL_MODEL = {23 EMISSIVE: 0,24 METALLIC: 1,25 DIELECTRIC: 2,26 LAMBERTIAN: 327};28// source:29// https://en.wikipedia.org/wiki/Refractive_index30const INDEX_OF_REFRACTION = {31 VACUUM: 1.0,32 AIR: 1.000293,33 HELIUM: 1.000036,34 HYDROGEN: 1.000132,35 CARBON_DIOXIDE: 1.00045,36 // Liquids at 20 °C37 WATER: 1.333,38 ETHANOL: 1.36,39 OLIVE_OIL: 1.47,40 // Solids41 ICE: 1.31,42 QUARTZ: 1.46,43 PMMA: 1.49,44 WINDOW_GLASS: 1.52,45 POLYCARBONATE: 1.58,46 FLINT_GLASS: 1.62,47 SAPPHIRE: 1.77,48 CUBIC_ZIRCONIA: 2.15,49 DIAMOND: 2.42,50 MOISSANITE: 2.6551};52let desiredSurfaceFormat = VK_FORMAT_B8G8R8A8_UNORM;53let requiredExtensions = [54 VK_KHR_SWAPCHAIN_EXTENSION_NAME,55 VK_NV_RAY_TRACING_EXTENSION_NAME,56 VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,57 VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME,58 VK_KHR_MAINTENANCE3_EXTENSION_NAME59];60let validationLayers = [61 "VK_LAYER_LUNARG_core_validation",62 "VK_LAYER_LUNARG_standard_validation",63 "VK_LAYER_LUNARG_parameter_validation"64];65class RayTracingDemo extends VulkanApplication {66 constructor() {67 super({ validationLayers, requiredExtensions, desiredSurfaceFormat });68 this.deviceName = "";69 this.rayTracer = null;70 }71};72RayTracingDemo.prototype.initialise = function() {73 LOG("Initializing TinyObjLoader (WebAssembly)");74 return tolw.init();75};76RayTracingDemo.prototype.create = async function() {77 LOG("Initializing TinyObjLoader (WebAssembly)");78 await tolw.init();79 LOG("Creating window");80 this.window = this.createWindow();81 LOG("Creating Instance");82 this.instance = this.createInstance();83 LOG("Creating Physical Device");84 this.physicalDevice = this.createPhysicalDevice();85 {86 let deviceProperties = this.physicalDevice.getDeviceProperties();87 let {type, properties} = deviceProperties;88 this.deviceName = `${properties.deviceName} (${type})`;89 LOG(`Using Device: ${this.deviceName}`);90 }91 LOG("Creating Logical Device");92 this.logicalDevice = this.createLogicalDevice();93 LOG("Creating Surface");94 this.surface = this.createSurface();95 LOG("Creating Swapchain");96 this.swapchain = this.createSwapchain();97 LOG("Instantiating RayTracer");98 this.rayTracer = this.createRayTracer();99};100RayTracingDemo.prototype.execute = function() {101 let drag = false;102 let {window, rayTracer} = this;103 LOG("Executing RayTracer");104 rayTracer.create();105 let {camera} = rayTracer;106 // add window event listeners107 {108 let isShiftPressed = false;109 window.onkeydown = e => {110 if (e.keyCode === 340) isShiftPressed = true;111 };112 window.onkeyup = e => {113 if (e.keyCode === 340) isShiftPressed = false;114 };115 window.onmousedown = e => (drag = true);116 window.onmouseup = e => (drag = false);117 window.onmousemove = e => {118 if (!drag) return;119 camera.rotation.vx += -e.movementX * 0.325;120 camera.rotation.vy += -e.movementY * 0.325;121 camera.resetSampleCount();122 };123 window.onmousewheel = e => {124 let {deltaY} = e;125 if (isShiftPressed) deltaY = deltaY * 0.25;126 camera.distance.vz += deltaY;127 camera.resetSampleCount();128 };129 }130 // draw loop131 let app = this;132 let then = 0;133 let frames = 0;134 (function drawLoop() {135 if (!window.shouldClose()) setTimeout(drawLoop, 0);136 let now = performance.now();137 let delta = (now - then);138 if (delta > 1.0 || frames === 0) {139 let fps = Math.floor((frames / delta) * 1e3);140 window.title = `Vulkan RTX - ${app.deviceName} - FPS: ${fps} - Samples: ${camera.totalSampleCount} (${camera.sampleCount} SPP)`;141 frames = 0;142 }143 frames++;144 app.drawFrame();145 camera.update();146 then = now;147 window.pollEvents();148 })();149};150RayTracingDemo.prototype.loadGeometryFile = function(path) {151 let ext = path.substr(path.lastIndexOf("."));152 if (ext !== ".obj") console.warn(`This Demo only supports Wavefront OBJ (.obj) as object files`);153 return this.addGeometryMesh(readObjectFile(path));154};155RayTracingDemo.prototype.loadTextureFile = function(path) {156 let ext = path.substr(path.lastIndexOf("."));157 if (ext !== ".png") console.warn(`This Demo only supports PNG (.png) as image files`);158 return this.rayTracer.addTexture(readPNGFile(path));159};160RayTracingDemo.prototype.addGeometryMesh = function(geometry) {161 return this.rayTracer.addGeometry(geometry);162};163RayTracingDemo.prototype.addMaterial = function(material) {164 return this.rayTracer.addMaterial(material);165};166RayTracingDemo.prototype.useSkyboxTexture = function(texture) {167 this.skyboxTexture = texture;168};169RayTracingDemo.prototype.drawFrame = function() {170 this.drawDefaultFrame();171};172RayTracingDemo.prototype.createRayTracer = function() {173 let {swapchain, surface, window, logicalDevice, physicalDevice} = this;174 let application = this;175 let rayTracer = new RayTracer({176 application,177 swapchain,178 surface,179 window,180 logicalDevice,181 physicalDevice182 });183 return rayTracer;184};185RayTracingDemo.MATERIAL_MODEL = MATERIAL_MODEL;186RayTracingDemo.INDEX_OF_REFRACTION = INDEX_OF_REFRACTION;...
capturer.js
Source:capturer.js
...93 await this._takeScreenshot(screenshotPath, ...clientAreaDimensions ? [clientAreaDimensions.width, clientAreaDimensions.height] : []);94 if (!await Capturer._isScreenshotCaptured(screenshotPath))95 return;96 try {97 const image = await readPngFile(screenshotPath);98 const croppedImage = await cropScreenshot(image, {99 markSeed,100 clientAreaDimensions,101 path: screenshotPath,102 cropDimensions: Capturer._getCropDimensions(cropDimensions, pageDimensions)103 });104 if (croppedImage)105 await writePng(screenshotPath, croppedImage);106 }107 catch (err) {108 await deleteFile(screenshotPath);109 throw err;110 }111 await generateThumbnail(screenshotPath, thumbnailPath);...
take-screenshot.js
Source:take-screenshot.js
...82 const screenshotName = 'custom/' + parsedUA.family + '.png';83 const scrollbarSize = await getScrollbarSize();84 await t.hover('#target');85 await t.takeScreenshot(screenshotName);86 const png = await readPngFile(join(config.testScreenshotsDir, screenshotName));87 const expectedWidth = width - scrollbarSize;88 const expectedHeight = height - scrollbarSize;89 // NOTE: IE clips screenshots not accurately90 const accuracy = is(ua).ie ? 1 : 0;91 await t.expect(scrollbarSize).gt(0);92 await t.expect(Math.abs(png.width - expectedWidth)).lte(accuracy);93 await t.expect(Math.abs(png.height - expectedHeight)).lte(accuracy);...
uber_noun.js
Source:uber_noun.js
...9 for (const folder of folders) {10 const folderpath = path.join(__dirname, "./images", folder);11 const files = await fs.readdir(folderpath);12 for (const file of files) {13 const image = await readPngFile(path.join(folderpath, file));14 encoder.encodeImage(file.replace(/\.png$/, ""), image, folder);15 }16 }17 await encoder.writeToFile(DESTINATION);18};...
rleEncodeSingleImage.js
Source:rleEncodeSingleImage.js
...8const DESTINATION = path.join(__dirname, '../output/singleWearable.json');9const encode = async () => {10 const encoder = new PNGCollectionEncoder()11 const filepath = path.join(__dirname, '../wearablesImages/customGlasses/fast-food-glasses.png')12 const image = await readPngFile(filepath)13 encoder.encodeImage(filepath.replace(/\.png$/, ''), image)14 await encoder.writeToFile(DESTINATION)15 16}...
Using AI Code Generation
1import { readPngFile } from 'testcafe-browser-tools';2test('My Test', async t => {3 .click('#populate')4 .click('#submit-button');5 const pngData = await readPngFile('C:\\Users\\test\\Desktop\\test.png');6 .takeScreenshot(pngData)7 .click('#restart-button');8});
Using AI Code Generation
1import { readPngFile } from 'testcafe-browser-tools';2test('My Test', async t => {3 const img = await readPngFile('path/to/image.png');4});5import { readPngFile } from 'testcafe-browser-tools';6test('My Test', async t => {7 const img = await readPngFile('path/to/image.png');8});9import { readPngFile } from 'testcafe-browser-tools';10test('My Test', async t => {11 const img = await readPngFile('path/to/image.png');12});13import { readPngFile } from 'testcafe-browser-tools';14test('My Test', async t => {15 const img = await readPngFile('path/to/image.png');16});17import { readPngFile } from 'testcafe-browser-tools';18test('My Test', async t => {19 const img = await readPngFile('path/to/image.png');20});21import { readPngFile } from 'testcafe-browser-tools';22test('My Test', async t => {23 const img = await readPngFile('path/to/image.png');24});25import { readPngFile
Using AI Code Generation
1import { readPngFile } from './readPngFile';2import { readJpegFile } from './readJpegFile';3import { readGifFile } from './readGifFile';4import { readBmpFile } from './readBmpFile';5import { readTiffFile } from './readTiffFile';6import { readWebpFile } from './readWebpFile';7test('My first test', async t => {8 const pngFile = await readPngFile('test.png');9 const jpegFile = await readJpegFile('test.jpg');10 const gifFile = await readGifFile('test.gif');11 const bmpFile = await readBmpFile('test.bmp');12 const tiffFile = await readTiffFile('test.tiff');13 const webpFile = await readWebpFile('test.webp');14});15import { Selector } from 'testcafe';16import { PNG } from 'pngjs';17import { createCanvas } from 'canvas';18import pixelmatch from 'pixelmatch';19export async function readPngFile(fileName) {20 let pngFile = null;21 await Selector('input[type=file]').addCustomDOMProperties({22 }).with({ boundTestRun: testController })23 .addCustomMethods({24 async readPngFile() {25 const files = await this.files;26 const file = files[0];27 if (
Using AI Code Generation
1test('My test', async t => {2 .click('#populate')3 .click('#submit-button')4 .takeScreenshot('screenshot1.png')5 .click('#tried-test-cafe')6 .takeScreenshot('screenshot2.png')7 .click('#slider')8 .takeScreenshot('screenshot3.png');9});10import { readPngFile } from 'testcafe-browser-tools';11test('My test', async t => {12 .click('#populate')13 .click('#submit-button')14 .takeScreenshot('screenshot1.png')15 .click('#tried-test-cafe')16 .takeScreenshot('screenshot2.png')17 .click('#slider')18 .takeScreenshot('screenshot3.png');19 const screenshot1 = await readPngFile('screenshot1.png');20 const screenshot2 = await readPngFile('screenshot2.png');21 const screenshot3 = await readPngFile('screenshot3.png');22});23import { readPngFile } from 'testcafe-browser-tools';24test('My test', async t => {25 .click('#populate')26 .click('#submit-button')27 .takeScreenshot('screenshot1.png')28 .click('#tried-test-cafe')29 .takeScreenshot('screenshot2.png')30 .click('#slider')31 .takeScreenshot('screenshot3.png');32 const screenshot1 = await readPngFile('screenshot1.png');33 const screenshot2 = await readPngFile('screenshot2.png');34 const screenshot3 = await readPngFile('screenshot3.png');35});36import { readPngFile, comparePngFiles } from 'testcafe-browser-tools';37test('My test', async t => {38 .click('#populate')39 .click('#submit-button')
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!