[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-3316":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":10,"pushedAt":10,"updatedAt":31,"readmeContent":32,"aiSummary":33,"trendingCount":16,"starSnapshotCount":16,"syncStatus":34,"lastSyncTime":35,"discoverSource":36},3316,"gpu.js","gpujs\u002Fgpu.js","gpujs","GPU Accelerated JavaScript","https:\u002F\u002Fgpu.rocks",null,"JavaScript",15357,665,241,204,0,4,43.47,"MIT License",false,"develop",true,[24,25,26,27,28,29,30],"glsl","gpgpu","gpu","javascript","math","nodejs","webgl","2026-06-12 02:00:48","[\u003Cimg width=\"100\" alt=\"Logo\" src=\"http:\u002F\u002Fgpu.rocks\u002Fstatic\u002Fmedia\u002Fjelly.3587de60.png\">](http:\u002F\u002Fgpu.rocks\u002F)\n# GPU.js\nGPU.js is a JavaScript Acceleration library for GPGPU (General purpose computing on GPUs) in JavaScript for Web and Node.\nGPU.js automatically transpiles simple JavaScript functions into shader language and compiles them so they run on your GPU.\nIn case a GPU is not available, the functions will still run in regular JavaScript.\nFor some more quick concepts, see [Quick Concepts](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fwiki\u002FQuick-Concepts) on the wiki.\n\n\n[![Join the chat at https:\u002F\u002Fgitter.im\u002Fgpujs\u002Fgpu.js](https:\u002F\u002Fbadges.gitter.im\u002Fgpujs\u002Fgpu.js.svg)](https:\u002F\u002Fgitter.im\u002Fgpujs\u002Fgpu.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[![Slack](https:\u002F\u002Fslack.bri.im\u002Fbadge.svg)](https:\u002F\u002Fslack.bri.im)\n\n# What is this sorcery?\n\nCreates a GPU accelerated kernel transpiled from a javascript function that computes a single element in the 512 x 512 matrix (2D array).\nThe kernel functions are ran in tandem on the GPU often resulting in very fast computations!\nYou can run a benchmark of this [here](http:\u002F\u002Fgpu.rocks). Typically, it will run 1-15x faster depending on your hardware.\nMatrix multiplication (perform matrix multiplication on 2 matrices of size 512 x 512) written in GPU.js:\n\n## Browser\n```html\n\u003Cscript src=\"dist\u002Fgpu-browser.min.js\">\u003C\u002Fscript>\n\u003Cscript>\n    \u002F\u002F GPU is a constructor and namespace for browser\n    const gpu = new GPU();\n    const multiplyMatrix = gpu.createKernel(function(a, b) {\n        let sum = 0;\n        for (let i = 0; i \u003C 512; i++) {\n            sum += a[this.thread.y][i] * b[i][this.thread.x];\n        }\n        return sum;\n    }).setOutput([512, 512]);\n\n    const c = multiplyMatrix(a, b);\n\u003C\u002Fscript>\n```\n\n## CDN\n``` \nhttps:\u002F\u002Funpkg.com\u002Fgpu.js@latest\u002Fdist\u002Fgpu-browser.min.js\nhttps:\u002F\u002Fcdn.jsdelivr.net\u002Fnpm\u002Fgpu.js@latest\u002Fdist\u002Fgpu-browser.min.js\n```\n\n## Node\n```js\nconst { GPU } = require('gpu.js');\nconst gpu = new GPU();\nconst multiplyMatrix = gpu.createKernel(function(a, b) {\n    let sum = 0;\n    for (let i = 0; i \u003C 512; i++) {\n        sum += a[this.thread.y][i] * b[i][this.thread.x];\n    }\n    return sum;\n}).setOutput([512, 512]);\n\nconst c = multiplyMatrix(a, b);\n```\n\n## Typescript\n```typescript\nimport { GPU } from 'gpu.js';\nconst gpu = new GPU();\nconst multiplyMatrix = gpu.createKernel(function(a: number[][], b: number[][]) {\n  let sum = 0;\n  for (let i = 0; i \u003C 512; i++) {\n    sum += a[this.thread.y][i] * b[i][this.thread.x];\n  }\n  return sum;\n}).setOutput([512, 512]);\n\nconst c = multiplyMatrix(a, b) as number[][];\n```\n\n[Click here](\u002Fexamples) for more typescript examples.\n\n# Table of Contents\n\nNotice documentation is off?  We do try our hardest, but if you find something,\n  [please bring it to our attention](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fissues), or _[become a contributor](#contributors)_!\n\n* [Demos](#demos)\n* [Installation](#installation)\n* [`GPU` Settings](#gpu-settings)\n* [`gpu.createKernel` Settings](#gpucreatekernel-settings)\n  * [Declaring variables\u002Ffunctions within kernels](#declaring-variablesfunctions-within-kernels)\n* [Creating and Running Functions](#creating-and-running-functions)\n* [Debugging](#debugging)\n* [Accepting Input](#accepting-input)\n* [Graphical Output](#graphical-output)\n* [Combining Kernels](#combining-kernels)\n* [Create Kernel Map](#create-kernel-map)\n* [Adding Custom Functions](#adding-custom-functions)\n* [Adding Custom Functions Directly to Kernel](#adding-custom-functions-directly-to-kernel)\n* [Types](#types)\n* [Loops](#loops)\n* [Pipelining](#pipelining)\n  * [Cloning Textures](#cloning-textures-new-in-v2)\n  * [Cleanup pipeline texture memory](#cleanup-pipeline-texture-memory-new-in-v24)\n* [Offscreen Canvas](#offscreen-canvas)\n* [Cleanup](#cleanup)\n* [Flattened typed array support](#flattened-typed-array-support)\n* [Precompiled and Lighter Weight Kernels](#precompiled-and-lighter-weight-kernels)\n  * [using JSON](#using-json)\n  * [Exporting kernel](#exporting-kernel)\n* [Supported Math functions](#supported-math-functions)\n* [How to check what is supported](#how-to-check-what-is-supported)\n* [Typescript Typings](#typescript-typings)\n* [Destructured Assignments](#destructured-assignments-new-in-v2)\n* [Dealing With Transpilation](#dealing-with-transpilation)\n* [Full API reference](#full-api-reference)\n* [How possible in node](#how-possible-in-node)\n* [Testing](#testing)\n* [Building](#building)\n* [Contributors](#contributors)\n* [Contributing](#contributing)\n* [Terms Explained](#terms-explained)\n* [License](#license)\n\n## Demos\nGPU.js in the wild, all around the net.  Add yours here!\n* [Temperature interpolation using GPU.js](https:\u002F\u002Fobservablehq.com\u002F@rveciana\u002Ftemperature-interpolation-using-gpu-js)\n* [Julia Set Fractal using GPU.js](https:\u002F\u002Fobservablehq.com\u002F@ukabuer\u002Fjulia-set-fractal-using-gpu-js)\n* [Hello, gpu.js v2](https:\u002F\u002Fobservablehq.com\u002F@fil\u002Fhello-gpu-js-v2)\n* [Basic gpu.js canvas example](https:\u002F\u002Fobservablehq.com\u002F@rveciana\u002Fbasic-gpu-js-canvas-example)\n* [Raster projection with GPU.js](https:\u002F\u002Fobservablehq.com\u002F@fil\u002Fraster-projection-with-gpu-js)\n* [GPU.js Example: Slow Fade](https:\u002F\u002Fobservablehq.com\u002F@robertleeplummerjr\u002Fgpu-js-example-slow-fade)\n* [GPU.JS CA Proof of Concept](https:\u002F\u002Fobservablehq.com\u002F@alexlamb\u002Fgpu-js-ca-proof-of-concept)\n* [Image Convolution using GPU.js](https:\u002F\u002Fobservablehq.com\u002F@ukabuer\u002Fimage-convolution-using-gpu-js)\n* [Leaflet + gpu.js canvas](https:\u002F\u002Fobservablehq.com\u002F@rveciana\u002Fleaflet-gpu-js-canvas)\n* [Image to GPU.js](https:\u002F\u002Fobservablehq.com\u002F@fil\u002Fimage-to-gpu)\n* [GPU Accelerated Heatmap using gpu.js](https:\u002F\u002Fobservablehq.com\u002F@tracyhenry\u002Fgpu-accelerated-heatmap-using-gpu-js)\n* [Dijkstra’s algorithm in gpu.js](https:\u002F\u002Fobservablehq.com\u002F@fil\u002Fdijkstras-algorithm-in-gpu-js)\n* [Voronoi with gpu.js](https:\u002F\u002Fobservablehq.com\u002F@fil\u002Fvoronoi-with-gpu-js)\n* [The gpu.js loop](https:\u002F\u002Fobservablehq.com\u002F@fil\u002Fthe-gpu-js-loop)\n* [GPU.js Example: Mandelbrot Set](https:\u002F\u002Fobservablehq.com\u002F@robertleeplummerjr\u002Fgpu-js-example-mandelbrot-set)\n* [GPU.js Example: Mandelbulb](https:\u002F\u002Fobservablehq.com\u002F@robertleeplummerjr\u002Fgpu-js-example-mandelbulb)\n* [Inverse of the distance with gpu.js](https:\u002F\u002Fobservablehq.com\u002F@rveciana\u002Finverse-of-the-distance-with-gpu-js)\n* [gpu.js laser detection v2](https:\u002F\u002Fobservablehq.com\u002F@robertleeplummerjr\u002Fgpu-js-laser-detection-v2)\n* [GPU.js Canvas](https:\u002F\u002Fobservablehq.com\u002F@hubgit\u002Fgpu-js-canvas)\n* [Video Convolution using GPU.js](https:\u002F\u002Fobservablehq.com\u002F@robertleeplummerjr\u002Fvideo-convolution-using-gpu-js)\n* [GPU Rock Paper Scissors](https:\u002F\u002Fobservablehq.com\u002F@alexlamb\u002Fgpu-rock-paper-scissors)\n* [Shaded relief with gpujs and d3js](https:\u002F\u002Fobservablehq.com\u002F@rveciana\u002Fshaded-relief-with-gpujs-and-d3js\u002F2)\n* [Caesar Cipher GPU.js Example](https:\u002F\u002Fobservablehq.com\u002F@robertleeplummerjr\u002Fcaesar-cipher-gpu-js-example)\n* [Matrix Multiplication GPU.js + Angular Example](https:\u002F\u002Fng-gpu.surge.sh\u002F)\n* [Conway's game of life](https:\u002F\u002Fobservablehq.com\u002F@brakdag\u002Fconway-game-of-life-gpu-js)\n\n## Installation\nOn Linux, ensure you have the correct header files installed: `sudo apt install mesa-common-dev libxi-dev` (adjust for your distribution)\n\n### npm\n\n```bash\nnpm install gpu.js --save\n```\n\n### yarn\n\n```bash\nyarn add gpu.js\n```\n\n[npm package](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fgpu.js)\n### Node\n```js\nconst { GPU } = require('gpu.js');\nconst gpu = new GPU();\n```\n\n### Node Typescript **New in V2!**\n```js\nimport { GPU } from 'gpu.js';\nconst gpu = new GPU();\n```\n\n### Browser\n\nDownload the latest version of GPU.js and include the files in your HTML page using the following tags:\n\n```html\n\u003Cscript src=\"dist\u002Fgpu-browser.min.js\">\u003C\u002Fscript>\n\u003Cscript>\n    const gpu = new GPU();\n\u003C\u002Fscript>\n```\n\n## `GPU` Settings\nSettings are an object used to create an instance of `GPU`.  Example: `new GPU(settings)`\n* `canvas`: `HTMLCanvasElement`.  Optional.  For sharing canvas.  Example: use THREE.js and GPU.js on same canvas.\n* `context`: `WebGL2RenderingContext` or `WebGLRenderingContext`.  For sharing rendering context.  Example: use THREE.js and GPU.js on same rendering context.\n* `mode`: Defaults to 'gpu', other values generally for debugging:\n  * 'dev' **New in V2!**: VERY IMPORTANT!  Use this so you can breakpoint and debug your kernel!  This wraps your javascript in loops but DOES NOT transpile your code, so debugging is much easier.\n  * 'webgl': Use the `WebGLKernel` for transpiling a kernel\n  * 'webgl2': Use the `WebGL2Kernel` for transpiling a kernel\n  * 'headlessgl' **New in V2!**: Use the `HeadlessGLKernel` for transpiling a kernel\n  * 'cpu': Use the `CPUKernel` for transpiling a kernel\n* `onIstanbulCoverageVariable`: Removed in v2.11.0, use v8 coverage\n* `removeIstanbulCoverage`: Removed in v2.11.0, use v8 coverage\n\n## `gpu.createKernel` Settings\nSettings are an object used to create a `kernel` or `kernelMap`.  Example: `gpu.createKernel(settings)`\n* `output` or `kernel.setOutput(output)`: `array` or `object` that describes the output of kernel.  When using `kernel.setOutput()` you _can_ call it after the kernel has compiled if `kernel.dynamicOutput` is `true`, to resize your output.  Example:\n  * as array: `[width]`, `[width, height]`, or `[width, height, depth]`\n  * as object: `{ x: width, y: height, z: depth }`\n* `pipeline` or `kernel.setPipeline(true)` **New in V2!**: boolean, default = `false`\n  * Causes `kernel()` calls to output a `Texture`.  To get array's from a `Texture`, use:\n  ```js\n  const result = kernel();\n  result.toArray();\n  ```\n  * Can be passed _directly_ into kernels, and is preferred:\n  ```js\n  kernel(texture);\n  ```\n* `graphical` or `kernel.setGraphical(boolean)`: boolean, default = `false`\n* `loopMaxIterations` or `kernel.setLoopMaxIterations(number)`: number, default = 1000\n* `constants` or `kernel.setConstants(object)`: object, default = null\n* `dynamicOutput` or `kernel.setDynamicOutput(boolean)`: boolean, default = false - turns dynamic output on or off\n* `dynamicArguments` or `kernel.setDynamicArguments(boolean)`: boolean, default = false - turns dynamic arguments (use different size arrays and textures) on or off\n* `optimizeFloatMemory` or `kernel.setOptimizeFloatMemory(boolean)` **New in V2!**: boolean - causes a float32 texture to use all 4 channels rather than 1, using less memory, but consuming more GPU.\n* `precision` or `kernel.setPrecision('unsigned' | 'single')` **New in V2!**: 'single' or 'unsigned' - if 'single' output texture uses float32 for each colour channel rather than 8\n* `fixIntegerDivisionAccuracy` or `kernel.setFixIntegerDivisionAccuracy(boolean)` : boolean - some cards have accuracy issues dividing by factors of three and some other primes (most apple kit?). Default on for affected cards, disable if accuracy not required.\n* `functions` or `kernel.setFunctions(array)`: array, array of functions to be used inside kernel.  If undefined, inherits from `GPU` instance. Can also be an array of `{ source: function, argumentTypes: object, returnType: string }`.\n* `nativeFunctions` or `kernel.setNativeFunctions(array)`: object, defined as: `{ name: string, source: string, settings: object }`.  This is generally set via using GPU.addNativeFunction()\n  * VERY IMPORTANT! - Use this to add special native functions to your environment when you need specific functionality is needed.\n* `injectedNative` or `kernel.setInjectedNative(string)` **New in V2!**: string, defined as: `{ functionName: functionSource }`.  This is for injecting native code before translated kernel functions.\n* `subKernels` or `kernel.setSubKernels(array)`: array, generally inherited from `GPU` instance.\n* `immutable` or `kernel.setImmutable(boolean)`: boolean, default = `false`\n  * VERY IMPORTANT! - This was removed in v2.4.0 - v2.7.0, and brought back in v2.8.0 [by popular demand](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fissues\u002F572), please upgrade to get the feature\n* `strictIntegers` or `kernel.setStrictIntegers(boolean)`: boolean, default = `false` - allows undefined argumentTypes and function return values to use strict integer declarations.\n* `useLegacyEncoder` or `kernel.setUseLegacyEncoder(boolean)`: boolean, default `false` - more info [here](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fwiki\u002FEncoder-details).\n* `tactic` or `kernel.setTactic('speed' | 'balanced' | 'precision')` **New in V2!**: Set the kernel's tactic for compilation.  Allows for compilation to better fit how GPU.js is being used (internally uses `lowp` for 'speed', `mediump` for 'balanced', and `highp` for 'precision').  Default is lowest resolution supported for output.\n\n\n## Creating and Running Functions\nDepending on your output type, specify the intended size of your output.\nYou cannot have an accelerated function that does not specify any output size.\n\nOutput size   |  How to specify output size   |  How to reference in kernel\n--------------|-------------------------------|--------------------------------\n 1D           | `[length]`                    |  `value[this.thread.x]`\n 2D           | `[width, height]`             |  `value[this.thread.y][this.thread.x]`\n 3D           | `[width, height, depth]`      |  `value[this.thread.z][this.thread.y][this.thread.x]`\n\n```js\nconst settings = {\n    output: [100]\n};\n```\n\nor\n\n```js\n\u002F\u002F You can also use x, y, and z\nconst settings = {\n    output: { x: 100 }\n};\n```\n\nCreate the function you want to run on the GPU. The first input parameter to `createKernel` is a kernel function which will compute a single number in the output. The thread identifiers, `this.thread.x`, `this.thread.y` or `this.thread.z` will allow you to specify the appropriate behavior of the kernel function at specific positions of the output.\n\n```js\nconst kernel = gpu.createKernel(function() {\n    return this.thread.x;\n}, settings);\n```\n\nThe created function is a regular JavaScript function, and you can use it like one.\n\n```js\nkernel();\n\u002F\u002F Result: Float32Array[0, 1, 2, 3, ... 99]\n```\n\nNote: Instead of creating an object, you can use the chainable shortcut methods as a neater way of specifying settings.\n\n```js\nconst kernel = gpu.createKernel(function() {\n    return this.thread.x;\n}).setOutput([100]);\n\nkernel();\n\u002F\u002F Result: Float32Array[0, 1, 2, 3, ... 99]\n```\n\n### Declaring variables\u002Ffunctions within kernels\n\nGPU.js makes variable declaration inside kernel functions easy.  Variable types supported are:\n* `Number` (Integer or Number), example: `let value = 1` or `let value = 1.1` \n* `Boolean`, example: `let value = true`\n* `Array(2)`, example: `let value = [1, 1]`\n* `Array(3)`, example: `let value = [1, 1, 1]`\n* `Array(4)`, example: `let value = [1, 1, 1, 1]`\n* `private Function`, example: `function myFunction(value) { return value + 1; }`\n\n`Number` kernel example:\n```js\nconst kernel = gpu.createKernel(function() {\n const i = 1;\n const j = 0.89;\n return i + j;\n}).setOutput([100]);\n```\n\n`Boolean` kernel example:\n```js\nconst kernel = gpu.createKernel(function() {\n  const i = true;\n  if (i) return 1;\n  return 0;\n}).setOutput([100]);\n```\n\n`Array(2)` kernel examples:\nUsing declaration\n```js\nconst kernel = gpu.createKernel(function() {\n const array2 = [0.08, 2];\n return array2;\n}).setOutput([100]);\n```\n\nDirectly returned\n```js\nconst kernel = gpu.createKernel(function() {\n return [0.08, 2];\n}).setOutput([100]);\n```\n\n`Array(3)` kernel example:\nUsing declaration\n```js\nconst kernel = gpu.createKernel(function() {\n const array2 = [0.08, 2, 0.1];\n return array2;\n}).setOutput([100]);\n```\n\nDirectly returned\n```js\nconst kernel = gpu.createKernel(function() {\n return [0.08, 2, 0.1];\n}).setOutput([100]);\n```\n\n`Array(4)` kernel example:\nUsing declaration\n```js\nconst kernel = gpu.createKernel(function() {\n const array2 = [0.08, 2, 0.1, 3];\n return array2;\n}).setOutput([100]);\n```\n\nDirectly returned\n```js\nconst kernel = gpu.createKernel(function() {\n return [0.08, 2, 0.1, 3];\n}).setOutput([100]);\n```\n\n`private Function` kernel example:\n```js\nconst kernel = gpu.createKernel(function() {\n  function myPrivateFunction() {\n    return [0.08, 2, 0.1, 3];\n  }\n  \n  return myPrivateFunction(); \u002F\u002F \u003C-- type inherited here\n}).setOutput([100]);\n```\n\n## Debugging\nDebugging can be done in a variety of ways, and there are different levels of debugging.\n* Debugging kernels with breakpoints can be done with `new GPU({ mode: 'dev' })`\n  * This puts `GPU.js` into development mode.  Here you can insert breakpoints, and be somewhat liberal in how your kernel is developed.\n  * This mode _does not_ actually \"compile\" (parse, and eval) a kernel, it simply iterates on your code.\n  * You can break a lot of rules here, because your kernel's function still has context of the state it came from.\n  * PLEASE NOTE: Mapped kernels are not supported in this mode.  They simply cannot work because of context.\n  * Example:\n    ```js\n    const gpu = new GPU({ mode: 'dev' });\n    const kernel = gpu.createKernel(function(arg1, time) {\n        \u002F\u002F put a breakpoint on the next line, and watch it get hit\n        const v = arg1[this.thread.y][this.thread.x * time];\n        return v;\n    }, { output: [100, 100] });\n    ```\n* Debugging actual kernels on CPU with `debugger`:\n  * This will cause \"breakpoint\" like behaviour, but in an actual CPU kernel.  You'll peer into the compiled kernel here, for a CPU.\n  * Example:\n    ```js\n    const gpu = new GPU({ mode: 'cpu' });\n    const kernel = gpu.createKernel(function(arg1, time) {\n        debugger; \u002F\u002F \u003C--NOTICE THIS, IMPORTANT!\n        const v = arg1[this.thread.y][this.thread.x * time];\n        return v;\n    }, { output: [100, 100] });\n    ```\n* Debugging an actual GPU kernel:\n  * There are no breakpoints available on the GPU, period.  By providing the same level of abstraction and logic, the above methods should give you enough insight to debug, but sometimes we just need to see what is on the GPU.\n  * Be VERY specific and deliberate, and use the kernel to your advantage, rather than just getting frustrated or giving up.\n  * Example:\n    ```js\n    const gpu = new GPU({ mode: 'cpu' });\n    const kernel = gpu.createKernel(function(arg1, time) {\n      const x = this.thread.x * time;\n      return x; \u002F\u002F \u003C--NOTICE THIS, IMPORTANT!\n      const v = arg1[this.thread.y][x];\n      return v;\n    }, { output: [100, 100] });\n    ```\n    In this example, we return early the value of x, to see exactly what it is.  The rest of the logic is ignored, but now you can see the value that is calculated from `x`, and debug it.\n    This is an overly simplified problem.\n  * Sometimes you need to solve graphical problems, that can be done similarly.\n  * Example:\n    ```js\n    const gpu = new GPU({ mode: 'cpu' });\n    const kernel = gpu.createKernel(function(arg1, time) {\n      const x = this.thread.x * time;\n      if (x \u003C 4 || x > 2) {\n        \u002F\u002F RED\n        this.color(1, 0, 0); \u002F\u002F \u003C--NOTICE THIS, IMPORTANT!\n        return;\n      }\n      if (x > 6 && x \u003C 12) {\n        \u002F\u002F GREEN\n        this.color(0, 1, 0); \u002F\u002F \u003C--NOTICE THIS, IMPORTANT!\n        return;\n      }\n      const v = arg1[this.thread.y][x];\n      return v;\n    }, { output: [100, 100], graphical: true });\n    ```\n    Here we are making the canvas red or green depending on the value of `x`.\n\n## Accepting Input\n### Supported Input Types\n* Numbers\n* 1d,2d, or 3d Array of numbers\n  * Arrays of `Array`, `Float32Array`, `Int16Array`, `Int8Array`, `Uint16Array`, `uInt8Array`\n* Pre-flattened 2d or 3d Arrays using 'Input', for faster upload of arrays\n  * Example:\n  ```js\n  const { input } = require('gpu.js');\n  const value = input(flattenedArray, [width, height, depth]);\n  ```\n* HTML Image\n* Array of HTML Images\n* Video Element **New in V2!**\nTo define an argument, simply add it to the kernel function like regular JavaScript.\n\n### Input Examples\n```js\nconst kernel = gpu.createKernel(function(x) {\n    return x;\n}).setOutput([100]);\n\nkernel(42);\n\u002F\u002F Result: Float32Array[42, 42, 42, 42, ... 42]\n```\n\nSimilarly, with array inputs:\n\n```js\nconst kernel = gpu.createKernel(function(x) {\n    return x[this.thread.x % 3];\n}).setOutput([100]);\n\nkernel([1, 2, 3]);\n\u002F\u002F Result: Float32Array[1, 2, 3, 1, ... 1 ]\n```\n\nAn HTML Image:\n\n```js\nconst kernel = gpu.createKernel(function(image) {\n    const pixel = image[this.thread.y][this.thread.x];\n    this.color(pixel[0], pixel[1], pixel[2], pixel[3]);\n})\n  .setGraphical(true)\n  .setOutput([100, 100]);\n\nconst image = document.createElement('img');\nimage.src = 'my\u002Fimage\u002Fsource.png';\nimage.onload = () => {\n  kernel(image);\n  \u002F\u002F Result: colorful image\n  \n  document.getElementsByTagName('body')[0].appendChild(kernel.canvas);\n};\n```\n\nAn Array of HTML Images:\n\n```js\nconst kernel = gpu.createKernel(function(image) {\n    const pixel = image[this.thread.z][this.thread.y][this.thread.x];\n    this.color(pixel[0], pixel[1], pixel[2], pixel[3]);\n})\n  .setGraphical(true)\n  .setOutput([100, 100]);\n\nconst image1 = document.createElement('img');\nimage1.src = 'my\u002Fimage\u002Fsource1.png';\nimage1.onload = onload;\nconst image2 = document.createElement('img');\nimage2.src = 'my\u002Fimage\u002Fsource2.png';\nimage2.onload = onload;\nconst image3 = document.createElement('img');\nimage3.src = 'my\u002Fimage\u002Fsource3.png';\nimage3.onload = onload;\nconst totalImages = 3;\nlet loadedImages = 0;\nfunction onload() {\n  loadedImages++;\n  if (loadedImages === totalImages) {\n    kernel([image1, image2, image3]);\n    \u002F\u002F Result: colorful image composed of many images\n\n     document.getElementsByTagName('body')[0].appendChild(kernel.canvas);\n  }\n};\n```\n\nAn HTML Video: **New in V2!**\n\n```js\nconst kernel = gpu.createKernel(function(videoFrame) {\n    const pixel = videoFrame[this.thread.y][this.thread.x];\n    this.color(pixel[0], pixel[1], pixel[2], pixel[3]);\n})\n  .setGraphical(true)\n  .setOutput([100, 100]);\n\nconst video = new document.createElement('video');\nvideo.src = 'my\u002Fvideo\u002Fsource.webm';\nkernel(image); \u002F\u002Fnote, try and use requestAnimationFrame, and the video should be ready or playing\n\u002F\u002F Result: video frame\n```\n\n## Graphical Output\n\nSometimes, you want to produce a `canvas` image instead of doing numeric computations. To achieve this, set the `graphical` flag to `true` and the output dimensions to `[width, height]`. The thread identifiers will now refer to the `x` and `y` coordinate of the pixel you are producing. Inside your kernel function, use `this.color(r,g,b)` or `this.color(r,g,b,a)` to specify the color of the pixel.\n\nFor performance reasons, the return value of your function will no longer be anything useful. Instead, to display the image, retrieve the `canvas` DOM node and insert it into your page.\n\n```js\nconst render = gpu.createKernel(function() {\n    this.color(0, 0, 0, 1);\n})\n  .setOutput([20, 20])\n  .setGraphical(true);\n\nrender();\n\nconst canvas = render.canvas;\ndocument.getElementsByTagName('body')[0].appendChild(canvas);\n```\n\nNote: To animate the rendering, use `requestAnimationFrame` instead of `setTimeout` for optimal performance. For more information, see [this](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002Fwindow\u002FrequestAnimationFrame).\n\n\n### .getPixels() **New in V2!**\nTo make it easier to get pixels from a context, use `kernel.getPixels()`, which returns a flat array similar to what you get from WebGL's `readPixels` method.\nA note on why: webgl's `readPixels` returns an array ordered differently from javascript's `getImageData`.\nThis makes them behave similarly.\nWhile the values may be somewhat different, because of graphical precision available in the kernel, and alpha, this allows us to easily get pixel data in unified way.\n\nExample:\n```js\nconst render = gpu.createKernel(function() {\n    this.color(0, 0, 0, 1);\n})\n  .setOutput([20, 20])\n  .setGraphical(true);\n\nrender();\nconst pixels = render.getPixels();\n\u002F\u002F [r,g,b,a, r,g,b,a...\n```\n\n### Alpha\n\nCurrently, if you need alpha do something like enabling `premultipliedAlpha` with your own gl context:\n```js\nconst canvas = DOM.canvas(500, 500);\nconst gl = canvas.getContext('webgl2', { premultipliedAlpha: false });\n\nconst gpu = new GPU({\n  canvas,\n  context: gl\n});\nconst krender = gpu.createKernel(function(x) {\n  this.color(this.thread.x \u002F 500, this.thread.y \u002F 500, x[0], x[1]);\n})\n  .setOutput([500, 500])\n  .setGraphical(true);\n ```\n\n## Combining kernels\n\nSometimes you want to do multiple math operations on the gpu without the round trip penalty of data transfer from cpu to gpu to cpu to gpu, etc.  To aid this there is the `combineKernels` method.\n_**Note:**_ Kernels can have different output sizes.\n```js\nconst add = gpu.createKernel(function(a, b) {\n  return a[this.thread.x] + b[this.thread.x];\n}).setOutput([20]);\n\nconst multiply = gpu.createKernel(function(a, b) {\n  return a[this.thread.x] * b[this.thread.x];\n}).setOutput([20]);\n\nconst superKernel = gpu.combineKernels(add, multiply, function(a, b, c) {\n  return multiply(add(a, b), c);\n});\n\nsuperKernel(a, b, c);\n```\nThis gives you the flexibility of using multiple transformations but without the performance penalty, resulting in a much much MUCH faster operation.\n\n## Create Kernel Map\n\nSometimes you want to do multiple math operations in one kernel, and save the output of each of those operations. An example is **Machine Learning** where the previous output is required for back propagation. To aid this there is the `createKernelMap` method.\n\n### object outputs\n```js\nconst megaKernel = gpu.createKernelMap({\n  addResult: function add(a, b) {\n    return a + b;\n  },\n  multiplyResult: function multiply(a, b) {\n    return a * b;\n  },\n}, function(a, b, c) {\n  return multiply(add(a[this.thread.x], b[this.thread.x]), c[this.thread.x]);\n}, { output: [10] });\n\nmegaKernel(a, b, c);\n\u002F\u002F Result: { addResult: Float32Array, multiplyResult: Float32Array, result: Float32Array }\n```\n### array outputs\n```js\nconst megaKernel = gpu.createKernelMap([\n  function add(a, b) {\n    return a + b;\n  },\n  function multiply(a, b) {\n    return a * b;\n  }\n], function(a, b, c) {\n  return multiply(add(a[this.thread.x], b[this.thread.x]), c[this.thread.x]);\n}, { output: [10] });\n\nmegaKernel(a, b, c);\n\u002F\u002F Result: { 0: Float32Array, 1: Float32Array, result: Float32Array }\n```\nThis gives you the flexibility of using parts of a single transformation without the performance penalty, resulting in much much _MUCH_ faster operation.\n\n## Adding custom functions\n### To `GPU` instance\nuse `gpu.addFunction(function() {}, settings)` for adding custom functions to all kernels.  Needs to be called BEFORE `gpu.createKernel`. Example:\n\n\n```js\ngpu.addFunction(function mySuperFunction(a, b) {\n  return a - b;\n});\nfunction anotherFunction(value) {\n  return value + 1;\n}\ngpu.addFunction(anotherFunction);\nconst kernel = gpu.createKernel(function(a, b) {\n  return anotherFunction(mySuperFunction(a[this.thread.x], b[this.thread.x]));\n}).setOutput([20]);\n```\n\n### To `Kernel` instance\nuse `kernel.addFunction(function() {}, settings)` for adding custom functions to all kernels.  Example:\n\n\n```js\nkernel.addFunction(function mySuperFunction(a, b) {\n  return a - b;\n});\nfunction anotherFunction(value) {\n  return value + 1;\n}\nkernel.addFunction(anotherFunction);\nconst kernel = gpu.createKernel(function(a, b) {\n  return anotherFunction(mySuperFunction(a[this.thread.x], b[this.thread.x]));\n}).setOutput([20]);\n```\n\n### Adding strongly typed functions\n\nTo manually strongly type a function you may use settings.\nBy setting this value, it makes the build step of the kernel less resource intensive.\nSettings take an optional hash values:\n* `returnType`: optional, defaults to inference from `FunctionBuilder`, the value you'd like to return from the function.\n* `argumentTypes`: optional, defaults to inference from `FunctionBuilder` for each param, a hash of param names with values of the return types.\n\nExample on `GPU` instance:\n```js\ngpu.addFunction(function mySuperFunction(a, b) {\n  return [a - b[1], b[0] - a];\n}, { argumentTypes: { a: 'Number', b: 'Array(2)'}, returnType: 'Array(2)' });\n```\n\nExample on `Kernel` instance:\n```js\nkernel.addFunction(function mySuperFunction(a, b) {\n  return [a - b[1], b[0] - a];\n}, { argumentTypes: { a: 'Number', b: 'Array(2)'}, returnType: 'Array(2)' });\n```\n\nNOTE: GPU.js infers types if they are not defined and is generally able to detect the types you need, however\n'Array(2)', 'Array(3)', and 'Array(4)' are exceptions, at least on the kernel level.  Also, it is nice to have power\nover the automatic type inference system.\n\n## Adding custom functions directly to kernel\n```js\nfunction mySuperFunction(a, b) {\n  return a - b;\n}\nconst kernel = gpu.createKernel(function(a, b) {\n  return mySuperFunction(a[this.thread.x], b[this.thread.x]);\n})\n  .setOutput([20])\n  .setFunctions([mySuperFunction]);\n\n```\n\n\n## Types\nGPU.js does type inference when types are not defined, so even if you code weak type, you are typing strongly typed.\nThis is needed because c++, which glsl is a subset of, is, of course, strongly typed.\nTypes that can be used with GPU.js are as follows:\n\n### Argument Types\n* 'Array'\n* 'Array(2)' **New in V2!**\n* 'Array(3)' **New in V2!**\n* 'Array(4)' **New in V2!**\n* 'Array1D(2)' **New in V2!**\n* 'Array1D(3)' **New in V2!**\n* 'Array1D(4)' **New in V2!**\n* 'Array2D(2)' **New in V2!**\n* 'Array2D(3)' **New in V2!**\n* 'Array2D(4)' **New in V2!**\n* 'Array3D(2)' **New in V2!**\n* 'Array3D(3)' **New in V2!**\n* 'Array3D(4)' **New in V2!**\n* 'HTMLCanvas' **New in V2.6**\n* 'OffscreenCanvas' **New in V2.13**\n* 'HTMLImage'\n* 'ImageBitmap' **New in V2.14**\n* 'ImageData' **New in V2.15**\n* 'HTMLImageArray'\n* 'HTMLVideo' **New in V2!**\n* 'Number'\n* 'Float'\n* 'Integer'\n* 'Boolean' **New in V2!**\n\n### Return Types\nNOTE: These refer the the return type of the kernel function, the actual result will always be a collection in the size of the defined `output`\n* 'Array(2)'\n* 'Array(3)'\n* 'Array(4)'\n* 'Number'\n* 'Float'\n* 'Integer'\n\n### Internal Types\nTypes generally used in the `Texture` class, for #pipelining or for advanced usage.\n* 'ArrayTexture(1)' **New in V2!**\n* 'ArrayTexture(2)' **New in V2!**\n* 'ArrayTexture(3)' **New in V2!**\n* 'ArrayTexture(4)' **New in V2!**\n* 'NumberTexture'\n* 'MemoryOptimizedNumberTexture' **New in V2!**\n\n## Loops\n* Any loops defined inside the kernel must have a maximum iteration count defined by the loopMaxIterations setting.\n* Other than defining the iterations by a constant or fixed value as shown [Dynamic sized via constants](dynamic-sized-via-constants), you can also simply pass the number of iterations as a variable to the kernel\n\n### Dynamic sized via constants\n```js\nconst matMult = gpu.createKernel(function(a, b) {\n    var sum = 0;\n    for (var i = 0; i \u003C this.constants.size; i++) {\n        sum += a[this.thread.y][i] * b[i][this.thread.x];\n    }\n    return sum;\n}, {\n  constants: { size: 512 },\n  output: [512, 512],\n});\n```\n\n### Fixed sized\n```js\nconst matMult = gpu.createKernel(function(a, b) {\n    var sum = 0;\n    for (var i = 0; i \u003C 512; i++) {\n        sum += a[this.thread.y][i] * b[i][this.thread.x];\n    }\n    return sum;\n}).setOutput([512, 512]);\n```\n\n## Pipelining\n[Pipeline](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPipeline_(computing)) is a feature where values are sent directly from kernel to kernel via a texture.\nThis results in extremely fast computing.  This is achieved with the kernel setting `pipeline: boolean` or by calling `kernel.setPipeline(true)`\nIn an effort to make the CPU and GPU work similarly, pipeline on CPU and GPU modes causes the kernel result to be reused when `immutable: false` (which is default).\nIf you'd like to keep kernel results around, use `immutable: true` and ensure you cleanup memory:\n* In gpu mode using `texture.delete()` when appropriate.\n* In cpu mode allowing values to go out of context\n\n### Cloning Textures **New in V2!**\nWhen using pipeline mode the outputs from kernels can be cloned using `texture.clone()`.\n\n```js\nconst kernel1 = gpu.createKernel(function(v) {\n    return v[this.thread.x];\n})\n  .setPipeline(true)\n  .setOutput([100]);\n\nconst kernel2 = gpu.createKernel(function(v) {\n    return v[this.thread.x];\n})\n  .setOutput([100]);\n\nconst result1 = kernel1(array);\n\u002F\u002F Result: Texture\nconsole.log(result1.toArray());\n\u002F\u002F Result: Float32Array[0, 1, 2, 3, ... 99]\n\nconst result2 = kernel2(result1);\n\u002F\u002F Result: Float32Array[0, 1, 2, 3, ... 99]\n```\n\n### Cleanup pipeline texture memory **New in V2.4!**\nWhen using `kernel.immutable = true` recycling GPU memory is handled internally, but a good practice is to clean up memory you no longer need it.\nCleanup kernel outputs by using `texture.delete()` to keep GPU memory as small as possible.\n\nNOTE: Internally textures will only release from memory if there are no references to them.\nWhen using pipeline mode on a kernel `K` the output for each call will be a newly allocated texture `T`.\nIf, after getting texture `T` as an output, `T.delete()` is called, the next call to K will reuse `T` as its output texture.\n\nAlternatively, if you'd like to clear out a `texture` and yet keep it in memory, you may use `texture.clear()`, which\nwill cause the `texture` to persist in memory, but its internal values to become all zeros.\n\n## Offscreen Canvas\nGPU.js supports offscreen canvas where available.  Here is an example of how to use it with two files, `gpu-worker.js`, and `index.js`:\n\nfile: `gpu-worker.js`\n```js\nimportScripts('path\u002Fto\u002Fgpu.js');\nonmessage = function() {\n  \u002F\u002F define gpu instance\n  const gpu = new GPU();\n\n  \u002F\u002F input values\n  const a = [1,2,3];\n  const b = [3,2,1];\n\n  \u002F\u002F setup kernel\n  const kernel = gpu.createKernel(function(a, b) {\n    return a[this.thread.x] - b[this.thread.x];\n  })\n    .setOutput([3]);\n\n  \u002F\u002F output some results!\n  postMessage(kernel(a, b));\n};\n```\n\nfile: `index.js`\n```js\nvar worker = new Worker('gpu-worker.js');\nworker.onmessage = function(e) {\n  var result = e.data;\n  console.log(result);\n};\n```\n\n## Cleanup\n* for instances of `GPU` use the `destroy` method.  Example: `gpu.destroy()`\n* for instances of `Kernel` use the `destroy` method.  Example: `kernel.destroy()`\n* for instances of `Texture` use the `delete` method. Example: `texture.delete()`\n* for instances of `Texture` that you might want to reuse\u002Freset to zeros, use the `clear` method. Example: `texture.clear()`\n\n## Flattened typed array support\nTo use the useful `x`, `y`, `z` `thread` lookup api inside of GPU.js, and yet use flattened arrays, there is the `Input` type.\nThis is generally much faster for when sending values to the gpu, especially with larger data sets.  Usage example:\n```js\nconst { GPU, input, Input } = require('gpu.js');\nconst gpu = new GPU();\nconst kernel = gpu.createKernel(function(a, b) {\n  return a[this.thread.y][this.thread.x] + b[this.thread.y][this.thread.x];\n}).setOutput([3,3]);\n\n\nkernel(\n  input(\n    new Float32Array([1,2,3,4,5,6,7,8,9]),\n    [3, 3]\n  ),\n  input(\n    new Float32Array([1,2,3,4,5,6,7,8,9]),\n    [3, 3]\n  )\n);\n```\n\nNote: `input(value, size)` is a simple pointer for `new Input(value, size)`\n\n## Precompiled and Lighter Weight Kernels\n\n### using JSON\nGPU.js packs a lot of functionality into a single file, such as a complete javascript parse, which may not be needed in some cases.\nTo aid in keeping your kernels lightweight, the `kernel.toJSON()` method was added.\nThis allows you to reuse a previously built kernel, without the need to re-parse the javascript.\nHere is an example:\n\n```js\nconst gpu = new GPU();\nconst kernel = gpu.createKernel(function() {\n  return [1,2,3,4];\n}, { output: [1] });\nconsole.log(kernel()); \u002F\u002F [Float32Array([1,2,3,4])];\nconst json = kernel.toJSON();\nconst newKernelFromJson = gpu.createKernel(json);\nconsole.log(newKernelFromJSON()); \u002F\u002F [Float32Array([1,2,3,4])];\n```\n\nNOTE: There is lighter weight, pre-built, version of GPU.js to assist with serializing from to and from json in the dist folder of the project, which include:\n* [dist\u002Fgpu-browser-core.js](dist\u002Fgpu-browser-core.js)\n* [dist\u002Fgpu-browser-core.min.js](dist\u002Fgpu-browser-core.min.js)\n\n### Exporting kernel\nGPU.js supports seeing exactly how it is interacting with the graphics processor by means of the `kernel.toString(...)` method.\nThis method, when called, creates a kernel that executes _exactly the instruction set given to the GPU (or CPU)_ *as a\nvery tiny reusable function* that instantiates a kernel.\n\nNOTE: When exporting a kernel and using `constants` the following constants are *not changeable*:\n* `Array(2)`\n* `Array(3)`\n* `Array(4)`\n* `Integer`\n* `Number`\n* `Float`\n* `Boolean`\n\nHere is an example used to\u002Ffrom file:\n```js\nimport { GPU } from 'gpu.js';\nimport * as fs from 'fs';\nconst gpu = new GPU();\nconst kernel = gpu.createKernel(function(v) {\n  return this.thread.x + v + this.constants.v1;\n}, { output: [10], constants: { v1: 100 } });\nconst result = kernel(1);\nconst kernelString = kernel.toString(1);\nfs.writeFileSync('.\u002Fmy-exported-kernel.js', 'module.exports = ' + kernelString);\nimport * as MyExportedKernel from '.\u002Fmy-exported-kernel';\nimport gl from 'gl';\nconst myExportedKernel = MyExportedKernel({ context: gl(1,1), constants: { v1: 100 } });\n```\n\n\nHere is an example for just-in-time function creation:\n\n```js\nconst gpu = new GPU();\nconst kernel = gpu.createKernel(function(a) {\n  let sum = 0;\n  for (let i = 0; i \u003C 6; i++) {\n    sum += a[this.thread.x][i];\n  }\n  return sum;\n  }, { output: [6] });\nkernel(input(a, [6, 6]));\nconst kernelString = kernel.toString(input(a, [6, 6]));\nconst newKernel = new Function('return ' + kernelString)()({ context });\nnewKernel(input(a, [6, 6]));\n```\n\n#### using constants with `kernel.toString(...args)`\nYou can assign _some_ new constants when using the function output from `.toString()`,\n\n## Supported Math functions\n\nSince the code running in the kernel is actually compiled to GLSL code, not all functions from the JavaScript Math module are supported.\n\nThis is a list of the supported ones:\n\n* `Math.abs()`\n* `Math.acos()`\n* `Math.acosh()`\n* `Math.asin()`\n* `Math.asinh()`\n* `Math.atan()`\n* `Math.atanh()`\n* `Math.atan2()`\n* `Math.cbrt()`\n* `Math.ceil()`\n* `Math.cos()`\n* `Math.cosh()`\n* `Math.exp()`\n* `Math.expm1()`\n* `Math.floor()`\n* `Math.fround()`\n* `Math.imul()`\n* `Math.log()`\n* `Math.log10()`\n* `Math.log1p()`\n* `Math.log2()`\n* `Math.max()`\n* `Math.min()`\n* `Math.pow()`\n* `Math.random()`\n  * A note on random.  We use [a plugin](src\u002Fplugins\u002Fmath-random-uniformly-distributed.js) to generate random.\n  Random seeded _and_ generated, _both from the GPU_, is not as good as random from the CPU as there are more things that the CPU can seed random from.\n  However, we seed random on the GPU, _from a random value in the CPU_.\n  We then seed the subsequent randoms from the previous random value.\n  So we seed from CPU, and generate from GPU.\n  Which is still not as good as CPU, but closer.\n  While this isn't perfect, it should suffice in most scenarios.\n  In any case, we must give thanks to [RandomPower](https:\u002F\u002Fwww.randompower.eu\u002F), and this [issue](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fissues\u002F498), for assisting in improving our implementation of random.\n* `Math.round()`\n* `Math.sign()`\n* `Math.sin()`\n* `Math.sinh()`\n* `Math.sqrt()`\n* `Math.tan()`\n* `Math.tanh()`\n* `Math.trunc()`\n\nThis is a list and reasons of unsupported ones:\n*  `Math.clz32` - bits directly are hard\n*  `Math.hypot` - dynamically sized\n\n## How to check what is supported\n\nTo assist with mostly unit tests, but perhaps in scenarios outside of GPU.js, there are the following logical checks to determine what support level the system executing a GPU.js kernel may have:\n* `GPU.disableValidation()` - turn off all kernel validation\n* `GPU.enableValidation()` - turn on all kernel validation\n* `GPU.isGPUSupported`: `boolean` - checks if GPU is in-fact supported\n* `GPU.isKernelMapSupported`: `boolean` - checks if kernel maps are supported\n* `GPU.isOffscreenCanvasSupported`: `boolean` - checks if offscreen canvas is supported\n* `GPU.isWebGLSupported`: `boolean` - checks if WebGL v1 is supported\n* `GPU.isWebGL2Supported`: `boolean` - checks if WebGL v2 is supported\n* `GPU.isHeadlessGLSupported`: `boolean` - checks if headlessgl is supported\n* `GPU.isCanvasSupported`: `boolean` - checks if canvas is supported\n* `GPU.isGPUHTMLImageArraySupported`: `boolean` - checks if the platform supports HTMLImageArray's\n* `GPU.isSinglePrecisionSupported`: `boolean` - checks if the system supports single precision float 32 values\n\n## Typescript Typings\nTypescript is supported!  Typings can be found [here](src\u002Findex.d.ts)!\nFor strongly typed kernels:\n```typescript\nimport { GPU, IKernelFunctionThis } from 'gpu.js';\nconst gpu = new GPU();\n\nfunction kernelFunction(this: IKernelFunctionThis): number {\n  return 1 + this.thread.x;\n}\n\nconst kernelMap = gpu.createKernel\u003Ctypeof kernelFunction>(kernelFunction)\n  .setOutput([3,3,3]);\n\nconst result = kernelMap();\n\nconsole.log(result as number[][][]);\n```\n\nFor strongly typed mapped kernels:\n```typescript\nimport { GPU, Texture, IKernelFunctionThis } from 'gpu.js';\nconst gpu = new GPU();\n\nfunction kernelFunction(this: IKernelFunctionThis): [number, number] {\n  return [1, 1];\n}\n\nfunction subKernel(): [number, number] {\n  return [1, 1];\n}\n\nconst kernelMap = gpu.createKernelMap\u003Ctypeof kernelFunction>({\n  test: subKernel,\n}, kernelFunction)\n  .setOutput([1])\n  .setPipeline(true);\n\nconst result = kernelMap();\n\nconsole.log((result.test as Texture).toArray() as [number, number][]);\n```\n\nFor extending constants:\n```typescript\nimport { GPU, IKernelFunctionThis } from 'gpu.js';\nconst gpu = new GPU();\n\ninterface IConstants {\n  screen: [number, number];\n}\n\ntype This = {\n  constants: IConstants\n} & IKernelFunctionThis;\n\nfunction kernelFunction(this: This): number {\n  const { screen } = this.constants;\n  return 1 + screen[0];\n}\n\nconst kernelMap = gpu.createKernel\u003Ctypeof kernelFunction>(kernelFunction)\n  .setOutput([3,3,3])\n  .setConstants\u003CIConstants>({\n    screen: [1, 1]\n  });\n\nconst result = kernelMap();\n\nconsole.log(result as number[][][]);\n```\n\n[Click here](\u002Fexamples) for more typescript examples.\n\n## Destructured Assignments **New in V2!**\nDestructured Objects and Arrays work in GPU.js.\n* Object destructuring\n  ```js\n  const gpu = new GPU();\n  const kernel = gpu.createKernel(function() {\n    const { thread: {x, y} } = this;\n    return x + y;\n  }, { output: [2] });\n  console.log(kernel());\n  ```\n* Array destructuring\n  ```js\n  const gpu = new GPU();\n  const kernel = gpu.createKernel(function(array) {\n    const [first, second] = array;\n    return first + second; \n  }, {\n    output: [2],\n    argumentTypes: { array: 'Array(2)' }\n  });\n  console.log(kernel([1, 2]));\n  ```\n\n## Dealing With Transpilation\nTranspilation doesn't do the best job of keeping code beautiful.  To aid in this endeavor GPU.js can handle some scenarios to still aid you harnessing the GPU in less than ideal circumstances.\nHere is a list of a few things that GPU.js does to fix transpilation:\n\n* When a transpiler such as [Babel](https:\u002F\u002Fbabeljs.io\u002F) changes `myCall()` to `(0, _myCall.myCall)`, it is gracefully handled.\n\n## Full API Reference\n\nYou can find a [complete API reference here](https:\u002F\u002Fdoxdox.org\u002Fgpujs\u002Fgpu.js\u002F).\n\n## How possible in node?\nGPU.js uses [HeadlessGL](https:\u002F\u002Fgithub.com\u002Fstackgl\u002Fheadless-gl) in node for GPU acceleration.\nGPU.js is written in such a way, you can introduce your own backend.  Have a suggestion?  We'd love to hear it!\n\n## Terms Explained\n* Kernel - A function that is tightly coupled to program that runs on the Graphic Processor\n* Texture - A graphical artifact that is packed with data, in the case of GPU.js, bit shifted parts of a 32 bit floating point decimal\n\n## Testing\nTesting is done (right now) manually, (help wanted [here](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fissues\u002F515) if you can!), using the following:\n* For browser, setup a webserver on the root of the gpu.js project and visit http:\u002F\u002Furl\u002Ftest\u002Fall.html\n* For node, run either of the 3 commands:\n  * `yarn test test\u002Ffeatures`\n  * `yarn test test\u002Finternal`\n  * `yarn test test\u002Fissues`\n\n## Building\nBuilding isn't required on node, but is for browser.  To build the browser's files, run: `yarn make`\n\n# Get Involved!\n\n## Contributing\n\nContributors are welcome! Create a merge request to the `develop` branch and we\nwill gladly review it. If you wish to get write access to the repository,\nplease email us and we will review your application and grant you access to\nthe `develop` branch.\n\nWe promise never to pass off your code as ours.\n\n### Issues\n\nIf you have an issue, either a bug or a feature you think would benefit your project let us know and we will do our best.\n\nCreate issues [here](https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fissues) and follow the template.\n\n### Contributors\n\nThis project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].\n\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fgpujs\u002Fgpu.js\u002Fgraphs\u002Fcontributors\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fcontributors.svg?width=890&button=false\" \u002F>\u003C\u002Fa>\n\n\n### Backers\n\nThank you to all our backers! 🙏 [[Become a backer](https:\u002F\u002Fopencollective.com\u002Fgpujs#backer)]\n\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs#backers\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fbackers.svg?width=890\">\u003C\u002Fa>\n\n\n### Sponsors\n\nSupport this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https:\u002F\u002Fopencollective.com\u002Fgpujs#sponsor)]\n\n![](https:\u002F\u002Fwww.leadergpu.com\u002Fassets\u002Fmain\u002Flogo_leadergpu-a8cacac0c90d204b7f7f6c8420c6a149e71ebe53f3f28f3fc94a01cd05c0bd93.png)\nSponsored NodeJS GPU environment from [LeaderGPU](https:\u002F\u002Fwww.leadergpu.com) - These guys rock!\n\n![](https:\u002F\u002F3fxtqy18kygf3on3bu39kh93-wpengine.netdna-ssl.com\u002Fwp-content\u002Fthemes\u002Fbrowserstack\u002Fimg\u002Fbrowserstack-logo.svg)\nSponsored Browser GPU environment's from [BrowserStack](https:\u002F\u002Fbrowserstack.com) - Second to none!\n\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F0\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F0\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F1\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F1\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F2\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F2\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F3\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F3\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F4\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F4\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F5\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F5\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F6\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F6\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F7\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F7\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F8\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F8\u002Favatar.svg\">\u003C\u002Fa>\n\u003Ca href=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F9\u002Fwebsite\" target=\"_blank\">\u003Cimg src=\"https:\u002F\u002Fopencollective.com\u002Fgpujs\u002Fsponsor\u002F9\u002Favatar.svg\">\u003C\u002Fa>\n\n## [License](LICENSE)\n","GPU.js 是一个用于Web和Node.js环境下的GPGPU（通用图形处理器计算）的JavaScript加速库。它能够自动将简单的JavaScript函数转译为着色器语言，并编译以在GPU上运行；若无可用GPU，则这些函数仍能在普通JavaScript环境中执行。该库支持GLSL、WebGL等技术，特别适合需要进行大量并行计算的场景，如矩阵运算、图像处理等，通常可实现1-15倍的速度提升。通过提供简洁直观的API接口，开发者可以轻松地在其项目中引入高性能计算能力，而无需深入了解底层GPU编程细节。",2,"2026-06-11 02:53:31","top_language"]