diff --git a/creator/src/index.js b/creator/src/index.js
index d1d77ec..97912e9 100644
--- a/creator/src/index.js
+++ b/creator/src/index.js
@@ -35,7 +35,7 @@ async function newProject(name, templateName = "static") {
// this will always be a valid.
const template = require("./templates/" + templateName);
- const writeTemplate = require("./writer");
+ const { writeTemplate } = require("./writer");
const autoComplete = require("./templates/autocomplete.js");
@@ -83,5 +83,5 @@ function main() {
main();
module.exports = {
- templateWriter: require("./writer"),
+ templateWriter: require("./writer").writeTemplate,
};
diff --git a/creator/src/server/server.js b/creator/src/server/server.js
index 6014116..6c45ae7 100644
--- a/creator/src/server/server.js
+++ b/creator/src/server/server.js
@@ -1,17 +1,21 @@
const express = require("express");
-const open = require('open');
-const chalk = require('chalk');
-
+const open = require("open");
+const chalk = require("chalk");
+const path = require("path");
function run_server(path_dir, port = 3000) {
const app = express();
- const server = app.listen(port);
-
- console.log("\nRunning Server: " + chalk.underline.blueBright(`http://localhost:${port}`));
-
+
app.use(express.static(path_dir));
- open(`http://localhost:${port}`);
+ app.listen(port, () => {
+ console.log(
+ "\nRunning Server: " +
+ chalk.underline.blueBright(`http://localhost:${port}`)
+ );
+ open(`http://localhost:${port}`);
+ });
+
}
-module.exports = run_server;
\ No newline at end of file
+module.exports = run_server;
diff --git a/creator/src/templates/autocomplete.js b/creator/src/templates/autocomplete.js
index dab992a..5ff9736 100644
--- a/creator/src/templates/autocomplete.js
+++ b/creator/src/templates/autocomplete.js
@@ -1,9003 +1,27 @@
+const path = require("path");
+const { DIR, FILE } = require("../writer");
+
module.exports = {
- // =============== jsconfig.json ==============
- "jsconfig.json": `{
- "compilerOptions": {
- "target": "es6",
- "lib": [
- "es2015",
- "es2020"
- ],
- "esModuleInterop": true
+ "jsconfig.json": {
+ type: FILE,
+ path: path.join(__dirname, "files", "jsconfig.json"),
},
- "include": [
- "./index.d.ts",
- "*.js"
- ]
-}
-`,
- // =============== index.d.ts ==============
- "index.d.ts": `type UNKNOWN_P5_CONSTANT = any;
- declare class p5 {
- /**
- * This is the p5 instance constructor. A p5 instance
- * holds all the properties and methods related to a
- * p5 sketch. It expects an incoming sketch closure
- * and it can also take an optional node parameter
- * for attaching the generated p5 canvas to a node.
- * The sketch closure takes the newly created p5
- * instance as its sole argument and may optionally
- * set preload(), setup(), and/or draw() properties
- * on it for running a sketch.
- *
- * A p5 sketch can run in "global" or "instance"
- * mode: "global" - all properties and methods are
- * attached to the window "instance" - all properties
- * and methods are bound to this p5 object
- *
- *
- * @param sketch a closure that can set optional
- * preload(), setup(), and/or draw() properties on
- * the given p5 instance
- * @param [node] p5.Element to attach canvas to
- * @return a p5 instance
- */
- constructor(sketch: (p5: p5) => void, node?: HTMLp5.Element);
-
- /**
- * Called directly before setup(), the preload()
- * function is used to handle asynchronous loading of
- * external files in a blocking way. If a preload
- * function is defined, setup() will wait until any
- * load calls within have finished. Nothing besides
- * load calls (loadp5.Image, loadJSON, loadFont,
- * loadStrings, etc.) should be inside the preload
- * function. If asynchronous loading is preferred,
- * the load methods can instead be called in setup()
- * or anywhere else with the use of a callback
- * parameter. By default the text "loading..." will
- * be displayed. To make your own loading page,
- * include an HTML p5.Element with id "p5_loading" in
- * your page. More information here.
- */
- preload(): void;
-
- /**
- * The setup() function is called once when the
- * program starts. It's used to define initial
- * environment properties such as screen size and
- * background p5.Color and to load media such as images
- * and fonts as the program starts. There can only be
- * one setup() function for each program and it
- * shouldn't be called again after its initial
- * execution. Note: Variables declared within
- * setup() are not accessible within other functions,
- * including draw().
- */
- setup(): void;
-
- /**
- * Called directly after setup(), the draw() function
- * continuously executes the lines of code contained
- * inside its block until the program is stopped or
- * noLoop() is called. Note if noLoop() is called in
- * setup(), draw() will still be executed once before
- * stopping. draw() is called automatically and
- * should never be called explicitly. It should
- * always be controlled with noLoop(), redraw() and
- * loop(). After noLoop() stops the code in draw()
- * from executing, redraw() causes the code inside
- * draw() to execute once, and loop() will cause the
- * code inside draw() to resume executing
- * continuously.
- *
- *
- * The number of times draw() executes in each second
- * may be controlled with the frameRate() function.
- *
- *
- * There can only be one draw() function for each
- * sketch, and draw() must exist if you want the code
- * to run continuously, or to process events such as
- * mousePressed(). Sometimes, you might have an empty
- * call to draw() in your program, as shown in the
- * above example.
- *
- *
- * It is important to note that the drawing
- * coordinate system will be reset at the beginning
- * of each draw() call. If any transformations are
- * performed within draw() (ex: scale, rotate,
- * translate), their effects will be undone at the
- * beginning of draw(), so transformations will not
- * accumulate over time. On the other hand, styling
- * applied (ex: fill, stroke, etc) will remain in
- * effect.
- */
- draw(): void;
-
- /**
- * Removes the entire p5 sketch. This will remove the
- * canvas and any p5.Elements created by p5.js. It will
- * also stop the draw loop and unbind any properties
- * or methods from the window global scope. It will
- * leave a variable p5 in case you wanted to create a
- * new p5 sketch. If you like, you can set p5 = null
- * to erase it. While all functions and variables and
- * objects created by the p5 library will be removed,
- * any other global variables created by your code
- * will remain.
- */
- remove(): void;
-
- /**
- * Allows for the friendly error system (FES) to be
- * turned off when creating a sketch, which can give
- * a significant boost to performance when needed.
- * See disabling the friendly error system.
- */
- disableFriendlyErrors: boolean;
- }
-
- namespace p5 {
-
- declare class Color {
- /**
- * This returns the p5.Color formatted as a
- * string. This can be useful for debugging, or for
- * using p5.js with other libraries.
- * @param [format] How the p5.Color string will be
- * formatted. Leaving this empty formats the string
- * as rgba(r, g, b, a). '#rgb' '#rgba' '#rrggbb' and
- * '#rrggbbaa' format as hexadecimal p5.Color codes.
- * 'rgb' 'hsb' and 'hsl' return the p5.Color formatted
- * in the specified p5.Color mode. 'rgba' 'hsba' and
- * 'hsla' are the same as above but with alpha
- * channels. 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and
- * 'hsla%' format as percentages.
- * @return the formatted string
- */
- toString(format?: string): string;
- setRed(red: number): void;
- setGreen(green: number): void;
- setBlue(blue: number): void;
- setAlpha(alpha: number): void;
- }
-
- declare class Element {
- /**
- * Attaches the p5.Element to the parent specified. A
- * way of setting the container for the p5.Element.
- * Accepts either a string ID, DOM node, or
- * p5.p5.Element. If no arguments given, parent node is
- * returned. For more ways to position the canvas,
- * see the positioning the canvas wiki page. All
- * above examples except for the first one require
- * the inclusion of the p5.dom library in your
- * index.html. See the using a library section for
- * information on how to include this library.
- * @param parent the ID, DOM node, or p5.p5.Element of
- * desired parent p5.Element
- * @chainable
- */
- parent(parent: string | p5.Element | object): p5.Element;
-
- /**
- * Attaches the p5.Element to the parent specified. A
- * way of setting the container for the p5.Element.
- * Accepts either a string ID, DOM node, or
- * p5.p5.Element. If no arguments given, parent node is
- * returned. For more ways to position the canvas,
- * see the positioning the canvas wiki page. All
- * above examples except for the first one require
- * the inclusion of the p5.dom library in your
- * index.html. See the using a library section for
- * information on how to include this library.
- */
- parent(): p5.Element;
-
- /**
- * Sets the ID of the p5.Element. If no ID argument is
- * passed in, it instead returns the current ID of
- * the p5.Element. Note that only one p5.Element can have a
- declare * particular id in a page. The .class() can
- * be used to identify multiple p5.Elements with the
- declare * same class name.
- * @param id ID of the p5.Element
- * @chainable
- */
- id(id: string): p5.Element;
-
- /**
- * Sets the ID of the p5.Element. If no ID argument is
- * passed in, it instead returns the current ID of
- * the p5.Element. Note that only one p5.Element can have a
- declare * particular id in a page. The .class() can
- * be used to identify multiple p5.Elements with the
- declare * same class name.
- * @return the id of the p5.Element
- */
- id(): string;
-
- /**
- * Adds given class to the p5.Element. If no class
- * argument is passed in, it instead returns a string
- * containing the current class(es) of the p5.Element.
- * @param class class to add
- * @chainable
- */
- class(theClass: string): p5.Element;
-
- /**
- declare * Adds given class to the p5.Element. If no class
- * argument is passed in, it instead returns a string
- * containing the current class(es) of the p5.Element.
- * @return the class of the p5.Element
- */
- class(): string;
-
- /**
- * The .mousePressed() is called once after
- * every time a mouse button is pressed over the
- * p5.Element. Some mobile browsers may also trigger
- * this event on a touch screen, if the user performs
- * a quick tap. This can be used to attach p5.Element
- * specific event listeners.
- * @param fxn to be fired when mouse is
- * pressed over the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- mousePressed(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .doubleClicked() is called once after
- * every time a mouse button is pressed twice over
- * the p5.Element. This can be used to attach p5.Element
- * and action specific event listeners.
- * @param fxn to be fired when mouse is
- * double clicked over the p5.Element. if false is
- * passed instead, the previously firing
- * will no longer fire.
- */
- doubleClicked(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .mouseWheel() is called once after
- * every time a mouse wheel is scrolled over the
- * p5.Element. This can be used to attach p5.Element
- * specific event listeners. The accepts a
- * callback as argument which will be
- * executed when the wheel event is triggered on the
- * p5.Element, the callback is passed one
- * argument event. The event.deltaY property returns
- * negative values if the mouse wheel is rotated up
- * or away from the user and positive in the other
- * direction. The event.deltaX does the same as
- * event.deltaY except it reads the horizontal wheel
- * scroll of the mouse wheel.
- *
- *
- * On OS X with "natural" scrolling enabled, the
- * event.deltaY values are reversed.
- * @param fxn to be fired when mouse is
- * scrolled over the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- mouseWheel(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .mouseReleased() is called once after
- * every time a mouse button is released over the
- * p5.Element. Some mobile browsers may also trigger
- * this event on a touch screen, if the user performs
- * a quick tap. This can be used to attach p5.Element
- * specific event listeners.
- * @param fxn to be fired when mouse is
- * released over the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- mouseReleased(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .mouseClicked() is called once after
- * a mouse button is pressed and released over the
- * p5.Element. Some mobile browsers may also trigger
- * this event on a touch screen, if the user performs
- * a quick tap. This can be used to attach p5.Element
- * specific event listeners.
- * @param fxn to be fired when mouse is
- * clicked over the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- mouseClicked(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .mouseMoved() is called once every
- * time a mouse moves over the p5.Element. This can be
- * used to attach an p5.Element specific event listener.
- * @param fxn to be fired when a mouse moves
- * over the p5.Element. if false is passed instead, the
- * previously firing will no longer fire.
- * @chainable
- */
- mouseMoved(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .mouseOver() is called once after
- * every time a mouse moves onto the p5.Element. This
- * can be used to attach an p5.Element specific event
- * listener.
- * @param fxn to be fired when a mouse moves
- * onto the p5.Element. if false is passed instead, the
- * previously firing will no longer fire.
- * @chainable
- */
- mouseOver(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .mouseOut() is called once after
- * every time a mouse moves off the p5.Element. This can
- * be used to attach an p5.Element specific event
- * listener.
- * @param fxn to be fired when a mouse moves
- * off of an p5.Element. if false is passed instead, the
- * previously firing will no longer fire.
- * @chainable
- */
- mouseOut(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .touchStarted() is called once after
- * every time a touch is registered. This can be used
- * to attach p5.Element specific event listeners.
- * @param fxn to be fired when a touch
- * starts over the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- touchStarted(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .touchMoved() is called once after
- * every time a touch move is registered. This can be
- * used to attach p5.Element specific event listeners.
- * @param fxn to be fired when a touch moves
- * over the p5.Element. if false is passed instead, the
- * previously firing will no longer fire.
- * @chainable
- */
- touchMoved(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .touchEnded() is called once after
- * every time a touch is registered. This can be used
- * to attach p5.Element specific event listeners.
- * @param fxn to be fired when a touch ends
- * over the p5.Element. if false is passed instead, the
- * previously firing will no longer fire.
- * @chainable
- */
- touchEnded(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .dragOver() is called once after
- * every time a file is dragged over the p5.Element.
- * This can be used to attach an p5.Element specific
- * event listener.
- * @param fxn to be fired when a file is
- * dragged over the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- dragOver(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * The .dragLeave() is called once after
- * every time a dragged file leaves the p5.Element area.
- * This can be used to attach an p5.Element specific
- * event listener.
- * @param fxn to be fired when a file is
- * dragged off the p5.Element. if false is passed
- * instead, the previously firing will no
- * longer fire.
- * @chainable
- */
- dragLeave(fxn: ((...args: any[]) => any) | boolean): p5.Element;
-
- /**
- * Underlying HTML p5.Element. All normal HTML methods
- * can be called on this.
- */
- elt: any;
- }
-
-
- declare class Graphics extends p5.Element {
- /**
- * Resets certain values such as those modified by
- * s in the Transform category and in the
- * Lights category that are not automatically reset
- * with graphics buffer objects. Calling this in
- * draw() will copy the behavior of the standard
- * canvas.
- */
- reset(): void;
-
- /**
- * Removes ap5.Graphics object from the page and frees
- * any resources associated with it.
- */
- remove(): void;
- }
-
- declare class Renderer extends p5.Element {
- /**
- * Main graphics and rendering context, as well as
- * the base API implementation for p5.js "core". To
- declare * be used as the superclass for p5.Renderer2D and
- declare * p5.Renderer3D classes, respecitvely.
- *
- * @param elt DOM node that is wrapped
- * @param [pInst] pointer to p5 instance
- * @param [isMainCanvas] whether we're using it as
- * main canvas
- */
- constructor(elt: string, pInst?: p5, isMainCanvas?: boolean);
- }
- declare class TypedDict {
- /**
- * Returns the number of key-value pairs currently
- * stored in the Dictionary.
- * @return the number of key-value pairs in the
- * Dictionary
- */
- size(): number;
-
- /**
- * Returns true if the given key exists in the
- * Dictionary, otherwise returns false.
- * @param key that you want to look up
- * @return whether that key exists in Dictionary
- */
- hasKey(key: number | string): boolean;
-
- /**
- * Returns the value stored at the given key.
- * @param the key you want to access
- * @return the value stored at that key
- */
- get(the: number | string): number | string;
-
- /**
- * Updates the value associated with the given key in
- * case it already exists in the Dictionary.
- * Otherwise a new key-value pair is added.
- */
- set(key: number | string, value: number | string): void;
-
- /**
- * Creates a new key-value pair in the Dictionary.
- */
- create(key: number | string, value: number | string): void;
-
- /**
- * Creates a new key-value pair in the Dictionary.
- * @param obj key/value pair
- */
- create(obj: object): void;
-
- /**
- * Removes all previously stored key-value pairs from
- * the Dictionary.
- */
- clear(): void;
-
- /**
- * Removes the key-value pair stored at the given key
- * from the Dictionary.
- * @param key for the pair to remove
- */
- remove(key: number | string): void;
-
- /**
- * Logs the set of items currently stored in the
- * Dictionary to the console.
- */
- print(): void;
-
- /**
- * Converts the Dictionary into a CSV file for local
- * download.
- */
- saveTable(): void;
-
- /**
- * Converts the Dictionary into a JSON file for local
- * download.
- */
- saveJSON(): void;
- }
- declare class Image {
- /**
- * Loads the pixels data for this image into the
- * [pixels] attribute.
- */
- loadPixels(): void;
-
- /**
- * Updates the backing canvas for this image with the
- * contents of the [pixels] array.
- * @param x x-offset of the target update area for
- * the underlying canvas
- * @param y y-offset of the target update area for
- * the underlying canvas
- * @param w height of the target update area for the
- * underlying canvas
- * @param h height of the target update area for the
- * underlying canvas
- */
- updatePixels(x: number, y: number, w: number, h: number): void;
-
- /**
- * Updates the backing canvas for this image with the
- * contents of the [pixels] array.
- */
- updatePixels(): void;
-
- /**
- * Get a region of pixels from an image. If no params
- * are passed, the whole image is returned. If x and
- * y are the only params passed a single pixel is
- * extracted. If all params are passed a rectangle
- * region is extracted and a p5.p5.Image is returned.
- * @param x x-coordinate of the pixel
- * @param y y-coordinate of the pixel
- * @param w width
- * @param h height
- * @return the rectangle p5.p5.Image
- */
- get(x: number, y: number, w: number, h: number): p5.Image;
-
- /**
- * Get a region of pixels from an image. If no params
- * are passed, the whole image is returned. If x and
- * y are the only params passed a single pixel is
- * extracted. If all params are passed a rectangle
- * region is extracted and a p5.p5.Image is returned.
- * @return the whole p5.p5.Image
- */
- get(): p5.Image;
-
- /**
- * Get a region of pixels from an image. If no params
- * are passed, the whole image is returned. If x and
- * y are the only params passed a single pixel is
- * extracted. If all params are passed a rectangle
- * region is extracted and a p5.p5.Image is returned.
- * @param x x-coordinate of the pixel
- * @param y y-coordinate of the pixel
- * @return p5.Color of pixel at x,y in array format [R,
- * G, B, A]
- */
- get(x: number, y: number): number[];
-
- /**
- * Set the p5.Color of a single pixel or write an image
- * into this p5.p5.Image. Note that for a large number
- * of pixels this will be slower than directly
- * manipulating the pixels array and then calling
- * updatePixels().
- * @param x x-coordinate of the pixel
- * @param y y-coordinate of the pixel
- * @param a grayscale value | pixel array | a
- * p5.p5.Color | image to copy
- */
- set(x: number, y: number, a: number | number[] | object): void;
-
- /**
- * Resize the image to a new width and height. To
- * make the image scale proportionally, use 0 as the
- * value for the wide or high parameter. For
- * instance, to make the width of an image 150
- * pixels, and change the height using the same
- * proportion, use resize(150, 0).
- * @param width the resized image width
- * @param height the resized image height
- */
- resize(width: number, height: number): void;
-
- /**
- * Copies a region of pixels from one image to
- * another. If no srcImage is specified this is used
- * as the source. If the source and destination
- * regions aren't the same size, it will
- * automatically resize source pixels to fit the
- * specified target region.
- * @param srcImage source image
- * @param sx X coordinate of the source's upper left
- * corner
- * @param sy Y coordinate of the source's upper left
- * corner
- * @param sw source image width
- * @param sh source image height
- * @param dx X coordinate of the destination's upper
- * left corner
- * @param dy Y coordinate of the destination's upper
- * left corner
- * @param dw destination image width
- * @param dh destination image height
- */
- copy(
- srcImage: p5.Image | p5.Element,
- sx: number,
- sy: number,
- sw: number,
- sh: number,
- dx: number,
- dy: number,
- dw: number,
- dh: number
- ): void;
-
- /**
- * Copies a region of pixels from one image to
- * another. If no srcImage is specified this is used
- * as the source. If the source and destination
- * regions aren't the same size, it will
- * automatically resize source pixels to fit the
- * specified target region.
- * @param sx X coordinate of the source's upper left
- * corner
- * @param sy Y coordinate of the source's upper left
- * corner
- * @param sw source image width
- * @param sh source image height
- * @param dx X coordinate of the destination's upper
- * left corner
- * @param dy Y coordinate of the destination's upper
- * left corner
- * @param dw destination image width
- * @param dh destination image height
- */
- copy(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
-
- /**
- * Masks part of an image from displaying by loading
- * another image and using it's alpha channel as an
- * alpha channel for this image.
- * @param srcImage source image
- */
- mask(srcImage: p5.Image): void;
-
- /**
- * Applies an image filter to a p5.p5.Image
- * @param filterType either THRESHOLD, GRAY, OPAQUE,
- * INVERT, POSTERIZE, BLUR, ERODE, DILATE or BLUR.
- * See Filters.js for docs on each available filter
- * @param [filterParam] an optional parameter unique
- * to each filter, see above
- */
- filter(filterType: FILTER_TYPE, filterParam?: number): void;
-
- /**
- * Copies a region of pixels from one image to
- * another, using a specified blend mode to do the
- * operation.
- * @param srcImage source image
- * @param sx X coordinate of the source's upper left
- * corner
- * @param sy Y coordinate of the source's upper left
- * corner
- * @param sw source image width
- * @param sh source image height
- * @param dx X coordinate of the destination's upper
- * left corner
- * @param dy Y coordinate of the destination's upper
- * left corner
- * @param dw destination image width
- * @param dh destination image height
- * @param blendMode the blend mode. either BLEND,
- * DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,
- * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
- * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
- *
- * Available blend modes are: normal | multiply |
- * screen | overlay | darken | lighten | p5.Color-dodge
- * | p5.Color-burn | hard-light | soft-light |
- * difference | exclusion | hue | saturation | p5.Color
- * | luminosity
- *
- * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
- */
- blend(
- srcImage: p5.Image,
- sx: number,
- sy: number,
- sw: number,
- sh: number,
- dx: number,
- dy: number,
- dw: number,
- dh: number,
- blendMode: BLEND_MODE
- ): void;
-
- /**
- * Copies a region of pixels from one image to
- * another, using a specified blend mode to do the
- * operation.
- * @param sx X coordinate of the source's upper left
- * corner
- * @param sy Y coordinate of the source's upper left
- * corner
- * @param sw source image width
- * @param sh source image height
- * @param dx X coordinate of the destination's upper
- * left corner
- * @param dy Y coordinate of the destination's upper
- * left corner
- * @param dw destination image width
- * @param dh destination image height
- * @param blendMode the blend mode. either BLEND,
- * DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,
- * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
- * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
- *
- * Available blend modes are: normal | multiply |
- * screen | overlay | darken | lighten | p5.Color-dodge
- * | p5.Color-burn | hard-light | soft-light |
- * difference | exclusion | hue | saturation | p5.Color
- * | luminosity
- *
- * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
- */
- blend(
- sx: number,
- sy: number,
- sw: number,
- sh: number,
- dx: number,
- dy: number,
- dw: number,
- dh: number,
- blendMode: UNKNOWN_P5_CONSTANT
- ): void;
-
- /**
- * Saves the image to a file and force the browser to
- * download it. Accepts two strings for filename and
- * file extension Supports png (default) and jpg.
- * @param filename give your file a name
- * @param extension 'png' or 'jpg'
- */
- save(filename: string, extension: string): void;
-
- /**
- * p5.Image width.
- */
- width: number;
-
- /**
- * p5.Image height.
- */
- height: number;
-
- /**
- * Array containing the values for all the pixels in
- * the display window. These values are numbers. This
- * array is the size (include an appropriate factor
- * for pixelDensity) of the display window x4,
- * representing the R, G, B, A values in order for
- * each pixel, moving from left to right across each
- * row, then down each column. Retina and other high
- * denisty displays may have more pixels (by a factor
- * of pixelDensity^2). For example, if the image is
- * 100x100 pixels, there will be 40,000. With
- * pixelDensity = 2, there will be 160,000. The first
- * four values (indices 0-3) in the array will be the
- * R, G, B, A values of the pixel at (0, 0). The
- * second four values (indices 4-7) will contain the
- * R, G, B, A values of the pixel at (1, 0). More
- * generally, to set values for a pixel at (x, y):
- * let d = pixelDensity(); for (let i = 0; i < d;
- * i++) { for (let j = 0; j < d; j++) { // loop over
- * index = 4 * ((y * d + j) * width * d + (x * d +
- * i)); pixels[index] = r; pixels[index+1] = g;
- * pixels[index+2] = b; pixels[index+3] = a; } }
- *
- *
- *
- *
- * Before accessing this array, the data must loaded
- * with the loadPixels() . After the array
- * data has been modified, the updatePixels()
- * must be run to update the changes.
- */
- pixels: number[];
- }
- declare class PrintWriter {
- /**
- * Writes data to the p5.PrintWriter stream
- * @param data all data to be written by the
- * p5.PrintWriter
- */
- write(data: any[]): void;
-
- /**
- * Writes data to the p5.PrintWriter stream, and adds a
- * new line at the end
- * @param data all data to be printed by the
- * p5.PrintWriter
- */
- print(data: any[]): void;
-
- /**
- * Clears the data already written to the p5.PrintWriter
- * object
- */
- clear(): void;
-
- /**
- * Closes the p5.PrintWriter
- */
- close(): void;
- }
- declare class Table {
- /**
- * p5.Table objects store data with multiple rows and
- * columns, much like in a traditional spreadsheet.
- * p5.Tables can be generated from scratch, dynamically,
- * or using data from an existing file.
- *
- * @param [rows] An array of p5.p5.TableRow objects
- */
- constructor(rows?: p5.TableRow[]);
-
- /**
- * Use addRow() to add a new row of data to a
- * p5.p5.Table object. By default, an empty row is
- * created. Typically, you would store a reference to
- * the new row in a p5.TableRow object (see newRow in
- * the example above), and then set individual values
- * using set(). If a p5.p5.TableRow object is included
- * as a parameter, then that row is duplicated and
- * added to the table.
- * @param [row] row to be added to the table
- * @return the row that was added
- */
- addRow(row?: p5.TableRow): p5.TableRow;
-
- /**
- * Removes a row from the table object.
- * @param id ID number of the row to remove
- */
- removeRow(id: number): void;
-
- /**
- * Returns a reference to the specified p5.p5.TableRow.
- * The reference can then be used to get and set
- * values of the selected row.
- * @param rowID ID number of the row to get
- * @return p5.p5.TableRow object
- */
- getRow(rowID: number): p5.TableRow;
-
- /**
- * Gets all rows from the table. Returns an array of
- * p5.p5.TableRows.
- * @return Array of p5.p5.TableRows
- */
- getRows(): p5.TableRow[];
-
- /**
- * Finds the first row in the p5.Table that contains the
- * value provided, and returns a reference to that
- * row. Even if multiple rows are possible matches,
- * only the first matching row is returned. The
- * column to search may be specified by either its ID
- * or title.
- * @param value The value to match
- * @param column ID number or title of the column to
- * search
- */
- findRow(value: string, column: number | string): p5.TableRow;
-
- /**
- * Finds the rows in the p5.Table that contain the value
- * provided, and returns references to those rows.
- * Returns an Array, so for must be used to iterate
- * through all the rows, as shown in the example
- * above. The column to search may be specified by
- * either its ID or title.
- * @param value The value to match
- * @param column ID number or title of the column to
- * search
- * @return An Array of p5.TableRow objects
- */
- findRows(value: string, column: number | string): p5.TableRow[];
-
- /**
- * Finds the first row in the p5.Table that matches the
- * regular expression provided, and returns a
- * reference to that row. Even if multiple rows are
- * possible matches, only the first matching row is
- * returned. The column to search may be specified by
- * either its ID or title.
- * @param regexp The regular expression to match
- * @param column The column ID (number) or title
- * (string)
- * @return p5.TableRow object
- */
- matchRow(regexp: string | RegExp, column: string | number): p5.TableRow;
-
- /**
- * Finds the rows in the p5.Table that match the regular
- * expression provided, and returns references to
- * those rows. Returns an array, so for must be used
- * to iterate through all the rows, as shown in the
- * example. The column to search may be specified by
- * either its ID or title.
- * @param regexp The regular expression to match
- * @param [column] The column ID (number) or title
- * (string)
- * @return An Array of p5.TableRow objects
- */
- matchRows(regexp: string, column?: string | number): p5.TableRow[];
-
- /**
- * Retrieves all values in the specified column, and
- * returns them as an array. The column may be
- * specified by either its ID or title.
- * @param column String or Number of the column to
- * return
- * @return Array of column values
- */
- getColumn(column: string | number): any[];
-
- /**
- * Removes all rows from a p5.Table. While all rows are
- * removed, columns and column titles are maintained.
- */
- clearRows(): void;
-
- /**
- * Use addColumn() to add a new column to a p5.Table
- * object. Typically, you will want to specify a
- * title, so the column may be easily referenced
- * later by name. (If no title is specified, the new
- * column's title will be null.)
- * @param [title] title of the given column
- */
- addColumn(title?: string): void;
-
- /**
- * Returns the total number of columns in a p5.Table.
- * @return Number of columns in this table
- */
- getColumnCount(): number;
-
- /**
- * Returns the total number of rows in a p5.Table.
- * @return Number of rows in this table
- */
- getRowCount(): number;
-
- /**
- * Removes any of the specified characters (or
- * "tokens"). If no column is specified, then the
- * values in all columns and rows are processed. A
- * specific column may be referenced by either its ID
- * or title.
- * @param chars String listing characters to be
- * removed
- * @param [column] Column ID (number) or name
- * (string)
- */
- removeTokens(chars: string, column?: string | number): void;
-
- /**
- * Trims leading and trailing whitespace, such as
- * spaces and tabs, from String table values. If no
- * column is specified, then the values in all
- * columns and rows are trimmed. A specific column
- * may be referenced by either its ID or title.
- * @param [column] Column ID (number) or name
- * (string)
- */
- trim(column?: string | number): void;
-
- /**
- * Use removeColumn() to remove an existing column
- * from a p5.Table object. The column to be removed may
- * be identified by either its title (a String) or
- * its index value (an int). removeColumn(0) would
- * remove the first column, removeColumn(1) would
- * remove the second column, and so on.
- * @param column columnName (string) or ID (number)
- */
- removeColumn(column: string | number): void;
-
- /**
- * Stores a value in the p5.Table's specified row and
- * column. The row is specified by its ID, while the
- * column may be specified by either its ID or title.
- * @param row row ID
- * @param column column ID (Number) or title (String)
- * @param value value to assign
- */
- set(row: number, column: string | number, value: string | number): void;
-
- /**
- * Stores a Float value in the p5.Table's specified row
- * and column. The row is specified by its ID, while
- * the column may be specified by either its ID or
- * title.
- * @param row row ID
- * @param column column ID (Number) or title (String)
- * @param value value to assign
- */
- setNum(row: number, column: string | number, value: number): void;
-
- /**
- * Stores a String value in the p5.Table's specified row
- * and column. The row is specified by its ID, while
- * the column may be specified by either its ID or
- * title.
- * @param row row ID
- * @param column column ID (Number) or title (String)
- * @param value value to assign
- */
- setString(row: number, column: string | number, value: string): void;
-
- /**
- * Retrieves a value from the p5.Table's specified row
- * and column. The row is specified by its ID, while
- * the column may be specified by either its ID or
- * title.
- * @param row row ID
- * @param column columnName (string) or ID (number)
- */
- get(row: number, column: string | number): string | number;
-
- /**
- * Retrieves a Float value from the p5.Table's specified
- * row and column. The row is specified by its ID,
- * while the column may be specified by either its ID
- * or title.
- * @param row row ID
- * @param column columnName (string) or ID (number)
- */
- getNum(row: number, column: string | number): number;
-
- /**
- * Retrieves a String value from the p5.Table's
- * specified row and column. The row is specified by
- * its ID, while the column may be specified by
- * either its ID or title.
- * @param row row ID
- * @param column columnName (string) or ID (number)
- */
- getString(row: number, column: string | number): string;
-
- /**
- * Retrieves all table data and returns as an object.
- * If a column name is passed in, each row object
- * will be stored with that attribute as its title.
- * @param [headerColumn] Name of the column which
- * should be used to title each row object (optional)
- */
- getObject(headerColumn?: string): object;
-
- /**
- * Retrieves all table data and returns it as a
- * multidimensional array.
- */
- getArray(): any[];
- columns: string[];
- rows: p5.TableRow[];
- }
- declare class TableRow {
- /**
- * A p5.TableRow object represents a single row of data
- * values, stored in columns, from a table. A p5.Table
- * Row contains both an ordered array, and an
- * unordered JSON object.
- *
- * @param [str] optional: populate the row with a
- * string of values, separated by the separator
- * @param [separator] comma separated values (csv) by
- * default
- */
- constructor(str?: string, separator?: string);
-
- /**
- * Stores a value in the p5.TableRow's specified column.
- * The column may be specified by either its ID or
- * title.
- * @param column Column ID (Number) or Title (String)
- * @param value The value to be stored
- */
- set(column: string | number, value: string | number): void;
-
- /**
- * Stores a Float value in the p5.TableRow's specified
- * column. The column may be specified by either its
- * ID or title.
- * @param column Column ID (Number) or Title (String)
- * @param value The value to be stored as a Float
- */
- setNum(column: string | number, value: number | string): void;
-
- /**
- * Stores a String value in the p5.TableRow's specified
- * column. The column may be specified by either its
- * ID or title.
- * @param column Column ID (Number) or Title (String)
- * @param value The value to be stored as a String
- */
- setString(column: string | number, value: string | number | boolean | object): void;
-
- /**
- * Retrieves a value from the p5.TableRow's specified
- * column. The column may be specified by either its
- * ID or title.
- * @param column columnName (string) or ID (number)
- */
- get(column: string | number): string | number;
-
- /**
- * Retrieves a Float value from the p5.TableRow's
- * specified column. The column may be specified by
- * either its ID or title.
- * @param column columnName (string) or ID (number)
- * @return Float Floating point number
- */
- getNum(column: string | number): number;
-
- /**
- * Retrieves an String value from the p5.TableRow's
- * specified column. The column may be specified by
- * either its ID or title.
- * @param column columnName (string) or ID (number)
- * @return String
- */
- getString(column: string | number): string;
- }
-
- declare class XML {
- /**
- * p5.XML is a representation of an p5.XML object, able to
- * parse p5.XML code. Use loadp5.XML() to load external p5.XML
- * files and create p5.XML objects.
- *
- */
- constructor();
-
- /**
- * Gets a copy of the p5.Element's parent. Returns the
- * parent as another p5.p5.XML object.
- * @return p5.Element parent
- */
- getParent(): p5.XML;
-
- /**
- * Gets the p5.Element's full name, which is returned as
- * a String.
- * @return the name of the node
- */
- getName(): string;
-
- /**
- * Sets the p5.Element's name, which is specified as a
- * String.
- * @param the new name of the node
- */
- setName(the: string): void;
-
- /**
- * Checks whether or not the p5.Element has any
- * children, and returns the result as a boolean.
- */
- hasChildren(): boolean;
-
- /**
- * Get the names of all of the p5.Element's children,
- * and returns the names as an array of Strings. This
- * is the same as looping through and calling
- * getName() on each child p5.Element individually.
- * @return names of the children of the p5.Element
- */
- listChildren(): string[];
-
- /**
- * Returns all of the p5.Element's children as an array
- * of p5.p5.XML objects. When the name parameter is
- * specified, then it will return all children that
- * match that name.
- * @param [name] p5.Element name
- * @return children of the p5.Element
- */
- getChildren(name?: string): p5.XML[];
-
- /**
- * Returns the first of the p5.Element's children that
- * matches the name parameter or the child of the
- * given index.It returns undefined if no matching
- * child is found.
- * @param name p5.Element name or index
- */
- getChild(name: string | number): p5.XML;
-
- /**
- * Appends a new child to the p5.Element. The child can
- * be specified with either a String, which will be
- * used as the new tag's name, or as a reference to
- * an existing p5.p5.XML object. A reference to the
- * newly created child is returned as an p5.p5.XML
- * object.
- * @param node a p5.p5.XML Object which will be the
- * child to be added
- */
- addChild(node: p5.XML): void;
-
- /**
- * Removes the p5.Element specified by name or index.
- * @param name p5.Element name or index
- */
- removeChild(name: string | number): void;
-
- /**
- * Counts the specified p5.Element's number of
- * attributes, returned as an Number.
- */
- getAttributeCount(): number;
-
- /**
- * Gets all of the specified p5.Element's attributes,
- * and returns them as an array of Strings.
- * @return an array of strings containing the names
- * of attributes
- */
- listAttributes(): string[];
-
- /**
- * Checks whether or not an p5.Element has the specified
- * attribute.
- * @param the attribute to be checked
- * @return true if attribute found else false
- */
- hasAttribute(the: string): boolean;
-
- /**
- * Returns an attribute value of the p5.Element as an
- * Number. If the defaultValue parameter is specified
- * and the attribute doesn't exist, then defaultValue
- * is returned. If no defaultValue is specified and
- * the attribute doesn't exist, the value 0 is
- * returned.
- * @param name the non-null full name of the
- * attribute
- * @param [defaultValue] the default value of the
- * attribute
- */
- getNum(name: string, defaultValue?: number): number;
-
- /**
- * Returns an attribute value of the p5.Element as an
- * String. If the defaultValue parameter is specified
- * and the attribute doesn't exist, then defaultValue
- * is returned. If no defaultValue is specified and
- * the attribute doesn't exist, null is returned.
- * @param name the non-null full name of the
- * attribute
- * @param [defaultValue] the default value of the
- * attribute
- */
- getString(name: string, defaultValue?: number): string;
-
- /**
- * Sets the content of an p5.Element's attribute. The
- * first parameter specifies the attribute name,
- * while the second specifies the new content.
- * @param name the full name of the attribute
- * @param value the value of the attribute
- */
- setAttribute(name: string, value: number | string | boolean): void;
-
- /**
- * Returns the content of an p5.Element. If there is no
- * such content, defaultValue is returned if
- * specified, otherwise null is returned.
- * @param [defaultValue] value returned if no content
- * is found
- */
- getContent(defaultValue?: string): string;
-
- /**
- * Sets the p5.Element's content.
- * @param text the new content
- */
- setContent(text: string): void;
-
- /**
- * Serializes the p5.Element into a string. This
- * is useful for preparing the content to be
- * sent over a http request or saved to file.
- * @return Serialized string of the p5.Element
- */
- serialize(): string;
- }
- declare class Vector {
- /**
- * Adds x, y, and z components to a vector, adds one
- * vector to another, or adds two independent vectors
- * together. The version of the method that adds two
- * vectors together is a static method and returns a
- * p5.Vector, the others acts directly on the vector.
- * See the examples for more context.
- * @param v1 a p5.Vector to add
- * @param v2 a p5.Vector to add
- * @param target the vector to receive the result
- */
- static add(v1: p5.Vector, v2: p5.Vector, target: p5.Vector): void;
-
- /**
- * Adds x, y, and z components to a vector, adds one
- * vector to another, or adds two independent vectors
- * together. The version of the method that adds two
- * vectors together is a static method and returns a
- * p5.Vector, the others acts directly on the vector.
- * See the examples for more context.
- * @param v1 a p5.Vector to add
- * @param v2 a p5.Vector to add
- * @return the resulting p5.Vector
- */
- static add(v1: p5.Vector, v2: p5.Vector): p5.Vector;
-
- /**
- * Subtracts x, y, and z components from a vector,
- * subtracts one vector from another, or subtracts
- * two independent vectors. The version of the method
- * that subtracts two vectors is a static method and
- * returns a p5.Vector, the other acts directly on
- * the vector. See the examples for more context.
- * @param v1 a p5.Vector to subtract from
- * @param v2 a p5.Vector to subtract
- * @param target if undefined a new vector will be
- * created
- */
- static sub(v1: p5.Vector, v2: p5.Vector, target: p5.Vector): void;
-
- /**
- * Subtracts x, y, and z components from a vector,
- * subtracts one vector from another, or subtracts
- * two independent vectors. The version of the method
- * that subtracts two vectors is a static method and
- * returns a p5.Vector, the other acts directly on
- * the vector. See the examples for more context.
- * @param v1 a p5.Vector to subtract from
- * @param v2 a p5.Vector to subtract
- * @return the resulting p5.Vector
- */
- static sub(v1: p5.Vector, v2: p5.Vector): p5.Vector;
-
- /**
- * Multiply the vector by a scalar. The static
- * version of this method creates a new p5.Vector
- * while the non static version acts on the vector
- * directly. See the examples for more context.
- * @param v the vector to multiply
- * @param n the number to multiply with the vector
- * @param target if undefined a new vector will be
- * created
- */
- static mult(v: p5.Vector, n: number, target: p5.Vector): void;
-
- /**
- * Multiply the vector by a scalar. The static
- * version of this method creates a new p5.Vector
- * while the non static version acts on the vector
- * directly. See the examples for more context.
- * @param v the vector to multiply
- * @param n the number to multiply with the vector
- * @return the resulting new p5.Vector
- */
- static mult(v: p5.Vector, n: number): p5.Vector;
-
- /**
- * Divide the vector by a scalar. The static version
- * of this method creates a new p5.Vector while the
- * non static version acts on the vector directly.
- * See the examples for more context.
- * @param v the vector to divide
- * @param n the number to divide the vector by
- * @param target if undefined a new vector will be
- * created
- */
- static div(v: p5.Vector, n: number, target: p5.Vector): void;
-
- /**
- * Divide the vector by a scalar. The static version
- * of this method creates a new p5.Vector while the
- * non static version acts on the vector directly.
- * See the examples for more context.
- * @param v the vector to divide
- * @param n the number to divide the vector by
- * @return the resulting new p5.Vector
- */
- static div(v: p5.Vector, n: number): p5.Vector;
-
- /**
- * Calculates the magnitude (length) of the vector
- * and returns the result as a float (this is simply
- * the equation sqrt(xx + yy + z*z).)
- * @param vecT the vector to return the magnitude of
- * @return the magnitude of vecT
- */
- static mag(vecT: p5.Vector): number;
-
- /**
- * Calculates the dot product of two vectors. The
- * version of the method that computes the dot
- * product of two independent vectors is a static
- * method. See the examples for more context.
- * @param v1 the first p5.Vector
- * @param v2 the second p5.Vector
- * @return the dot product
- */
- static dot(v1: p5.Vector, v2: p5.Vector): number;
-
- /**
- * Calculates and returns a vector composed of the
- * cross product between two vectors. Both the static
- * and non static methods return a new p5.Vector. See
- * the examples for more context.
- * @param v1 the first p5.Vector
- * @param v2 the second p5.Vector
- * @return the cross product
- */
- static cross(v1: p5.Vector, v2: p5.Vector): number;
-
- /**
- * Calculates the Euclidean distance between two
- * points (considering a point as a vector object).
- * @param v1 the first p5.Vector
- * @param v2 the second p5.Vector
- * @return the distance
- */
- static dist(v1: p5.Vector, v2: p5.Vector): number;
-
- /**
- * Linear interpolate the vector to another vector
- * @param amt the amount of interpolation; some value
- * between 0.0 (old vector) and 1.0 (new vector). 0.9
- * is very near the new vector. 0.5 is halfway in
- * between.
- * @param target if undefined a new vector will be
- * created
- */
- static lerp(v1: p5.Vector, v2: p5.Vector, amt: number, target: p5.Vector): void;
-
- /**
- * Linear interpolate the vector to another vector
- * @param amt the amount of interpolation; some value
- * between 0.0 (old vector) and 1.0 (new vector). 0.9
- * is very near the new vector. 0.5 is halfway in
- * between.
- * @return the lerped value
- */
- static lerp(v1: p5.Vector, v2: p5.Vector, amt: number): number;
-
- /**
- * Make a new 2D vector from an angle
- * @param angle the desired angle, in radians
- * (unaffected by angleMode)
- * @param [length] the length of the new vector
- * (defaults to 1)
- * @return the new p5.Vector object
- */
- static fromAngle(angle: number, length?: number): p5.Vector;
-
- /**
- * Make a new 3D vector from a pair of ISO spherical
- * angles
- * @param theta the polar angle, in radians (zero is
- * up)
- * @param phi the azimuthal angle, in radians (zero
- * is out of the screen)
- * @param [length] the length of the new vector
- * (defaults to 1)
- * @return the new p5.Vector object
- */
- static fromAngles(theta: number, phi: number, length?: number): p5.Vector;
-
- /**
- * Make a new 2D unit vector from a random angle
- * @return the new p5.Vector object
- */
- static random2D(): p5.Vector;
-
- /**
- * Make a new random 3D unit vector.
- * @return the new p5.Vector object
- */
- static random3D(): p5.Vector;
-
- /**
- * Returns a string representation of a vector v by
- * calling String(v) or v.toString(). This method is
- * useful for logging vectors in the console.
- */
- toString(): string;
-
- /**
- * Sets the x, y, and z component of the vector using
- * two or three separate variables, the data from a
- * p5.Vector, or the values from a float array.
- * @param [x] the x component of the vector
- * @param [y] the y component of the vector
- * @param [z] the z component of the vector
- * @chainable
- */
- set(x?: number, y?: number, z?: number): p5.Vector;
-
- /**
- * Sets the x, y, and z component of the vector using
- * two or three separate variables, the data from a
- * p5.Vector, or the values from a float array.
- * @param value the vector to set
- * @chainable
- */
- set(value: p5.Vector | number[]): p5.Vector;
-
- /**
- * Gets a copy of the vector, returns a p5.Vector
- * object.
- * @return the copy of the p5.Vector object
- */
- copy(): p5.Vector;
-
- /**
- * Adds x, y, and z components to a vector, adds one
- * vector to another, or adds two independent vectors
- * together. The version of the method that adds two
- * vectors together is a static method and returns a
- * p5.Vector, the others acts directly on the vector.
- * See the examples for more context.
- * @param x the x component of the vector to be added
- * @param [y] the y component of the vector to be
- * added
- * @param [z] the z component of the vector to be
- * added
- * @chainable
- */
- add(x: number, y?: number, z?: number): p5.Vector;
-
- /**
- * Adds x, y, and z components to a vector, adds one
- * vector to another, or adds two independent vectors
- * together. The version of the method that adds two
- * vectors together is a static method and returns a
- * p5.Vector, the others acts directly on the vector.
- * See the examples for more context.
- * @param value the vector to add
- * @chainable
- */
- add(value: p5.Vector | number[]): p5.Vector;
-
- /**
- * Subtracts x, y, and z components from a vector,
- * subtracts one vector from another, or subtracts
- * two independent vectors. The version of the method
- * that subtracts two vectors is a static method and
- * returns a p5.Vector, the other acts directly on
- * the vector. See the examples for more context.
- * @param x the x component of the vector to subtract
- * @param [y] the y component of the vector to
- * subtract
- * @param [z] the z component of the vector to
- * subtract
- * @chainable
- */
- sub(x: number, y?: number, z?: number): p5.Vector;
-
- /**
- * Subtracts x, y, and z components from a vector,
- * subtracts one vector from another, or subtracts
- * two independent vectors. The version of the method
- * that subtracts two vectors is a static method and
- * returns a p5.Vector, the other acts directly on
- * the vector. See the examples for more context.
- * @param value the vector to subtract
- * @chainable
- */
- sub(value: p5.Vector | number[]): p5.Vector;
-
- /**
- * Multiply the vector by a scalar. The static
- * version of this method creates a new p5.Vector
- * while the non static version acts on the vector
- * directly. See the examples for more context.
- * @param n the number to multiply with the vector
- * @chainable
- */
- mult(n: number): p5.Vector;
-
- /**
- * Divide the vector by a scalar. The static version
- * of this method creates a new p5.Vector while the
- * non static version acts on the vector directly.
- * See the examples for more context.
- * @param n the number to divide the vector by
- * @chainable
- */
- div(n: number): p5.Vector;
-
- /**
- * Calculates the magnitude (length) of the vector
- * and returns the result as a float (this is simply
- * the equation sqrt(xx + yy + z*z).)
- * @return magnitude of the vector
- */
- mag(): number;
-
- /**
- * Calculates the squared magnitude of the vector and
- * returns the result as a float (this is simply the
- * equation (xx + yy + z*z).) Faster if the real
- * length is not required in the case of comparing
- * vectors, etc.
- * @return squared magnitude of the vector
- */
- magSq(): number;
-
- /**
- * Calculates the dot product of two vectors. The
- * version of the method that computes the dot
- * product of two independent vectors is a static
- * method. See the examples for more context.
- * @param x x component of the vector
- * @param [y] y component of the vector
- * @param [z] z component of the vector
- * @return the dot product
- */
- dot(x: number, y?: number, z?: number): number;
-
- /**
- * Calculates the dot product of two vectors. The
- * version of the method that computes the dot
- * product of two independent vectors is a static
- * method. See the examples for more context.
- * @param value value component of the vector or a
- * p5.Vector
- */
- dot(value: p5.Vector): number;
-
- /**
- * Calculates and returns a vector composed of the
- * cross product between two vectors. Both the static
- * and non static methods return a new p5.Vector. See
- * the examples for more context.
- * @param v p5.Vector to be crossed
- * @return p5.Vector composed of cross product
- */
- cross(v: p5.Vector): p5.Vector;
-
- /**
- * Calculates the Euclidean distance between two
- * points (considering a point as a vector object).
- * @param v the x, y, and z coordinates of a
- * p5.Vector
- * @return the distance
- */
- dist(v: p5.Vector): number;
-
- /**
- * Normalize the vector to length 1 (make it a unit
- * vector).
- * @return normalized p5.Vector
- */
- normalize(): p5.Vector;
-
- /**
- * Limit the magnitude of this vector to the value
- * used for the max parameter.
- * @param max the maximum magnitude for the vector
- * @chainable
- */
- limit(max: number): p5.Vector;
-
- /**
- * Set the magnitude of this vector to the value used
- * for the len parameter.
- * @param len the new length for this vector
- * @chainable
- */
- setMag(len: number): p5.Vector;
-
- /**
- * Calculate the angle of rotation for this vector
- * (only 2D vectors)
- * @return the angle of rotation
- */
- heading(): number;
-
- /**
- * Rotate the vector by an angle (only 2D vectors),
- * magnitude remains the same
- * @param angle the angle of rotation
- * @chainable
- */
- rotate(angle: number): p5.Vector;
-
- /**
- * Calculates and returns the angle (in radians)
- * between two vectors.
- * @param value the x, y, and z components of a
- * p5.Vector
- * @return the angle between (in radians)
- */
- angleBetween(value: p5.Vector): number;
-
- /**
- * Linear interpolate the vector to another vector
- * @param x the x component
- * @param y the y component
- * @param z the z component
- * @param amt the amount of interpolation; some value
- * between 0.0 (old vector) and 1.0 (new vector). 0.9
- * is very near the new vector. 0.5 is halfway in
- * between.
- * @chainable
- */
- lerp(x: number, y: number, z: number, amt: number): p5.Vector;
-
- /**
- * Linear interpolate the vector to another vector
- * @param v the p5.Vector to lerp to
- * @param amt the amount of interpolation; some value
- * between 0.0 (old vector) and 1.0 (new vector). 0.9
- * is very near the new vector. 0.5 is halfway in
- * between.
- * @chainable
- */
- lerp(v: p5.Vector, amt: number): p5.Vector;
-
- /**
- * Return a representation of this vector as a float
- * array. This is only for temporary use. If used in
- * any other fashion, the contents should be copied
- * by using the p5.Vector.copy() method to copy into
- * your own array.
- * @return an Array with the 3 values
- */
- array(): number[];
-
- /**
- * Equality check against a p5.Vector
- * @param [x] the x component of the vector
- * @param [y] the y component of the vector
- * @param [z] the z component of the vector
- * @return whether the vectors are equals
- */
- equals(x?: number, y?: number, z?: number): boolean;
-
- /**
- * Equality check against a p5.Vector
- * @param value the vector to compare
- */
- equals(value: p5.Vector | any[]): boolean;
-
- /**
- * The x component of the vector
- */
- x: number;
-
- /**
- * The y component of the vector
- */
- y: number;
-
- /**
- * The z component of the vector
- */
- z: number;
- }
- declare class Font {
- /**
- * Returns a tight bounding box for the given text
- * string using this font (currently only supports
- * single lines)
- * @param line a line of text
- * @param x x-position
- * @param y y-position
- * @param [fontSize] font size to use (optional)
- * Default is 12.
- * @param [options] opentype options (optional)
- * opentype fonts contains alignment and baseline
- * options. Default is 'LEFT' and 'alphabetic'
- * @return a rectangle object with properties: x, y,
- * w, h
- */
- textBounds(line: string, x: number, y: number, fontSize?: number, options?: object): object;
-
- /**
- * Computes an array of points following the path for
- * specified text
- * @param txt a line of text
- * @param x x-position
- * @param y y-position
- * @param fontSize font size to use (optional)
- * @param [options] an (optional) object that can
- * contain:
- *
- *
- * sampleFactor - the ratio of path-length to number
- * of samples (default=.1); higher values yield more
- * points and are therefore more precise
- *
- *
- * simplifyThreshold - if set to a non-zero value,
- * collinear points will be be removed from the
- * polygon; the value represents the threshold angle
- * to use when determining whether two edges are
- * collinear
- * @return an array of points, each with x, y, alpha
- * (the path angle)
- */
- textToPoints(txt: string, x: number, y: number, fontSize: number, options?: object): any[];
-
- /**
- * Underlying opentype font implementation
- */
- font: any;
- }
- declare class Camera {
- /**
- * Sets a perspective projection for a p5.Camera
- * object and sets parameters for that projection
- * according to perspective() syntax.
- */
- perspective(): void;
-
- /**
- * Sets an orthographic projection for a p5.Camera
- * object and sets parameters for that projection
- * according to ortho() syntax.
- */
- ortho(): void;
-
- /**
- * Panning rotates the camera view to the left and
- * right.
- * @param angle amount to rotate camera in current
- * angleMode units. Greater than 0 values rotate
- * counterclockwise (to the left).
- */
- pan(angle: number): void;
-
- /**
- * Tilting rotates the camera view up and down.
- * @param angle amount to rotate camera in current
- * angleMode units. Greater than 0 values rotate
- * counterclockwise (to the left).
- */
- tilt(angle: number): void;
-
- /**
- * Reorients the camera to look at a position in
- * world space.
- * @param x x position of a point in world space
- * @param y y position of a point in world space
- * @param z z position of a point in world space
- */
- lookAt(x: number, y: number, z: number): void;
-
- /**
- * Sets a camera's position and orientation. This is
- * equivalent to calling camera() on a p5.Camera
- * object.
- */
- camera(): void;
-
- /**
- * Move camera along its local axes while maintaining
- * current camera orientation.
- * @param x amount to move along camera's left-right
- * axis
- * @param y amount to move along camera's up-down
- * axis
- * @param z amount to move along camera's
- * forward-backward axis
- */
- move(x: number, y: number, z: number): void;
-
- /**
- * Set camera position in world-space while
- * maintaining current camera orientation.
- * @param x x position of a point in world space
- * @param y y position of a point in world space
- * @param z z position of a point in world space
- */
- setPosition(x: number, y: number, z: number): void;
- }
- declare class Geometry {
- /**
- declare * p5 p5.Geometry class
- *
- * @param [detailX] number of vertices on horizontal
- * surface
- * @param [detailY] number of vertices on horizontal
- * surface
- * @param [callback] to call upon object
- * instantiation.
- */
- constructor(detailX?: number, detailY?: number, callback?: (...args: any[]) => any);
- computeFaces(): p5.Geometry;
-
- /**
- * computes smooth normals per vertex as an average
- * of each face.
- * @chainable
- */
- computeNormals(): p5.Geometry;
-
- /**
- * Averages the vertex normals. Used in curved
- * surfaces
- * @chainable
- */
- averageNormals(): p5.Geometry;
-
- /**
- * Averages pole normals. Used in spherical
- * primitives
- * @chainable
- */
- averagePoleNormals(): p5.Geometry;
-
- /**
- * Modifies all vertices to be centered within the
- * range -100 to 100.
- * @chainable
- */
- normalize(): p5.Geometry;
- }
- declare class Shader {
- /**
- * Wrapper around gl.uniform s. As we store
- * uniform info in the shader we can use that to do
- * type checking on the supplied data and call the
- * appropriate .
- * @param uniformName the name of the uniform in the
- * shader program
- * @param data the data to be associated with that
- * uniform; type varies (could be a single numerical
- * value, array, matrix, or texture / sampler
- * reference)
- * @chainable
- */
- setUniform(uniformName: string, data: object | number | boolean | number[]):p5.Shader;
- }
-
- }
-
- /**
- * Set attributes for the WebGL Drawing context. This
- * is a way of adjusting how the WebGL renderer works
- * to fine-tune the display and performance. Note
- * that this will reinitialize the drawing context if
- * called after the WebGL canvas is made.
- *
- *
- * If an object is passed as the parameter, all
- * attributes not declared in the object will be set
- * to defaults.
- *
- *
- * The available attributes are:
- *
- * alpha - indicates if the canvas contains an alpha
- * buffer default is true
- *
- *
- * depth - indicates whether the drawing buffer has a
- * depth buffer of at least 16 bits - default is true
- *
- *
- * stencil - indicates whether the drawing buffer has
- * a stencil buffer of at least 8 bits
- *
- *
- * antialias - indicates whether or not to perform
- * anti-aliasing default is false
- *
- *
- * premultipliedAlpha - indicates that the page
- * compositor will assume the drawing buffer contains
- * p5.Colors with pre-multiplied alpha default is false
- *
- *
- * preserveDrawingBuffer - if true the buffers will
- * not be cleared and and will preserve their values
- * until cleared or overwritten by author (note that
- * p5 clears automatically on draw loop) default is
- * true
- *
- *
- * perPixelLighting - if true, per-pixel lighting
- * will be used in the lighting shader. default is
- * false
- * @param key Name of attribute
- * @param value New value of named attribute
- */
- function setAttributes(key: string, value: boolean): void;
-
- /**
- * Set attributes for the WebGL Drawing context. This
- * is a way of adjusting how the WebGL renderer works
- * to fine-tune the display and performance. Note
- * that this will reinitialize the drawing context if
- * called after the WebGL canvas is made.
- *
- *
- * If an object is passed as the parameter, all
- * attributes not declared in the object will be set
- * to defaults.
- *
- *
- * The available attributes are:
- *
- * alpha - indicates if the canvas contains an alpha
- * buffer default is true
- *
- *
- * depth - indicates whether the drawing buffer has a
- * depth buffer of at least 16 bits - default is true
- *
- *
- * stencil - indicates whether the drawing buffer has
- * a stencil buffer of at least 8 bits
- *
- *
- * antialias - indicates whether or not to perform
- * anti-aliasing default is false
- *
- *
- * premultipliedAlpha - indicates that the page
- * compositor will assume the drawing buffer contains
- * p5.Colors with pre-multiplied alpha default is false
- *
- *
- * preserveDrawingBuffer - if true the buffers will
- * not be cleared and and will preserve their values
- * until cleared or overwritten by author (note that
- * p5 clears automatically on draw loop) default is
- * true
- *
- *
- * perPixelLighting - if true, per-pixel lighting
- * will be used in the lighting shader. default is
- * false
- * @param obj object with key-value pairs
- */
- function setAttributes(obj: object): void;
-
-
- /**
- * Sets the camera position for a 3D sketch.
- * Parameters for this function define the position
- * for the camera, the center of the sketch (where
- * the camera is pointing), and an up direction (the
- * orientation of the camera). When called with no
- * arguments, this function creates a default camera
- * equivalent to camera(0, 0, (height/2.0) /
- * tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);
- * @param [x] camera position value on x axis
- * @param [y] camera position value on y axis
- * @param [z] camera position value on z axis
- * @param [centerX] x coordinate representing center
- * of the sketch
- * @param [centerY] y coordinate representing center
- * of the sketch
- * @param [centerZ] z coordinate representing center
- * of the sketch
- * @param [upX] x component of direction 'up' from
- * camera
- * @param [upY] y component of direction 'up' from
- * camera
- * @param [upZ] z component of direction 'up' from
- * camera
- * @chainable
- */
- function camera(
- x?: number,
- y?: number,
- z?: number,
- centerX?: number,
- centerY?: number,
- centerZ?: number,
- upX?: number,
- upY?: number,
- upZ?: number
- ): p5;
-
- /**
- * Sets a perspective projection for the camera in a
- * 3D sketch. This projection represents depth
- * through foreshortening: objects that are close to
- * the camera appear their actual size while those
- * that are further away from the camera appear
- * smaller. The parameters to this function define
- * the viewing frustum (the truncated pyramid within
- * which objects are seen by the camera) through
- * vertical field of view, aspect ratio (usually
- * width/height), and near and far clipping planes.
- * When called with no arguments, the defaults
- * provided are equivalent to perspective(PI/3.0,
- * width/height, eyeZ/10.0, eyeZ10.0), where eyeZ is
- * equal to ((height/2.0) / tan(PI60.0/360.0));
- * @param [fovy] camera frustum vertical field of
- * view, from bottom to top of view, in angleMode
- * units
- * @param [aspect] camera frustum aspect ratio
- * @param [near] frustum near plane length
- * @param [far] frustum far plane length
- * @chainable
- */
- function perspective(fovy?: number, aspect?: number, near?: number, far?: number): p5;
-
- /**
- * Sets an orthographic projection for the camera in
- * a 3D sketch and defines a box-shaped viewing
- * frustum within which objects are seen. In this
- * projection, all objects with the same dimension
- * appear the same size, regardless of whether they
- * are near or far from the camera. The parameters to
- * this function specify the viewing frustum where
- * left and right are the minimum and maximum x
- * values, top and bottom are the minimum and maximum
- * y values, and near and far are the minimum and
- * maximum z values. If no parameters are given, the
- * default is used: ortho(-width/2, width/2,
- * -height/2, height/2).
- * @param [left] camera frustum left plane
- * @param [right] camera frustum right plane
- * @param [bottom] camera frustum bottom plane
- * @param [top] camera frustum top plane
- * @param [near] camera frustum near plane
- * @param [far] camera frustum far plane
- * @chainable
- */
- function ortho(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): p5;
-
- /**
- * Creates a new p5.Camera object and tells the
- * renderer to use that camera. Returns the p5.Camera
- * object.
- * @return The newly created camera object.
- */
- function createCamera(): p5.Camera;
-
- /**
- * Sets rendererGL's current camera to a p5.Camera
- * object. Allows switching between multiple cameras.
- * @param cam p5.Camera object
- */
- function setCamera(cam: p5.Camera): void;
-
-
- /**
- * Allows movement around a 3D sketch using a mouse
- * or trackpad. Left-clicking and dragging will
- * rotate the camera position about the center of the
- * sketch, right-clicking and dragging will pan the
- * camera position without rotation, and using the
- * mouse wheel (scrolling) will move the camera
- * closer or further from the center of the sketch.
- * This function can be called with parameters
- * dictating sensitivity to mouse movement along the
- * X and Y axes. Calling this function without
- * parameters is equivalent to calling
- * orbitControl(1,1). To reverse direction of
- * movement in either axis, enter a negative number
- * for sensitivity.
- * @param [sensitivityX] sensitivity to mouse
- * movement along X axis
- * @param [sensitivityY] sensitivity to mouse
- * movement along Y axis
- * @chainable
- */
- function orbitControl(sensitivityX?: number, sensitivityY?: number): p5;
-
- /**
- * debugMode() helps visualize 3D space by adding a
- * grid to indicate where the ‘ground’ is in a sketch
- * and an axes icon which indicates the +X, +Y, and
- * +Z directions. This function can be called without
- * parameters to create a default grid and axes icon,
- * or it can be called according to the examples
- * above to customize the size and position of the
- * grid and/or axes icon. The grid is drawn using the
- * most recently set stroke p5.Color and weight. To
- * specify these parameters, add a call to stroke()
- * and strokeWeight() just before the end of the
- * draw() loop. By default, the grid will run through
- * the origin (0,0,0) of the sketch along the XZ
- * plane and the axes icon will be offset from the
- * origin. Both the grid and axes icon will be sized
- * according to the current canvas size. Note that
- * because the grid runs parallel to the default
- * camera view, it is often helpful to use debugMode
- * along with orbitControl to allow full view of the
- * grid.
- */
- function debugMode(): void;
-
- /**
- * debugMode() helps visualize 3D space by adding a
- * grid to indicate where the ‘ground’ is in a sketch
- * and an axes icon which indicates the +X, +Y, and
- * +Z directions. This function can be called without
- * parameters to create a default grid and axes icon,
- * or it can be called according to the examples
- * above to customize the size and position of the
- * grid and/or axes icon. The grid is drawn using the
- * most recently set stroke p5.Color and weight. To
- * specify these parameters, add a call to stroke()
- * and strokeWeight() just before the end of the
- * draw() loop. By default, the grid will run through
- * the origin (0,0,0) of the sketch along the XZ
- * plane and the axes icon will be offset from the
- * origin. Both the grid and axes icon will be sized
- * according to the current canvas size. Note that
- * because the grid runs parallel to the default
- * camera view, it is often helpful to use debugMode
- * along with orbitControl to allow full view of the
- * grid.
- * @param mode either GRID or AXES
- */
- function debugMode(mode: DEBUG_MODE): void;
-
- /**
- * debugMode() helps visualize 3D space by adding a
- * grid to indicate where the ‘ground’ is in a sketch
- * and an axes icon which indicates the +X, +Y, and
- * +Z directions. This function can be called without
- * parameters to create a default grid and axes icon,
- * or it can be called according to the examples
- * above to customize the size and position of the
- * grid and/or axes icon. The grid is drawn using the
- * most recently set stroke p5.Color and weight. To
- * specify these parameters, add a call to stroke()
- * and strokeWeight() just before the end of the
- * draw() loop. By default, the grid will run through
- * the origin (0,0,0) of the sketch along the XZ
- * plane and the axes icon will be offset from the
- * origin. Both the grid and axes icon will be sized
- * according to the current canvas size. Note that
- * because the grid runs parallel to the default
- * camera view, it is often helpful to use debugMode
- * along with orbitControl to allow full view of the
- * grid.
- * @param mode either GRID or AXES
- * @param [gridSize] size of one side of the grid
- * @param [gridDivisions] number of divisions in the
- * grid
- * @param [xOff] X axis offset from origin (0,0,0)
- * @param [yOff] Y axis offset from origin (0,0,0)
- * @param [zOff] Z axis offset from origin (0,0,0)
- */
- function debugMode(
- mode: UNKNOWN_P5_CONSTANT,
- gridSize?: number,
- gridDivisions?: number,
- xOff?: number,
- yOff?: number,
- zOff?: number
- ): void;
-
- /**
- * debugMode() helps visualize 3D space by adding a
- * grid to indicate where the ‘ground’ is in a sketch
- * and an axes icon which indicates the +X, +Y, and
- * +Z directions. This function can be called without
- * parameters to create a default grid and axes icon,
- * or it can be called according to the examples
- * above to customize the size and position of the
- * grid and/or axes icon. The grid is drawn using the
- * most recently set stroke p5.Color and weight. To
- * specify these parameters, add a call to stroke()
- * and strokeWeight() just before the end of the
- * draw() loop. By default, the grid will run through
- * the origin (0,0,0) of the sketch along the XZ
- * plane and the axes icon will be offset from the
- * origin. Both the grid and axes icon will be sized
- * according to the current canvas size. Note that
- * because the grid runs parallel to the default
- * camera view, it is often helpful to use debugMode
- * along with orbitControl to allow full view of the
- * grid.
- * @param mode either GRID or AXES
- * @param [axesSize] size of axes icon
- * @param [xOff] X axis offset from origin (0,0,0)
- * @param [yOff] Y axis offset from origin (0,0,0)
- * @param [zOff] Z axis offset from origin (0,0,0)
- */
- function debugMode(mode: UNKNOWN_P5_CONSTANT, axesSize?: number, xOff?: number, yOff?: number, zOff?: number): void;
-
- /**
- * debugMode() helps visualize 3D space by adding a
- * grid to indicate where the ‘ground’ is in a sketch
- * and an axes icon which indicates the +X, +Y, and
- * +Z directions. This function can be called without
- * parameters to create a default grid and axes icon,
- * or it can be called according to the examples
- * above to customize the size and position of the
- * grid and/or axes icon. The grid is drawn using the
- * most recently set stroke p5.Color and weight. To
- * specify these parameters, add a call to stroke()
- * and strokeWeight() just before the end of the
- * draw() loop. By default, the grid will run through
- * the origin (0,0,0) of the sketch along the XZ
- * plane and the axes icon will be offset from the
- * origin. Both the grid and axes icon will be sized
- * according to the current canvas size. Note that
- * because the grid runs parallel to the default
- * camera view, it is often helpful to use debugMode
- * along with orbitControl to allow full view of the
- * grid.
- * @param [gridSize] size of one side of the grid
- * @param [gridDivisions] number of divisions in the
- * grid
- * @param [axesSize] size of axes icon
- */
- function debugMode(
- gridSize?: number,
- gridDivisions?: number,
- gridXOff?: number,
- gridYOff?: number,
- gridZOff?: number,
- axesSize?: number,
- axesXOff?: number,
- axesYOff?: number,
- axesZOff?: number
- ): void;
-
- /**
- * Turns off debugMode() in a 3D sketch.
- */
- function noDebugMode(): void;
-
- /**
- * Creates an ambient light with a p5.Color
- * @param v1 red or hue value relative to the current
- * p5.Color range
- * @param v2 green or saturation value relative to
- * the current p5.Color range
- * @param v3 blue or brightness value relative to the
- * current p5.Color range
- * @param [alpha] the alpha value
- * @chainable
- */
- function ambientLight(v1: number, v2: number, v3: number, alpha?: number): p5;
-
- /**
- * Creates an ambient light with a p5.Color
- * @param value a p5.Color string
- * @chainable
- */
- function ambientLight(value: string): p5;
-
- /**
- * Creates an ambient light with a p5.Color
- * @param gray a gray value
- * @param [alpha] the alpha value
- * @chainable
- */
- function ambientLight(gray: number, alpha?: number): p5;
-
- /**
- * Creates an ambient light with a p5.Color
- * @param values an array containing the
- * red,green,blue & and alpha components of the p5.Color
- * @chainable
- */
- function ambientLight(values: number[]): p5;
-
- /**
- * Creates an ambient light with a p5.Color
- * @param p5.Color the ambient light p5.Color
- * @chainable
- */
- function ambientLight(color: p5.Color): p5;
-
- /**
- * Creates a directional light with a p5.Color and a
- * direction
- * @param v1 red or hue value (depending on the
- * current p5.Color mode),
- * @param v2 green or saturation value
- * @param v3 blue or brightness value
- * @param position the direction of the light
- * @chainable
- */
- function directionalLight(v1: number, v2: number, v3: number, position: p5.Vector): p5;
-
- /**
- * Creates a directional light with a p5.Color and a
- * direction
- * @param p5.Color p5.Color Array, CSS p5.Color string, or
- * p5.p5.Color value
- * @param x x axis direction
- * @param y y axis direction
- * @param z z axis direction
- * @chainable
- */
- function directionalLight(color: number[] | string | p5.Color, x: number, y: number, z: number): p5;
-
- /**
- * Creates a directional light with a p5.Color and a
- * direction
- * @param p5.Color p5.Color Array, CSS p5.Color string, or
- * p5.p5.Color value
- * @param position the direction of the light
- * @chainable
- */
- function directionalLight(color: number[] | string | p5.Color, position: p5.Vector): p5;
-
- /**
- * Creates a directional light with a p5.Color and a
- * direction
- * @param v1 red or hue value (depending on the
- * current p5.Color mode),
- * @param v2 green or saturation value
- * @param v3 blue or brightness value
- * @param x x axis direction
- * @param y y axis direction
- * @param z z axis direction
- * @chainable
- */
- function directionalLight(v1: number, v2: number, v3: number, x: number, y: number, z: number): p5;
-
- /**
- * Creates a point light with a p5.Color and a light
- * position
- * @param v1 red or hue value (depending on the
- * current p5.Color mode),
- * @param v2 green or saturation value
- * @param v3 blue or brightness value
- * @param x x axis position
- * @param y y axis position
- * @param z z axis position
- * @chainable
- */
- function pointLight(v1: number, v2: number, v3: number, x: number, y: number, z: number): p5;
-
- /**
- * Creates a point light with a p5.Color and a light
- * position
- * @param v1 red or hue value (depending on the
- * current p5.Color mode),
- * @param v2 green or saturation value
- * @param v3 blue or brightness value
- * @param position the position of the light
- * @chainable
- */
- function pointLight(v1: number, v2: number, v3: number, position: p5.Vector): p5;
-
- /**
- * Creates a point light with a p5.Color and a light
- * position
- * @param p5.Color p5.Color Array, CSS p5.Color string, or
- * p5.p5.Color value
- * @param x x axis position
- * @param y y axis position
- * @param z z axis position
- * @chainable
- */
- function pointLight(color: number[] | string | p5.Color, x: number, y: number, z: number): p5;
-
- /**
- * Creates a point light with a p5.Color and a light
- * position
- * @param p5.Color p5.Color Array, CSS p5.Color string, or
- * p5.p5.Color value
- * @param position the position of the light
- * @chainable
- */
- function pointLight(color: number[] | string | p5.Color, position: p5.Vector): p5;
-
- /**
- * Sets the default ambient and directional light.
- * The defaults are ambientLight(128, 128, 128) and
- * directionalLight(128, 128, 128, 0, 0, -1). Lights
- * need to be included in the draw() to remain
- * persistent in a looping program. Placing them in
- * the setup() of a looping program will cause them
- * to only have an effect the first time through the
- * loop.
- * @chainable
- */
- function lights(): p5;
-
- /**
- * Sets the falloff rates for point lights. It
- * affects only the p5.Elements which are created after
- * it in the code. The default value is
- * lightFalloff(1.0, 0.0, 0.0), and the parameters
- * are used to calculate the falloff with the
- * following equation: d = distance from light
- * position to vertex position
- *
- * falloff = 1 / (CONSTANT + d * LINEAR + ( d * d ) *
- * QUADRATIC)
- * @param constant constant value for determining
- * falloff
- * @param linear linear value for determining falloff
- * @param quadratic quadratic value for determining
- * falloff
- * @chainable
- */
- function lightFalloff(constant: number, linear: number, quadratic: number): p5;
-
- /**
- * Load a 3d model from an OBJ or STL file. One of
- * the limitations of the OBJ and STL format is that
- * it doesn't have a built-in sense of scale. This
- * means that models exported from different programs
- * might be very different sizes. If your model isn't
- * displaying, try calling loadModel() with the
- * normalized parameter set to true. This will resize
- * the model to a scale appropriate for p5. You can
- * also make additional changes to the final size of
- * your model with the scale() function.
- *
- * Also, the support for p5.Colored STL files is not
- * present. STL files with p5.Color will be rendered
- * without p5.Color properties.
- * @param path Path of the model to be loaded
- * @param normalize If true, scale the model to a
- * standardized size when loading
- * @param [successCallback] Function to be called
- * once the model is loaded. Will be passed the 3D
- * model object.
- * @param [failureCallback] called with event error
- * if the model fails to load.
- * @return the p5.Geometry object
- */
- function loadModel(
- path: string,
- normalize: boolean,
- successCallback?: (p1: p5.Geometry) => any,
- failureCallback?: (p1: Event) => any
- ): p5.Geometry;
-
- /**
- * Load a 3d model from an OBJ or STL file. One of
- * the limitations of the OBJ and STL format is that
- * it doesn't have a built-in sense of scale. This
- * means that models exported from different programs
- * might be very different sizes. If your model isn't
- * displaying, try calling loadModel() with the
- * normalized parameter set to true. This will resize
- * the model to a scale appropriate for p5. You can
- * also make additional changes to the final size of
- * your model with the scale() function.
- *
- * Also, the support for p5.Colored STL files is not
- * present. STL files with p5.Color will be rendered
- * without p5.Color properties.
- * @param path Path of the model to be loaded
- * @param [successCallback] Function to be called
- * once the model is loaded. Will be passed the 3D
- * model object.
- * @param [failureCallback] called with event error
- * if the model fails to load.
- * @return the p5.Geometry object
- */
- function loadModel(
- path: string,
- successCallback?: (p1: p5.Geometry) => any,
- failureCallback?: (p1: Event) => any
- ): p5.Geometry;
-
- /**
- * Render a 3d model to the screen.
- * @param model Loaded 3d model to be rendered
- */
- function model(model: p5.Geometry): void;
-
- /**
- * Loads a custom shader from the provided vertex and
- * fragment shader paths. The shader files are loaded
- * asynchronously in the background, so this method
- * should be used in preload(). For now, there are
- * three main types of shaders. p5 will automatically
- * supply appropriate vertices, normals, p5.Colors, and
- * lighting attributes if the parameters defined in
- * the shader match the names.
- * @param vertFilename path to file containing vertex
- * shader source code
- * @param fragFilename path to file containing
- * fragment shader source code
- * @param [callback] callback to be executed after
- * loadShader completes. On success, thep5.Shader
- * object is passed as the first argument.
- * @param [errorCallback] callback to be executed
- * when an error occurs inside loadShader. On error,
- * the error is passed as the first argument.
- * @return a shader object created from the provided
- * vertex and fragment shader files.
- */
- function loadShader(
- vertFilename: string,
- fragFilename: string,
- callback?: (...args: any[]) => any,
- errorCallback?: (...args: any[]) => any
- ):p5.Shader;
- function createShader(vertSrc: string, fragSrc: string):p5.Shader;
-
- /**
- * The shader() function lets the user provide a
- * custom shader to fill in shapes in WEBGL mode.
- * Users can create their own shaders by loading
- * vertex and fragment shaders with loadShader().
- * @param [s] the desired p5.Shader to use for
- * rendering shapes.
- * @chainable
- */
- function shader(s?:p5.Shader): p5;
-
- /**
- * This function restores the default shaders in
- * WEBGL mode. Code that runs after resetShader()
- * will not be affected by previously defined
- * shaders. Should be run after shader().
- * @chainable
- */
- function resetShader(): p5;
-
- /**
- * Normal material for geometry. You can view all
- * possible materials in this example.
- * @chainable
- */
- function normalMaterial(): p5;
-
- /**
- * Texture for geometry. You can view other possible
- * materials in this example.
- * @param tex 2-dimensional graphics to render as
- * texture
- * @chainable
- */
- function texture(tex: p5.Image |p5.Graphics): p5;
-
- /**
- * Sets the coordinate space for texture mapping. The
- * default mode is IMAGE which refers to the actual
- * coordinates of the image. NORMAL refers to a
- * normalized space of values ranging from 0 to 1.
- * This function only works in WEBGL mode. With
- * IMAGE, if an image is 100 x 200 pixels, mapping
- * the image onto the entire size of a quad would
- * require the points (0,0) (100, 0) (100,200)
- * (0,200). The same mapping in NORMAL is (0,0) (1,0)
- * (1,1) (0,1).
- * @param mode either IMAGE or NORMAL
- */
- function textureMode(mode: TEXTURE_MODE): void;
-
- /**
- * Sets the global texture wrapping mode. This
- * controls how textures behave when their uv's go
- * outside of the 0 - 1 range. There are three
- * options: CLAMP, REPEAT, and MIRROR. CLAMP causes
- * the pixels at the edge of the texture to extend to
- * the bounds REPEAT causes the texture to tile
- * repeatedly until reaching the bounds MIRROR works
- * similarly to REPEAT but it flips the texture with
- * every new tile
- *
- * REPEAT & MIRROR are only available if the texture
- * is a power of two size (128, 256, 512, 1024,
- * etc.).
- *
- * This method will affect all textures in your
- * sketch until a subsequent textureWrap call is
- * made.
- *
- * If only one argument is provided, it will be
- * applied to both the horizontal and vertical axes.
- * @param wrapX either CLAMP, REPEAT, or MIRROR
- * @param [wrapY] either CLAMP, REPEAT, or MIRROR
- */
- function textureWrap(wrapX: WRAP_X, wrapY?: WRAP_Y): void;
-
- /**
- * Ambient material for geometry with a given p5.Color.
- * You can view all possible materials in this
- * example.
- * @param v1 gray value, red or hue value (depending
- * on the current p5.Color mode),
- * @param [v2] green or saturation value
- * @param [v3] blue or brightness value
- * @param [a] opacity
- * @chainable
- */
- function ambientMaterial(v1: number, v2?: number, v3?: number, a?: number): p5;
-
- /**
- * Ambient material for geometry with a given p5.Color.
- * You can view all possible materials in this
- * example.
- * @param p5.Color p5.Color, p5.Color Array, or CSS p5.Color
- * string
- * @chainable
- */
- function ambientMaterial(color: number[] | string | p5.Color): p5;
-
- /**
- * Specular material for geometry with a given p5.Color.
- * You can view all possible materials in this
- * example.
- * @param v1 gray value, red or hue value (depending
- * on the current p5.Color mode),
- * @param [v2] green or saturation value
- * @param [v3] blue or brightness value
- * @param [a] opacity
- * @chainable
- */
- function specularMaterial(v1: number, v2?: number, v3?: number, a?: number): p5;
-
- /**
- * Specular material for geometry with a given p5.Color.
- * You can view all possible materials in this
- * example.
- * @param p5.Color p5.Color Array, or CSS p5.Color string
- * @chainable
- */
- function specularMaterial(color: number[] | string | p5.Color): p5;
-
- /**
- * Sets the amount of gloss in the surface of shapes.
- * Used in combination with specularMaterial() in
- * setting the material properties of shapes. The
- * default and minimum value is 1.
- * @param shine Degree of Shininess. Defaults to 1.
- * @chainable
- */
- function shininess(shine: number): p5;
-
-
- /**
- * Draw a plane with given a width and height
- * @param [width] width of the plane
- * @param [height] height of the plane
- * @param [detailX] Optional number of triangle
- * subdivisions in x-dimension
- * @param [detailY] Optional number of triangle
- * subdivisions in y-dimension
- * @chainable
- */
- function plane(width?: number, height?: number, detailX?: number, detailY?: number): p5;
-
- /**
- * Draw a box with given width, height and depth
- * @param [width] width of the box
- * @param [Height] height of the box
- * @param [depth] depth of the box
- * @param [detailX] Optional number of triangle
- * subdivisions in x-dimension
- * @param [detailY] Optional number of triangle
- * subdivisions in y-dimension
- * @chainable
- */
- function box(width?: number, Height?: number, depth?: number, detailX?: number, detailY?: number): p5;
-
- /**
- * Draw a sphere with given radius
- * @param [radius] radius of circle
- * @param [detailX] number of segments, the more
- * segments the smoother geometry default is 24
- * @param [detailY] number of segments, the more
- * segments the smoother geometry default is 16
- * @chainable
- */
- function sphere(radius?: number, detailX?: number, detailY?: number): p5;
-
- /**
- * Draw a cylinder with given radius and height
- * @param [radius] radius of the surface
- * @param [height] height of the cylinder
- * @param [detailX] number of segments, the more
- * segments the smoother geometry default is 24
- * @param [detailY] number of segments in
- * y-dimension, the more segments the smoother
- * geometry default is 1
- * @param [bottomCap] whether to draw the bottom of
- * the cylinder
- * @param [topCap] whether to draw the top of the
- * cylinder
- * @chainable
- */
- function cylinder(
- radius?: number,
- height?: number,
- detailX?: number,
- detailY?: number,
- bottomCap?: boolean,
- topCap?: boolean
- ): p5;
-
- /**
- * Draw a cone with given radius and height
- * @param [radius] radius of the bottom surface
- * @param [height] height of the cone
- * @param [detailX] number of segments, the more
- * segments the smoother geometry default is 24
- * @param [detailY] number of segments, the more
- * segments the smoother geometry default is 1
- * @param [cap] whether to draw the base of the cone
- * @chainable
- */
- function cone(radius?: number, height?: number, detailX?: number, detailY?: number, cap?: boolean): p5;
-
- /**
- * Draw an ellipsoid with given radius
- * @param [radiusx] x-radius of ellipsoid
- * @param [radiusy] y-radius of ellipsoid
- * @param [radiusz] z-radius of ellipsoid
- * @param [detailX] number of segments, the more
- * segments the smoother geometry default is 24.
- * Avoid detail number above 150, it may crash the
- * browser.
- * @param [detailY] number of segments, the more
- * segments the smoother geometry default is 16.
- * Avoid detail number above 150, it may crash the
- * browser.
- * @chainable
- */
- function ellipsoid(radiusx?: number, radiusy?: number, radiusz?: number, detailX?: number, detailY?: number): p5;
-
- /**
- * Draw a torus with given radius and tube radius
- * @param [radius] radius of the whole ring
- * @param [tubeRadius] radius of the tube
- * @param [detailX] number of segments in
- * x-dimension, the more segments the smoother
- * geometry default is 24
- * @param [detailY] number of segments in
- * y-dimension, the more segments the smoother
- * geometry default is 16
- * @chainable
- */
- function torus(radius?: number, tubeRadius?: number, detailX?: number, detailY?: number): p5;
-
-
- /**
- * p5.js communicates with the clock on your
- * computer. The day() function returns the current
- * day as a value from 1 - 31.
- * @return the current day
- */
- function day(): number;
-
- /**
- * p5.js communicates with the clock on your
- * computer. The hour() function returns the current
- * hour as a value from 0 - 23.
- * @return the current hour
- */
- function hour(): number;
-
- /**
- * p5.js communicates with the clock on your
- * computer. The minute() function returns the
- * current minute as a value from 0 - 59.
- * @return the current minute
- */
- function minute(): number;
-
- /**
- * Returns the number of milliseconds (thousandths of
- * a second) since starting the program. This
- * information is often used for timing events and
- * animation sequences.
- * @return the number of milliseconds since starting
- * the program
- */
- function millis(): number;
-
- /**
- * p5.js communicates with the clock on your
- * computer. The month() function returns the current
- * month as a value from 1 - 12.
- * @return the current month
- */
- function month(): number;
-
- /**
- * p5.js communicates with the clock on your
- * computer. The second() function returns the
- * current second as a value from 0 - 59.
- * @return the current second
- */
- function second(): number;
-
- /**
- * p5.js communicates with the clock on your
- * computer. The year() function returns the current
- * year as an integer (2014, 2015, 2016, etc).
- * @return the current year
- */
- function year(): number;
-
-
- /**
- * Combines an array of Strings into one String, each
- * separated by the character(s) used for the
- * separator parameter. To join arrays of ints or
- * floats, it's necessary to first convert them to
- * Strings using nf() or nfs().
- * @param list array of Strings to be joined
- * @param separator String to be placed between each
- * item
- * @return joined String
- */
- function join(list: any[], separator: string): string;
-
- /**
- * This function is used to apply a regular
- * expression to a piece of text, and return matching
- * groups (p5.Elements found inside parentheses) as a
- * String array. If there are no matches, a null
- * value will be returned. If no groups are specified
- * in the regular expression, but the sequence
- * matches, an array of length 1 (with the matched
- * text as the first p5.Element of the array) will be
- * returned. To use the function, first check to see
- * if the result is null. If the result is null, then
- * the sequence did not match at all. If the sequence
- * did match, an array is returned.
- *
- *
- * If there are groups (specified by sets of
- * parentheses) in the regular expression, then the
- * contents of each will be returned in the array.
- * p5.Element [0] of a regular expression match returns
- * the entire matching string, and the match groups
- * start at p5.Element [1] (the first group is [1], the
- * second [2], and so on).
- * @param str the String to be searched
- * @param regexp the regexp to be used for matching
- * @return Array of Strings found
- */
- function match(str: string, regexp: string): string[];
-
- /**
- * This function is used to apply a regular
- * expression to a piece of text, and return a list
- * of matching groups (p5.Elements found inside
- * parentheses) as a two-dimensional String array. If
- * there are no matches, a null value will be
- * returned. If no groups are specified in the
- * regular expression, but the sequence matches, a
- * two dimensional array is still returned, but the
- * second dimension is only of length one. To use
- * the function, first check to see if the result is
- * null. If the result is null, then the sequence did
- * not match at all. If the sequence did match, a 2D
- * array is returned.
- *
- *
- * If there are groups (specified by sets of
- * parentheses) in the regular expression, then the
- * contents of each will be returned in the array.
- * Assuming a loop with counter variable i, p5.Element
- * [i][0] of a regular expression match returns the
- * entire matching string, and the match groups start
- * at p5.Element [i][1] (the first group is [i][1], the
- * second [i][2], and so on).
- * @param str the String to be searched
- * @param regexp the regexp to be used for matching
- * @return 2d Array of Strings found
- */
- function matchAll(str: string, regexp: string): string[];
-
- /**
- * Utility function for formatting numbers into
- * strings. There are two versions: one for
- * formatting floats, and one for formatting ints.
- * The values for the digits, left, and right
- * parameters should always be positive integers.
- * (NOTE): Be cautious when using left and right
- * parameters as it prepends numbers of 0's if the
- * parameter if greater than the current length of
- * the number. For example if number is 123.2 and
- * left parameter passed is 4 which is greater than
- * length of 123 (integer part) i.e 3 than result
- * will be 0123.2. Same case for right parameter i.e.
- * if right is 3 than the result will be 123.200.
- * @param num the Number to format
- * @param [left] number of digits to the left of the
- * decimal point
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted String
- */
- function nf(num: number | string, left?: number | string, right?: number | string): string;
-
- /**
- * Utility function for formatting numbers into
- * strings. There are two versions: one for
- * formatting floats, and one for formatting ints.
- * The values for the digits, left, and right
- * parameters should always be positive integers.
- * (NOTE): Be cautious when using left and right
- * parameters as it prepends numbers of 0's if the
- * parameter if greater than the current length of
- * the number. For example if number is 123.2 and
- * left parameter passed is 4 which is greater than
- * length of 123 (integer part) i.e 3 than result
- * will be 0123.2. Same case for right parameter i.e.
- * if right is 3 than the result will be 123.200.
- * @param nums the Numbers to format
- * @param [left] number of digits to the left of the
- * decimal point
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted Strings
- */
- function nf(nums: any[], left?: number | string, right?: number | string): string[];
-
- /**
- * Utility function for formatting numbers into
- * strings and placing appropriate commas to mark
- * units of 1000. There are two versions: one for
- * formatting ints, and one for formatting an array
- * of ints. The value for the right parameter should
- * always be a positive integer.
- * @param num the Number to format
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted String
- */
- function nfc(num: number | string, right?: number | string): string;
-
- /**
- * Utility function for formatting numbers into
- * strings and placing appropriate commas to mark
- * units of 1000. There are two versions: one for
- * formatting ints, and one for formatting an array
- * of ints. The value for the right parameter should
- * always be a positive integer.
- * @param nums the Numbers to format
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted Strings
- */
- function nfc(nums: any[], right?: number | string): string[];
-
- /**
- * Utility function for formatting numbers into
- * strings. Similar to nf() but puts a "+" in front
- * of positive numbers and a "-" in front of negative
- * numbers. There are two versions: one for
- * formatting floats, and one for formatting ints.
- * The values for left, and right parameters should
- * always be positive integers.
- * @param num the Number to format
- * @param [left] number of digits to the left of the
- * decimal point
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted String
- */
- function nfp(num: number, left?: number, right?: number): string;
-
- /**
- * Utility function for formatting numbers into
- * strings. Similar to nf() but puts a "+" in front
- * of positive numbers and a "-" in front of negative
- * numbers. There are two versions: one for
- * formatting floats, and one for formatting ints.
- * The values for left, and right parameters should
- * always be positive integers.
- * @param nums the Numbers to format
- * @param [left] number of digits to the left of the
- * decimal point
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted Strings
- */
- function nfp(nums: number[], left?: number, right?: number): string[];
-
- /**
- * Utility function for formatting numbers into
- * strings. Similar to nf() but puts an additional
- * "_" (space) in front of positive numbers just in
- * case to align it with negative numbers which
- * includes "-" (minus) sign. The main usecase of
- * nfs() can be seen when one wants to align the
- * digits (place values) of a non-negative number
- * with some negative number (See the example to get
- * a clear picture). There are two versions: one for
- * formatting float, and one for formatting int. The
- * values for the digits, left, and right parameters
- * should always be positive integers. (IMP): The
- * result on the canvas basically the expected
- * alignment can vary based on the typeface you are
- * using. (NOTE): Be cautious when using left and
- * right parameters as it prepends numbers of 0's if
- * the parameter if greater than the current length
- * of the number. For example if number is 123.2 and
- * left parameter passed is 4 which is greater than
- * length of 123 (integer part) i.e 3 than result
- * will be 0123.2. Same case for right parameter i.e.
- * if right is 3 than the result will be 123.200.
- * @param num the Number to format
- * @param [left] number of digits to the left of the
- * decimal point
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted String
- */
- function nfs(num: number, left?: number, right?: number): string;
-
- /**
- * Utility function for formatting numbers into
- * strings. Similar to nf() but puts an additional
- * "_" (space) in front of positive numbers just in
- * case to align it with negative numbers which
- * includes "-" (minus) sign. The main usecase of
- * nfs() can be seen when one wants to align the
- * digits (place values) of a non-negative number
- * with some negative number (See the example to get
- * a clear picture). There are two versions: one for
- * formatting float, and one for formatting int. The
- * values for the digits, left, and right parameters
- * should always be positive integers. (IMP): The
- * result on the canvas basically the expected
- * alignment can vary based on the typeface you are
- * using. (NOTE): Be cautious when using left and
- * right parameters as it prepends numbers of 0's if
- * the parameter if greater than the current length
- * of the number. For example if number is 123.2 and
- * left parameter passed is 4 which is greater than
- * length of 123 (integer part) i.e 3 than result
- * will be 0123.2. Same case for right parameter i.e.
- * if right is 3 than the result will be 123.200.
- * @param nums the Numbers to format
- * @param [left] number of digits to the left of the
- * decimal point
- * @param [right] number of digits to the right of
- * the decimal point
- * @return formatted Strings
- */
- function nfs(nums: any[], left?: number, right?: number): string[];
-
- /**
- * The split() function maps to String.split(), it
- * breaks a String into pieces using a character or
- * string as the delimiter. The delim parameter
- * specifies the character or characters that mark
- * the boundaries between each piece. A String[]
- * array is returned that contains each of the
- * pieces. The splitTokens() function works in a
- * similar fashion, except that it splits using a
- * range of characters instead of a specific
- * character or sequence.
- * @param value the String to be split
- * @param delim the String used to separate the data
- * @return Array of Strings
- */
- function split(value: string, delim: string): string[];
-
- /**
- * The splitTokens() function splits a String at one
- * or many character delimiters or "tokens." The
- * delim parameter specifies the character or
- * characters to be used as a boundary. If no delim
- * characters are specified, any whitespace character
- * is used to split. Whitespace characters include
- * tab (\t), line feed (\n), carriage return (\r),
- * form feed (\f), and space.
- * @param value the String to be split
- * @param [delim] list of individual Strings that
- * will be used as separators
- * @return Array of Strings
- */
- function splitTokens(value: string, delim?: string): string[];
-
- /**
- * Removes whitespace characters from the beginning
- * and end of a String. In addition to standard
- * whitespace characters such as space, carriage
- * return, and tab, this function also removes the
- * Unicode "nbsp" character.
- * @param str a String to be trimmed
- * @return a trimmed String
- */
- function trim(str: string): string;
-
- /**
- * Removes whitespace characters from the beginning
- * and end of a String. In addition to standard
- * whitespace characters such as space, carriage
- * return, and tab, this function also removes the
- * Unicode "nbsp" character.
- * @param strs an Array of Strings to be trimmed
- * @return an Array of trimmed Strings
- */
- function trim(strs: any[]): string[];
-
-
- /**
- * Converts a string to its floating point
- * representation. The contents of a string must
- * resemble a number, or NaN (not a number) will be
- * returned. For example, float("1234.56") evaluates
- * to 1234.56, but float("giraffe") will return NaN.
- * When an array of values is passed in, then an
- * array of floats of the same length is returned.
- * @param str float string to parse
- * @return floating point representation of string
- */
- function float(str: string): number;
-
- /**
- * Converts a boolean, string, or float to its
- * integer representation. When an array of values is
- * passed in, then an int array of the same length is
- * returned.
- * @param n value to parse
- * @param [radix] the radix to convert to (default:
- * 10)
- * @return integer representation of value
- */
- function int(n: string | boolean | number, radix?: number): number;
-
- /**
- * Converts a boolean, string, or float to its
- * integer representation. When an array of values is
- * passed in, then an int array of the same length is
- * returned.
- * @param ns values to parse
- * @return integer representation of values
- */
- function int(ns: any[]): number[];
-
- /**
- * Converts a boolean, string or number to its string
- * representation. When an array of values is passed
- * in, then an array of strings of the same length is
- * returned.
- * @param n value to parse
- * @return string representation of value
- */
- function str(n: string | boolean | number | any[]): string;
-
- /**
- * Converts a number or string to its boolean
- * representation. For a number, any non-zero value
- * (positive or negative) evaluates to true, while
- * zero evaluates to false. For a string, the value
- * "true" evaluates to true, while any other value
- * evaluates to false. When an array of number or
- * string values is passed in, then a array of
- * booleans of the same length is returned.
- * @param n value to parse
- * @return boolean representation of value
- */
- function boolean(n: string | boolean | number | any[]): boolean;
-
- /**
- * Converts a number, string representation of a
- * number, or boolean to its byte representation. A
- * byte can be only a whole number between -128 and
- * 127, so when a value outside of this range is
- * converted, it wraps around to the corresponding
- * byte representation. When an array of number,
- * string or boolean values is passed in, then an
- * array of bytes the same length is returned.
- * @param n value to parse
- * @return byte representation of value
- */
- function byte(n: string | boolean | number): number;
-
- /**
- * Converts a number, string representation of a
- * number, or boolean to its byte representation. A
- * byte can be only a whole number between -128 and
- * 127, so when a value outside of this range is
- * converted, it wraps around to the corresponding
- * byte representation. When an array of number,
- * string or boolean values is passed in, then an
- * array of bytes the same length is returned.
- * @param ns values to parse
- * @return array of byte representation of values
- */
- function byte(ns: any[]): number[];
-
- /**
- * Converts a number or string to its corresponding
- * single-character string representation. If a
- * string parameter is provided, it is first parsed
- * as an integer and then translated into a
- * single-character string. When an array of number
- * or string values is passed in, then an array of
- * single-character strings of the same length is
- * returned.
- * @param n value to parse
- * @return string representation of value
- */
- function char(n: string | number): string;
-
- /**
- * Converts a number or string to its corresponding
- * single-character string representation. If a
- * string parameter is provided, it is first parsed
- * as an integer and then translated into a
- * single-character string. When an array of number
- * or string values is passed in, then an array of
- * single-character strings of the same length is
- * returned.
- * @param ns values to parse
- * @return array of string representation of values
- */
- function char(ns: any[]): string[];
-
- /**
- * Converts a single-character string to its
- * corresponding integer representation. When an
- * array of single-character string values is passed
- * in, then an array of integers of the same length
- * is returned.
- * @param n value to parse
- * @return integer representation of value
- */
- function unchar(n: string): number;
-
- /**
- * Converts a single-character string to its
- * corresponding integer representation. When an
- * array of single-character string values is passed
- * in, then an array of integers of the same length
- * is returned.
- * @param ns values to parse
- * @return integer representation of values
- */
- function unchar(ns: any[]): number[];
-
- /**
- * Converts a number to a string in its equivalent
- * hexadecimal notation. If a second parameter is
- * passed, it is used to set the number of characters
- * to generate in the hexadecimal notation. When an
- * array is passed in, an array of strings in
- * hexadecimal notation of the same length is
- * returned.
- * @param n value to parse
- * @return hexadecimal string representation of value
- */
- function hex(n: number, digits?: number): string;
-
- /**
- * Converts a number to a string in its equivalent
- * hexadecimal notation. If a second parameter is
- * passed, it is used to set the number of characters
- * to generate in the hexadecimal notation. When an
- * array is passed in, an array of strings in
- * hexadecimal notation of the same length is
- * returned.
- * @param ns array of values to parse
- * @return hexadecimal string representation of
- * values
- */
- function hex(ns: number[], digits?: number): string[];
-
- /**
- * Converts a string representation of a hexadecimal
- * number to its equivalent integer value. When an
- * array of strings in hexadecimal notation is passed
- * in, an array of integers of the same length is
- * returned.
- * @param n value to parse
- * @return integer representation of hexadecimal
- * value
- */
- function unhex(n: string): number;
-
- /**
- * Converts a string representation of a hexadecimal
- * number to its equivalent integer value. When an
- * array of strings in hexadecimal notation is passed
- * in, an array of integers of the same length is
- * returned.
- * @param ns values to parse
- * @return integer representations of hexadecimal
- * value
- */
- function unhex(ns: any[]): number[];
-
- /**
- * Adds a value to the end of an array. Extends the
- * length of the array by one. Maps to Array.push().
- * @param array Array to append
- * @param value to be added to the Array
- * @return the array that was appended to
- */
- function append(array: any[], value: any): any[];
-
- /**
- * Copies an array (or part of an array) to another
- * array. The src array is copied to the dst array,
- * beginning at the position specified by srcPosition
- * and into the position specified by dstPosition.
- * The number of p5.Elements to copy is determined by
- * length. Note that copying values overwrites
- * existing values in the destination array. To
- * append values instead of overwriting them, use
- * concat(). The simplified version with only two
- * arguments, arrayCopy(src, dst), copies an entire
- * array to another of the same size. It is
- * equivalent to arrayCopy(src, 0, dst, 0,
- * src.length).
- *
- *
- * Using this function is far more efficient for
- * copying array data than iterating through a for()
- * loop and copying each p5.Element individually.
- * @param src the source Array
- * @param srcPosition starting position in the source
- * Array
- * @param dst the destination Array
- * @param dstPosition starting position in the
- * destination Array
- * @param length number of Array p5.Elements to be
- * copied
- */
- function arrayCopy(src: any[], srcPosition: number, dst: any[], dstPosition: number, length: number): void;
-
- /**
- * Copies an array (or part of an array) to another
- * array. The src array is copied to the dst array,
- * beginning at the position specified by srcPosition
- * and into the position specified by dstPosition.
- * The number of p5.Elements to copy is determined by
- * length. Note that copying values overwrites
- * existing values in the destination array. To
- * append values instead of overwriting them, use
- * concat(). The simplified version with only two
- * arguments, arrayCopy(src, dst), copies an entire
- * array to another of the same size. It is
- * equivalent to arrayCopy(src, 0, dst, 0,
- * src.length).
- *
- *
- * Using this function is far more efficient for
- * copying array data than iterating through a for()
- * loop and copying each p5.Element individually.
- * @param src the source Array
- * @param dst the destination Array
- * @param [length] number of Array p5.Elements to be
- * copied
- */
- function arrayCopy(src: any[], dst: any[], length?: number): void;
-
- /**
- * Concatenates two arrays, maps to Array.concat().
- * Does not modify the input arrays.
- * @param a first Array to concatenate
- * @param b second Array to concatenate
- * @return concatenated array
- */
- function concat(a: any[], b: any[]): any[];
-
- /**
- * Reverses the order of an array, maps to
- * Array.reverse()
- * @param list Array to reverse
- * @return the reversed list
- */
- function reverse(list: any[]): any[];
-
- /**
- * Decreases an array by one p5.Element and returns the
- * shortened array, maps to Array.pop().
- * @param list Array to shorten
- * @return shortened Array
- */
- function shorten(list: any[]): any[];
-
- /**
- * Randomizes the order of the p5.Elements of an array.
- * Implements Fisher-Yates Shuffle Algorithm.
- * @param array Array to shuffle
- * @param [bool] modify passed array
- * @return shuffled Array
- */
- function shuffle(array: any[], bool?: boolean): any[];
-
- /**
- * Sorts an array of numbers from smallest to
- * largest, or puts an array of words in alphabetical
- * order. The original array is not modified; a
- * re-ordered array is returned. The count parameter
- * states the number of p5.Elements to sort. For
- * example, if there are 12 p5.Elements in an array and
- * count is set to 5, only the first 5 p5.Elements in
- * the array will be sorted.
- * @param list Array to sort
- * @param [count] number of p5.Elements to sort,
- * starting from 0
- * @return the sorted list
- */
- function sort(list: any[], count?: number): any[];
-
- /**
- * Inserts a value or an array of values into an
- * existing array. The first parameter specifies the
- * initial array to be modified, and the second
- * parameter defines the data to be inserted. The
- * third parameter is an index value which specifies
- * the array position from which to insert data.
- * (Remember that array index numbering starts at
- * zero, so the first position is 0, the second
- * position is 1, and so on.)
- * @param list Array to splice into
- * @param value value to be spliced in
- * @param position in the array from which to insert
- * data
- * @return the list
- */
- function splice(list: any[], value: any, position: number): any[];
-
- /**
- * Extracts an array of p5.Elements from an existing
- * array. The list parameter defines the array from
- * which the p5.Elements will be copied, and the start
- * and count parameters specify which p5.Elements to
- * extract. If no count is given, p5.Elements will be
- * extracted from the start to the end of the array.
- * When specifying the start, remember that the first
- * array p5.Element is 0. This function does not change
- * the source array.
- * @param list Array to extract from
- * @param start position to begin
- * @param [count] number of values to extract
- * @return Array of extracted p5.Elements
- */
- function subset(list: any[], start: number, count?: number): any[];
-
-
- /**
- * Loads an opentype font file (.otf, .ttf) from a
- * file or a URL, and returns a PFont Object. This
- * method is asynchronous, meaning it may not finish
- * before the next line in your sketch is executed.
- * The path to the font should be relative to the
- * HTML file that links in your sketch. Loading fonts
- * from a URL or other remote location may be blocked
- * due to your browser's built-in security.
- * @param path name of the file or url to load
- * @param [callback] function to be executed after
- * loadFont() completes
- * @param [onError] function to be executed if an
- * error occurs
- * @return p5.Font object
- */
- function loadFont(path: string, callback?: (...args: any[]) => any, onError?: (...args: any[]) => any):p5.Font;
-
- /**
- * Draws text to the screen. Displays the information
- * specified in the first parameter on the screen in
- * the position specified by the additional
- * parameters. A default font will be used unless a
- * font is set with the textFont() function and a
- * default size will be used unless a font is set
- * with textSize(). Change the p5.Color of the text with
- * the fill() function. Change the outline of the
- * text with the stroke() and strokeWeight()
- * functions. The text displays in relation to the
- * textAlign() function, which gives the option to
- * draw to the left, right, and center of the
- * coordinates.
- *
- *
- * The x2 and y2 parameters define a rectangular area
- * to display within and may only be used with string
- * data. When these parameters are specified, they
- * are interpreted based on the current rectMode()
- * setting. Text that does not fit completely within
- * the rectangle specified will not be drawn to the
- * screen. If x2 and y2 are not specified, the
- * baseline alignment is the default, which means
- * that the text will be drawn upwards from x and y.
- *
- *
- * WEBGL: Only opentype/truetype fonts are supported.
- * You must load a font using the loadFont() method
- * (see the example above). stroke() currently has no
- * effect in webgl mode.
- * @param str the alphanumeric symbols to be
- * displayed
- * @param x x-coordinate of text
- * @param y y-coordinate of text
- * @param [x2] by default, the width of the text box,
- * see rectMode() for more info
- * @param [y2] by default, the height of the text
- * box, see rectMode() for more info
- * @chainable
- */
- function text(str: string | object | any[] | number | boolean, x: number, y: number, x2?: number, y2?: number): p5;
-
- /**
- * Sets the current font that will be drawn with the
- * text() function. WEBGL: Only fonts loaded via
- * loadFont() are supported.
- * @return the current font
- */
- function textFont(): object;
-
- /**
- * Sets the current font that will be drawn with the
- * text() function. WEBGL: Only fonts loaded via
- * loadFont() are supported.
- * @param font a font loaded via loadFont(), or a
- * String representing a web safe font (a font that
- * is generally available across all systems)
- * @param [size] the font size to use
- * @chainable
- */
- function textFont(font: object | string, size?: number): p5;
-
-
- /**
- * Sets the current alignment for drawing text.
- * Accepts two arguments: horizAlign (LEFT, CENTER,
- * or RIGHT) and vertAlign (TOP, BOTTOM, CENTER, or
- * BASELINE). The horizAlign parameter is in
- * reference to the x value of the text() function,
- * while the vertAlign parameter is in reference to
- * the y value.
- *
- * So if you write textAlign(LEFT), you are aligning
- * the left edge of your text to the x value you give
- * in text(). If you write textAlign(RIGHT, TOP), you
- * are aligning the right edge of your text to the x
- * value and the top of edge of the text to the y
- * value.
- * @param horizAlign horizontal alignment, either
- * LEFT, CENTER, or RIGHT
- * @param [vertAlign] vertical alignment, either TOP,
- * BOTTOM, CENTER, or BASELINE
- * @chainable
- */
- function textAlign(horizAlign: HORIZ_ALIGN, vertAlign?: VERT_ALIGN): p5;
-
- /**
- * Sets the current alignment for drawing text.
- * Accepts two arguments: horizAlign (LEFT, CENTER,
- * or RIGHT) and vertAlign (TOP, BOTTOM, CENTER, or
- * BASELINE). The horizAlign parameter is in
- * reference to the x value of the text() function,
- * while the vertAlign parameter is in reference to
- * the y value.
- *
- * So if you write textAlign(LEFT), you are aligning
- * the left edge of your text to the x value you give
- * in text(). If you write textAlign(RIGHT, TOP), you
- * are aligning the right edge of your text to the x
- * value and the top of edge of the text to the y
- * value.
- */
- function textAlign(): object;
-
- /**
- * Sets/gets the spacing, in pixels, between lines of
- * text. This setting will be used in all subsequent
- * calls to the text() function.
- * @param leading the size in pixels for spacing
- * between lines
- * @chainable
- */
- function textLeading(leading: number): p5;
-
- /**
- * Sets/gets the spacing, in pixels, between lines of
- * text. This setting will be used in all subsequent
- * calls to the text() function.
- */
- function textLeading(): number;
-
- /**
- * Sets/gets the current font size. This size will be
- * used in all subsequent calls to the text()
- * function.p5.Font size is measured in pixels.
- * @param theSize the size of the letters in units of
- * pixels
- * @chainable
- */
- function textSize(theSize: number): p5;
-
- /**
- * Sets/gets the current font size. This size will be
- * used in all subsequent calls to the text()
- * function.p5.Font size is measured in pixels.
- */
- function textSize(): number;
-
- /**
- * Sets/gets the style of the text for system fonts
- * to NORMAL, ITALIC, BOLD or BOLDITALIC. Note: this
- * may be is overridden by CSS styling. For
- * non-system fonts (opentype, truetype, etc.) please
- * load styled fonts instead.
- * @param theStyle styling for text, either NORMAL,
- * ITALIC, BOLD or BOLDITALIC
- * @chainable
- */
- function textStyle(theStyle: THE_STYLE): p5;
-
- /**
- * Sets/gets the style of the text for system fonts
- * to NORMAL, ITALIC, BOLD or BOLDITALIC. Note: this
- * may be is overridden by CSS styling. For
- * non-system fonts (opentype, truetype, etc.) please
- * load styled fonts instead.
- */
- function textStyle(): string;
-
- /**
- * Calculates and returns the width of any character
- * or text string.
- * @param theText the String of characters to measure
- */
- function textWidth(theText: string): number;
-
- /**
- * Returns the ascent of the current font at its
- * current size. The ascent represents the distance,
- * in pixels, of the tallest character above the
- * baseline.
- */
- function textAscent(): number;
-
- /**
- * Returns the descent of the current font at its
- * current size. The descent represents the distance,
- * in pixels, of the character with the longest
- * descender below the baseline.
- */
- function textDescent(): number;
-
- /**
- * The inverse of cos(), returns the arc cosine of a
- * value. This function expects the values in the
- * range of -1 to 1 and values are returned in the
- * range 0 to PI (3.1415927).
- * @param value the value whose arc cosine is to be
- * returned
- * @return the arc cosine of the given value
- */
- function acos(value: number): number;
-
- /**
- * The inverse of sin(), returns the arc sine of a
- * value. This function expects the values in the
- * range of -1 to 1 and values are returned in the
- * range -PI/2 to PI/2.
- * @param value the value whose arc sine is to be
- * returned
- * @return the arc sine of the given value
- */
- function asin(value: number): number;
-
- /**
- * The inverse of tan(), returns the arc tangent of a
- * value. This function expects the values in the
- * range of -Infinity to Infinity (exclusive) and
- * values are returned in the range -PI/2 to PI/2.
- * @param value the value whose arc tangent is to be
- * returned
- * @return the arc tangent of the given value
- */
- function atan(value: number): number;
-
- /**
- * Calculates the angle (in radians) from a specified
- * point to the coordinate origin as measured from
- * the positive x-axis. Values are returned as a
- * float in the range from PI to -PI. The atan2()
- * function is most often used for orienting geometry
- * to the position of the cursor. Note: The
- * y-coordinate of the point is the first parameter,
- * and the x-coordinate is the second parameter, due
- * the the structure of calculating the tangent.
- * @param y y-coordinate of the point
- * @param x x-coordinate of the point
- * @return the arc tangent of the given point
- */
- function atan2(y: number, x: number): number;
-
- /**
- * Calculates the cosine of an angle. This function
- * takes into account the current angleMode. Values
- * are returned in the range -1 to 1.
- * @param angle the angle
- * @return the cosine of the angle
- */
- function cos(angle: number): number;
-
- /**
- * Calculates the sine of an angle. This function
- * takes into account the current angleMode. Values
- * are returned in the range -1 to 1.
- * @param angle the angle
- * @return the sine of the angle
- */
- function sin(angle: number): number;
-
- /**
- * Calculates the tangent of an angle. This function
- * takes into account the current angleMode. Values
- * are returned in the range -1 to 1.
- * @param angle the angle
- * @return the tangent of the angle
- */
- function tan(angle: number): number;
-
- /**
- * Converts a radian measurement to its corresponding
- * value in degrees. Radians and degrees are two ways
- * of measuring the same thing. There are 360 degrees
- * in a circle and 2*PI radians in a circle. For
- * example, 90° = PI/2 = 1.5707964. This function
- * does not take into account the current angleMode.
- * @param radians the radians value to convert to
- * degrees
- * @return the converted angle
- */
- function degrees(radians: number): number;
-
- /**
- * Converts a degree measurement to its corresponding
- * value in radians. Radians and degrees are two ways
- * of measuring the same thing. There are 360 degrees
- * in a circle and 2*PI radians in a circle. For
- * example, 90° = PI/2 = 1.5707964. This function
- * does not take into account the current angleMode.
- * @param degrees the degree value to convert to
- * radians
- * @return the converted angle
- */
- function radians(degrees: number): number;
-
- /**
- * Sets the current mode of p5 to given mode. Default
- * mode is RADIANS.
- * @param mode either RADIANS or DEGREES
- */
- function angleMode(mode: ANGLE_MODE): void;
-
-
- /**
- * Sets the seed value for random(). By default,
- * random() produces different results each time the
- * program is run. Set the seed parameter to a
- * constant to return the same pseudo-random numbers
- * each time the software is run.
- * @param seed the seed value
- */
- function randomSeed(seed: number): void;
-
- /**
- * Return a random floating-point number. Takes
- * either 0, 1 or 2 arguments.
- *
- * If no argument is given, returns a random number
- * from 0 up to (but not including) 1.
- *
- * If one argument is given and it is a number,
- * returns a random number from 0 up to (but not
- * including) the number.
- *
- * If one argument is given and it is an array,
- * returns a random p5.Element from that array.
- *
- * If two arguments are given, returns a random
- * number from the first argument up to (but not
- * including) the second argument.
- * @param [min] the lower bound (inclusive)
- * @param [max] the upper bound (exclusive)
- * @return the random number
- */
- function random(min?: number, max?: number): number;
-
- /**
- * Return a random floating-point number. Takes
- * either 0, 1 or 2 arguments.
- *
- * If no argument is given, returns a random number
- * from 0 up to (but not including) 1.
- *
- * If one argument is given and it is a number,
- * returns a random number from 0 up to (but not
- * including) the number.
- *
- * If one argument is given and it is an array,
- * returns a random p5.Element from that array.
- *
- * If two arguments are given, returns a random
- * number from the first argument up to (but not
- * including) the second argument.
- * @param choices the array to choose from
- * @return the random p5.Element from the array
- */
- function random(choices: any[]): any;
-
- /**
- * Returns a random number fitting a Gaussian, or
- * normal, distribution. There is theoretically no
- * minimum or maximum value that randomGaussian()
- * might return. Rather, there is just a very low
- * probability that values far from the mean will be
- * returned; and a higher probability that numbers
- * near the mean will be returned. Takes either 0, 1
- * or 2 arguments.
- *
- * If no args, returns a mean of 0 and standard
- * deviation of 1.
- *
- * If one arg, that arg is the mean (standard
- * deviation is 1).
- *
- * If two args, first is mean, second is standard
- * deviation.
- * @param mean the mean
- * @param sd the standard deviation
- * @return the random number
- */
- function randomGaussian(mean: number, sd: number): number;
-
-
- /**
- * Returns the Perlin noise value at specified
- * coordinates. Perlin noise is a random sequence
- * generator producing a more natural ordered,
- * harmonic succession of numbers compared to the
- * standard random() function. It was invented by Ken
- * Perlin in the 1980s and been used since in
- * graphical applications to produce procedural
- * textures, natural motion, shapes, terrains etc.
- * The main difference to the random() function is
- * that Perlin noise is defined in an infinite
- * n-dimensional space where each pair of coordinates
- * corresponds to a fixed semi-random value (fixed
- * only for the lifespan of the program; see the
- * noiseSeed() function). p5.js can compute 1D, 2D
- * and 3D noise, depending on the number of
- * coordinates given. The resulting value will always
- * be between 0.0 and 1.0. The noise value can be
- * animated by moving through the noise space as
- * demonstrated in the example above. The 2nd and 3rd
- * dimension can also be interpreted as time.
- *
- * The actual noise is structured similar to an audio
- * signal, in respect to the function's use of
- * frequencies. Similar to the concept of harmonics
- * in physics, perlin noise is computed over several
- * octaves which are added together for the final
- * result.
- *
- * Another way to adjust the character of the
- * resulting sequence is the scale of the input
- * coordinates. As the function works within an
- * infinite space the value of the coordinates
- * doesn't matter as such, only the distance between
- * successive coordinates does (eg. when using
- * noise() within a loop). As a general rule the
- * smaller the difference between coordinates, the
- * smoother the resulting noise sequence will be.
- * Steps of 0.005-0.03 work best for most
- * applications, but this will differ depending on
- * use.
- * @param x x-coordinate in noise space
- * @param [y] y-coordinate in noise space
- * @param [z] z-coordinate in noise space
- * @return Perlin noise value (between 0 and 1) at
- * specified coordinates
- */
- function noise(x: number, y?: number, z?: number): number;
-
- /**
- * Adjusts the character and level of detail produced
- * by the Perlin noise function. Similar to harmonics
- * in physics, noise is computed over several
- * octaves. Lower octaves contribute more to the
- * output signal and as such define the overall
- * intensity of the noise, whereas higher octaves
- * create finer grained details in the noise
- * sequence. By default, noise is computed over 4
- * octaves with each octave contributing exactly half
- * than its predecessor, starting at 50% strength for
- * the 1st octave. This falloff amount can be changed
- * by adding an additional function parameter. Eg. a
- * falloff factor of 0.75 means each octave will now
- * have 75% impact (25% less) of the previous lower
- * octave. Any value between 0.0 and 1.0 is valid,
- * however note that values greater than 0.5 might
- * result in greater than 1.0 values returned by
- * noise().
- *
- *
- * By changing these parameters, the signal created
- * by the noise() function can be adapted to fit very
- * specific needs and characteristics.
- * @param lod number of octaves to be used by the
- * noise
- * @param falloff falloff factor for each octave
- */
- function noiseDetail(lod: number, falloff: number): void;
-
- /**
- * Sets the seed value for noise(). By default,
- * noise() produces different results each time the
- * program is run. Set the value parameter to a
- * constant to return the same pseudo-random numbers
- * each time the software is run.
- * @param seed the seed value
- */
- function noiseSeed(seed: number): void;
-
- /**
- * Creates a new p5.Vector (the datatype for storing
- * vectors). This provides a two or three dimensional
- * vector, specifically a Euclidean (also known as
- * geometric) vector. A vector is an entity that has
- * both magnitude and direction.
- * @param [x] x component of the vector
- * @param [y] y component of the vector
- * @param [z] z component of the vector
- */
- function createVector(x?: number, y?: number, z?: number): p5.Vector;
-
-
- /**
- * Calculates the absolute value (magnitude) of a
- * number. Maps to Math.abs(). The absolute value of
- * a number is always positive.
- * @param n number to compute
- * @return absolute value of given number
- */
- function abs(n: number): number;
-
- /**
- * Calculates the closest int value that is greater
- * than or equal to the value of the parameter. Maps
- * to Math.ceil(). For example, ceil(9.03) returns
- * the value 10.
- * @param n number to round up
- * @return rounded up number
- */
- function ceil(n: number): number;
-
- /**
- * Constrains a value between a minimum and maximum
- * value.
- * @param n number to constrain
- * @param low minimum limit
- * @param high maximum limit
- * @return constrained number
- */
- function constrain(n: number, low: number, high: number): number;
-
- /**
- * Calculates the distance between two points, in
- * either two or three dimensions.
- * @param x1 x-coordinate of the first point
- * @param y1 y-coordinate of the first point
- * @param x2 x-coordinate of the second point
- * @param y2 y-coordinate of the second point
- * @return distance between the two points
- */
- function dist(x1: number, y1: number, x2: number, y2: number): number;
-
- /**
- * Calculates the distance between two points, in
- * either two or three dimensions.
- * @param x1 x-coordinate of the first point
- * @param y1 y-coordinate of the first point
- * @param z1 z-coordinate of the first point
- * @param x2 x-coordinate of the second point
- * @param y2 y-coordinate of the second point
- * @param z2 z-coordinate of the second point
- * @return distance between the two points
- */
- function dist(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number): number;
-
- /**
- * Returns Euler's number e (2.71828...) raised to
- * the power of the n parameter. Maps to Math.exp().
- * @param n exponent to raise
- * @return e^n
- */
- function exp(n: number): number;
-
- /**
- * Calculates the closest int value that is less than
- * or equal to the value of the parameter. Maps to
- * Math.floor().
- * @param n number to round down
- * @return rounded down number
- */
- function floor(n: number): number;
-
- /**
- * Calculates a number between two numbers at a
- * specific increment. The amt parameter is the
- * amount to interpolate between the two values where
- * 0.0 equal to the first point, 0.1 is very near the
- * first point, 0.5 is half-way in between, and 1.0
- * is equal to the second point. If the value of amt
- * is more than 1.0 or less than 0.0, the number will
- * be calculated accordingly in the ratio of the two
- * given numbers. The lerp function is convenient for
- * creating motion along a straight path and for
- * drawing dotted lines.
- * @param start first value
- * @param stop second value
- * @param amt number
- * @return lerped value
- */
- function lerp(start: number, stop: number, amt: number): number;
-
- /**
- * Calculates the natural logarithm (the base-e
- * logarithm) of a number. This function expects the
- * n parameter to be a value greater than 0.0. Maps
- * to Math.log().
- * @param n number greater than 0
- * @return natural logarithm of n
- */
- function log(n: number): number;
-
- /**
- * Calculates the magnitude (or length) of a vector.
- * A vector is a direction in space commonly used in
- * computer graphics and linear algebra. Because it
- * has no "start" position, the magnitude of a vector
- * can be thought of as the distance from the
- * coordinate 0,0 to its x,y value. Therefore, mag()
- * is a shortcut for writing dist(0, 0, x, y).
- * @param a first value
- * @param b second value
- * @return magnitude of vector from (0,0) to (a,b)
- */
- function mag(a: number, b: number): number;
-
- /**
- * Re-maps a number from one range to another. In
- * the first example above, the number 25 is
- * converted from a value in the range of 0 to 100
- * into a value that ranges from the left edge of the
- * window (0) to the right edge (width).
- * @param value the incoming value to be converted
- * @param start1 lower bound of the value's current
- * range
- * @param stop1 upper bound of the value's current
- * range
- * @param start2 lower bound of the value's target
- * range
- * @param stop2 upper bound of the value's target
- * range
- * @param [withinBounds] constrain the value to the
- * newly mapped range
- * @return remapped number
- */
- function map(
- value: number,
- start1: number,
- stop1: number,
- start2: number,
- stop2: number,
- withinBounds?: boolean
- ): number;
-
- /**
- * Determines the largest value in a sequence of
- * numbers, and then returns that value. max()
- * accepts any number of Number parameters, or an
- * Array of any length.
- * @param n0 Number to compare
- * @param n1 Number to compare
- * @return maximum Number
- */
- function max(n0: number, n1: number): number;
-
- /**
- * Determines the largest value in a sequence of
- * numbers, and then returns that value. max()
- * accepts any number of Number parameters, or an
- * Array of any length.
- * @param nums Numbers to compare
- */
- function max(nums: number[]): number;
-
- /**
- * Determines the smallest value in a sequence of
- * numbers, and then returns that value. min()
- * accepts any number of Number parameters, or an
- * Array of any length.
- * @param n0 Number to compare
- * @param n1 Number to compare
- * @return minimum Number
- */
- function min(n0: number, n1: number): number;
-
- /**
- * Determines the smallest value in a sequence of
- * numbers, and then returns that value. min()
- * accepts any number of Number parameters, or an
- * Array of any length.
- * @param nums Numbers to compare
- */
- function min(nums: number[]): number;
-
- /**
- * Normalizes a number from another range into a
- * value between 0 and 1. Identical to map(value,
- * low, high, 0, 1). Numbers outside of the range are
- * not clamped to 0 and 1, because out-of-range
- * values are often intentional and useful. (See the
- * example above.)
- * @param value incoming value to be normalized
- * @param start lower bound of the value's current
- * range
- * @param stop upper bound of the value's current
- * range
- * @return normalized number
- */
- function norm(value: number, start: number, stop: number): number;
-
- /**
- * Facilitates exponential expressions. The pow()
- * function is an efficient way of multiplying
- * numbers by themselves (or their reciprocals) in
- * large quantities. For example, pow(3, 5) is
- * equivalent to the expression 33333 and pow(3, -5)
- * is equivalent to 1 / 33333. Maps to Math.pow().
- * @param n base of the exponential expression
- * @param e power by which to raise the base
- * @return n^e
- */
- function pow(n: number, e: number): number;
-
- /**
- * Calculates the integer closest to the n parameter.
- * For example, round(133.8) returns the value 134.
- * Maps to Math.round().
- * @param n number to round
- * @return rounded number
- */
- function round(n: number): number;
-
- /**
- * Squares a number (multiplies a number by itself).
- * The result is always a positive number, as
- * multiplying two negative numbers always yields a
- * positive result. For example, -1 * -1 = 1.
- * @param n number to square
- * @return squared number
- */
- function sq(n: number): number;
-
- /**
- * Calculates the square root of a number. The square
- * root of a number is always positive, even though
- * there may be a valid negative root. The square
- * root s of number a is such that s*s = a. It is the
- * opposite of squaring. Maps to Math.sqrt().
- * @param n non-negative number to square root
- * @return square root of number
- */
- function sqrt(n: number): number;
-
-
- /**
- * Loads a JSON file from a file or a URL, and
- * returns an Object. Note that even if the JSON file
- * contains an Array, an Object will be returned with
- * index numbers as keys. This method is
- * asynchronous, meaning it may not finish before the
- * next line in your sketch is executed. JSONP is
- * supported via a polyfill and you can pass in as
- * the second argument an object with definitions of
- * the json callback following the syntax specified
- * here.
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param path name of the file or url to load
- * @param [jsonpOptions] options object for jsonp
- * related settings
- * @param [datatype] "json" or "jsonp"
- * @param [callback] function to be executed after
- * loadJSON() completes, data is passed in as first
- * argument
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- * @return JSON data
- */
- function loadJSON(
- path: string,
- jsonpOptions?: object,
- datatype?: string,
- callback?: (...args: any[]) => any,
- errorCallback?: (...args: any[]) => any
- ): object | any[];
-
- /**
- * Loads a JSON file from a file or a URL, and
- * returns an Object. Note that even if the JSON file
- * contains an Array, an Object will be returned with
- * index numbers as keys. This method is
- * asynchronous, meaning it may not finish before the
- * next line in your sketch is executed. JSONP is
- * supported via a polyfill and you can pass in as
- * the second argument an object with definitions of
- * the json callback following the syntax specified
- * here.
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param path name of the file or url to load
- * @param datatype "json" or "jsonp"
- * @param [callback] function to be executed after
- * loadJSON() completes, data is passed in as first
- * argument
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- */
- function loadJSON(
- path: string,
- datatype: string,
- callback?: (...args: any[]) => any,
- errorCallback?: (...args: any[]) => any
- ): object | any[];
-
- /**
- * Loads a JSON file from a file or a URL, and
- * returns an Object. Note that even if the JSON file
- * contains an Array, an Object will be returned with
- * index numbers as keys. This method is
- * asynchronous, meaning it may not finish before the
- * next line in your sketch is executed. JSONP is
- * supported via a polyfill and you can pass in as
- * the second argument an object with definitions of
- * the json callback following the syntax specified
- * here.
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param path name of the file or url to load
- * @param callback function to be executed after
- * loadJSON() completes, data is passed in as first
- * argument
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- */
- function loadJSON(
- path: string,
- callback: (...args: any[]) => any,
- errorCallback?: (...args: any[]) => any
- ): object | any[];
-
- /**
- * Reads the contents of a file and creates a String
- * array of its individual lines. If the name of the
- * file is used as the parameter, as in the above
- * example, the file must be located in the sketch
- * directory/folder. Alternatively, the file maybe
- * be loaded from anywhere on the local computer
- * using an absolute path (something that starts with
- * / on Unix and Linux, or a drive letter on
- * Windows), or the filename parameter can be a URL
- * for a file found on a network.
- *
- *
- * This method is asynchronous, meaning it may not
- * finish before the next line in your sketch is
- * executed.
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param filename name of the file or url to load
- * @param [callback] function to be executed after
- * loadStrings() completes, Array is passed in as
- * first argument
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- * @return Array of Strings
- */
- function loadStrings(
- filename: string,
- callback?: (...args: any[]) => any,
- errorCallback?: (...args: any[]) => any
- ): string[];
-
- /**
- * Reads the contents of a file or URL and creates a
- * p5.p5.Table object with its values. If a file is
- * specified, it must be located in the sketch's
- * "data" folder. The filename parameter can also be
- * a URL to a file found online. By default, the file
- * is assumed to be comma-separated (in CSV format).
- * p5.Table only looks for a header row if the 'header'
- * option is included. Possible options include:
- *
- * - csv - parse the table as comma-separated values
- * - tsv - parse the table as tab-separated values
- * - header - this table has a header (title) row
- *
- *
- *
- * When passing in multiple options, pass them in as
- * separate parameters, seperated by commas. For
- * example:
- *
- *
- * loadp5.Table('my_csv_file.csv', 'csv', 'header');
- *
- *
- * All files loaded and saved use UTF-8 encoding.
- *
- * This method is asynchronous, meaning it may not
- * finish before the next line in your sketch is
- * executed. Calling loadp5.Table() inside preload()
- * guarantees to complete the operation before
- * setup() and draw() are called.
- *
- * Outside of preload(), you may supply a callback
- * function to handle the object:
- *
- *
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param filename name of the file or URL to load
- * @param options "header" "csv" "tsv"
- * @param [callback] function to be executed after
- * loadp5.Table() completes. On success, the p5.Table
- * object is passed in as the first argument.
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- * @return p5.Table object containing data
- */
- function loadTable(
- filename: string,
- options: string,
- callback ?: (...args: any[]) => any,
- errorCallback ?: (...args: any[]) => any
- ): object;
-
- /**
- * Reads the contents of a file or URL and creates a
- * p5.p5.Table object with its values. If a file is
- * specified, it must be located in the sketch's
- * "data" folder. The filename parameter can also be
- * a URL to a file found online. By default, the file
- * is assumed to be comma-separated (in CSV format).
- * p5.Table only looks for a header row if the 'header'
- * option is included. Possible options include:
- *
- * - csv - parse the table as comma-separated values
- * - tsv - parse the table as tab-separated values
- * - header - this table has a header (title) row
- *
- *
- *
- * When passing in multiple options, pass them in as
- * separate parameters, seperated by commas. For
- * example:
- *
- *
- * loadp5.Table('my_csv_file.csv', 'csv', 'header');
- *
- *
- * All files loaded and saved use UTF-8 encoding.
- *
- * This method is asynchronous, meaning it may not
- * finish before the next line in your sketch is
- * executed. Calling loadp5.Table() inside preload()
- * guarantees to complete the operation before
- * setup() and draw() are called.
- *
- * Outside of preload(), you may supply a callback
- * function to handle the object:
- *
- *
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param filename name of the file or URL to load
- * @param [callback] function to be executed after
- * loadp5.Table() completes. On success, the p5.Table
- * object is passed in as the first argument.
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- */
- function loadTable(
- filename: string,
- callback ?: (...args: any[]) => any,
- errorCallback ?: (...args: any[]) => any
- ): object;
-
- /**
- * Reads the contents of a file and creates an p5.XML
- * object with its values. If the name of the file is
- * used as the parameter, as in the above example,
- * the file must be located in the sketch
- * directory/folder. Alternatively, the file maybe be
- * loaded from anywhere on the local computer using
- * an absolute path (something that starts with / on
- * Unix and Linux, or a drive letter on Windows), or
- * the filename parameter can be a URL for a file
- * found on a network.
- *
- * This method is asynchronous, meaning it may not
- * finish before the next line in your sketch is
- * executed. Calling loadp5.XML() inside preload()
- * guarantees to complete the operation before
- * setup() and draw() are called.
- *
- * Outside of preload(), you may supply a callback
- * function to handle the object.
- *
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param filename name of the file or URL to load
- * @param [callback] function to be executed after
- * loadp5.XML() completes, p5.XML object is passed in as
- * first argument
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- * @return p5.XML object containing data
- */
- function loadXML(filename: string, callback ?: (...args: any[]) => any, errorCallback ?: (...args: any[]) => any): object;
-
- /**
- * This method is suitable for fetching files up to
- * size of 64MB.
- * @param file name of the file or URL to load
- * @param [callback] function to be executed after
- * loadBytes() completes
- * @param [errorCallback] function to be executed if
- * there is an error
- * @return an object whose 'bytes' property will be
- * the loaded buffer
- */
- function loadBytes(file: string, callback?: (...args: any[]) => any, errorCallback?: (...args: any[]) => any): object;
-
- /**
- * Method for executing an HTTP GET request. If data
- * type is not specified, p5 will try to guess based
- * on the URL, defaulting to text. This is equivalent
- * to calling httpDo(path, 'GET'). The 'binary'
- * datatype will return a Blob object, and the
- * 'arrayBuffer' datatype will return an ArrayBuffer
- * which can be used to initialize typed arrays (such
- * as Uint8Array).
- * @param path name of the file or url to load
- * @param [datatype] "json", "jsonp", "binary",
- * "arrayBuffer", "xml", or "text"
- * @param [data] param data passed sent with request
- * @param [callback] function to be executed after
- * httpGet() completes, data is passed in as first
- * argument
- * @param [errorCallback] function to be executed if
- * there is an error, response is passed in as first
- * argument
- * @return A promise that resolves with the data when
- * the operation completes successfully or rejects
- * with the error after one occurs.
- */
- function httpGet(
- path: string,
- datatype?: string,
- data?: object | boolean,
- callback?: (...args: any[]) => any,
- errorCallback?: (...args: any[]) => any
- ): Promise Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested. Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer. We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed. The web is much more than just canvas and the DOM functionality makes it easy to interact\nwith other HTML5 objects, including text, hyperlink, image, input, video,\naudio, and webcam. There is a set of creation methods, DOM manipulation methods, and\nan extended p5.Element that supports a range of HTML elements. See the\n\nbeyond the canvas tutorial for a full overview of how this addon works.\n\n See tutorial: beyond the canvas\nfor more info on how to use this library.",
+ requires: ['p5']
+ },
+ Rendering: {
+ name: 'Rendering',
+ submodules: {
+ undefined: 1
+ },
+ elements: {},
+ classes: {
+ 'p5.RendererGL': 1,
+ 'p5.Graphics': 1,
+ 'p5.Renderer': 1
+ },
+ fors: {
+ p5: 1
+ },
+ namespaces: {},
+ module: 'Rendering',
+ file: 'src/webgl/p5.RendererGL.js',
+ line: 548,
+ description:
+ ' Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5. Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class. Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n This module defines the p5.Font class and functions for\ndrawing text to the display canvas. XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects. This is the p5 instance constructor. A p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch. A p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file. A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n This module defines the p5.Shader class This class describes a camera for use in p5's\n\nWebGL mode. It contains camera position, orientation, and projection\ninformation necessary for rendering a 3D scene. New p5.Camera objects can be made through the\ncreateCamera() function and controlled through\nthe methods described below. A camera created in this way will use a default\nposition in the scene and a default perspective projection until these\nproperties are changed through the various methods available. It is possible\nto create multiple cameras, in which case the current camera\ncan be set through the setCamera() method. Note:\nThe methods below operate in two coordinate systems: the 'world' coordinate\nsystem describe positions in terms of their relationship to the origin along\nthe X, Y and Z axes whereas the camera's 'local' coordinate system\ndescribes positions from the camera's point of view: left-right, up-down,\nand forward-backward. The move() method,\nfor instance, moves the camera along its own axes, whereas the\nsetPosition()\nmethod sets the camera's position in world-space. p5.sound extends p5 with Web Audio functionality including audio input,\nplayback, analysis and synthesis.\n This is the p5 instance constructor. A p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch. A p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object a closure that can set optional preload(),\n setup(), and/or draw() properties on the\n given p5 instance element to attach canvas to Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested. Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer. We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed. Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. It is not called directly, but p5.Element\nobjects are created by calling createCanvas, createGraphics,\ncreateDiv, createImg, createInput, etc. DOM node that is wrapped pointer to p5 instance Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5. width height the renderer to use, either P2D or WEBGL pointer to p5 instance Main graphics and rendering context, as well as the base API\nimplementation for p5.js "core". To be used as the superclass for\nRenderer2D and Renderer3D classes, respecitvely. DOM node that is wrapped pointer to p5 instance whether we're using it as main canvas Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class. A simple Dictionary class for Strings. A simple Dictionary class for Numbers. Extends p5.Element to handle audio and video. In addition to the methods\nof p5.Element, it also contains methods for controlling media. It is not\ncalled directly, but p5.MediaElements are created by calling createVideo,\ncreateAudio, and createCapture. DOM node that is wrapped Base class for a file.\nUsed for Element.drop and createFileInput. File that is wrapped Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file. An array of p5.TableRow objects A TableRow object represents a single row of data values,\nstored in columns, from a table. A Table Row contains both an ordered array, and an unordered\nJSON object. optional: populate the row with a\n string of values, separated by the\n separator comma separated values (csv) by default XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects. A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n x component of the vector y component of the vector z component of the vector Base class for font handling pointer to p5 instance This class describes a camera for use in p5's\n\nWebGL mode. It contains camera position, orientation, and projection\ninformation necessary for rendering a 3D scene. New p5.Camera objects can be made through the\ncreateCamera() function and controlled through\nthe methods described below. A camera created in this way will use a default\nposition in the scene and a default perspective projection until these\nproperties are changed through the various methods available. It is possible\nto create multiple cameras, in which case the current camera\ncan be set through the setCamera() method. Note:\nThe methods below operate in two coordinate systems: the 'world' coordinate\nsystem describe positions in terms of their relationship to the origin along\nthe X, Y and Z axes whereas the camera's 'local' coordinate system\ndescribes positions from the camera's point of view: left-right, up-down,\nand forward-backward. The move() method,\nfor instance, moves the camera along its own axes, whereas the\nsetPosition()\nmethod sets the camera's position in world-space. instance of WebGL renderer p5 Geometry class number of vertices on horizontal surface number of vertices on horizontal surface function to call upon object instantiation. Shader class for WEBGL Mode an instance of p5.RendererGL that\nwill provide the GL context for this new p5.Shader source code for the vertex shader (as a string) source code for the fragment shader (as a string) SoundFile object with a path to a file. The p5.SoundFile may not be available immediately because\nit loads the file information asynchronously. To do something with the sound as soon as it loads\npass the name of a function as the second parameter. Only one file path is required. However, audio file formats\n(i.e. mp3, ogg, wav and m4a/aac) are not supported by all\nweb browsers. If you want to ensure compatability, instead of a single\nfile path, you may include an Array of filepaths, and the browser will\nchoose a format that works. path to a sound file (String). Optionally,\n you may include multiple file formats in\n an array. Alternately, accepts an object\n from the HTML5 File API, or a p5.File. Name of a function to call once file loads Name of a function to call if file fails to\n load. This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong. Name of a function to call while file\n is loading. That function will\n receive progress of the request to\n load the sound file\n (between 0 and 1) as its first\n parameter. This progress\n does not account for the additional\n time needed to decode the audio data. Amplitude measures volume between 0.0 and 1.0.\nListens to all p5sound by default, or use setInput()\nto listen to a specific sound source. Accepts an optional\nsmoothing value, which defaults to 0. between 0.0 and .999 to smooth\n amplitude readings (defaults to 0) FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n\naudio frequencies within a waveform. Once instantiated, a p5.FFT object can return an array based on\ntwo types of analyses: FFT analyzes a very short snapshot of sound called a sample\nbuffer. It returns an array of amplitude measurements, referred\nto as Smooth results of Freq Spectrum.\n 0.0 < smoothing < 1.0.\n Defaults to 0.8. Length of resulting array.\n Must be a power of two between\n 16 and 1024. Defaults to 1024. p5.Signal is a constant audio-rate signal used by p5.Oscillator\nand p5.Envelope for modulation math. This is necessary because Web Audio is processed on a seprate clock.\nFor example, the p5 draw loop runs about 60 times per second. But\nthe audio clock must process samples 44100 times per second. If we\nwant to add a value to each of those samples, we can't do it in the\ndraw loop, but we can do it by adding a constant-rate audio signal.This class mostly functions behind the scenes in p5.sound, and returns\na Tone.Signal from the Tone.js library by Yotam Mann.\nIf you want to work directly with audio signals for modular\nsynthesis, check out\ntone.js. Creates a signal that oscillates between -1.0 and 1.0.\nBy default, the oscillation takes the form of a sinusoidal\nshape ('sine'). Additional types include 'triangle',\n'sawtooth' and 'square'. The frequency defaults to\n440 oscillations per second (440Hz, equal to the pitch of an\n'A' note). Set the type of oscillation with setType(), or by instantiating a\nspecific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc.\n frequency defaults to 440Hz type of oscillator. Options:\n 'sine' (default), 'triangle',\n 'sawtooth', 'square' Constructor: Set the frequency Constructor: Set the frequency Constructor: Set the frequency Constructor: Set the frequency Envelopes are pre-defined amplitude distribution over time.\nTypically, envelopes are used to control the output volume\nof an object, a series of fades referred to as Attack, Decay,\nSustain and Release (\nADSR\n). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can\ncontrol an Oscillator\'s frequency like this: Use Use the Creates a Pulse object, an oscillator that implements\nPulse Width Modulation.\nThe pulse is created with two oscillators.\nAccepts a parameter for frequency, and to set the\nwidth between the pulses. See \n Frequency in oscillations per second (Hz) Width between the pulses (0 to 1.0,\n defaults to 0) Noise is a type of oscillator that generates a buffer with random values. Type of noise can be 'white' (default),\n 'brown' or 'pink'. Get audio from an input, i.e. your computer\'s microphone. Turn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object. If you want to hear the AudioIn, use the .connect() method.\nAudioIn does not connect to p5.sound output by default to prevent\nfeedback. Note: This uses the getUserMedia/\nStream API, which is not supported by certain browsers. Access in Chrome browser\nis limited to localhost and https, but access over http may be limited. A function to call if there is an error\n accessing the AudioIn. For example,\n Safari and iOS devices do not\n currently allow microphone access. Effect is a base class for audio effects in p5. This class is extended by p5.Distortion, \np5.Compressor,\np5.Delay, \np5.Filter, \np5.Reverb. Reference to the audio context of the p5 object Gain Node effect wrapper Gain Node effect wrapper Tone.JS CrossFade node (defaults to value: 1) Effects that extend this class should connect\n to the wet signal to this gain node, so that dry and wet \n signals are mixed properly. A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Subclasses\ninclude: The This class extends p5.Effect. \nMethods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available. 'lowpass' (default), 'highpass', 'bandpass' Constructor: Constructor: Constructor: p5.EQ is an audio effect that performs the function of a multiband\naudio equalizer. Equalization is used to adjust the balance of\nfrequency compoenents of an audio signal. This process is commonly used\nin sound production and recording to change the waveform before it reaches\na sound output device. EQ can also be used as an audio effect to create\ninteresting distortions by filtering out parts of the spectrum. p5.EQ is\nbuilt using a chain of Web Audio Biquad Filter Nodes and can be\ninstantiated with 3 or 8 bands. Bands can be added or removed from\nthe EQ by directly modifying p5.EQ.bands (the array that stores filters). This class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available. Constructor will accept 3 or 8, defaults to 3 Panner3D is based on the \nWeb Audio Spatial Panner Node.\nThis panner is a spatial processing node that allows audio to be positioned\nand oriented in 3D space. The position is relative to an \nAudio Context Listener, which can be accessed\nby Delay is an echo effect. It processes an existing sound source,\nand outputs a delayed version of that sound. The p5.Delay can\nproduce different effects depending on the delayTime, feedback,\nfilter, and type. In the example below, a feedback of 0.5 (the\ndefaul value) will produce a looping delay that decreases in\nvolume by 50% each repeat. A filter will cut out the high\nfrequencies so that the delay does not sound as piercing as the\noriginal source. This class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available. Reverb adds depth to a sound through a large number of decaying\nechoes. It creates the perception that sound is occurring in a\nphysical space. The p5.Reverb has paramters for Time (how long does the\nreverb last) and decayRate (how much the sound decays with each echo)\nthat can be set with the .set() or .process() methods. The p5.Convolver\nextends p5.Reverb allowing you to recreate the sound of actual physical\nspaces through convolution. This class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available. p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called \nconvolution. Convolution multiplies any audio input by an "impulse response"\nto simulate the dispersion of sound over time. The impulse response is\ngenerated from an audio file that you provide. One way to\ngenerate an impulse response is to pop a balloon in a reverberant space\nand record the echo. Convolution can also be used to experiment with\nsound. Use the method path to a sound file function to call when loading succeeds function to call if loading fails.\n This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong. A phrase is a pattern of musical events over time, i.e.\na series of notes and rests. Phrases must be added to a p5.Part for playback, and\neach part can play multiple phrases at the same time.\nFor example, one Phrase might be a kick drum, another\ncould be a snare, and another could be the bassline. The first parameter is a name so that the phrase can be\nmodified or deleted later. The callback is a a function that\nthis phrase will call at every step—for example it might be\ncalled Name so that you can access the Phrase. The name of a function that this phrase\n will call. Typically it will play a sound,\n and accept two parameters: a time at which\n to play the sound (in seconds from now),\n and a value from the sequence array. The\n time should be passed into the play() or\n start() method to ensure precision. Array of values to pass into the callback\n at each step of the phrase. A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents a 1/16th note. See p5.Phrase for more about musical timing. Steps in the part Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note) A Score consists of a series of Parts. The parts will\nbe played back in order. For example, you could have an\nA part, a B part, and a C part, and play them back in this order\n One or multiple parts, to be played in sequence. SoundLoop this function will be called on each iteration of theloop amount of time or beats for each iteration of the loop\n defaults to 1 Compressor is an audio effect class that performs dynamics compression\non an audio input source. This is a very commonly used technique in music\nand sound production. Compression creates an overall louder, richer, \nand fuller sound by lowering the volume of louds and raising that of softs.\nCompression can be used to avoid clipping (sound distortion due to \npeaks in volume) and is especially useful when many sounds are played \nat once. Compression can be used on indivudal sound sources in addition\nto the master output. This class extends p5.Effect. \nMethods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available. Record sounds for playback and/or to save as a .wav file.\nThe p5.SoundRecorder records all sound output from your sketch,\nor can be assigned a specific source with setInput(). The record() method accepts a p5.SoundFile as a parameter.\nWhen playback is stopped (either after the given amount of time,\nor with the stop() method), the p5.SoundRecorder will send its\nrecording to that p5.SoundFile for playback. PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n \nTo use p5.PeakDetect, call \nYou can listen for a specific part of the frequency spectrum by\nsetting the range between \nThe update method is meant to be run in the draw loop, and\nframes determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n \nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by Felix Turner.\n lowFrequency - defaults to 20Hz highFrequency - defaults to 20000 Hz Threshold for detecting a beat between 0 and 1\n scaled logarithmically where 0.1 is 1/2 the loudness\n of 1.0. Defaults to 0.35. Defaults to 20. A gain node is usefull to set the relative volume of sound.\nIt's typically used to build mixers. Base class for monophonic synthesizers. Any extensions of this class\nshould follow the API and implement the methods below in order to \nremain compatible with p5.PolySynth(); A MonoSynth is used as a single voice for sound synthesis.\nThis is a class to be used in conjunction with the PolySynth\nclass. Custom synthetisers should be built inheriting from\nthis class. An AudioVoice is used as a single voice for sound synthesis.\nThe PolySynth class holds an array of AudioVoice, and deals\nwith voices allocations, with setting notes to be played, and\nparameters to be set. A monophonic synth voice inheriting\n the AudioVoice class. Defaults to p5.MonoSynth Number of voices, defaults to 8; A Distortion effect created with a Waveshaper Node,\nwith an approach adapted from\nKevin Ennis This class extends p5.Effect. \nMethods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available. Unbounded distortion amount.\n Normal values range from 0-1. 'none', '2x', or '4x'. Conversions adapted from http://www.easyrgb.com/en/math.php. In these functions, hue is always in the range [0, 1], just like all other\ncomponents are in the range [0, 1]. 'Brightness' and 'value' are used\ninterchangeably. Convert an HSBA array to HSLA. Convert an HSBA array to RGBA. Convert an HSLA array to HSBA. Convert an HSLA array to RGBA. We need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation. Convert an RGBA array to HSBA. Convert an RGBA array to HSLA. Extracts the alpha value from a color or pixel array. p5.Color object, color components,\n or CSS color Extracts the blue value from a color or pixel array. p5.Color object, color components,\n or CSS color Extracts the HSB brightness value from a color or pixel array. p5.Color object, color components,\n or CSS color Creates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent colorMode(). The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.\n number specifying value between white\n and black. alpha value relative to current color range\n (default is 0-255) red or hue value relative to\n the current color range green or saturation value\n relative to the current color range blue or brightness value\n relative to the current color range a color string an array containing the red,green,blue &\n and alpha components of the color Extracts the green value from a color or pixel array. p5.Color object, color components,\n or CSS color Extracts the hue value from a color or pixel array. Hue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.) p5.Color object, color components,\n or CSS color Blends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first color, 0.1 is very near the first color, 0.5 is halfway\nin between, etc. An amount below 0 will be treated as 0. Likewise, amounts\nabove 1 will be capped at 1. This is different from the behavior of lerp(),\nbut necessary because otherwise numbers outside the range will produce\nstrange and unexpected colors.\n interpolate from this color interpolate to this color number between 0 and 1 Extracts the HSL lightness value from a color or pixel array. p5.Color object, color components,\n or CSS color Extracts the red value from a color or pixel array. p5.Color object, color components,\n or CSS color Extracts the saturation value from a color or pixel array. Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise. p5.Color object, color components,\n or CSS color This function returns the color formatted as a string. This can be useful\nfor debugging, or for using p5.js with other libraries. How the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n'#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.\n'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.\n'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.\n'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. The setRed function sets the red component of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255. the new red value The setGreen function sets the green component of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255. the new green value The setBlue function sets the blue component of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255. the new blue value The setAlpha function sets the transparency (alpha) value of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255. the new alpha value Hue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise. Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise. CSS named colors. These regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code. Note that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency. Full color string patterns. The capture groups are necessary. For HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum. The background() function sets the color used for the background of the\np5.js canvas. The default background is transparent. This function is\ntypically used within draw() to clear the display window at the beginning\nof each frame, but it can be used inside setup() to set the background on\nthe first frame of animation or if the background need only be set once.\n any value created by the color() function color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex opacity of the background relative to current\n color range (default is 0-255) specifies a value between white and black red or hue value (depending on the current color\n mode) green or saturation value (depending on the current\n color mode) blue or brightness value (depending on the current\n color mode) an array containing the red, green, blue\n and alpha components of the color image created with loadImage() or createImage(),\n to set as background\n (must be same size as the sketch window) Clears the pixels within a buffer. This function only clears the canvas.\nIt will not clear objects created by createX() methods such as\ncreateVideo() or createDiv().\nUnlike the main graphics context, pixels in additional graphics areas created\nwith createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent. colorMode() changes the way p5.js interprets color data. By default, the\nparameters for fill(), stroke(), background(), and color() are defined by\nvalues between 0 and 255 using the RGB color model. This is equivalent to\nsetting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB\nsystem instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You\ncan also use HSL.\n either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness) range for all values range for the red or hue depending on the\n current color mode range for the green or saturation depending\n on the current color mode range for the blue or brightness/lightness\n depending on the current color mode range for the alpha Sets the color used to fill shapes. For example, if you run\nfill(204, 102, 0), all shapes drawn after the fill command will be filled with the color orange. This\ncolor is either specified in terms of the RGB or HSB color depending on\nthe current colorMode(). (The default color space is RGB, with each value\nin the range from 0 to 255). The alpha range by default is also 0 to 255.\n red or hue value relative to\n the current color range green or saturation value\n relative to the current color range blue or brightness value\n relative to the current color range a color string a gray value an array containing the red,green,blue &\n and alpha components of the color the fill color Disables filling geometry. If both noStroke() and noFill() are called,\nnothing will be drawn to the screen. Disables drawing the stroke (outline). If both noStroke() and noFill()\nare called, nothing will be drawn to the screen. Sets the color used to draw lines and borders around shapes. This color\nis either specified in terms of the RGB or HSB color depending on the\ncurrent colorMode() (the default color space is RGB, with each value in\nthe range from 0 to 255). The alpha range by default is also 0 to 255.\n red or hue value relative to\n the current color range green or saturation value\n relative to the current color range blue or brightness value\n relative to the current color range a color string a gray value an array containing the red,green,blue &\n and alpha components of the color the stroke color All drawing that follows erase() will subtract from the canvas.\nErased areas will reveal the web page underneath the canvas.\nErasing can be canceled with noErase().\n A number (0-255) for the strength of erasing for a shape's fill.\n This will default to 255 when no argument is given, which\n is full strength. A number (0-255) for the strength of erasing for a shape's stroke.\n This will default to 255 when no argument is given, which\n is full strength. Ends erasing that was started with erase().\nThe fill(), stroke(), and\nblendMode() settings will return to what they were\nprior to calling erase(). This function does 3 things: Bounds the desired start/stop angles for an arc (in radians) so that: This means that the arc rendering functions don't have to be concerned\nwith what happens if stop is smaller than start, or if the arc 'goes\nround more than once', etc.: they can just start at start and increase\nuntil stop and the correct arc will be drawn. Optionally adjusts the angles within each quadrant to counter the naive\nscaling of the underlying ellipse up from the unit circle. Without\nthis, the angles become arbitrary when width != height: 45 degrees\nmight be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on\na 'tall' ellipse. Flags up when start and stop correspond to the same place on the\nunderlying ellipse. This is useful if you want to do something special\nthere (like rendering a whole ellipse instead). Draw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The\norigin may be changed with the ellipseMode() function. x-coordinate of the arc's ellipse y-coordinate of the arc's ellipse width of the arc's ellipse by default height of the arc's ellipse by default angle to start the arc, specified in radians angle to stop the arc, specified in radians optional parameter to determine the way of drawing\n the arc. either CHORD, PIE or OPEN optional parameter for WebGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the arc. Default value is 25. Draws an ellipse (oval) to the screen. An ellipse with equal width and\nheight is a circle. By default, the first two parameters set the location,\nand the third and fourth parameters set the shape's width and height. If\nno height is specified, the value of width is used for both the width and\nheight. If a negative height or width is specified, the absolute value is taken.\nThe origin may be changed with the ellipseMode() function. x-coordinate of the ellipse. y-coordinate of the ellipse. width of the ellipse. height of the ellipse. number of radial sectors to draw (for WebGL mode) Draws a circle to the screen. A circle is a simple closed shape.\nIt is the set of all points in a plane that are at a given distance from a given point, the centre.\nThis function is a special case of the ellipse() function, where the width and height of the ellipse are the same.\nHeight and width of the ellipse correspond to the diameter of the circle.\nBy default, the first two parameters set the location of the centre of the circle, the third sets the diameter of the circle. x-coordinate of the centre of the circle. y-coordinate of the centre of the circle. diameter of the circle. Draws a line (a direct path between two points) to the screen. The version\nof line() with four parameters draws the line in 2D. To color a line, use\nthe stroke() function. A line cannot be filled, therefore the fill()\nfunction will not affect the color of a line. 2D lines are drawn with a\nwidth of one pixel by default, but this can be changed with the\nstrokeWeight() function. the x-coordinate of the first point the y-coordinate of the first point the x-coordinate of the second point the y-coordinate of the second point the z-coordinate of the first point the z-coordinate of the second point Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nvalue is the vertical value for the point. The color of the point is\nchanged with the stroke() function. The size of the point\nis changed with the strokeWeight() function. the x-coordinate the y-coordinate the z-coordinate (for WebGL mode) the coordinate vector Draw a quad. A quad is a quadrilateral, a four sided polygon. It is\nsimilar to a rectangle, but the angles between its edges are not\nconstrained to ninety degrees. The first pair of parameters (x1,y1)\nsets the first vertex and the subsequent pairs should proceed\nclockwise or counter-clockwise around the defined shape.\nz-arguments only work when quad() is used in WEBGL mode. the x-coordinate of the first point the y-coordinate of the first point the x-coordinate of the second point the y-coordinate of the second point the x-coordinate of the third point the y-coordinate of the third point the x-coordinate of the fourth point the y-coordinate of the fourth point the z-coordinate of the first point the z-coordinate of the second point the z-coordinate of the third point the z-coordinate of the fourth point Draws a rectangle to the screen. A rectangle is a four-sided shape with\nevery angle at ninety degrees. By default, the first two parameters set\nthe location of the upper-left corner, the third sets the width, and the\nfourth sets the height. The way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n x-coordinate of the rectangle. y-coordinate of the rectangle. width of the rectangle. height of the rectangle. optional radius of top-left corner. optional radius of top-right corner. optional radius of bottom-right corner. optional radius of bottom-left corner. number of segments in the x-direction (for WebGL mode) number of segments in the y-direction (for WebGL mode) Draws a square to the screen. A square is a four-sided shape with\nevery angle at ninety degrees, and equal side size.\nThis function is a special case of the rect() function, where the width and height are the same, and the parameter is called "s" for side size.\nBy default, the first two parameters set the location of the upper-left corner, the third sets the side size of the square.\nThe way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n x-coordinate of the square. y-coordinate of the square. side size of the square. optional radius of top-left corner. optional radius of top-right corner. optional radius of bottom-right corner. optional radius of bottom-left corner. A triangle is a plane created by connecting three points. The first two\narguments specify the first point, the middle two arguments specify the\nsecond point, and the last two arguments specify the third point. x-coordinate of the first point y-coordinate of the first point x-coordinate of the second point y-coordinate of the second point x-coordinate of the third point y-coordinate of the third point Modifies the location from which ellipses are drawn by changing the way\nin which parameters given to ellipse(),\ncircle() and arc() are interpreted.\n either CENTER, RADIUS, CORNER, or CORNERS Draws all geometry with jagged (aliased) edges. Note that smooth() is\nactive by default in 2D mode, so it is necessary to call noSmooth() to disable\nsmoothing of geometry, images, and fonts. In 3D mode, noSmooth() is enabled\nby default, so it is necessary to call smooth() if you would like\nsmooth (antialiased) edges on your geometry. Modifies the location from which rectangles are drawn by changing the way\nin which parameters given to rect() are interpreted.\n either CORNER, CORNERS, CENTER, or RADIUS Draws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault in 2D mode; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts. In 3D mode, noSmooth() is enabled\nby default, so it is necessary to call smooth() if you would like\nsmooth (antialiased) edges on your geometry. Sets the style for rendering line endings. These ends are either squared,\nextended, or rounded, each of which specified with the corresponding\nparameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND. either SQUARE, PROJECT, or ROUND Sets the style of the joints which connect line segments. These joints\nare either mitered, beveled, or rounded and specified with the\ncorresponding parameters MITER, BEVEL, and ROUND. The default joint is\nMITER. either MITER, BEVEL, ROUND Sets the width of the stroke used for lines, points, and the border\naround shapes. All widths are set in units of pixels. the weight (in pixels) of the stroke Draws a cubic Bezier curve on the screen. These curves are defined by a\nseries of anchor and control points. The first two parameters specify\nthe first anchor point and the last two parameters specify the other\nanchor point, which become the first and last points on the curve. The\nmiddle parameters specify the two control points which define the shape\nof the curve. Approximately speaking, control points "pull" the curve\ntowards them. x-coordinate for the first anchor point y-coordinate for the first anchor point x-coordinate for the first control point y-coordinate for the first control point x-coordinate for the second control point y-coordinate for the second control point x-coordinate for the second anchor point y-coordinate for the second anchor point z-coordinate for the first anchor point z-coordinate for the first control point z-coordinate for the second control point z-coordinate for the second anchor point Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this information. resolution of the curves Evaluates the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a bezier curve at t. coordinate of first point on the curve coordinate of first control point coordinate of second control point coordinate of second point on the curve value between 0 and 1 Evaluates the tangent to the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1. coordinate of first point on the curve coordinate of first control point coordinate of second control point coordinate of second point on the curve value between 0 and 1 Draws a curved line on the screen between two points, given as the\nmiddle four parameters. The first two parameters are a control point, as\nif the curve came from this point even though it's not drawn. The last\ntwo parameters similarly describe the other control point. x-coordinate for the beginning control point y-coordinate for the beginning control point x-coordinate for the first point y-coordinate for the first point x-coordinate for the second point y-coordinate for the second point x-coordinate for the ending control point y-coordinate for the ending control point z-coordinate for the beginning control point z-coordinate for the first point z-coordinate for the second point z-coordinate for the ending control point Sets the resolution at which curves display. The default value is 20 while the minimum value is 3. This function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this\ninformation. resolution of the curves Modifies the quality of forms created with curve() and curveVertex().\nThe parameter tightness determines how the curve fits to the vertex\npoints. The value 0.0 is the default value for tightness (this value\ndefines the curves to be Catmull-Rom splines) and the value 1.0 connects\nall the points with straight lines. Values within the range -5.0 and 5.0\nwill deform the curves but will leave them recognizable and as values\nincrease in magnitude, they will continue to deform. amount of deformation from the original vertices Evaluates the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are control points\nof the curve, and b and c are the start and end points of the curve.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a curve at t. coordinate of first control point of the curve coordinate of first point coordinate of second point coordinate of second control point value between 0 and 1 Evaluates the tangent to the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points on the curve,\nand b and c are the control points. coordinate of first point on the curve coordinate of first control point coordinate of second control point coordinate of second point on the curve value between 0 and 1 Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n Using the beginShape() and endShape() functions allow creating more\ncomplex forms. beginShape() begins recording vertices for a shape and\nendShape() stops recording. The value of the kind parameter tells it which\ntypes of shapes to create from the provided vertices. With no mode\nspecified, the shape can be any irregular polygon.\n either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, or QUAD_STRIP Specifies vertex coordinates for Bezier curves. Each call to\nbezierVertex() defines the position of two control points and\none anchor point of a Bezier curve, adding a new segment to a\nline or shape. For WebGL mode bezierVertex() can be used in 2D\nas well as 3D mode. 2D mode expects 6 parameters, while 3D mode\nexpects 9 parameters (including z coordinates).\n x-coordinate for the first control point y-coordinate for the first control point x-coordinate for the second control point y-coordinate for the second control point x-coordinate for the anchor point y-coordinate for the anchor point z-coordinate for the first control point (for WebGL mode) z-coordinate for the second control point (for WebGL mode) z-coordinate for the anchor point (for WebGL mode) Specifies vertex coordinates for curves. This function may only\nbe used between beginShape() and endShape() and only when there\nis no MODE parameter specified to beginShape().\nFor WebGL mode curveVertex() can be used in 2D as well as 3D mode.\n2D mode expects 2 parameters, while 3D mode expects 3 parameters.\n x-coordinate of the vertex y-coordinate of the vertex z-coordinate of the vertex (for WebGL mode) Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n The endShape() function is the companion to beginShape() and may only be\ncalled after beginShape(). When endShape() is called, all of image data\ndefined since the previous call to beginShape() is written into the image\nbuffer. The constant CLOSE as the value for the MODE parameter to close\nthe shape (to connect the beginning and the end). use CLOSE to close the shape Specifies vertex coordinates for quadratic Bezier curves. Each call to\nquadraticVertex() defines the position of one control points and one\nanchor point of a Bezier curve, adding a new segment to a line or shape.\nThe first time quadraticVertex() is used within a beginShape() call, it\nmust be prefaced with a call to vertex() to set the first anchor point.\nFor WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.\n2D mode expects 4 parameters, while 3D mode expects 6 parameters\n(including z coordinates).\n x-coordinate for the control point y-coordinate for the control point x-coordinate for the anchor point y-coordinate for the anchor point z-coordinate for the control point (for WebGL mode) z-coordinate for the anchor point (for WebGL mode) All shapes are constructed by connecting a series of vertices. vertex()\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the beginShape() and\nendShape() functions. x-coordinate of the vertex y-coordinate of the vertex z-coordinate of the vertex the vertex's texture u-coordinate the vertex's texture v-coordinate The default, two-dimensional renderer. One of the two render modes in p5.js: P2D (default renderer) and WEBGL\nEnables 3D render by introducing the third dimension: Z HALF_PI is a mathematical constant with the value\n1.57079632679489661923. It is half the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos(). PI is a mathematical constant with the value\n3.14159265358979323846. It is the ratio of the circumference\nof a circle to its diameter. It is useful in combination with\nthe trigonometric functions sin() and cos(). QUARTER_PI is a mathematical constant with the value 0.7853982.\nIt is one quarter the ratio of the circumference of a circle to\nits diameter. It is useful in combination with the trigonometric\nfunctions sin() and cos(). TAU is an alias for TWO_PI, a mathematical constant with the\nvalue 6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos(). TWO_PI is a mathematical constant with the value\n6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos(). Constant to be used with angleMode() function, to set the mode which\np5.js interprates and calculates angles (either DEGREES or RADIANS). Constant to be used with angleMode() function, to set the mode which\np5.js interprates and calculates angles (either RADIANS or DEGREES). AUTO allows us to automatically set the width or height of an element (but not both),\nbased on the current height and width of the element. Only one parameter can\nbe passed to the size function as AUTO, at a time. The print() function writes to the console area of your browser.\nThis function is often helpful for looking at the data a program is\nproducing. This function creates a new line of text for each call to\nthe function. Individual elements can be\nseparated with quotes ("") and joined with the addition operator (+). Note that calling print() without any arguments invokes the window.print()\nfunction which opens the browser's print dialog. To print a blank line\nto console you can write print('\\n'). any combination of Number, String, Object, Boolean,\n Array to print The system variable frameCount contains the number of frames that have\nbeen displayed since the program started. Inside setup() the value is 0,\nafter the first iteration of draw it is 1, etc. The system variable deltaTime contains the time\ndifference between the beginning of the previous frame and the beginning\nof the current frame in milliseconds.\n Confirms if the window a p5.js program is in is "focused," meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n"true" if the window is focused and "false" if not. Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16x16 or 32x32 pixels. The values for parameters x and y\nmust be less than the dimensions of the image. Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: 'grab', 'progress', 'cell' etc.\n External: path for cursor's images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor the horizontal active spot of the cursor (must be less than 32) the vertical active spot of the cursor (must be less than 32) Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default frame rate is based on the frame rate of the display\n(here also called "refresh rate"), which is set to 60 frames per second on most\ncomputers. A frame rate of 24 frames per second (usual for movies) or above\nwill be enough for smooth animations\nThis is the same as setFrameRate(val).\n number of frames to be displayed every second Hides the cursor from view. System variable that stores the width of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity. System variable that stores the height of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity. System variable that stores the width of the inner window, it maps to\nwindow.innerWidth. System variable that stores the height of the inner window, it maps to\nwindow.innerHeight. The windowResized() function is called once every time the browser window\nis resized. This is a good place to resize the canvas or do any other\nadjustments to accommodate the new window size. System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the createCanvas() function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\ncreateCanvas() is not used in a program. System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the createCanvas() function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\ncreateCanvas() is not used in a program. If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow. whether the sketch should be in fullscreen mode\nor not Sets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling pixelDensity() with no arguments returns\nthe current pixel density of the sketch. whether or how much the sketch should scale Returns the pixel density of the current display the sketch is running on. Gets the current URL. Gets the current URL path as an array. Gets the current URL params as an Object. Validates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments example:\n const a;\n ellipse(10,10,a,5);\nconsole ouput:\n "It looks like ellipse received an empty variable in spot #2." example:\n ellipse(10,"foo",5,5);\nconsole output:\n "ellipse was expecting a number for parameter #1,\n received "foo" instead." Prints out all the colors in the color pallete with white text.\nFor color blindness testing. Called directly before setup(), the preload() function is used to handle\nasynchronous loading of external files in a blocking way. If a preload\nfunction is defined, setup() will wait until any load calls within have\nfinished. Nothing besides load calls (loadImage, loadJSON, loadFont,\nloadStrings, etc.) should be inside the preload function. If asynchronous\nloading is preferred, the load methods can instead be called in setup()\nor anywhere else with the use of a callback parameter.\n The setup() function is called once when the program starts. It's used to\ndefine initial environment properties such as screen size and background\ncolor and to load media such as images and fonts as the program starts.\nThere can only be one setup() function for each program and it shouldn't\nbe called again after its initial execution.\n Called directly after setup(), the draw() function continuously executes\nthe lines of code contained inside its block until the program is stopped\nor noLoop() is called. Note if noLoop() is called in setup(), draw() will\nstill be executed once before stopping. draw() is called automatically and\nshould never be called explicitly.\n Removes the entire p5 sketch. This will remove the canvas and any\nelements created by p5.js. It will also stop the draw loop and unbind\nany properties or methods from the window global scope. It will\nleave a variable p5 in case you wanted to create a new p5 sketch.\nIf you like, you can set p5 = null to erase it. While all functions and\nvariables and objects created by the p5 library will be removed, any\nother global variables created by your code will remain. Allows for the friendly error system (FES) to be turned off when creating a sketch,\nwhich can give a significant boost to performance when needed.\nSee \ndisabling the friendly error system. Underlying HTML element. All normal HTML methods can be called on this. Attaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page. the ID, DOM node, or p5.Element\n of desired parent element Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.\n Note that only one element can have a particular id in a page.\n The .class() function can be used\n to identify multiple elements with the same class name. ID of the element Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element. class to add The .mousePressed() function is called once after every time a\nmouse button is pressed over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners. function to be fired when mouse is\n pressed over the element.\n if The .doubleClicked() function is called once after every time a\nmouse button is pressed twice over the element. This can be used to\nattach element and action specific event listeners. function to be fired when mouse is\n double clicked over the element.\n if The .mouseWheel() function is called once after every time a\nmouse wheel is scrolled over the element. This can be used to\nattach element specific event listeners.\n function to be fired when mouse is\n scrolled over the element.\n if The .mouseReleased() function is called once after every time a\nmouse button is released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners. function to be fired when mouse is\n released over the element.\n if The .mouseClicked() function is called once after a mouse button is\npressed and released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners. function to be fired when mouse is\n clicked over the element.\n if The .mouseMoved() function is called once every time a\nmouse moves over the element. This can be used to attach an\nelement specific event listener. function to be fired when a mouse moves\n over the element.\n if The .mouseOver() function is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement specific event listener. function to be fired when a mouse moves\n onto the element.\n if The .mouseOut() function is called once after every time a\nmouse moves off the element. This can be used to attach an\nelement specific event listener. function to be fired when a mouse\n moves off of an element.\n if The .touchStarted() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners. function to be fired when a touch\n starts over the element.\n if The .touchMoved() function is called once after every time a touch move is\nregistered. This can be used to attach element specific event listeners. function to be fired when a touch moves over\n the element.\n if The .touchEnded() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners. function to be fired when a touch ends\n over the element.\n if The .dragOver() function is called once after every time a\nfile is dragged over the element. This can be used to attach an\nelement specific event listener. function to be fired when a file is\n dragged over the element.\n if The .dragLeave() function is called once after every time a\ndragged file leaves the element area. This can be used to attach an\nelement specific event listener. function to be fired when a file is\n dragged off the element.\n if Helper fxn for sharing pixel methods Resets certain values such as those modified by functions in the Transform category\nand in the Lights category that are not automatically reset\nwith graphics buffer objects. Calling this in draw() will copy the behavior\nof the standard canvas. Removes a Graphics object from the page and frees any resources\nassociated with it. Resize our canvas element. Helper fxn to check font type (system or otf) Helper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178 p5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer Generate a cubic Bezier representing an arc on the unit circle of total\nangle See www.joecridge.me/bezier.pdf for an explanation of the method. Creates and names a new variable. A variable is a container for a value. Variables that are declared with let will have block-scope.\nThis means that the variable only exists within the \nblock that it is created within. From the MDN entry:\nDeclares a block scope local variable, optionally initializing it to a value. Creates and names a new constant. Like a variable created with let, a constant\nthat is created with const is a container for a value,\nhowever constants cannot be changed once they are declared. Constants have block-scope. This means that the constant only exists within\nthe \nblock that it is created within. A constant cannot be redeclared within a scope in which it\nalready exists. From the MDN entry:\nDeclares a read-only named constant.\nConstants are block-scoped, much like variables defined using the 'let' statement.\nThe value of a constant can't be changed through reassignment, and it can't be redeclared. The strict equality operator ===\nchecks to see if two values are equal and of the same type. A comparison expression always evaluates to a boolean. From the MDN entry:\nThe non-identity operator returns true if the operands are not equal and/or not of the same type. Note: In some examples around the web you may see a double-equals-sign\n==,\nused for comparison instead. This is the non-strict equality operator in Javascript.\nThis will convert the two values being compared to the same type before comparing them. The greater than operator >\nevaluates to true if the left value is greater than\nthe right value. There is more info on comparison operators on MDN. The greater than or equal to operator >=\nevaluates to true if the left value is greater than or equal to\nthe right value. There is more info on comparison operators on MDN. The less than operator <\nevaluates to true if the left value is less than\nthe right value. There is more info on comparison operators on MDN. The less than or equal to operator <=\nevaluates to true if the left value is less than or equal to\nthe right value. There is more info on comparison operators on MDN. The if-else statement helps control the flow of your code. A condition is placed between the parenthesis following 'if',\nwhen that condition evalues to truthy,\nthe code between the following curly braces is run.\nAlternatively, when the condition evaluates to falsy,\nthe code between the curly braces that follow 'else' is run instead. From the MDN entry:\nThe 'if' statement executes a statement if a specified condition is truthy.\nIf the condition is falsy, another statement can be executed Creates and names a function.\nA function is a set of statements that perform a task. Optionally, functions can have parameters. Parameters\nare variables that are scoped to the function, that can be assigned a value when calling the function. From the MDN entry:\nDeclares a function with the specified parameters. Specifies the value to be returned by a function.\nFor more info checkout \nthe MDN entry for return. A boolean is one of the 7 primitive data types in Javascript.\nA boolean can only be From the MDN entry:\nBoolean represents a logical entity and can have two values: true, and false. A string is one of the 7 primitive data types in Javascript.\nA string is a series of text characters. In Javascript, a string value must be surrounded by either single-quotation marks(') or double-quotation marks("). From the MDN entry:\nA string is a sequence of characters used to represent text. A number is one of the 7 primitive data types in Javascript.\nA number can be a whole number or a decimal number. From MDN's object basics:\n An object is a collection of related data and/or functionality (which usually consists of several variables and functions —\n which are called properties and methods when they are inside objects.) Creates and names a class which is a template for the creation of objects. From the MDN entry:\nThe class declaration creates a new Class with a given name using prototype-based inheritance. for creates a loop that is useful for executing one section of code multiple times. A 'for loop' consists of three different expressions inside of a parenthesis, all of which are optional.\nThese expressions are used to control the number of times the loop is run.\nThe first expression is a statement that is used to set the initial state for the loop.\nThe second expression is a condition that you would like to check before each loop. If this expression returns\nfalse then the loop will exit.\nThe third expression is executed at the end of each loop. The code inside of the loop body (in between the curly braces) is executed between the evaluation of the second\nand third expression. As with any loop, it is important to ensure that the loop can 'exit', or that\nthe test condition will eventually evaluate to false. The test condition with a for loop\nis the second expression detailed above. Ensuring that this expression can eventually\nbecome false ensures that your loop doesn't attempt to run an infinite amount of times,\nwhich can crash your browser. From the MDN entry:\nCreates a loop that executes a specified statement until the test condition evaluates to false.\nThe condition is evaluated after executing the statement, resulting in the specified statement executing at least once. while creates a loop that is useful for executing one section of code multiple times. With a 'while loop', the code inside of the loop body (between the curly braces) is run repeatedly until the test condition\n(inside of the parenthesis) evaluates to false. Unlike a for loop, the condition is tested before executing the code body with while,\nso if the condition is initially false the loop body, or statement, will never execute. As with any loop, it is important to ensure that the loop can 'exit', or that\nthe test condition will eventually evaluate to false. This is to keep your loop from trying to run an infinite amount of times,\nwhich can crash your browser. From the MDN entry:\nThe while statement creates a loop that executes a specified statement as long as the test condition evaluates to true.\nThe condition is evaluated before executing the statement. From the MDN entry:\nThe JSON.stringify() method converts a JavaScript object or value to a JSON string. :Javascript object that you would like to convert to JSON Prints a message to your browser's web console. When using p5, you can use print\nand console.log interchangeably. The console is opened differently depending on which browser you are using.\nHere are links on how to open the console in Firefox\n, Chrome, Edge,\nand Safari. With the online p5 editor the\nconsole is embedded directly in the page underneath the code editor. From the MDN entry:\nThe Console method log() outputs a message to the web console. The message may be a single string (with optional substitution values),\nor it may be any one or more JavaScript objects. :Message that you would like to print to the console Creates a canvas element in the document, and sets the dimensions of it\nin pixels. This method should be called only once at the start of setup.\nCalling createCanvas more than once in a sketch will result in very\nunpredictable behavior. If you want more than one drawing canvas\nyou could use createGraphics (hidden by default but it can be shown).\n width of the canvas height of the canvas either P2D or WEBGL Resizes the canvas to given width and height. The canvas will be cleared\nand draw will be called immediately, allowing the sketch to re-render itself\nin the resized canvas. width of the canvas height of the canvas don't redraw the canvas immediately Removes the default canvas for a p5 sketch that doesn't\nrequire a canvas Creates and returns a new p5.Renderer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. width of the offscreen graphics buffer height of the offscreen graphics buffer either P2D or WEBGL\nundefined defaults to p2d Blends the pixels in the display window according to the defined mode.\nThere is a choice of the following modes to blend the source pixels (A)\nwith the ones of pixels already in the display window (B): blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT shim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution. this is implementation of Object.assign() which is unavailable in\nIE11 and (non-Chrome) Android browsers.\nThe assign() method is used to copy the values of all enumerable\nown properties from one or more source objects to a target object.\nIt will return the target object.\nModified from https://github.com/ljharb/object.assign Stops p5.js from continuously executing the code within draw().\nIf loop() is called, the code in draw() begins to run continuously again.\nIf using noLoop() in setup(), it should be the last line inside the block.\n By default, p5.js loops through draw() continuously, executing the code\nwithin it. However, the draw() loop may be stopped by calling noLoop().\nIn that case, the draw() loop can be resumed with loop(). Avoid calling loop() from inside setup(). The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n Executes the code within draw() one time. This functions allows the\n program to update the display window only when necessary, for example\n when an event registered by mousePressed() or keyPressed() occurs.\n Redraw for n-times. The default value is 1. Multiplies the current matrix by the one specified through the parameters.\nThis is a powerful operation that can perform the equivalent of translate,\nscale, shear and rotate all at once. You can learn more about transformation\nmatrices on \nWikipedia. The naming of the arguments here follows the naming of the \nWHATWG specification and corresponds to a\ntransformation matrix of the\nform: numbers which define the 2x3 matrix to be multiplied numbers which define the 2x3 matrix to be multiplied numbers which define the 2x3 matrix to be multiplied numbers which define the 2x3 matrix to be multiplied numbers which define the 2x3 matrix to be multiplied numbers which define the 2x3 matrix to be multiplied Replaces the current matrix with the identity matrix. Rotates a shape the amount specified by the angle parameter. This\nfunction accounts for angleMode, so angles can be entered in either\nRADIANS or DEGREES.\n the angle of rotation, specified in radians\n or degrees, depending on current angleMode (in 3d) the axis to rotate around Rotates around X axis. the angle of rotation, specified in radians\n or degrees, depending on current angleMode Rotates around Y axis. the angle of rotation, specified in radians\n or degrees, depending on current angleMode Rotates around Z axis. Webgl mode only. the angle of rotation, specified in radians\n or degrees, depending on current angleMode Increases or decreases the size of a shape by expanding and contracting\nvertices. Objects always scale from their relative origin to the\ncoordinate system. Scale values are specified as decimal percentages.\nFor example, the function call scale(2.0) increases the dimension of a\nshape by 200%.\n percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given percent to scale the object in the y-axis percent to scale the object in the z-axis (webgl only) per-axis percents to scale the object Shears a shape around the x-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode.\nObjects are always sheared around their relative position to the origin\nand positive numbers shear objects in a clockwise direction.\n angle of shear specified in radians or degrees,\n depending on current angleMode Shears a shape around the y-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode. Objects\nare always sheared around their relative position to the origin and\npositive numbers shear objects in a clockwise direction.\n angle of shear specified in radians or degrees,\n depending on current angleMode Specifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.\n left/right translation up/down translation forward/backward translation (webgl only) the vector to translate by Stores a value in local storage under the key name.\n Local storage is saved in the browser and persists\n between browsing sessions and page reloads.\n The key can be the name of the variable but doesn't\n have to be. To retrieve stored items\n see getItem.\n Returns the value of an item that was stored in local storage\n using storeItem() name that you wish to use to store in local storage Clears all local storage items set with storeItem()\n for the current domain. Removes an item that was stored with storeItem() Creates a new instance of p5.StringDict using the key-value pair\n or the object you provide. object Creates a new instance of p5.NumberDict using the key-value pair\n or object you provide. object Returns the number of key-value pairs currently stored in the Dictionary. Returns true if the given key exists in the Dictionary,\notherwise returns false. that you want to look up Returns the value stored at the given key. key you want to access Updates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added. private helper function to handle the user passing in objects\nduring construction or calls to create() Creates a new key-value pair in the Dictionary. key/value pair Removes all previously stored key-value pairs from the Dictionary. Removes the key-value pair stored at the given key from the Dictionary. for the pair to remove Logs the set of items currently stored in the Dictionary to the console. Converts the Dictionary into a CSV file for local download. Converts the Dictionary into a JSON file for local download. private helper function to ensure that the user passed in valid\nvalues for the Dictionary type private helper function to ensure that the user passed in valid\nvalues for the Dictionary type Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary. for the value you wish to add to to add to the value Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary. for the value you wish to subtract from to subtract from the value Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary. for value you wish to multiply to multiply the value by Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary. for value you wish to divide to divide the value by private helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than' Return the lowest number currently stored in the Dictionary. Return the highest number currently stored in the Dictionary. private helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than' Return the lowest key currently used in the Dictionary. Return the highest key currently used in the Dictionary. Searches the page for an element with the given ID, class, or tag name (using the '#' or '.'\nprefixes to specify an ID or class respectively, and none for a tag) and returns it as\na p5.Element. If a class or tag name is given with more than 1 element,\nonly the first element will be returned.\nThe DOM node itself can be accessed with .elt.\nReturns null if none found. You can also specify a container to search within. id, class, or tag name of element to search for id, p5.Element, or\n HTML element to search within Searches the page for elements with the given class or tag name (using the '.' prefix\nto specify a class and no prefix for a tag) and returns them as p5.Elements\nin an array.\nThe DOM node itself can be accessed with .elt.\nReturns an empty array if none found.\nYou can also specify a container to search within. class or tag name of elements to search for id, p5.Element, or HTML element to search within Helper function for select and selectAll Helper function for getElement and getElements. Removes all elements created by p5, except any canvas / graphics\nelements created by createCanvas or createGraphics.\nEvent handlers are removed, and element is removed from the DOM. The .changed() function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener. function to be fired when the value of\n an element changes.\n if The .input() function is called when any user input is\ndetected with an element. The input event is often used\nto detect keystrokes in a input element, or changes on a\nslider element. This can be used to attach an element specific\nevent listener. function to be fired when any user input is\n detected within the element.\n if Helpers for create methods. Creates a <div></div> element in the DOM with given inner HTML. inner HTML for element created Creates a <p></p> element in the DOM with given inner HTML. Used\nfor paragraph length text. inner HTML for element created Creates a <span></span> element in the DOM with given inner HTML. inner HTML for element created Creates an <img> element in the DOM with given src and\nalternate text. src path or url for image alternate text to be used if image does not load. You can use also an empty string ( crossOrigin property of the callback to be called once image data is loaded Creates an <a></a> element in the DOM for including a hyperlink. url of page to link to inner html of link element to display target where new link should open,\n could be _blank, _self, _parent, _top. Creates a slider <input></input> element in the DOM.\nUse .size() to set the display length of the slider. minimum value of the slider maximum value of the slider default value of the slider step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) Creates a <button></button> element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press. label displayed on the button value of the button Creates a checkbox <input></input> element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not label displayed after checkbox value of the checkbox; checked is true, unchecked is false Creates a dropdown menu <select></select> element in the DOM.\nIt also helps to assign select-box methods to p5.Element when selecting existing select box true if dropdown should support multiple selections DOM select element Creates a radio button <input></input> element in the DOM.\nThe .option() method can be used to set options for the radio after it is\ncreated. The .value() method will return the currently selected option. the id and name of the created div and input field respectively Creates a colorPicker element in the DOM for color input.\nThe .value() method will return a hex string (#rrggbb) of the color.\nThe .color() method will return a p5.Color object with the current chosen color. default color of element Creates an <input></input> element in the DOM for text input.\nUse .size() to set the display length of the box. default value of the input box type of text, ie text, password etc. Defaults to text Creates an <input></input> element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch. callback function for when a file loaded optional to allow multiple files selected Creates an HTML5 <video> element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using video(). The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats. path to a video file, or array of paths for\n supporting different browsers callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content Creates a hidden HTML5 <audio> element in the DOM for simple audio\nplayback. The first parameter can be either a single string path to a\naudio file, or an array of string paths to different formats of the same\naudio. This is useful for ensuring that your audio can play across\ndifferent browsers, as each supports different formats.\nSee this\npage for further information about supported formats. path to an audio file, or array of paths\n for supporting different browsers callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content Creates a new HTML5 <video> element that contains the audio/video\nfeed from a webcam. The element is separate from the canvas and is\ndisplayed by default. The element can be hidden using .hide(). The feed\ncan be drawn onto the canvas using image(). The loadedmetadata property can\nbe used to detect when the element has fully loaded (see second example). More specific properties of the feed can be passing in a Constraints object.\nSee the\n W3C\nspec for possible properties. Note that not all of these are supported\nby all browsers. Security note: A new browser security specification requires that getUserMedia,\nwhich is behind createCapture(), only works when you're running the code locally,\nor on HTTPS. Learn more here\nand here. type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object function to be called once\n stream has loaded Creates element with given tag in the DOM with given content. tag for the new element html content to be inserted into the element Adds specified class to the element. name of class to add Removes specified class from the element. name of class to remove Checks if specified class already set to element class name of class to check Toggles element class class name to toggle Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned. the ID, DOM node, or p5.Element\n to add to the current element Centers a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally. passing 'vertical', 'horizontal' aligns element accordingly If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If true is included as a second\n argument, html is appended instead of replacing existing html.\n If no arguments are given, returns\n the inner HTML of the element. the HTML to be placed inside the element whether to append HTML to existing Sets the position of the element relative to (0, 0) of the\n window. Essentially, sets position:absolute and left and top\n properties of style. If no arguments given returns the x and y position\n of the element in an object. x-position relative to upper left of window y-position relative to upper left of window Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriately. property to be set value to assign to property Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set. attribute to set value to assign to attribute Removes an attribute on the specified element. attribute to remove Either returns the value of the element if no arguments\ngiven, or sets the value of the element. Shows the current element. Essentially, setting display:block for the style. Hides the current element. Essentially, setting display:none for the style. Sets the width and height of the element. AUTO can be used to\n only adjust one dimension at a time. If no arguments are given, it\n returns the width and height of the element in an object. In case of\n elements which need to be loaded, such as images, it is recommended\n to call the function after the element has finished loading. width of the element, either AUTO, or a number height of the element, either AUTO, or a number Removes the element and deregisters all listeners. Registers a callback that gets called every time a file that is\ndropped on the element has been loaded.\np5 will load every dropped file into memory and pass it as a p5.File object to the callback.\nMultiple files dropped at the same time will result in multiple calls to the callback. You can optionally pass a second callback which will be registered to the raw\ndrop event.\nThe callback will thus be provided the original\nDragEvent.\nDropping multiple files at the same time will trigger the second callback once per drop,\nwhereas the first callback will trigger for each loaded file. callback to receive loaded file, called for each file dropped. callback triggered once when files are dropped with the drop event. Path to the media element source. Play an HTML5 media element. Stops an HTML5 media element (sets current time to zero). Pauses an HTML5 media element. Set 'loop' to true for an HTML5 media element, and starts playing. Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end. Set HTML5 media element to autoplay or not. whether the element should autoplay Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume. volume between 0.0 and 1.0 If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.) speed multiplier for element playback If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it. time to jump to (in seconds) Returns the duration of the HTML5 media element. Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback. function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback. Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5's master\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method. This method is meant to be used with the p5.sound.js addon library. AudioNode from the Web Audio API,\nor an object from the p5.sound library Disconnect all Web Audio routing, including to master output.\nThis is useful if you want to re-route the output through\naudio effects, for example. Show the default MediaElement controls, as determined by the web browser. Hide the default mediaElement controls. Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point. Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback. Time will be passed as the first parameter to the callback function,\nand param will be the second parameter. Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function. Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters. An object to be passed as the\n second parameter to the\n callback function. Remove a callback based on its ID. The ID is returned by the\naddCue method. ID of the cue, as returned by addCue Remove all of the callbacks that had originally been scheduled\nvia the addCue method. ID of the cue, as returned by addCue Underlying File object. All normal File methods can be called on this. File type (image, text, etc.) File subtype (usually the file extension jpg, png, xml, etc.) File name File size URL string containing image data. The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.\neither LANDSCAPE or PORTRAIT. The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared. The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared. The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared. The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared. The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared. The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared. The system variable rotationX always contains the rotation of the\ndevice along the x axis. Value is represented as 0 to +/-180 degrees.\n The system variable rotationY always contains the rotation of the\ndevice along the y axis. Value is represented as 0 to +/-90 degrees.\n The system variable rotationZ always contains the rotation of the\ndevice along the z axis. Value is represented as 0 to 359 degrees.\n The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as 0 to +/-180 degrees.\n The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as 0 to +/-90 degrees.\n The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as 0 to 359 degrees.\n When a device is rotated, the axis that triggers the deviceTurned()\nmethod is stored in the turnAxis variable. The turnAxis variable is only defined within\nthe scope of deviceTurned(). The setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5. The threshold value The setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30. The threshold value The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to 0.5.\nThe threshold value can be changed using setMoveThreshold(). The deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.\n The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.\nThe threshold value can be changed using setShakeThreshold(). The boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed. The system variable key always contains the value of the most recent\nkey on the keyboard that was typed. To get the proper capitalization, it\nis best to use it within keyTyped(). For non-ASCII keys, use the keyCode\nvariable. The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: keycode.info. The keyPressed() function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the keyCode variable.\n The keyReleased() function is called once every time a key is released.\nSee key and keyCode for more information. The keyTyped() function is called once every time a key is pressed, but\naction keys such as Backspace, Delete, Ctrl, Shift, and Alt are ignored. If you are trying to detect\na keyCode for one of these keys, use the keyPressed() function instead.\nThe most recent key typed will be stored in the key variable.\n The onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released. The keyIsDown() function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable keyCode names listed\nhere. The key to check for. The variable movedX contains the horizontal movement of the mouse since the last frame The variable movedY contains the vertical movement of the mouse since the last frame The system variable mouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the canvas. The value at\nthe top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.\nIf touch is used instead of mouse input, mouseX will hold the x value\nof the most recent touch point. The system variable mouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the canvas. The value at\nthe top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.\nIf touch is used instead of mouse input, mouseY will hold the y value\nof the most recent touch point. The system variable pmouseX always contains the horizontal position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and\n(-width/2, -height/2) for WebGL. Note: pmouseX will be reset to the current mouseX\nvalue at the start of each touch event. The system variable pmouseY always contains the vertical position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and\n(-width/2, -height/2) for WebGL. Note: pmouseY will be reset to the current mouseY\nvalue at the start of each touch event. The system variable winMouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the window. The system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window. The system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX\nvalue at the start of each touch event. The system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window. Note: pwinMouseY will be reset to the current winMouseY\nvalue at the start of each touch event. Processing automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently. The boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not. The mouseMoved() function is called every time the mouse moves and a mouse\nbutton is not pressed. optional MouseEvent callback argument. The mouseDragged() function is called once every time the mouse moves and\na mouse button is pressed. If no mouseDragged() function is defined, the\ntouchMoved() function will be called instead if it is defined. optional MouseEvent callback argument. The mousePressed() function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\nmousePressed() function is defined, the touchStarted() function will be\ncalled instead if it is defined. optional MouseEvent callback argument. The mouseReleased() function is called every time a mouse button is\nreleased. If no mouseReleased() function is defined, the touchEnded()\nfunction will be called instead if it is defined. optional MouseEvent callback argument. The mouseClicked() function is called once after a mouse button has been\npressed and then released. optional MouseEvent callback argument. The doubleClicked() function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse's primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla's documentation here:\nhttps://developer.mozilla.org/en-US/docs/Web/Events/dblclick optional MouseEvent callback argument. The function mouseWheel() is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad. optional WheelEvent callback argument. The function requestPointerLock()\nlocks the pointer to its current position and makes it invisible.\nUse movedX and movedY to get the difference the mouse was moved since\nthe last call of draw Note that not all browsers support this feature This enables you to create experiences that aren\'t limited by the mouse moving out of the screen\neven if it is repeatedly moved into one direction. For example a first person perspective experience The function exitPointerLock()\nexits a previously triggered pointer Lock\nfor example to make ui elements usable etc',
+ itemtype: 'method',
+ name: 'exitPointerLock',
+ example: [
+ '\n The system variable touches[] contains an array of the positions of all\ncurrent touch points, relative to (0, 0) of the canvas, and IDs identifying a\nunique touch as it moves. Each element in the array is an object with x, y,\nand id properties. The touches[] array is not supported on Safari and IE on touch-based\ndesktops (laptops). The touchStarted() function is called once after every time a touch is\nregistered. If no touchStarted() function is defined, the mousePressed()\nfunction will be called instead if it is defined. optional TouchEvent callback argument. The touchMoved() function is called every time a touch move is registered.\nIf no touchMoved() function is defined, the mouseDragged() function will\nbe called instead if it is defined. optional TouchEvent callback argument. The touchEnded() function is called every time a touch ends. If no\ntouchEnded() function is defined, the mouseReleased() function will be\ncalled instead if it is defined. optional TouchEvent callback argument. This module defines the filters for use with image buffers. This module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy. Generally speaking users of this module will use the Filters.apply method\non a canvas to create an effect. A number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation. This module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas. Creates a new p5.Image (the datatype for storing images). This provides a\nfresh buffer of pixels to play with. Set the size of the buffer with the\nwidth and height parameters.\n width in pixels height in pixels Save the current canvas as an image. The browser will either save the\nfile immediately, or prompt the user with a dialogue window. a variable\n representing a specific html5 canvas (optional) 'jpg' or 'png' Capture a sequence of frames that can be used to create a movie.\nAccepts a callback. For example, you may wish to send the frames\nto a server where they can be stored or converted into a movie.\nIf no callback is provided, the browser will pop up save dialogues in an\nattempt to download all of the images that have just been created. With the\ncallback provided the image data isn't saved by default but instead passed\nas an argument to the callback function as an array of objects, with the\nsize of array equal to the total number of frames. Note that saveFrames() will only save the first 15 frames of an animation.\nTo export longer animations, you might look into a library like\nccapture.js. 'jpg' or 'png' Duration in seconds to save the frames for. Framerate to save the frames in. A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension. Loads an image from a path and creates a p5.Image from it.\n Path of the image to be loaded Function to be called once\n the image is loaded. Will be passed the\n p5.Image. called with event error if\n the image fails to load. Helper function for loading GIF-based images Draw an image to the p5.js canvas. This function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image. This function can also be used with all eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n"destination rectangle" (which corresponds to "dx", "dy", etc.) and "source\nimage" (which corresponds to "sx", "sy", etc.) below. Specifying the\n"source image" dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here's a diagram\nto explain further:\n the image to display the x-coordinate of the top-left corner of the image the y-coordinate of the top-left corner of the image the width to draw the image the height to draw the image the x-coordinate of the destination\n rectangle in which to draw the source image the y-coordinate of the destination\n rectangle in which to draw the source image the width of the destination rectangle the height of the destination rectangle the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle the width of the subsection of the\n source image to draw into the destination\n rectangle the height of the subsection of the\n source image to draw into the destination rectangle Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.\n red or hue value relative to\n the current color range green or saturation value\n relative to the current color range blue or brightness value\n relative to the current color range a color string a gray value an array containing the red,green,blue &\n and alpha components of the color the tint color Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues. Set image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.\n either CORNER, CORNERS, or CENTER This module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas. Image width. Image height. Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y): Helper function for animating GIF-based images with time Helper fxn for sharing pixel methods Loads the pixels data for this image into the [pixels] attribute. Updates the backing canvas for this image with the contents of\nthe [pixels] array.\n x-offset of the target update area for the\n underlying canvas y-offset of the target update area for the\n underlying canvas height of the target update area for the\n underlying canvas height of the target update area for the\n underlying canvas Get a region of pixels from an image. If no params are passed, the whole image is returned.\nIf x and y are the only params passed a single pixel is extracted.\nIf all params are passed a rectangle region is extracted and a p5.Image\nis returned. x-coordinate of the pixel y-coordinate of the pixel width height Set the color of a single pixel or write an image into\nthis p5.Image. Note that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels(). x-coordinate of the pixel y-coordinate of the pixel grayscale value | pixel array |\n a p5.Color | image to copy Resize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0). the resized image width the resized image height Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region. source image X coordinate of the source's upper left corner Y coordinate of the source's upper left corner source image width source image height X coordinate of the destination's upper left corner Y coordinate of the destination's upper left corner destination image width destination image height Masks part of an image from displaying by loading another\nimage and using it's alpha channel as an alpha channel for\nthis image. source image Applies an image filter to a p5.Image either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter an optional parameter unique\n to each filter, see above Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation. source image X coordinate of the source's upper left corner Y coordinate of the source's upper left corner source image width source image height X coordinate of the destination's upper left corner Y coordinate of the destination's upper left corner destination image width destination image height the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. Available blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default), jpg, and gif\n give your file a name 'png' or 'jpg' Starts an animated GIF over at the beginning state. Gets the index for the frame that is currently visible in an animated GIF. Sets the index of the frame that is currently visible in an animated GIF the index for the frame that should be displayed Returns the number of frames in an animated GIF Plays an animated GIF that was paused with\npause() Pauses an animated GIF. Changes the delay between frames in an animated GIF the amount in milliseconds to delay between switching frames Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n While the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation. source image X coordinate of the source's upper left corner Y coordinate of the source's upper left corner source image width source image height X coordinate of the destination's upper left corner Y coordinate of the destination's upper left corner destination image width destination image height the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. Copies a region of the canvas to another region of the canvas\nand copies a region of pixels from an image used as the srcImg parameter\ninto the canvas srcImage is specified this is used as the source. If\nthe source and destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region. source image X coordinate of the source's upper left corner Y coordinate of the source's upper left corner source image width source image height X coordinate of the destination's upper left corner Y coordinate of the destination's upper left corner destination image width destination image height Applies a filter to the canvas.\n The presets options are:\n THRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n GRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.\n OPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.\n INVERT\nSets each pixel to its inverse value. No parameter is used.\n POSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n BLUR\nExecutes a Gaussian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGaussian blur of radius 1. Larger values increase the blur.\n ERODE\nReduces the light areas. No parameter is used.\n DILATE\nIncreases the light areas. No parameter is used. either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter an optional parameter unique\n to each filter, see above Get a region of pixels, or a single pixel, from the canvas. Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n See the reference for pixels[] for more information. If you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at p5.Image.get() x-coordinate of the pixel y-coordinate of the pixel width height Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].\nNote that only changes made with set() or direct manipulation of pixels[]\nwill occur. Changes the color of any pixel, or writes an image directly to the\ndisplay window. The x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().\n \nAfter using set(), you must call updatePixels() for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .get() or drawing the image.\n Setting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop. See the reference for pixels[] for more information. x-coordinate of the pixel y-coordinate of the pixel insert a grayscale value | a pixel array |\n a p5.Color object | a p5.Image to copy Updates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called, and only changes made with\nset() or direct changes to pixels[] will occur. x-coordinate of the upper-left corner of region\n to update y-coordinate of the upper-left corner of region\n to update width of region to update height of region to update Loads a JSON file from a file or a URL, and returns an Object.\nNote that even if the JSON file contains an Array, an Object will be\nreturned with index numbers as keys. This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. JSONP is supported via a polyfill and you\ncan pass in as the second argument an object with definitions of the json\ncallback following the syntax specified here. This method is suitable for fetching files up to size of 64MB. Calling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called. Outside of preload(), you may supply a callback function to handle the\nobject: name of the file or url to load options object for jsonp related settings "json" or "jsonp" function to be executed after\n loadJSON() completes, data is passed\n in as first argument function to be executed if\n there is an error, response is passed\n in as first argument Reads the contents of a file and creates a String array of its individual\nlines. If the name of the file is used as the parameter, as in the above\nexample, the file must be located in the sketch directory/folder.\n This method is suitable for fetching files up to size of 64MB. name of the file or url to load function to be executed after loadStrings()\n completes, Array is passed in as first\n argument function to be executed if\n there is an error, response is passed\n in as first argument Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called. Outside of preload(), you may supply a callback function to handle the\nobject: Reads the contents of a file or URL and creates a p5.Table object with\nits values. If a file is specified, it must be located in the sketch\'s\n"data" folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the \'header\' option is\nincluded. Possible options include:\n
\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n
\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n
\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.
\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n
\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.
\np5.SoundFile: Load and play sound files.
\np5.Amplitude: Get the current volume of a sound.
\np5.AudioIn: Get sound from an input source, typically\n a computer microphone.
\np5.FFT: Analyze the frequency of sound. Returns\n results from the frequency spectrum or time domain (waveform).
\np5.Oscillator: Generate Sine,\n Triangle, Square and Sawtooth waveforms. Base class of\n p5.Noise and p5.Pulse.\n
\np5.Envelope: An Envelope is a series\n of fades over time. Often used to control an object's\n output gain level as an "ADSR Envelope" (Attack, Decay,\n Sustain, Release). Can also modulate other parameters.
\np5.Delay: A delay effect with\n parameters for feedback, delayTime, and lowpass filter.
\np5.Filter: Filter the frequency range of a\n sound.\n
\np5.Reverb: Add reverb to a sound by specifying\n duration and decay.
\np5.Convolver: Extends\np5.Reverb to simulate the sound of real\n physical spaces through convolution.
\np5.SoundRecorder: Record sound for playback\n / save the .wav file.\np5.Phrase, p5.Part and\np5.Score: Compose musical sequences.\n
\np5.sound is on GitHub.\nDownload the latest version\nhere.
\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n
\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n
\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.\nfunction setup() {\n let img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n let index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n let x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n let red = random(255);\n let green = random(255);\n let blue = random(255);\n let alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let children = xml.getChildren(\'animal\');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum(\'id\');\n let coloring = children[i].getString(\'species\');\n let name = children[i].getContent();\n print(id + \', \' + coloring + \', \' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n
\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.\nlet v1 = createVector(40, 50);\nlet v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n\n \nlet sound, amplitude, cnv;\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n cnv = createCanvas(100,100);\n amplitude = new p5.Amplitude();\n\n // start / stop the sound when canvas is clicked\n cnv.mouseClicked(function() {\n if (sound.isPlaying() ){\n sound.stop();\n } else {\n sound.play();\n }\n });\n}\nfunction draw() {\n background(0);\n fill(255);\n let level = amplitude.getLevel();\n let size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\n
• FFT.waveform() computes\namplitude values along the time domain. The array indices correspond\nto samples across a brief moment in time. Each value represents\namplitude of the waveform at that sample of time.
\n• FFT.analyze() computes amplitude values along the\nfrequency domain. The array indices correspond to frequencies (i.e.\npitches), from the lowest to the highest that humans can hear. Each\nvalue represents amplitude at that slice of the frequency spectrum.\nUse with getEnergy() to measure amplitude at specific\nfrequencies, or within a range of frequencies. bins. The array is 1024 bins long by default.\nYou can change the bin array length, but it must be a power of 2\nbetween 16 and 1024 in order for the FFT algorithm to function\ncorrectly. The actual size of the FFT buffer is twice the\nnumber of bins, so given a standard sample rate, the buffer is\n2048/44100 seconds long.\nfunction preload(){\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup(){\n let cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n fft = new p5.FFT();\n sound.amp(0.2);\n}\n\nfunction draw(){\n background(0);\n\n let spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n let x = map(i, 0, spectrum.length, 0, width);\n let h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h )\n }\n\n let waveform = fft.waveform();\n noFill();\n beginShape();\n stroke(255,0,0); // waveform is red\n strokeWeight(1);\n for (var i = 0; i< waveform.length; i++){\n let x = map(i, 0, waveform.length, 0, width);\n let y = map( waveform[i], -1, 1, 0, height);\n vertex(x,y);\n }\n endShape();\n\n text('click to play/pause', 4, 10);\n}\n\n// fade sound if mouse is over canvas\nfunction togglePlay() {\n if (sound.isPlaying()) {\n sound.pause();\n } else {\n sound.loop();\n }\n}\n\nfunction setup() {\n carrier = new p5.Oscillator('sine');\n carrier.amp(1); // set amplitude\n carrier.freq(220); // set frequency\n carrier.start(); // start oscillating\n\n modulator = new p5.Oscillator('sawtooth');\n modulator.disconnect();\n modulator.amp(1);\n modulator.freq(4);\n modulator.start();\n\n // Modulator's default amplitude range is -1 to 1.\n // Multiply it by -200, so the range is -200 to 200\n // then add 220 so the range is 20 to 420\n carrier.freq( modulator.mult(-200).add(220) );\n}\n\nlet osc;\nlet playing = false;\n\nfunction setup() {\n backgroundColor = color(255,0,255);\n textAlign(CENTER);\n\n osc = new p5.Oscillator();\n osc.setType('sine');\n osc.freq(240);\n osc.amp(0);\n osc.start();\n}\n\nfunction draw() {\n background(backgroundColor)\n text('click to play', width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n if (!playing) {\n // ramp amplitude to 0.5 over 0.05 seconds\n osc.amp(0.5, 0.05);\n playing = true;\n backgroundColor = color(0,255,255);\n } else {\n // ramp amplitude to 0 over 0.5 seconds\n osc.amp(0, 0.5);\n playing = false;\n backgroundColor = color(255,0,255);\n }\n }\n}\n new p5.SinOsc().\nThis creates a Sine Wave Oscillator and is\nequivalent to new p5.Oscillator('sine')\n or creating a p5.Oscillator and then calling\nits method setType('sine').\nSee p5.Oscillator for methods.new p5.TriOsc().\nThis creates a Triangle Wave Oscillator and is\nequivalent to new p5.Oscillator('triangle')\n or creating a p5.Oscillator and then calling\nits method setType('triangle').\nSee p5.Oscillator for methods.new p5.SawOsc().\nThis creates a SawTooth Wave Oscillator and is\nequivalent to new p5.Oscillator('sawtooth')\n or creating a p5.Oscillator and then calling\nits method setType('sawtooth').\nSee p5.Oscillator for methods.new p5.SqrOsc().\nThis creates a Square Wave Oscillator and is\nequivalent to new p5.Oscillator('square')\n or creating a p5.Oscillator and then calling\nits method setType('square').\nSee p5.Oscillator for methods.osc.freq(env).setRange to change the attack/release level.\nUse setADSR to change attackTime, decayTime, sustainPercent and releaseTime.play method to play the entire envelope,\nthe ramp method for a pingable trigger,\nor triggerAttack/\ntriggerRelease to trigger noteOn/noteOff.\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n env.play();\n}\np5.Oscillator for a full list of methods.\nlet pulse;\nfunction setup() {\n background(0);\n\n // Create and start the pulse wave oscillator\n pulse = new p5.Pulse();\n pulse.amp(0.5);\n pulse.freq(220);\n pulse.start();\n}\n\nfunction draw() {\n let w = map(mouseX, 0, width, 0, 1);\n w = constrain(w, 0, 1);\n pulse.width(w)\n}\n\nlet mic;\nfunction setup(){\n mic = new p5.AudioIn()\n mic.start();\n}\nfunction draw(){\n background(0);\n micLevel = mic.getLevel();\n ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10);\n}\n
\nThis module handles the nodes and methods that are \ncommon and useful for current and future effects.p5.LowPass:\nAllows frequencies below the cutoff frequency to pass through,\nand attenuates frequencies above the cutoff.
\n* p5.HighPass:\nThe opposite of a lowpass filter.
\n* p5.BandPass:\nAllows a range of frequencies to pass through and attenuates\nthe frequencies below and above this frequency range.
\n\n.res() method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.\nlet fft, noise, filter;\n\nfunction setup() {\n fill(255, 40, 255);\n\n filter = new p5.BandPass();\n\n noise = new p5.Noise();\n // disconnect unfiltered noise,\n // and connect to filter\n noise.disconnect();\n noise.connect(filter);\n noise.start();\n\n fft = new p5.FFT();\n}\n\nfunction draw() {\n background(30);\n\n // set the BandPass frequency based on mouseX\n let freq = map(mouseX, 0, width, 20, 10000);\n filter.freq(freq);\n // give the filter a narrow band (lower res = wider bandpass)\n filter.res(50);\n\n // draw filtered spectrum\n let spectrum = fft.analyze();\n noStroke();\n for (let i = 0; i < spectrum.length; i++) {\n let x = map(i, 0, spectrum.length, 0, width);\n let h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width/spectrum.length, h);\n }\n\n isMouseOverCanvas();\n}\n\nfunction isMouseOverCanvas() {\n let mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n noise.amp(0.5, 0.2);\n } else {\n noise.amp(0, 0.2);\n }\n}\nnew p5.LowPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('lowpass').\nSee p5.Filter for methods.new p5.HighPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('highpass').\nSee p5.Filter for methods.new p5.BandPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('bandpass').\nSee p5.Filter for methods.\nlet eq;\nlet band_names;\nlet band_index;\n\nlet soundFile, play;\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n soundFile = loadSound('assets/beat');\n}\n\nfunction setup() {\n eq = new p5.EQ(3);\n soundFile.disconnect();\n eq.process(soundFile);\n\n band_names = ['lows','mids','highs'];\n band_index = 0;\n play = false;\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(30);\n noStroke();\n fill(255);\n text('click to kill',50,25);\n\n fill(255, 40, 255);\n textSize(26);\n text(band_names[band_index],50,55);\n\n fill(255);\n textSize(9);\n text('space = play/pause',50,80);\n}\n\n//If mouse is over canvas, cycle to the next band and kill the frequency\nfunction mouseClicked() {\n for (let i = 0; i < eq.bands.length; i++) {\n eq.bands[i].gain(0);\n }\n eq.bands[band_index].gain(-40);\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n band_index === 2 ? band_index = 0 : band_index++;\n }\n}\n\n//use space bar to trigger play / pause\nfunction keyPressed() {\n if (key===' ') {\n play = !play\n play ? soundFile.loop() : soundFile.pause();\n }\n}\np5.soundOut.audiocontext.listener\nlet noise, env, delay;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n noise = new p5.Noise('brown');\n noise.amp(0);\n noise.start();\n\n delay = new p5.Delay();\n\n // delay.process() accepts 4 parameters:\n // source, delayTime, feedback, filter frequency\n // play with these numbers!!\n delay.process(noise, .12, .7, 2300);\n\n // play the noise with an envelope,\n // a series of fades ( time / value pairs )\n env = new p5.Envelope(.01, 0.2, .2, .1);\n}\n\n// mouseClick triggers envelope\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(noise);\n }\n}\n\nlet soundFile, reverb;\nfunction preload() {\n soundFile = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n reverb = new p5.Reverb();\n soundFile.disconnect(); // so we'll only hear reverb...\n\n // connect soundFile to reverb, process w/\n // 3 second reverbTime, decayRate of 2%\n reverb.process(soundFile, 3, 2);\n soundFile.play();\n}\ncreateConvolution(path) to instantiate a\np5.Convolver with a path to your impulse response audio file.\nlet cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\nplayNote(value){}. The array determines\nwhich value is passed into the callback at each step of the\nphrase. It can be numbers, an object with multiple numbers,\nor a zero (0) indicates a rest so the callback won't be called).\nlet mySound, myPhrase, myPart;\nlet pattern = [1,0,0,2,0,2,0,0];\nlet msg = 'click to play';\n\nfunction preload() {\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n myPhrase = new p5.Phrase('bbox', makeSound, pattern);\n myPart = new p5.Part();\n myPart.addPhrase(myPhrase);\n myPart.setBPM(60);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction makeSound(time, playbackRate) {\n mySound.rate(playbackRate);\n mySound.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing pattern';\n }\n}\n\n\nlet box, drum, myPart;\nlet boxPat = [1,0,0,2,0,2,0,0];\nlet drumPat = [0,1,1,0,2,0,1,0];\nlet msg = 'click to play';\n\nfunction preload() {\n box = loadSound('assets/beatbox.mp3');\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n let boxPhrase = new p5.Phrase('box', playBox, boxPat);\n let drumPhrase = new p5.Phrase('drum', playDrum, drumPat);\n myPart = new p5.Part();\n myPart.addPhrase(boxPhrase);\n myPart.addPhrase(drumPhrase);\n myPart.setBPM(60);\n masterVolume(0.1);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction playBox(time, playbackRate) {\n box.rate(playbackRate);\n box.play(time);\n}\n\nfunction playDrum(time, playbackRate) {\n drum.rate(playbackRate);\n drum.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing part';\n }\n}\nnew p5.Score(a, a, b, a, c)\nlet click;\nlet looper1;\n\nfunction preload() {\n click = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n //the looper's callback is passed the timeFromNow\n //this value should be used as a reference point from\n //which to schedule sounds\n looper1 = new p5.SoundLoop(function(timeFromNow){\n click.play(timeFromNow);\n background(255 * (looper1.iterations % 2));\n }, 2);\n\n //stop after 10 iteratios;\n looper1.maxIterations = 10;\n //start the loop\n looper1.start();\n}\n\nlet mic, recorder, soundFile;\nlet state = 0;\n\nfunction setup() {\n background(200);\n // create an audio in\n mic = new p5.AudioIn();\n\n // prompts user to enable their browser mic\n mic.start();\n\n // create a sound recorder\n recorder = new p5.SoundRecorder();\n\n // connect the mic to the recorder\n recorder.setInput(mic);\n\n // this sound file will be used to\n // playback & save the recording\n soundFile = new p5.SoundFile();\n\n text('keyPress to record', 20, 20);\n}\n\nfunction keyPressed() {\n // make sure user enabled the mic\n if (state === 0 && mic.enabled) {\n\n // record to our p5.SoundFile\n recorder.record(soundFile);\n\n background(255,0,0);\n text('Recording!', 20, 20);\n state++;\n }\n else if (state === 1) {\n background(0,255,0);\n\n // stop recorder and\n // send result to soundFile\n recorder.stop();\n\n text('Stopped', 20, 20);\n state++;\n }\n\n else if (state === 2) {\n soundFile.play(); // play the result!\n save(soundFile, 'mySound.wav');\n state++;\n }\n}\nupdate in the draw loop\nand pass in a p5.FFT object.\nfreq1 and freq2.\nthreshold is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0. framesPerPeak = 60 / (estimatedBPM / 60 );\n\n\nlet cnv, soundFile, fft, peakDetect;\nlet ellipseWidth = 10;\n\nfunction preload() {\n soundFile = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n\n // p5.PeakDetect requires a p5.FFT\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n}\n\nfunction draw() {\n background(0);\n text('click to play/pause', width/2, height/2);\n\n // peakDetect accepts an fft post-analysis\n fft.analyze();\n peakDetect.update(fft);\n\n if ( peakDetect.isDetected ) {\n ellipseWidth = 50;\n } else {\n ellipseWidth *= 0.95;\n }\n\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// toggle play/stop when canvas is clicked\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n }\n}\n\n\n // load two soundfile and crossfade beetween them\n let sound1,sound2;\n let gain1, gain2, gain3;\n\n function preload(){\n soundFormats('ogg', 'mp3');\n sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01');\n sound2 = loadSound('assets/beat.mp3');\n }\n\n function setup() {\n createCanvas(400,200);\n\n // create a 'master' gain to which we will connect both soundfiles\n gain3 = new p5.Gain();\n gain3.connect();\n\n // setup first sound for playing\n sound1.rate(1);\n sound1.loop();\n sound1.disconnect(); // diconnect from p5 output\n\n gain1 = new p5.Gain(); // setup a gain node\n gain1.setInput(sound1); // connect the first sound to its input\n gain1.connect(gain3); // connect its output to the 'master'\n\n sound2.rate(1);\n sound2.disconnect();\n sound2.loop();\n\n gain2 = new p5.Gain();\n gain2.setInput(sound2);\n gain2.connect(gain3);\n\n }\n\n function draw(){\n background(180);\n\n // calculate the horizontal distance beetween the mouse and the right of the screen\n let d = dist(mouseX,0,width,0);\n\n // map the horizontal position of the mouse to values useable for volume control of sound1\n let vol1 = map(mouseX,0,width,0,1);\n let vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa\n\n gain1.amp(vol1,0.5,0);\n gain2.amp(vol2,0.5,0);\n\n // map the vertical position of the mouse to values useable for 'master volume control'\n let vol3 = map(mouseY,0,height,0,1);\n gain3.amp(vol3,0.5,0);\n }\n\nlet monoSynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n monoSynth = new p5.MonoSynth();\n\n textAlign(CENTER);\n text(\'click to play\', width/2, height/2);\n}\n\nfunction playSynth() {\n // time from now (in seconds)\n let time = 0;\n // note duration (in seconds)\n let dur = 0.25;\n // velocity (volume, from 0 to 1)\n let v = 0.2;\n\n monoSynth.play("G3", v, time, dur);\n monoSynth.play("C4", v, time += dur, dur);\n\n background(random(255), random(255), 255);\n text(\'click to play\', width/2, height/2);\n}\n\nlet polySynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n polySynth = new p5.PolySynth();\n\n textAlign(CENTER);\n text(\'click to play\', width/2, height/2);\n}\n\nfunction playSynth() {\n // note duration (in seconds)\n let dur = 1.5;\n\n // time from now (in seconds)\n let time = 0;\n\n // velocity (volume, from 0 to 1)\n let vel = 0.1;\n\n // notes can overlap with each other\n polySynth.play("G2", vel, 0, dur);\n polySynth.play("C3", vel, time += 1/3, dur);\n polySynth.play("G3", vel, time += 1/3, dur);\n\n background(random(255), random(255), 255);\n text(\'click to play\', width/2, height/2);\n}\n\nnoStroke();\nlet c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nlet value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n\n\nlet c = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color('hsb(60, 100%, 50%)');\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // A 'value' of 50% is 127.5\nfill(value);\nrect(50, 20, 35, 60);\n\n
\nNote that if only one value is provided to color(), it will be interpreted\nas a grayscale value. Add a second value, and it will be used for alpha\ntransparency. When three values are specified, they are interpreted as\neither RGB or HSB values. Adding a fourth value applies alpha\ntransparency.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.\nlet c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(30, 20, 55, 55); // Draw rectangle\n\n\nlet c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nellipse(25, 25, 80, 80); // Draw left circle\n\n// Using only one value with color()\n// generates a grayscale value.\nc = color(65); // Update 'c' with grayscale value\nfill(c); // Use updated 'c' as fill color\nellipse(75, 75, 80, 80); // Draw right circle\n\n\n// Named SVG & CSS colors may be used,\nlet c = color('magenta');\nfill(c); // Use 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(20, 20, 60, 60); // Draw rectangle\n\n\n// as can hex color codes:\nnoStroke(); // Don't draw a stroke around shapes\nlet c = color('#0f0');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('#00ff00');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n\n// RGB and RGBA color strings are also supported:\n// these all set to the same color (solid blue)\nlet c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('rgb(0,0,255)');\nfill(c); // Use 'c' as fill color\nrect(10, 10, 35, 35); // Draw rectangle\n\nc = color('rgb(0%, 0%, 100%)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 35, 35); // Draw rectangle\n\nc = color('rgba(0, 0, 255, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(10, 55, 35, 35); // Draw rectangle\n\nc = color('rgba(0%, 0%, 100%, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 55, 35, 35); // Draw rectangle\n\n\n// HSL color is also supported and can be specified\n// by value\nlet c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsl(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsla(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n\n// HSB color is also supported and can be specified\n// by value\nlet c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsb(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsba(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n\nlet c; // Declare color 'c'\nnoStroke(); // Don't draw a stroke around shapes\n\n// If no colorMode is specified, then the\n// default of RGB with scale of 0-255 is used.\nc = color(50, 55, 100); // Create a color for 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(0, 10, 45, 80); // Draw left rect\n\ncolorMode(HSB, 100); // Use HSB with scale of 0-100\nc = color(50, 55, 100); // Update 'c' with new color\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw right rect\n\n\nlet c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = hue(c); // Sets \'value\' to "0"\nfill(value);\nrect(50, 20, 35, 60);\n\n
\nThe way that colours are interpolated depends on the current color mode.\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nlet from = color(218, 165, 32);\nlet to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nlet interA = lerpColor(from, to, 0.33);\nlet interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n\n\nnoStroke();\ncolorMode(HSL);\nlet c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n\n\nlet c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n\ncolorMode(RGB, 255); // Sets the range for red, green, and blue to 255\nlet c = color(127, 255, 0);\ncolorMode(RGB, 1); // Sets the range for red, green, and blue to 1\nlet myColor = red(c);\nprint(myColor); // 0.4980392156862745\n\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n\n\nlet myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n rotate(HALF_PI);\n text(myColor.toString(), 0, -5);\n text(myColor.toString('#rrggbb'), 0, -30);\n text(myColor.toString('rgba%'), 0, -55);\n}\n\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n\nlet squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n\n
\nThe color is either specified in terms of the RGB, HSB, or HSL color\ndepending on the current colorMode. (The default color space is RGB, with\neach value in the range from 0 to 255). The alpha range by default is also 0 to 255.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5.Color object can also be provided to set the background color.\n
\nA p5.Image can also be provided to set the background image.\n// Grayscale integer value\nbackground(51);\n\n\n// R, G & B integer values\nbackground(255, 204, 0);\n\n\n// H, S & B integer values\ncolorMode(HSB);\nbackground(255, 204, 100);\n\n\n// Named SVG/CSS color string\nbackground('red');\n\n\n// three-digit hexadecimal RGB notation\nbackground('#fae');\n\n\n// six-digit hexadecimal RGB notation\nbackground('#222222');\n\n\n// integer RGB notation\nbackground('rgb(0,255,0)');\n\n\n// integer RGBA notation\nbackground('rgba(0,255,0, 0.25)');\n\n\n// percentage RGB notation\nbackground('rgb(100%,0%,10%)');\n\n\n// percentage RGBA notation\nbackground('rgba(100%,0%,100%,0.5)');\n\n\n// p5 Color object\nbackground(color(0, 0, 255));\n\n\n// Clear the screen on mouse press.\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n ellipse(mouseX, mouseY, 20, 20);\n}\n\nfunction mousePressed() {\n clear();\n}\n\n
\nNote: existing color objects remember the mode that they were created in,\nso you can change modes as you like without affecting their appearance.\nnoStroke();\ncolorMode(RGB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n\n\ncolorMode(RGB, 255);\nlet c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nlet myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n\n\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\n\nstrokeWeight(4);\nstroke(255, 0, 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\n\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5 Color object can also be provided to set the fill color.\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\n\n\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\n\n\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\n\n\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\n\n\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\n\n\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\n\n\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\n\n\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\n\n\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\n\n\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\n\n\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\n\n\nrect(15, 10, 55, 55);\nnoFill();\nrect(20, 20, 60, 60);\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noFill();\n stroke(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n}\n\n\nnoStroke();\nrect(20, 20, 60, 60);\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noStroke();\n fill(240, 150, 150);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n}\n\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.\n
\nA p5 Color object can also be provided to set the stroke color.\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\n\n\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\n\n\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\nDrawing done with image()\nand background() will not be affected by erase()\n\nbackground(100, 100, 250);\nfill(250, 100, 100);\nrect(20, 20, 60, 60);\nerase();\nellipse(25, 30, 30);\nnoErase();\n\n\nbackground(150, 250, 150);\nfill(100, 100, 250);\nrect(20, 20, 60, 60);\nstrokeWeight(5);\nerase(150, 255);\ntriangle(50, 10, 70, 50, 90, 10);\nnoErase();\n\n\nfunction setup() {\n smooth();\n createCanvas(100, 100, WEBGL);\n // Make a <p> element and put it behind the canvas\n let p = createP('I am a dom element');\n p.center();\n p.style('font-size', '20px');\n p.style('text-align', 'center');\n p.style('z-index', '-9999');\n}\n\nfunction draw() {\n background(250, 250, 150);\n fill(15, 195, 185);\n noStroke();\n sphere(30);\n erase();\n rotateY(frameCount * 0.02);\n translate(0, 0, 40);\n torus(15, 5);\n noErase();\n}\n\n\nbackground(235, 145, 15);\nnoStroke();\nfill(30, 45, 220);\nrect(30, 10, 10, 80);\nerase();\nellipse(50, 50, 60);\nnoErase();\nrect(70, 10, 10, 80);\n\n\n
\n',
+ class: 'p5',
+ module: 'Shape',
+ submodule: '2D Primitives'
+ },
+ {
+ file: 'src/core/shape/2d_primitives.js',
+ line: 100,
+ description:
+ '0 <= start < TWO_PI ; start <= stop < start + TWO_PI
\nThe arc is always drawn clockwise from wherever start falls to wherever stop falls on the ellipse.\nAdding or subtracting TWO_PI to either angle does not change where they fall.\nIf both start and stop fall at the same place, a full ellipse will be drawn. Be aware that the the\ny-axis increases in the downward direction, therefore angles are measured clockwise from the positive\nx-direction ("3 o'clock").\narc(50, 55, 50, 50, 0, HALF_PI);\nnoFill();\narc(50, 55, 60, 60, HALF_PI, PI);\narc(50, 55, 70, 70, PI, PI + QUARTER_PI);\narc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI);\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);\n\n\nellipse(56, 46, 55, 55);\n\n\n// Draw a circle at location (30, 30) with a diameter of 20.\ncircle(30, 30, 20);\n\n\nline(30, 20, 85, 75);\n\n\nline(30, 20, 85, 20);\nstroke(126);\nline(85, 20, 85, 75);\nstroke(255);\nline(85, 75, 30, 75);\n\n\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\n\n\nstroke('purple'); // Change the color\nstrokeWeight(10); // Make the points 10 pixels in size\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\n\n\nlet a = createVector(10, 10);\npoint(a);\nlet b = createVector(10, 20);\npoint(b);\npoint(createVector(20, 10));\npoint(createVector(20, 20));\n\n\nquad(38, 31, 86, 20, 69, 63, 30, 76);\n\n
\nThe fifth, sixth, seventh and eighth parameters, if specified,\ndetermine corner radius for the top-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.\n// Draw a rectangle at location (30, 20) with a width and height of 55.\nrect(30, 20, 55, 55);\n\n\n// Draw a rectangle with rounded corners, each having a radius of 20.\nrect(30, 20, 55, 55, 20);\n\n\n// Draw a rectangle with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nrect(30, 20, 55, 55, 20, 15, 10, 5);\n\n
\nThe fourth, fifth, sixth and seventh parameters, if specified,\ndetermine corner radius for the top-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.\n// Draw a square at location (30, 20) with a side size of 55.\nsquare(30, 20, 55);\n\n\n// Draw a square with rounded corners, each having a radius of 20.\nsquare(30, 20, 55, 20);\n\n\n// Draw a square with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nsquare(30, 20, 55, 20, 15, 10, 5);\n\n\ntriangle(30, 75, 58, 20, 86, 75);\n\n
\nThe default mode is ellipseMode(CENTER), which interprets the first two\nparameters of ellipse() as the shape's center point, while the third and\nfourth parameters are its width and height.\n
\nellipseMode(RADIUS) also uses the first two parameters of ellipse() as\nthe shape's center point, but uses the third and fourth parameters to\nspecify half of the shapes's width and height.\n
\nellipseMode(CORNER) interprets the first two parameters of ellipse() as\nthe upper-left corner of the shape, while the third and fourth parameters\nare its width and height.\n
\nellipseMode(CORNERS) interprets the first two parameters of ellipse() as\nthe location of one corner of the ellipse's bounding box, and the third\nand fourth parameters as the location of the opposite corner.\n
\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.\nellipseMode(RADIUS); // Set ellipseMode to RADIUS\nfill(255); // Set fill to white\nellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode\n\nellipseMode(CENTER); // Set ellipseMode to CENTER\nfill(100); // Set fill to gray\nellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode\n\n\nellipseMode(CORNER); // Set ellipseMode is CORNER\nfill(255); // Set fill to white\nellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode\n\nellipseMode(CORNERS); // Set ellipseMode to CORNERS\nfill(100); // Set fill to gray\nellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode\n\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n\n
\nThe default mode is rectMode(CORNER), which interprets the first two\nparameters of rect() as the upper-left corner of the shape, while the\nthird and fourth parameters are its width and height.\n
\nrectMode(CORNERS) interprets the first two parameters of rect() as the\nlocation of one corner, and the third and fourth parameters as the\nlocation of the opposite corner.\n
\nrectMode(CENTER) interprets the first two parameters of rect() as the\nshape's center point, while the third and fourth parameters are its\nwidth and height.\n
\nrectMode(RADIUS) also uses the first two parameters of rect() as the\nshape's center point, but uses the third and fourth parameters to specify\nhalf of the shapes's width and height.\n
\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.\nrectMode(CORNER); // Default rectMode is CORNER\nfill(255); // Set fill to white\nrect(25, 25, 50, 50); // Draw white rect using CORNER mode\n\nrectMode(CORNERS); // Set rectMode to CORNERS\nfill(100); // Set fill to gray\nrect(25, 25, 50, 50); // Draw gray rect using CORNERS mode\n\n\nrectMode(RADIUS); // Set rectMode to RADIUS\nfill(255); // Set fill to white\nrect(50, 50, 30, 30); // Draw white rect using RADIUS mode\n\nrectMode(CENTER); // Set rectMode to CENTER\nfill(100); // Set fill to gray\nrect(50, 50, 30, 30); // Draw gray rect using CENTER mode\n\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n\n\nstrokeWeight(12.0);\nstrokeCap(ROUND);\nline(20, 30, 80, 30);\nstrokeCap(SQUARE);\nline(20, 50, 80, 50);\nstrokeCap(PROJECT);\nline(20, 70, 80, 70);\n\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(MITER);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(BEVEL);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(ROUND);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nstrokeWeight(4); // Thicker\nline(20, 40, 80, 40);\nstrokeWeight(10); // Beastly\nline(20, 70, 80, 70);\n\n
Bezier curves were developed by French\nautomotive engineer Pierre Bezier, and are commonly used in computer\ngraphics to define gently sloping curves. See also curve().\nnoFill();\nstroke(255, 102, 0);\nline(85, 20, 10, 10);\nline(90, 90, 15, 80);\nstroke(0, 0, 0);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n\n\nbackground(0, 0, 0);\nnoFill();\nstroke(255);\nbezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n\n\nnoFill();\nlet x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nlet y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nlet steps = 10;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(x1, x2, x3, x4, t);\n let y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nlet steps = 6;\nfill(255);\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n // Get the location of the point\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n let a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nlet steps = 16;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n let a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
\nLonger curves can be created by putting a series of curve() functions\ntogether or using curveVertex(). An additional function called\ncurveTightness() provides control for the visual quality of the curve.\nThe curve() function is an implementation of Catmull-Rom splines.\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n\n\n// Define the curve points as JavaScript objects\nlet p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nlet p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n curveDetail(5);\n}\nfunction draw() {\n background(200);\n\n curve(250, 600, 0, -30, 40, 0, 30, 30, 0, -250, 600, 0);\n}\n\n\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n let t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 5, 73, 73, t);\n let y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 73, 73, 15, t);\n let y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n let tx = curveTangent(5, 73, 73, 15, t);\n let ty = curveTangent(26, 24, 61, 65, t);\n let a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n\n
\nThe parameters available for beginShape() are POINTS, LINES, TRIANGLES,\nTRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the\nbeginShape() function, a series of vertex() commands must follow. To stop\ndrawing the shape, call endShape(). Each shape will be outlined with the\ncurrent stroke color and filled with the fill color.\n
\nTransformations such as translate(), rotate(), and scale() do not work\nwithin beginShape(). It is also not possible to use other shapes, such as\nellipse() or rect() within beginShape().\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n\n\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n\nbeginShape(LINES);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n\n\nbeginShape(TRIANGLES);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nendShape();\n\n\nbeginShape(TRIANGLE_STRIP);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nvertex(90, 75);\nendShape();\n\n\nbeginShape(TRIANGLE_FAN);\nvertex(57.5, 50);\nvertex(57.5, 15);\nvertex(92, 50);\nvertex(57.5, 85);\nvertex(22, 50);\nvertex(57.5, 15);\nendShape();\n\n\nbeginShape(QUADS);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 75);\nvertex(50, 20);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 75);\nvertex(85, 20);\nendShape();\n\n\nbeginShape(QUAD_STRIP);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 20);\nvertex(50, 75);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 20);\nvertex(85, 75);\nendShape();\n\n\nbeginShape();\nvertex(20, 20);\nvertex(40, 20);\nvertex(40, 40);\nvertex(60, 40);\nvertex(60, 60);\nvertex(20, 60);\nendShape(CLOSE);\n\n
\nThe first time bezierVertex() is used within a beginShape()\ncall, it must be prefaced with a call to vertex() to set the first anchor\npoint. This function must be used between beginShape() and endShape()\nand only when there is no MODE or POINTS parameter specified to\nbeginShape().\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\nfunction draw() {\n orbitControl();\n background(50);\n strokeWeight(4);\n stroke(255);\n point(-25, 30);\n point(25, 30);\n point(25, -30);\n point(-25, -30);\n\n strokeWeight(1);\n noFill();\n\n beginShape();\n vertex(-25, 30);\n bezierVertex(25, 30, 25, -30, -25, -30);\n endShape();\n\n beginShape();\n vertex(-25, 30, 20);\n bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20);\n endShape();\n}\n\n
\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of a the curve. A minimum of four\npoints is required to draw a tiny curve between the second and\nthird points. Adding a fifth point with curveVertex() will draw\nthe curve between the second, third, and fourth points. The\ncurveVertex() function is an implementation of Catmull-Rom\nsplines.\nstrokeWeight(5);\npoint(84, 91);\npoint(68, 19);\npoint(21, 17);\npoint(32, 91);\nstrokeWeight(1);\n\nnoFill();\nbeginShape();\ncurveVertex(84, 91);\ncurveVertex(84, 91);\ncurveVertex(68, 19);\ncurveVertex(21, 17);\ncurveVertex(32, 91);\ncurveVertex(32, 91);\nendShape();\n\n
\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n\n\nnoFill();\n\nbeginShape();\nvertex(20, 20);\nvertex(45, 20);\nvertex(45, 80);\nendShape(CLOSE);\n\nbeginShape();\nvertex(50, 20);\nvertex(75, 20);\nvertex(75, 80);\nendShape();\n\n
\nThis function must be used between beginShape() and endShape()\nand only when there is no MODE or POINTS parameter specified to\nbeginShape().\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nendShape();\n\n\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\npoint(20, 80);\npoint(80, 80);\npoint(80, 60);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nquadraticVertex(20, 80, 80, 80);\nvertex(80, 60);\nendShape();\n\n\nstrokeWeight(3);\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n\ncreateCanvas(100, 100, WEBGL);\nbackground(240, 240, 240);\nfill(237, 34, 93);\nnoStroke();\nbeginShape();\nvertex(0, 35);\nvertex(35, 0);\nvertex(0, -35);\nvertex(-35, 0);\nendShape();\n\n\ncreateCanvas(100, 100, WEBGL);\nbackground(240, 240, 240);\nfill(237, 34, 93);\nnoStroke();\nbeginShape();\nvertex(-10, 10);\nvertex(0, 35);\nvertex(10, 10);\nvertex(35, 0);\nvertex(10, -8);\nvertex(0, -35);\nvertex(-10, -8);\nvertex(-35, 0);\nendShape();\n\n\nstrokeWeight(3);\nstroke(237, 34, 93);\nbeginShape(LINES);\nvertex(10, 35);\nvertex(90, 35);\nvertex(10, 65);\nvertex(90, 65);\nvertex(35, 10);\nvertex(35, 90);\nvertex(65, 10);\nvertex(65, 90);\nendShape();\n\n\n// Click to change the number of sides.\n// In WebGL mode, custom shapes will only\n// display hollow fill sections when\n// all calls to vertex() use the same z-value.\n\nlet sides = 3;\nlet angle, px, py;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n fill(237, 34, 93);\n strokeWeight(3);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n ngon(sides, 0, 0, 80);\n}\n\nfunction mouseClicked() {\n if (sides > 6) {\n sides = 3;\n } else {\n sides++;\n }\n}\n\nfunction ngon(n, x, y, d) {\n beginShape();\n for (let i = 0; i < n + 1; i++) {\n angle = TWO_PI / n * i;\n px = x + sin(angle) * d / 2;\n py = y - cos(angle) * d / 2;\n vertex(px, py, 0);\n }\n for (let i = 0; i < n + 1; i++) {\n angle = TWO_PI / n * i;\n px = x + sin(angle) * d / 4;\n py = y - cos(angle) * d / 4;\n vertex(px, py, 0);\n }\n endShape();\n}\n\n\narc(50, 50, 80, 80, 0, HALF_PI);\n\narc(50, 50, 80, 80, 0, PI);\n\narc(50, 50, 80, 80, 0, QUARTER_PI);\n\narc(50, 50, 80, 80, 0, TAU);\n\narc(50, 50, 80, 80, 0, TWO_PI);\n\nfunction setup() {\n angleMode(DEGREES);\n}\n\nfunction setup() {\n angleMode(RADIANS);\n}\n\nlet x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n\nfunction setup() {\n frameRate(30);\n textSize(30);\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n text(frameCount, width / 2, height / 2);\n}\n
\nThis variable is useful for creating time sensitive animation or physics\ncalculation that should stay constant regardless of frame rate.\nlet rectX = 0;\nlet fr = 30; //starting FPS\nlet clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX + 1 * (deltaTime / 50); // Move Rectangle in relation to deltaTime\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n\n// To demonstrate, put two windows side by side.\n// Click on the window that the p5 sketch isn\'t in!\nfunction draw() {\n background(200);\n noStroke();\n fill(0, 200, 0);\n ellipse(25, 25, 50, 50);\n\n if (!focused) {\n // or "if (focused === false)"\n stroke(200, 0, 0);\n line(0, 0, 100, 100);\n line(100, 0, 0, 100);\n }\n}\n\n// Move the mouse across the quadrants\n// to see the cursor change\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n line(0, height / 2, width, height / 2);\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');\n } else {\n cursor('grab');\n }\n}\n
\nCalling frameRate() with no arguments returns the current framerate. The\ndraw function must run at least once before it will return a value. This\nis the same as getFrameRate().\n
\nCalling frameRate() with arguments that are not of the type numbers\nor are non positive also returns current framerate.\nlet rectX = 0;\nlet fr = 30; //starting FPS\nlet clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n\nfunction setup() {\n noCursor();\n}\n\nfunction draw() {\n background(200);\n ellipse(mouseX, mouseY, 10, 10);\n}\n\ncreateCanvas(displayWidth, displayHeight);\n\ncreateCanvas(displayWidth, displayHeight);\n\ncreateCanvas(windowWidth, windowHeight);\n\ncreateCanvas(windowWidth, windowHeight);\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n\n\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n\nfunction setup() {\n pixelDensity(3.0);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n\nfunction setup() {\n let density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n\nlet url;\nlet x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n\n\nfunction setup() {\n let urlPath = getURLPath();\n for (let i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n\n
\nBy default the text "loading..." will be displayed. To make your own\nloading page, include an HTML element with id "p5_loading" in your\npage. More information here.\nlet img;\nlet c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
\nNote: Variables declared within setup() are not accessible within other\nfunctions, including draw().\nlet a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
\nIt should always be controlled with noLoop(), redraw() and loop(). After\nnoLoop() stops the code in draw() from executing, redraw() causes the\ncode inside draw() to execute once, and loop() will cause the code\ninside draw() to resume executing continuously.\n
\nThe number of times draw() executes in each second may be controlled with\nthe frameRate() function.\n
\nThere can only be one draw() function for each sketch, and draw() must\nexist if you want the code to run continuously, or to process events such\nas mousePressed(). Sometimes, you might have an empty call to draw() in\nyour program, as shown in the above example.\n
\nIt is important to note that the drawing coordinate system will be reset\nat the beginning of each draw() call. If any transformations are performed\nwithin draw() (ex: scale, rotate, translate), their effects will be\nundone at the beginning of draw(), so transformations will not accumulate\nover time. On the other hand, styling applied (ex: fill, stroke, etc) will\nremain in effect.\nlet yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n\nfunction draw() {\n ellipse(50, 50, 10, 10);\n}\n\nfunction mousePressed() {\n remove(); // remove whole sketch on mouse press\n}\n\np5.disableFriendlyErrors = true;\n\nfunction setup() {\n createCanvas(100, 50);\n}\n\nfunction setup() {\n let c = createCanvas(50, 50);\n c.elt.style.border = '5px solid red';\n}\n\nfunction draw() {\n background(220);\n}\n\n\n // in the html file:\n // <div id=\"myContainer\"></div>\n// in the js file:\n let cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n \n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n \n let div0 = createDiv('this is the parent');\n div0.id('apples');\n let div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n \n let elt = document.getElementById('myParentDiv');\n let div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n \n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n \n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n false is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
\nThe function accepts a callback function as argument which will be executed\nwhen the wheel event is triggered on the element, the callback function is\npassed one argument event. The event.deltaY property returns negative\nvalues if the mouse wheel is rotated up or away from the user and positive\nin the other direction. The event.deltaX does the same as event.deltaY\nexcept it reads the horizontal wheel scroll of the mouse wheel.\n
\nOn OS X with "natural" scrolling enabled, the event.deltaY values are\nreversed.false is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d = 30;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n pg = createGraphics(50, 100);\n pg.fill(0);\n frameRate(5);\n}\nfunction draw() {\n image(pg, width / 2, 0);\n pg.background(255);\n // p5.Graphics object behave a bit differently in some cases\n // The normal canvas on the left resets the translate\n // with every loop through draw()\n // the graphics object on the right doesn't automatically reset\n // so translate() is additive and it moves down the screen\n rect(0, 0, width / 2, 5);\n pg.rect(0, 0, width / 2, 5);\n translate(0, 5, 0);\n pg.translate(0, 5, 0);\n}\nfunction mouseClicked() {\n // if you click you will see that\n // reset() resets the translate back to the initial state\n // of the Graphics object\n pg.reset();\n}\n\nlet bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n\nlet bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n let t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n let p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\nsize radians, beginning start radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.\nlet x = 2;\nconsole.log(x); // prints 2 to the console\nx = 1;\nconsole.log(x); // prints 1 to the console\n\n\n// define myFavNumber as a constant and give it the value 7\nconst myFavNumber = 7;\nconsole.log('my favorite number is: ' + myFavNumber);\n\n\nconsole.log(1 === 1); // prints true to the console\nconsole.log(1 === '1'); // prints false to the console\n\n\nconsole.log(100 > 1); // prints true to the console\nconsole.log(1 > 100); // prints false to the console\n\n\nconsole.log(100 >= 100); // prints true to the console\nconsole.log(101 >= 100); // prints true to the console\n\n\nconsole.log(1 < 100); // prints true to the console\nconsole.log(100 < 99); // prints false to the console\n\n\nconsole.log(100 <= 100); // prints true to the console\nconsole.log(99 <= 100); // prints true to the console\n\n\nlet a = 4;\nif (a > 0) {\n console.log('positive');\n} else {\n console.log('negative');\n}\n\n\nlet myName = 'Hridi';\nfunction sayHello(name) {\n console.log('Hello ' + name + '!');\n}\nsayHello(myName); // calling the function, prints \"Hello Hridi!\" to console.\n\n\nfunction calculateSquare(x) {\n return x * x;\n}\ncalculateSquare(4); // returns 16\n\ntrue or false.\nlet myBoolean = false;\nconsole.log(typeof myBoolean); // prints 'boolean' to the console\n\n\nlet mood = 'chill';\nconsole.log(typeof mood); // prints 'string' to the console\n\n\nlet num = 46.5;\nconsole.log(typeof num); // prints 'number' to the console\n\n\n let author = {\n name: 'Ursula K Le Guin',\n books: [\n 'The Left Hand of Darkness',\n 'The Dispossessed',\n 'A Wizard of Earthsea'\n ]\n };\n console.log(author.name); // prints 'Ursula K Le Guin' to the console\n \n \nclass Rectangle {\n constructor(name, height, width) {\n this.name = name;\n this.height = height;\n this.width = width;\n }\n}\nlet square = new Rectangle('square', 1, 1); // creating new instance of Polygon Class.\nconsole.log(square.width); // prints '1' to the console\n\n\nfor (let i = 0; i < 9; i++) {\n console.log(i);\n}\n\n\n// This example logs the lines below to the console\n// 4\n// 3\n// 2\n// 1\n// 0\nlet num = 5;\nwhile (num > 0) {\n num = num - 1;\n console.log(num);\n}\n\n\nlet myObject = { x: 5, y: 6 };\nlet myObjectAsString = JSON.stringify(myObject);\nconsole.log(myObjectAsString); // prints "{"x":5,"y":6}" to the console\nconsole.log(typeof myObjectAsString); // prints \'string\' to the console\n\n\nlet myNum = 5;\nconsole.log(myNum); // prints 5 to the console\nconsole.log(myNum + 12); // prints 17 to the console\n\n
\nThe system variables width and height are set by the parameters passed\nto this function. If createCanvas() is not used, the window will be\ngiven a default size of 100x100 pixels.\n
\nFor more ways to position the canvas, see the\n\npositioning the canvas wiki page.\nfunction setup() {\n createCanvas(100, 50);\n background(153);\n line(0, 0, width, height);\n}\n\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n\nfunction setup() {\n noCanvas();\n}\n\n\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n\n\n
\nBLEND - linear interpolation of colours: C =\nA\\*factor + B. This is the default blending mode.ADD - sum of A and BDARKEST - only the darkest colour succeeds: C =\nmin(A\\*factor, B).LIGHTEST - only the lightest colour succeeds: C =\nmax(A\\*factor, B).DIFFERENCE - subtract colors from underlying image.EXCLUSION - similar to DIFFERENCE, but less\nextreme.MULTIPLY - multiply the colors, result will always be\ndarker.SCREEN - opposite multiply, uses inverse values of the\ncolors.REPLACE - the pixels entirely replace the others and\ndon't utilize alpha (transparency) values.REMOVE - removes pixels from B with the alpha strength of A.OVERLAY - mix of MULTIPLY and SCREEN\n. Multiplies dark values, and screens light values. (2D)HARD_LIGHT - SCREEN when greater than 50%\ngray, MULTIPLY when lower. (2D)SOFT_LIGHT - mix of DARKEST and\nLIGHTEST. Works like OVERLAY, but not as harsh. (2D)\nDODGE - lightens light tones and increases contrast,\nignores darks. (2D)BURN - darker areas are applied, increasing contrast,\nignores lights. (2D)SUBTRACT - remainder of A and B (3D)
\n(2D) indicates that this blend mode only works in the 2D renderer.
\n(3D) indicates that this blend mode only works in the WEBGL renderer.",
+ itemtype: 'method',
+ name: 'blendMode',
+ params: [
+ {
+ name: 'mode',
+ description:
+ '\nblendMode(LIGHTEST);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n\n\nblendMode(MULTIPLY);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n\n
\nWhen noLoop() is used, it's not possible to manipulate or access the\nscreen inside event handling functions such as mousePressed() or\nkeyPressed(). Instead, use those functions to call redraw() or loop(),\nwhich will run draw(), which can update the screen properly. This means\nthat when noLoop() has been called, no drawing can happen, and functions\nlike saveFrame() or loadPixels() may not be used.\n
\nNote that if the sketch is resized, redraw() will be called to update\nthe sketch, even after noLoop() has been specified. Otherwise, the sketch\nwould enter an odd state until loop() was called.\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n\nlet x = 0;\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n noLoop();\n}\n\nfunction mouseReleased() {\n loop();\n}\n\nlet x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n loop();\n}\n\nfunction mouseReleased() {\n noLoop();\n}\n
\npush() stores information related to the current transformation state\nand style settings controlled by the following functions:\nfill(),\nnoFill(),\nnoStroke(),\nstroke(),\ntint(),\nnoTint(),\nstrokeWeight(),\nstrokeCap(),\nstrokeJoin(),\nimageMode(),\nrectMode(),\nellipseMode(),\ncolorMode(),\ntextAlign(),\ntextFont(),\ntextSize(),\ntextLeading(),\napplyMatrix(),\nresetMatrix(),\nrotate(),\nscale(),\nshearX(),\nshearY(),\ntranslate(),\nnoiseSeed().\n
\nIn WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),\npointLight(), texture(), specularMaterial(), shininess(), normalMaterial()\nand shader().\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\ntranslate(50, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
\npush() stores information related to the current transformation state\nand style settings controlled by the following functions:\nfill(),\nnoFill(),\nnoStroke(),\nstroke(),\ntint(),\nnoTint(),\nstrokeWeight(),\nstrokeCap(),\nstrokeJoin(),\nimageMode(),\nrectMode(),\nellipseMode(),\ncolorMode(),\ntextAlign(),\ntextFont(),\ntextSize(),\ntextLeading(),\napplyMatrix(),\nresetMatrix(),\nrotate(),\nscale(),\nshearX(),\nshearY(),\ntranslate(),\nnoiseSeed().\n
\nIn WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),\npointLight(), texture(), specularMaterial(), shininess(), normalMaterial()\nand shader().\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\ntranslate(50, 0);\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
\n In structuring a program, it only makes sense to call redraw() within\n events such as mousePressed(). This is because redraw() does not run\n draw() immediately (it only sets a flag that indicates an update is\n needed).\n
\n The redraw() function does not work properly when called inside draw().\n To enable/disable animations, use loop() and noLoop().\n
\n In addition you can set the number of redraws per method call. Just\n add an integer as single parameter for the number of redraws.\n let x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n \n let x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n \n
\n',
+ itemtype: 'method',
+ name: 'applyMatrix',
+ params: [
+ {
+ name: 'a',
+ description:
+ '
\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n let angle = map(step, 0, 20, 0, TWO_PI);\n let cos_a = cos(angle);\n let sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n let angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n let shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n}\n\nfunction draw() {\n background(200);\n rotateY(PI / 6);\n stroke(153);\n box(35);\n let rad = millis() / 1000;\n // Set rotation angles\n let ct = cos(rad);\n let st = sin(rad);\n // Matrix for rotation around the Y axis\n applyMatrix( ct, 0.0, st, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n -st, 0.0, ct, 0.0,\n 0.0, 0.0, 0.0, 1.0);\n stroke(255);\n box(50);\n}\n\n\ntranslate(50, 50);\napplyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);\nrect(0, 0, 20, 20);\n// Note that the translate is also reset.\nresetMatrix();\nrect(0, 0, 20, 20);\n\n
\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nrotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).\nAll tranformations are reset when draw() begins again.\n
\nTechnically, rotate() multiplies the current transformation matrix\nby a rotation matrix. This function can be further controlled by\nthe push() and pop().\ntranslate(width / 2, height / 2);\nrotate(PI / 3.0);\nrect(-26, -26, 52, 52);\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateX(millis() / 1000);\n box();\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateY(millis() / 1000);\n box();\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateZ(millis() / 1000);\n box();\n}\n\n
\nTransformations apply to everything that happens after and subsequent\ncalls to the function multiply the effect. For example, calling scale(2.0)\nand then scale(1.5) is the same as scale(3.0). If scale() is called\nwithin draw(), the transformation is reset when the loop begins again.\n
\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with push() and pop().\nrect(30, 20, 50, 50);\nscale(0.5);\nrect(30, 20, 50, 50);\n\n\nrect(30, 20, 50, 50);\nscale(0.5, 1.3);\nrect(30, 20, 50, 50);\n\n
\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).\nIf shearX() is called within the draw(), the transformation is reset when\nthe loop begins again.\n
\nTechnically, shearX() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.\ntranslate(width / 4, height / 4);\nshearX(PI / 4.0);\nrect(0, 0, 30, 30);\n\n
\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If\nshearY() is called within the draw(), the transformation is reset when\nthe loop begins again.\n
\nTechnically, shearY() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.\ntranslate(width / 4, height / 4);\nshearY(PI / 4.0);\nrect(0, 0, 30, 30);\n\n
\nTransformations are cumulative and apply to everything that happens after\nand subsequent calls to the function accumulates the effect. For example,\ncalling translate(50, 0) and then translate(20, 0) is the same as\ntranslate(70, 0). If translate() is called within draw(), the\ntransformation is reset when the loop begins again. This function can be\nfurther controlled by using push() and pop().\ntranslate(30, 20);\nrect(0, 0, 55, 55);\n\n\nrect(0, 0, 55, 55); // Draw rect at original 0,0\ntranslate(30, 20);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\ntranslate(14, 14);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\n\n\nfunction draw() {\n background(200);\n rectMode(CENTER);\n translate(width / 2, height / 2);\n translate(p5.Vector.fromAngle(millis() / 1000, 40));\n rect(0, 0, 20, 20);\n}\n\n
\n Sensitive data such as passwords or personal information\n should not be stored in local storage.\n // Type to change the letter in the\n // center of the canvas.\n // If you reload the page, it will\n // still display the last key you entered\nlet myText;\nfunction setup() {\n createCanvas(100, 100);\n myText = getItem('myText');\n if (myText === null) {\n myText = '';\n }\n }\nfunction draw() {\n textSize(40);\n background(255);\n text(myText, width / 2, height / 2);\n }\nfunction keyPressed() {\n myText = key;\n storeItem('myText', myText);\n }\n \n // Click the mouse to change\n // the color of the background\n // Once you have changed the color\n // it will stay changed even when you\n // reload the page.\nlet myColor;\nfunction setup() {\n createCanvas(100, 100);\n myColor = getItem('myColor');\n }\nfunction draw() {\n if (myColor !== null) {\n background(myColor);\n }\n }\nfunction mousePressed() {\n myColor = color(random(255), random(255), random(255));\n storeItem('myColor', myColor);\n }\n \n function setup() {\n let myNum = 10;\n let myBool = false;\n storeItem('myNum', myNum);\n storeItem('myBool', myBool);\n print(getItem('myNum')); // logs 10 to the console\n print(getItem('myBool')); // logs false to the console\n clearStorage();\n print(getItem('myNum')); // logs null to the console\n print(getItem('myBool')); // logs null to the console\n }\n \n function setup() {\n let myVar = 10;\n storeItem('myVar', myVar);\n print(getItem('myVar')); // logs 10 to the console\n removeItem('myVar');\n print(getItem('myVar')); // logs null to the console\n }\n \n function setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n let anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n \n function setup() {\n let myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n let anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n \nfunction setup() {\n let myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n let myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n }\n}\n\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n }\n}\n\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n //translates canvas 50px down\n select('canvas').position(100, 100);\n}\n\n// these are all valid calls to select()\nlet a = select('#moo');\nlet b = select('#blah', '#myContainer');\nlet c, e;\nif (b) {\n c = select('#foo', b);\n}\nlet d = document.getElementById('beep');\nif (d) {\n e = select('p', d);\n}\n[a, b, c, d, e]; // unused\n\nfunction setup() {\n createButton('btn');\n createButton('2nd btn');\n createButton('3rd btn');\n let buttons = selectAll('button');\n\n for (let i = 0; i < buttons.length; i++) {\n buttons[i].size(100, 100);\n }\n}\n\n// these are all valid calls to selectAll()\nlet a = selectAll('.moo');\na = selectAll('div');\na = selectAll('button', '#myContainer');\n\nlet d = select('#container');\na = selectAll('p', d);\n\nlet f = document.getElementById('beep');\na = select('.blah', f);\n\na; // unused\n\nfunction setup() {\n createCanvas(100, 100);\n createDiv('this is some text');\n createP('this is a paragraph');\n}\nfunction mousePressed() {\n removeElements(); // this will remove the div and p, not canvas\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\nlet sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n let item = sel.value();\n background(200);\n text(\"it's a \" + item + '!', 50, 50);\n}\n\nlet checkbox;\nlet cnv;\n\nfunction setup() {\n checkbox = createCheckbox(' fill');\n checkbox.changed(changeFill);\n cnv = createCanvas(100, 100);\n cnv.position(0, 30);\n noFill();\n}\n\nfunction draw() {\n background(200);\n ellipse(50, 50, 50, 50);\n}\n\nfunction changeFill() {\n if (checkbox.checked()) {\n fill(0);\n } else {\n noFill();\n }\n}\nfalse is passed instead, the previously\n firing function will no longer fire.\n// Open your console to see the output\nfunction setup() {\n let inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n\ncreateDiv('this is some text');\n\ncreateP('this is some text');\n\ncreateSpan('this is some text');\n\ncreateImg(\n 'https://p5js.org/assets/img/asterisk-01.png',\n 'the p5 magenta asterisk'\n);\n"") if that an image is not intended to be viewed.img element; use either 'anonymous' or 'use-credentials' to retrieve the image with cross-origin access (for later use with canvas. if an empty string("") is passed, CORS is not used\ncreateA('http://p5js.org/', 'this is a link');\n\nlet slider;\nfunction setup() {\n slider = createSlider(0, 255, 100);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n let val = slider.value();\n background(val);\n}\n\nlet slider;\nfunction setup() {\n colorMode(HSB);\n slider = createSlider(0, 360, 60, 40);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n let val = slider.value();\n background(val, 100, 100, 1);\n}\n\nlet button;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n button = createButton('click me');\n button.position(19, 19);\n button.mousePressed(changeBG);\n}\n\nfunction changeBG() {\n let val = random(255);\n background(val);\n}\n\nlet checkbox;\n\nfunction setup() {\n checkbox = createCheckbox('label', false);\n checkbox.changed(myCheckedEvent);\n}\n\nfunction myCheckedEvent() {\n if (this.checked()) {\n console.log('Checking!');\n } else {\n console.log('Unchecking!');\n }\n}\n\nlet sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n let item = sel.value();\n background(200);\n text('It is a ' + item + '!', 50, 50);\n}\n\nlet radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('black');\n radio.option('white');\n radio.option('gray');\n radio.style('width', '60px');\n textAlign(CENTER);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n let val = radio.value();\n background(val);\n text(val, width / 2, height / 2);\n}\n\nlet radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('apple', 1);\n radio.option('bread', 2);\n radio.option('juice', 3);\n radio.style('width', '60px');\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n let val = radio.value();\n if (val) {\n text('item cost is $' + val, width / 2, height / 2);\n }\n}\n\nlet inp1, inp2;\nfunction setup() {\n createCanvas(100, 100);\n background('grey');\n inp1 = createColorPicker('#ff0000');\n inp2 = createColorPicker(color('yellow'));\n inp1.input(setShade1);\n inp2.input(setShade2);\n setMidShade();\n}\n\nfunction setMidShade() {\n // Finding a shade between the two\n let commonShade = lerpColor(inp1.color(), inp2.color(), 0.5);\n fill(commonShade);\n rect(20, 20, 60, 60);\n}\n\nfunction setShade1() {\n setMidShade();\n console.log('You are choosing shade 1 to be : ', this.value());\n}\nfunction setShade2() {\n setMidShade();\n console.log('You are choosing shade 2 to be : ', this.value());\n}\n\n\nfunction setup() {\n let inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n\nlet input;\nlet img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n background(255);\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data, '');\n img.hide();\n } else {\n img = null;\n }\n}\n\nlet vid;\nfunction setup() {\n noCanvas();\n\n vid = createVideo(\n ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],\n vidLoad\n );\n\n vid.size(100, 100);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.loop();\n vid.volume(0);\n}\n\nlet ele;\nfunction setup() {\n ele = createAudio('assets/beat.mp3');\n\n // here we set the element to autoplay\n // The element will play as soon\n // as it is able to do so.\n ele.autoplay(true);\n}\n\nlet capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n\nfunction setup() {\n createCanvas(480, 120);\n let constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n\ncreateElement('h2', 'im an h2 p5.element!');\n\n let div = createDiv('div');\n div.addClass('myClass');\n \n // In this example, a class is set when the div is created\n // and removed when mouse is pressed. This could link up\n // with a CSS style rule to toggle style properties.\nlet div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('myClass');\n }\nfunction mousePressed() {\n div.removeClass('myClass');\n }\n \n let div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n }\n \n let div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n div.toggleClass('show');\n }\n \n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n \n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n \n // this example assumes there is a div already on the page\n // with id \"myChildDiv\"\n let div0 = createDiv('this is the parent');\n let elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n \nfunction setup() {\n let div = createDiv('').size(10, 10);\n div.style('background-color', 'orange');\n div.center();\n}\n\n let div = createDiv('').size(100, 100);\n div.html('hi');\n \n let div = createDiv('Hello ').size(100, 100);\n div.html('World', true);\n \n function setup() {\n let cnv = createCanvas(100, 100);\n // positions canvas 50px to the right and 100px\n // below upper left corner of the window\n cnv.position(50, 100);\n }\n \nlet myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n\nlet col = color(25, 23, 200, 50);\nlet button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n\nlet myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv('I like gray.');\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style('font-size', mouseX + 'px');\n}\n\n let myDiv = createDiv('I like pandas.');\n myDiv.attribute('align', 'center');\n \n let button;\n let checkbox;\nfunction setup() {\n checkbox = createCheckbox('enable', true);\n checkbox.changed(enableButton);\n button = createButton('button');\n button.position(10, 10);\n }\nfunction enableButton() {\n if (this.checked()) {\n // Re-enable the button\n button.removeAttribute('disabled');\n } else {\n // Disable the button\n button.attribute('disabled', '');\n }\n }\n \n// gets the value\nlet inp;\nfunction setup() {\n inp = createInput('');\n}\n\nfunction mousePressed() {\n print(inp.value());\n}\n\n// sets the value\nlet inp;\nfunction setup() {\n inp = createInput('myValue');\n}\n\nfunction mousePressed() {\n inp.value('myValue');\n}\n\n let div = createDiv('div');\n div.style('display', 'none');\n div.show(); // turns display to block\n \nlet div = createDiv('this is a div');\ndiv.hide();\n\n let div = createDiv('this is a div');\n div.size(100, 100);\n let img = createImg(\n 'assets/rockies.jpg',\n 'A tall mountain with a small forest and field in front of it on a sunny day',\n '',\n () => {\n img.size(10, AUTO);\n }\n );\n \nlet myDiv = createDiv('this is some text');\nmyDiv.remove();\n\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n\nlet img;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data, '').hide();\n}\n\nlet ele;\n\nfunction setup() {\n background(250);\n\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n //We'll set up our example so that\n //when you click on the text,\n //an alert box displays the MediaElement's\n //src field.\n textAlign(CENTER);\n text('Click Me!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Show our p5.MediaElement's src field\n alert(ele.src);\n }\n}\n\nlet ele;\n\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Here we call the play() function on\n //the p5.MediaElement we created above.\n //This will start the audio sample.\n ele.play();\n\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n }\n}\n\n//This example both starts\n//and stops a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n\n//while our audio is playing,\n//this will be set to true\nlet sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //if the sample is currently playing\n //calling the stop() function on\n //our p5.MediaElement will stop\n //it and reset its current\n //time to 0 (i.e. it will start\n //at the beginning the next time\n //you play it)\n ele.stop();\n\n sampleIsPlaying = false;\n text('Click to play!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to stop!', width / 2, height / 2);\n }\n }\n}\n\n//This example both starts\n//and pauses a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n\n//while our audio is playing,\n//this will be set to true\nlet sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //Calling pause() on our\n //p5.MediaElement will stop it\n //playing, but when we call the\n //loop() or play() functions\n //the sample will start from\n //where we paused it.\n ele.pause();\n\n sampleIsPlaying = false;\n text('Click to resume!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.pause() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to pause!', width / 2, height / 2);\n }\n }\n}\n\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n\n//while our audio is playing,\n//this will be set to true\nlet sampleIsLooping = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to loop!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (!sampleIsLooping) {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsLooping = true;\n text('Click to stop!', width / 2, height / 2);\n } else {\n ele.stop();\n\n sampleIsLooping = false;\n text('Click to loop!', width / 2, height / 2);\n }\n }\n}\n\n//This example both starts\n//and stops loop of sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n//while our audio is playing,\n//this will be set to true\nlet sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n ele.noLoop();\n text('No more Loops!', width / 2, height / 2);\n } else {\n ele.loop();\n sampleIsPlaying = true;\n text('Click to stop looping!', width / 2, height / 2);\n }\n }\n}\n\nlet ele;\nfunction setup() {\n // p5.MediaElement objects are usually created\n // by calling the createAudio(), createVideo(),\n // and createCapture() functions.\n // In this example we create\n // a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\nfunction mouseClicked() {\n // Here we call the volume() function\n // on the sound element to set its volume\n // Volume must be between 0.0 and 1.0\n ele.volume(0.2);\n ele.play();\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n}\n\nlet audio;\nlet counter = 0;\n\nfunction loaded() {\n audio.play();\n}\n\nfunction setup() {\n audio = createAudio('assets/lucky_dragons.mp3', loaded);\n textAlign(CENTER);\n}\n\nfunction draw() {\n if (counter === 0) {\n background(0, 255, 0);\n text('volume(0.9)', width / 2, height / 2);\n } else if (counter === 1) {\n background(255, 255, 0);\n text('volume(0.5)', width / 2, height / 2);\n } else if (counter === 2) {\n background(255, 0, 0);\n text('volume(0.1)', width / 2, height / 2);\n }\n}\n\nfunction mousePressed() {\n counter++;\n if (counter === 0) {\n audio.volume(0.9);\n } else if (counter === 1) {\n audio.volume(0.5);\n } else if (counter === 2) {\n audio.volume(0.1);\n } else {\n counter = 0;\n audio.volume(0.9);\n }\n}\n\n\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\nlet button;\n\nfunction setup() {\n createCanvas(710, 400);\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n ele.loop();\n background(200);\n\n button = createButton('2x speed');\n button.position(100, 68);\n button.mousePressed(twice_speed);\n\n button = createButton('half speed');\n button.position(200, 68);\n button.mousePressed(half_speed);\n\n button = createButton('reverse play');\n button.position(300, 68);\n button.mousePressed(reverse_speed);\n\n button = createButton('STOP');\n button.position(400, 68);\n button.mousePressed(stop_song);\n\n button = createButton('PLAY!');\n button.position(500, 68);\n button.mousePressed(play_speed);\n}\n\nfunction twice_speed() {\n ele.speed(2);\n}\n\nfunction half_speed() {\n ele.speed(0.5);\n}\n\nfunction reverse_speed() {\n ele.speed(-1);\n}\n\nfunction stop_song() {\n ele.stop();\n}\n\nfunction play_speed() {\n ele.play();\n}\n\nlet ele;\nlet beginning = true;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('start at beginning', width / 2, height / 2);\n}\n\n// this function fires with click anywhere\nfunction mousePressed() {\n if (beginning === true) {\n // here we start the sound at the beginning\n // time(0) is not necessary here\n // as this produces the same result as\n // play()\n ele.play().time(0);\n background(200);\n text('jump 2 sec in', width / 2, height / 2);\n beginning = false;\n } else {\n // here we jump 2 seconds into the sound\n ele.play().time(2);\n background(250);\n text('start at beginning', width / 2, height / 2);\n beginning = true;\n }\n}\n\nlet ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/doorbell.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to know the duration!', 10, 25, 70, 80);\n}\nfunction mouseClicked() {\n ele.play();\n background(200);\n //ele.duration dislpays the duration\n text(ele.duration() + ' seconds', width / 2, height / 2);\n}\n\nfunction setup() {\n let audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n audioEl.onended(sayDone);\n}\n\nfunction sayDone(elt) {\n alert('done playing ' + elt.src);\n}\n\nlet ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to Show Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.showControls();\n background(200);\n text('Controls Shown', width / 2, height / 2);\n}\n\nlet ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n ele.showControls();\n background(200);\n textAlign(CENTER);\n text('Click to hide Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.hideControls();\n background(200);\n text('Controls hidden', width / 2, height / 2);\n}\n\n//\n//\nfunction setup() {\n noCanvas();\n\n let audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n\n // schedule three calls to changeBackground\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n audioEl.addCue(5.0, changeBackground, color(255, 255, 0));\n}\n\nfunction changeBackground(val) {\n background(val);\n}\n\nlet audioEl, id1, id2;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n // schedule five calls to changeBackground\n id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n text('Click to remove first and last Cue!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n audioEl.removeCue(id1);\n audioEl.removeCue(id2);\n}\nfunction changeBackground(val) {\n background(val);\n}\n\nlet audioEl;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n //Show the default MediaElement controls, as determined by the web browser\n audioEl.showControls();\n // schedule calls to changeBackground\n background(200);\n text('Click to change Cue!', 10, 25, 70, 80);\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n}\nfunction mousePressed() {\n // here we clear the scheduled callbacks\n audioEl.clearCues();\n // then we add some more callbacks\n audioEl.addCue(1, changeBackground, color(2, 2, 2));\n audioEl.addCue(3, changeBackground, color(255, 255, 0));\n}\nfunction changeBackground(val) {\n background(val);\n}\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationX);\n}\n\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationY);\n}\n\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationZ);\n}\n\n
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.\n
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rX = rotationX + 180;\nlet pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\n\n
\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rY = rotationY + 180;\nlet pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square\'s color gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box\'s fill gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === \'X\') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n\nfunction draw() {\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n rect(25, 25, 50, 50);\n}\n\n\n// Click any key to display it!\n// (Not Guaranteed to be Case Sensitive)\nfunction setup() {\n fill(245, 123, 158);\n textSize(50);\n}\n\nfunction draw() {\n background(200);\n text(key, 33, 65); // Display last key pressed.\n}\n\nlet fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode === UP_ARROW) {\n fillVal = 255;\n } else if (keyCode === DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\n}\n\nfunction draw() {}\nfunction keyPressed() {\n background('yellow');\n text(`${key} ${keyCode}`, 10, 40);\n print(key, ' ', keyCode);\n return false; // prevent default\n}\n
\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\n
\nFor ASCII keys, the key that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.\n
\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n\n
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n\n
\nBecause of how operating systems handle key repeats, holding down a key\nwill cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.
\nBrowsers may have different default behaviors attached to various key\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n\n\nlet x = 100;\nlet y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n ellipse(x, y, 50, 50);\n}\n\nlet diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for "+"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for "-"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n}\n\n let x = 50;\n function setup() {\n rectMode(CENTER);\n }\nfunction draw() {\n if (x > 48) {\n x -= 2;\n } else if (x < 48) {\n x += 2;\n }\n x += floor(movedX / 5);\n background(237, 34, 93);\n fill(0);\n rect(x, 50, 50, 50);\n }\n \n \nlet y = 50;\nfunction setup() {\n rectMode(CENTER);\n}\n\nfunction draw() {\n if (y > 48) {\n y -= 2;\n } else if (y < 48) {\n y += 2;\n }\n y += floor(movedY / 5);\n background(237, 34, 93);\n fill(0);\n rect(y, 50, 50, 50);\n}\n\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, 0, mouseX, 100);\n}\n\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(0, mouseY, 100, mouseY);\n}\n\n\n// Move the mouse across the canvas to leave a trail\nfunction setup() {\n //slow down the frameRate to make it more visible\n frameRate(10);\n}\n\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, mouseY, pmouseX, pmouseY);\n print(pmouseX + ' -> ' + mouseX);\n}\n\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if (mouseY === pmouseY && mouseX === pmouseX) {\n rect(20, 20, 60, 60);\n }\n\n print(pmouseY + ' -> ' + mouseY);\n}\n\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n let body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //relative to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n}\n\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n let body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //relative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n}\n\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n let speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n let speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n if (mouseButton === LEFT) {\n ellipse(50, 50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n rect(25, 25, 50, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n\n print(mouseButton);\n}\n\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n ellipse(50, 50, 50, 50);\n } else {\n rect(25, 25, 50, 50);\n }\n\n print(mouseIsPressed);\n}\n\n
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\n// Move the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseMoved(event) {\n console.log(event);\n}\n\n
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\n// Drag the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseDragged(event) {\n console.log(event);\n}\n\n
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\n// Click within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mousePressed(event) {\n console.log(event);\n}\n\n
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseReleased(event) {\n console.log(event);\n}\n\n
\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see mousePressed() or mouseReleased().
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseClicked(event) {\n console.log(event);\n}\n\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a MouseEvent object\n// as a callback argument\nfunction doubleClicked(event) {\n console.log(event);\n}\n\n
\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on OS X with "natural" scrolling enabled, the signs\nare inverted).
\nBrowsers may have different default behaviors attached to various\nmouse events. To prevent any default behavior for this event, add\n"return false" to the end of the method.
\nDue to the current support of the "wheel" event on Safari, the function\nmay only work as expected if "return false" is included while using Safari.\nlet pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n\n\nlet cam;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n requestPointerLock();\n cam = createCamera();\n}\n\nfunction draw() {\n background(255);\n cam.pan(-movedX * 0.001);\n cam.tilt(movedY * 0.001);\n sphere(25);\n}\n\n\n//click the canvas to lock the pointer\n//click again to exit (otherwise escape)\nlet locked = false;\nfunction draw() {\n background(237, 34, 93);\n}\nfunction mouseClicked() {\n if (!locked) {\n locked = true;\n requestPointerLock();\n } else {\n exitPointerLock();\n locked = false;\n }\n}\n\n\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n let display = touches.length + ' touches';\n text(display, 5, 10);\n}\n\n
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.\n// Touch within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchStarted(event) {\n console.log(event);\n}\n\n
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.\n// Move your finger across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchMoved(event) {\n console.log(event);\n}\n\n
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.\n// Release touch within the image to\n// change the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchEnded(event) {\n console.log(event);\n}\n\n
\n.pixels gives access to an array containing the values for all the pixels\nin the display window.\nThese values are numbers. This array is the size (including an appropriate\nfactor for the pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. See .pixels for\nmore info. It may also be simpler to use set() or get().\n
\nBefore accessing the pixels of an image, the data must loaded with the\nloadPixels() function. After the array data has been modified, the\nupdatePixels() function must be run to update the changes.\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (img.width * d) * (img.height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n \n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n \n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, data => {\n print(data);\n });\n }\n
\nThe image may not be immediately available for rendering\nIf you want to ensure that the image is ready before doing\nanything with it, place the loadImage() call in preload().\nYou may also supply a callback function to handle the image when it's ready.\n
\nThe path to the image should be relative to the HTML file\nthat links in your sketch. Loading an image from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n\n
\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n\n
\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with colorMode()).\n
\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by colorMode(). The default maximum value is\n255.\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n\n
\nimageMode(CORNERS) interprets the second and third parameters of image()\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.\n
\nimageMode(CENTER) interprets the second and third parameters of image()\nas the image's center point. If two additional parameters are specified,\nthey are used to set the image's width and height.\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.width; i++) {\n let c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.height; i++) {\n let c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n
\nlet d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n for (let j = 0; j < d; j++) {\n // loop over\n index = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[index] = r;\n pixels[index+1] = g;\n pixels[index+2] = b;\n pixels[index+3] = a;\n }\n}
\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
\nIf this image is an animated GIF then the pixels will be updated\nin the frame that is currently displayed.\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n\nlet myImage;\nlet c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n\nlet photo;\nlet bricks;\nlet x;\nlet y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n\nlet photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n\nlet photo1;\nlet photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter(GRAY);\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nNote that the file will only be downloaded as an animated GIF\nif the p5.Image was loaded from a GIF file.\nlet photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-wink-loop-once.gif');\n}\n\nfunction draw() {\n background(255);\n // The GIF file that we loaded only loops once\n // so it freezes on the last frame after playing through\n image(gif, 0, 0);\n}\n\nfunction mousePressed() {\n // Click to reset the GIF and begin playback from start\n gif.reset();\n}\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction draw() {\n let frame = gif.getCurrentFrame();\n image(gif, 0, 0);\n text(frame, 10, 90);\n}\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\n// Move your mouse up and down over canvas to see the GIF\n// frames animate\nfunction draw() {\n gif.pause();\n image(gif, 0, 0);\n // Get the highest frame number which is the number of frames - 1\n let maxFrame = gif.numFrames() - 1;\n // Set the current frame that is mapped to be relative to mouse position\n let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));\n gif.setFrame(frameNumber);\n}\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\n// Move your mouse up and down over canvas to see the GIF\n// frames animate\nfunction draw() {\n gif.pause();\n image(gif, 0, 0);\n // Get the highest frame number which is the number of frames - 1\n let maxFrame = gif.numFrames() - 1;\n // Set the current frame that is mapped to be relative to mouse position\n let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));\n gif.setFrame(frameNumber);\n}\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction draw() {\n background(255);\n image(gif, 0, 0);\n}\n\nfunction mousePressed() {\n gif.pause();\n}\n\nfunction mouseReleased() {\n gif.play();\n}\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction draw() {\n background(255);\n image(gif, 0, 0);\n}\n\nfunction mousePressed() {\n gif.pause();\n}\n\nfunction mouseReleased() {\n gif.play();\n}\n\nlet gifFast, gifSlow;\n\nfunction preload() {\n gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n gifFast.resize(width / 2, height / 2);\n gifSlow.resize(width / 2, height / 2);\n\n //Change the delay here\n gifFast.delay(10);\n gifSlow.delay(100);\n}\n\nfunction draw() {\n background(255);\n image(gifFast, 0, 0);\n image(gifSlow, width / 2, 0);\n}\n
\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):
\nlet d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n for (let j = 0; j < d; j++) {\n // loop over\n index = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[index] = r;\n pixels[index+1] = g;\n pixels[index+2] = b;\n pixels[index+3] = a;\n }\n}
\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\n
\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.\nlet pink = color(255, 102, 204);\nloadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (width * d) * (height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n\n\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n\n
\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is
\nlet x, y, d; // set these to the coordinates\nlet off = (y * width + x) * d * 4;\nlet components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get();\n image(c, width / 2, 0);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n\nlet black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n\n\nfor (let i = 30; i < width - 15; i++) {\n for (let j = 20; j < height - 25; j++) {\n let c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n \'https://earthquake.usgs.gov/earthquakes/feed/v1.0/\' +\n \'summary/all_day.geojson\';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n\nfunction setup() {\n noLoop();\n let url =\n \'https://earthquake.usgs.gov/earthquakes/feed/v1.0/\' +\n \'summary/all_day.geojson\';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.\n
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.\nlet result;\nfunction preload() {\n result = loadStrings(\'assets/test.txt\');\n}\n\nfunction setup() {\n background(200);\n text(random(result), 10, 10, 80, 80);\n}\n\nfunction setup() {\n loadStrings(\'assets/test.txt\', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n text(random(result), 10, 10, 80, 80);\n}\n\n
\n
When passing in multiple options, pass them in as separate parameters,\nseperated by commas. For example:\n
\n\nloadTable(\'my_csv_file.csv\', \'csv\', \'header\');\n\n
All files loaded and saved use UTF-8 encoding.
\n\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadTable() inside preload()\nguarantees to complete the operation before setup() and draw() are called.\n
Outside of preload(), you may supply a callback function to handle the\nobject:
\n\n\nThis method is suitable for fetching files up to size of 64MB.
\n', + itemtype: 'method', + name: 'loadTable', + return: { + description: 'Table object containing data', + type: 'Object' + }, + example: [ + '\n\n// Given the following CSV file called "mammals.csv"\n// located in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n //the file can be remote\n //table = loadTable("http://p5js.org/reference/assets/mammals.csv",\n // "csv", "header");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + \' total rows in table\');\n print(table.getColumnCount() + \' total columns in table\');\n\n print(table.getColumn(\'name\'));\n //["Goat", "Leopard", "Zebra"]\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n\nname of the file or URL to load
\n', + type: 'String' + }, + { + name: 'options', + description: + '"header" "csv" "tsv"
\n', + type: 'String' + }, + { + name: 'callback', + description: + 'function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to be executed if\n there is an error, response is passed\n in as first argument
\n', + type: 'Function', + optional: true + } + ], + return: { + description: 'Table object containing data', + type: 'Object' + } + }, + { + line: 384, + params: [ + { + name: 'filename', + description: '', + type: 'String' + }, + { + name: 'callback', + description: '', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: '', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'Object' + } + } + ] + }, + { + file: 'src/io/files.js', + line: 604, + description: + 'Reads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadXML() inside preload()\nguarantees to complete the operation before setup() and draw() are called.
\nOutside of preload(), you may supply a callback function to handle the\nobject.
\nThis method is suitable for fetching files up to size of 64MB.
\n', + itemtype: 'method', + name: 'loadXML', + params: [ + { + name: 'filename', + description: 'name of the file or URL to load
\n', + type: 'String' + }, + { + name: 'callback', + description: + 'function to be executed after loadXML()\n completes, XML object is passed in as\n first argument
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to be executed if\n there is an error, response is passed\n in as first argument
\n', + type: 'Function', + optional: true + } + ], + return: { + description: 'XML object containing data', + type: 'Object' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let children = xml.getChildren(\'animal\');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum(\'id\');\n let coloring = children[i].getString(\'species\');\n let name = children[i].getContent();\n print(id + \', \' + coloring + \', \' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\nThis method is suitable for fetching files up to size of 64MB.
\n', + itemtype: 'method', + name: 'loadBytes', + params: [ + { + name: 'file', + description: 'name of the file or URL to load
\n', + type: 'String' + }, + { + name: 'callback', + description: + 'function to be executed after loadBytes()\n completes
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to be executed if there\n is an error
\n', + type: 'Function', + optional: true + } + ], + return: { + description: "an object whose 'bytes' property will be the loaded buffer", + type: 'Object' + }, + example: [ + "\n\nlet data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (let i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\nMethod for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET'). The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\nname of the file or url to load
\n', + type: 'String' + }, + { + name: 'datatype', + description: + '"json", "jsonp", "binary", "arrayBuffer",\n "xml", or "text"
\n', + type: 'String', + optional: true + }, + { + name: 'data', + description: 'param data passed sent with request
\n', + type: 'Object|Boolean', + optional: true + }, + { + name: 'callback', + description: + 'function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to be executed if\n there is an error, response is passed\n in as first argument
\n', + type: 'Function', + optional: true + } + ], + return: { + description: + 'A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.', + type: 'Promise' + } + }, + { + line: 829, + params: [ + { + name: 'path', + description: '', + type: 'String' + }, + { + name: 'data', + description: '', + type: 'Object|Boolean' + }, + { + name: 'callback', + description: '', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: '', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'Promise' + } + }, + { + line: 837, + params: [ + { + name: 'path', + description: '', + type: 'String' + }, + { + name: 'callback', + description: '', + type: 'Function' + }, + { + name: 'errorCallback', + description: '', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'Promise' + } + } + ] + }, + { + file: 'src/io/files.js', + line: 852, + description: + "Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST').
\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nlet url = 'https://jsonplaceholder.typicode.com/posts';\nlet postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n let r = random(255);\n let g = random(255);\n let b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n\n\nlet url = 'https://invalidURL'; // A bad URL that will cause errors\nlet postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n let r = random(255);\n let g = random(255);\n let b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\nname of the file or url to load
\n', + type: 'String' + }, + { + name: 'datatype', + description: + '"json", "jsonp", "xml", or "text".\n If omitted, httpPost() will guess.
\n', + type: 'String', + optional: true + }, + { + name: 'data', + description: 'param data passed sent with request
\n', + type: 'Object|Boolean', + optional: true + }, + { + name: 'callback', + description: + 'function to be executed after\n httpPost() completes, data is passed in\n as first argument
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to be executed if\n there is an error, response is passed\n in as first argument
\n', + type: 'Function', + optional: true + } + ], + return: { + description: + 'A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.', + type: 'Promise' + } + }, + { + line: 934, + params: [ + { + name: 'path', + description: '', + type: 'String' + }, + { + name: 'data', + description: '', + type: 'Object|Boolean' + }, + { + name: 'callback', + description: '', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: '', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'Promise' + } + }, + { + line: 942, + params: [ + { + name: 'path', + description: '', + type: 'String' + }, + { + name: 'callback', + description: '', + type: 'Function' + }, + { + name: 'errorCallback', + description: '', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'Promise' + } + } + ] + }, + { + file: 'src/io/files.js', + line: 957, + description: + 'Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.
\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when "GET" is used.
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nlet earthquakes;\nlet eqFeatureIndex = 0;\n\nfunction preload() {\n let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n let feature = earthquakes.features[eqFeatureIndex];\n let mag = feature.properties.mag;\n let rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n\nname of the file or url to load
\n', + type: 'String' + }, + { + name: 'method', + description: + 'either "GET", "POST", or "PUT",\n defaults to "GET"
\n', + type: 'String', + optional: true + }, + { + name: 'datatype', + description: + '"json", "jsonp", "xml", or "text"
\n', + type: 'String', + optional: true + }, + { + name: 'data', + description: 'param data passed sent with request
\n', + type: 'Object', + optional: true + }, + { + name: 'callback', + description: + 'function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to be executed if\n there is an error, response is passed\n in as first argument
\n', + type: 'Function', + optional: true + } + ], + return: { + description: + 'A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.', + type: 'Promise' + } + }, + { + line: 1028, + params: [ + { + name: 'path', + description: '', + type: 'String' + }, + { + name: 'options', + description: + 'Request object options as documented in the\n "fetch" API\nreference
\n', + type: 'Object' + }, + { + name: 'callback', + description: '', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: '', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'Promise' + } + } + ] + }, + { + file: 'src/io/files.js', + line: 1190, + itemtype: 'method', + name: 'createWriter', + params: [ + { + name: 'name', + description: 'name of the file to be created
\n', + type: 'String' + }, + { + name: 'extension', + description: '', + type: 'String', + optional: true + } + ], + return: { + description: '', + type: 'p5.PrintWriter' + }, + example: [ + "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n const writer = createWriter('squares.txt');\n for (let i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n }\n}\n\nWrites data to the PrintWriter stream
\n', + itemtype: 'method', + name: 'write', + params: [ + { + name: 'data', + description: 'all data to be written by the PrintWriter
\n', + type: 'Array' + } + ], + example: [ + "\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n\n\n// creates a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n\n\n// creates a file called 'newFile3.txt'\nlet writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\nWrites data to the PrintWriter stream, and adds a new line at the end
\n', + itemtype: 'method', + name: 'print', + params: [ + { + name: 'data', + description: 'all data to be printed by the PrintWriter
\n', + type: 'Array' + } + ], + example: [ + "\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n\nlet writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n\nClears the data already written to the PrintWriter object
\n', + itemtype: 'method', + name: 'clear', + example: [ + "\n\n// create writer object\nlet writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\nCloses the PrintWriter
\n', + itemtype: 'method', + name: 'close', + example: [ + "\n\n// create a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n\n\n// create a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n\nSave an image, text, json, csv, wav, or html. Prompts download to\nthe client's computer. Note that it is not recommended to call save()\nwithin draw if it's looping, as the save() function will open a new save\ndialog every frame.
\nThe default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:
\n\n save();\n save('myCanvas.jpg'); // save a specific canvas with a filename\n \n\nAlternately, the first parameter can be a pointer to a canvas\np5.Element, an Array of Strings,\nan Array of JSON, a JSON object, a p5.Table, a p5.Image, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven parameters. For example:
\n\n\n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n let img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n let cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n let gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n let myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n let myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n let arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n ",
+ itemtype: 'method',
+ name: 'save',
+ params: [
+ {
+ name: 'objectOrFilename',
+ description:
+ 'If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).
\n', + type: 'Object|String', + optional: true + }, + { + name: 'filename', + description: + 'If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).
\n', + type: 'String', + optional: true + }, + { + name: 'options', + description: + 'Additional options depend on\n filetype. For example, when saving JSON,\n true indicates that the\n output will be optimized for filesize,\n rather than readability.
Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n', + itemtype: 'method', + name: 'saveJSON', + params: [ + { + name: 'json', + description: '', + type: 'Array|Object' + }, + { + name: 'filename', + description: '', + type: 'String' + }, + { + name: 'optimize', + description: + 'If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).
\n', + type: 'Boolean', + optional: true + } + ], + example: [ + '\n\n let json = {}; // new JSON Object\n\n json.id = 0;\n json.species = \'Panthera leo\';\n json.name = \'Lion\';\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text(\'click here to save\', 10, 10, 70, 80);\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveJSON(json, \'lion.json\');\n }\n }\n\n // saves the following to a file called "lion.json":\n // {\n // "id": 0,\n // "species": "Panthera leo",\n // "name": "Lion"\n // }\n Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n', + itemtype: 'method', + name: 'saveStrings', + params: [ + { + name: 'list', + description: 'string array to be written
\n', + type: 'String[]' + }, + { + name: 'filename', + description: 'filename for output
\n', + type: 'String' + }, + { + name: 'extension', + description: 'the filename's extension
\n', + type: 'String', + optional: true + } + ], + example: [ + "\n\n let words = 'apple bear cat dog';\n\n // .split() outputs an Array\n let list = split(words, ' ');\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveStrings(list, 'nouns.txt');\n }\n }\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.
\n', + itemtype: 'method', + name: 'saveTable', + params: [ + { + name: 'Table', + description: + 'the Table object to save to a file
\n', + type: 'p5.Table' + }, + { + name: 'filename', + description: 'the filename to which the Table should be saved
\n', + type: 'String' + }, + { + name: 'options', + description: + 'can be one of "tsv", "csv", or "html"
\n', + type: 'String', + optional: true + } + ], + example: [ + "\n\n let table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n let newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n Table Options
\nGeneric class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.
\nCSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don\'t bother with the\nquotes.
\nFile names should end with .csv if they\'re comma separated.
\nA rough "spec" for CSV can be found\nhere.
\nTo load files, use the loadTable method.
\nTo save tables to your computer, use the save method\n or the saveTable method.
\n\nPossible options include:
\nAn array containing the names of the columns in the table, if the "header" the table is\nloaded with the "header" parameter.
\n', + itemtype: 'property', + name: 'columns', + type: 'String[]', + example: [ + "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //print the column names\n for (let c = 0; c < table.getColumnCount(); c++) {\n print('column ' + c + ' is named ' + table.columns[c]);\n }\n}\n\nAn array containing the p5.TableRow objects that make up the\nrows of the table. The same result as calling getRows()
\n', + itemtype: 'property', + name: 'rows', + type: 'p5.TableRow[]', + class: 'p5.Table', + module: 'IO', + submodule: 'Table' + }, + { + file: 'src/io/p5.Table.js', + line: 85, + description: + 'Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n', + itemtype: 'method', + name: 'addRow', + params: [ + { + name: 'row', + description: 'row to be added to the table
\n', + type: 'p5.TableRow', + optional: true + } + ], + return: { + description: 'the row that was added', + type: 'p5.TableRow' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n Removes a row from the table object.
\n', + itemtype: 'method', + name: 'removeRow', + params: [ + { + name: 'id', + description: 'ID number of the row to remove
\n', + type: 'Integer' + } + ], + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\nReturns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n', + itemtype: 'method', + name: 'getRow', + params: [ + { + name: 'rowID', + description: 'ID number of the row to get
\n', + type: 'Integer' + } + ], + return: { + description: 'p5.TableRow object', + type: 'p5.TableRow' + }, + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n let row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n}\n\nGets all rows from the table. Returns an array of p5.TableRows.
\n', + itemtype: 'method', + name: 'getRows', + return: { + description: 'Array of p5.TableRows', + type: 'p5.TableRow[]' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n\n //warning: rows is an array of objects\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n', + itemtype: 'method', + name: 'findRow', + params: [ + { + name: 'value', + description: 'The value to match
\n', + type: 'String' + }, + { + name: 'column', + description: + 'ID number or title of the\n column to search
\n', + type: 'Integer|String' + } + ], + return: { + description: '', + type: 'p5.TableRow' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n let row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n }\n \n Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n', + itemtype: 'method', + name: 'findRows', + params: [ + { + name: 'value', + description: 'The value to match
\n', + type: 'String' + }, + { + name: 'column', + description: + 'ID number or title of the\n column to search
\n', + type: 'Integer|String' + } + ], + return: { + description: 'An Array of TableRow objects', + type: 'p5.TableRow[]' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n let rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n }\n \n Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n', + itemtype: 'method', + name: 'matchRow', + params: [ + { + name: 'regexp', + description: 'The regular expression to match
\n', + type: 'String|RegExp' + }, + { + name: 'column', + description: + 'The column ID (number) or\n title (string)
\n', + type: 'String|Integer' + } + ], + return: { + description: 'TableRow object', + type: 'p5.TableRow' + }, + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n let mammal = table.matchRow(new RegExp(\'ant\'), 1);\n print(mammal.getString(1));\n //Output "Panthera pardus"\n}\n\nFinds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n', + itemtype: 'method', + name: 'matchRows', + params: [ + { + name: 'regexp', + description: 'The regular expression to match
\n', + type: 'String' + }, + { + name: 'column', + description: + 'The column ID (number) or\n title (string)
\n', + type: 'String|Integer', + optional: true + } + ], + return: { + description: 'An Array of TableRow objects', + type: 'p5.TableRow[]' + }, + example: [ + "\n\nlet table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n let rows = table.matchRows('R.*', 'type');\n for (let i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n\nRetrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n', + itemtype: 'method', + name: 'getColumn', + params: [ + { + name: 'column', + description: 'String or Number of the column to return
\n', + type: 'String|Number' + } + ], + return: { + description: 'Array of column values', + type: 'Array' + }, + example: [ + '\n\n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn(\'species\'));\n //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"]\n }\n \n Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n', + itemtype: 'method', + name: 'clearRows', + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n \n Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n', + itemtype: 'method', + name: 'addColumn', + params: [ + { + name: 'title', + description: 'title of the given column
\n', + type: 'String', + optional: true + } + ], + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n Returns the total number of columns in a Table.
\n', + itemtype: 'method', + name: 'getColumnCount', + return: { + description: 'Number of columns in this table', + type: 'Integer' + }, + example: [ + "\n\n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n let numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n \n Returns the total number of rows in a Table.
\n', + itemtype: 'method', + name: 'getRowCount', + return: { + description: 'Number of rows in this table', + type: 'Integer' + }, + example: [ + "\n\n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n \n Removes any of the specified characters (or "tokens").
\n\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
', + itemtype: 'method', + name: 'removeTokens', + params: [ + { + name: 'chars', + description: 'String listing characters to be removed
\n', + type: 'String' + }, + { + name: 'column', + description: + 'Column ID (number)\n or name (string)
\n', + type: 'String|Integer', + optional: true + } + ], + example: [ + "\n\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n', + itemtype: 'method', + name: 'trim', + params: [ + { + name: 'column', + description: + 'Column ID (number)\n or name (string)
\n', + type: 'String|Integer', + optional: true + } + ], + example: [ + "\n\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n', + itemtype: 'method', + name: 'removeColumn', + params: [ + { + name: 'column', + description: 'columnName (string) or ID (number)
\n', + type: 'String|Integer' + } + ], + example: [ + "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n }\n \n Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'row', + description: 'row ID
\n', + type: 'Integer' + }, + { + name: 'column', + description: + 'column ID (Number)\n or title (String)
\n', + type: 'String|Integer' + }, + { + name: 'value', + description: 'value to assign
\n', + type: 'String|Number' + } + ], + example: [ + "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\nStores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n', + itemtype: 'method', + name: 'setNum', + params: [ + { + name: 'row', + description: 'row ID
\n', + type: 'Integer' + }, + { + name: 'column', + description: + 'column ID (Number)\n or title (String)
\n', + type: 'String|Integer' + }, + { + name: 'value', + description: 'value to assign
\n', + type: 'Number' + } + ], + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n table.setNum(1, \'id\', 1);\n\n print(table.getColumn(0));\n //["0", 1, "2"]\n}\n\nStores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n', + itemtype: 'method', + name: 'setString', + params: [ + { + name: 'row', + description: 'row ID
\n', + type: 'Integer' + }, + { + name: 'column', + description: + 'column ID (Number)\n or title (String)
\n', + type: 'String|Integer' + }, + { + name: 'value', + description: 'value to assign
\n', + type: 'String' + } + ], + example: [ + "\n\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n}\nRetrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n', + itemtype: 'method', + name: 'get', + params: [ + { + name: 'row', + description: 'row ID
\n', + type: 'Integer' + }, + { + name: 'column', + description: + 'columnName (string) or\n ID (number)
\n', + type: 'String|Integer' + } + ], + return: { + description: '', + type: 'String|Number' + }, + example: [ + "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n\nRetrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n', + itemtype: 'method', + name: 'getNum', + params: [ + { + name: 'row', + description: 'row ID
\n', + type: 'Integer' + }, + { + name: 'column', + description: + 'columnName (string) or\n ID (number)
\n', + type: 'String|Integer' + } + ], + return: { + description: '', + type: 'Number' + }, + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n\nRetrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n', + itemtype: 'method', + name: 'getString', + params: [ + { + name: 'row', + description: 'row ID
\n', + type: 'Integer' + }, + { + name: 'column', + description: + 'columnName (string) or\n ID (number)
\n', + type: 'String|Integer' + } + ], + return: { + description: '', + type: 'String' + }, + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value "CSV"\n // and has specifiying header for column labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n\nRetrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n', + itemtype: 'method', + name: 'getObject', + params: [ + { + name: 'headerColumn', + description: + 'Name of the column which should be used to\n title each row object (optional)
\n', + type: 'String', + optional: true + } + ], + return: { + description: '', + type: 'Object' + }, + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n let tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n\nRetrieves all table data and returns it as a multidimensional array.
\n', + itemtype: 'method', + name: 'getArray', + return: { + description: '', + type: 'Array' + }, + example: [ + '\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value "CSV"\n // and has specifiying header for column labels\n table = loadTable(\'assets/mammals.csv\', \'csv\', \'header\');\n}\n\nfunction setup() {\n let tableArray = table.getArray();\n for (let i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n\nStores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'column', + description: + 'Column ID (Number)\n or Title (String)
\n', + type: 'String|Integer' + }, + { + name: 'value', + description: 'The value to be stored
\n', + type: 'String|Number' + } + ], + example: [ + "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n', + itemtype: 'method', + name: 'setNum', + params: [ + { + name: 'column', + description: + 'Column ID (Number)\n or Title (String)
\n', + type: 'String|Integer' + }, + { + name: 'value', + description: + 'The value to be stored\n as a Float
\n', + type: 'Number|String' + } + ], + example: [ + "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n', + itemtype: 'method', + name: 'setString', + params: [ + { + name: 'column', + description: + 'Column ID (Number)\n or Title (String)
\n', + type: 'String|Integer' + }, + { + name: 'value', + description: + 'The value to be stored\n as a String
\n', + type: 'String|Number|Boolean|Object' + } + ], + example: [ + "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n let name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n', + itemtype: 'method', + name: 'get', + params: [ + { + name: 'column', + description: + 'columnName (string) or\n ID (number)
\n', + type: 'String|Integer' + } + ], + return: { + description: '', + type: 'String|Number' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let names = [];\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n', + itemtype: 'method', + name: 'getNum', + params: [ + { + name: 'column', + description: + 'columnName (string) or\n ID (number)
\n', + type: 'String|Integer' + } + ], + return: { + description: 'Float Floating point number', + type: 'Number' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let minId = Infinity;\n let maxId = -Infinity;\n for (let r = 0; r < rows.length; r++) {\n let id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n', + itemtype: 'method', + name: 'getString', + params: [ + { + name: 'column', + description: + 'columnName (string) or\n ID (number)
\n', + type: 'String|Integer' + } + ], + return: { + description: 'String', + type: 'String' + }, + example: [ + "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let longest = '';\n for (let r = 0; r < rows.length; r++) {\n let species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n Gets a copy of the element's parent. Returns the parent as another\np5.XML object.
\n', + itemtype: 'method', + name: 'getParent', + return: { + description: 'element parent', + type: 'p5.XML' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let children = xml.getChildren(\'animal\');\n let parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\nGets the element's full name, which is returned as a String.
\n', + itemtype: 'method', + name: 'getName', + return: { + description: 'the name of the node', + type: 'String' + }, + example: [ + '<animal\n\n // The following short XML file called "mammals.xml" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id="0" species="Capra hircus">Goat</animal>\n // <animal id="1" species="Panthera pardus">Leopard</animal>\n // <animal id="2" species="Equus zebra">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML(\'assets/mammals.xml\');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n Sets the element's name, which is specified as a String.
\n', + itemtype: 'method', + name: 'setName', + params: [ + { + name: 'the', + description: 'new name of the node
\n', + type: 'String' + } + ], + example: [ + '<animal\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName(\'fish\');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\nChecks whether or not the element has any children, and returns the result\nas a boolean.
\n', + itemtype: 'method', + name: 'hasChildren', + return: { + description: '', + type: 'Boolean' + }, + example: [ + '<animal\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\nGet the names of all of the element's children, and returns the names as an\narray of Strings. This is the same as looping through and calling getName()\non each child element individually.
\n', + itemtype: 'method', + name: 'listChildren', + return: { + description: 'names of the children of the element', + type: 'String[]' + }, + example: [ + '<animal\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// ["animal", "animal", "animal"]\nReturns all of the element's children as an array of p5.XML objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.
\n', + itemtype: 'method', + name: 'getChildren', + params: [ + { + name: 'name', + description: 'element name
\n', + type: 'String', + optional: true + } + ], + return: { + description: 'children of the element', + type: 'p5.XML[]' + }, + example: [ + '<animal\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let animals = xml.getChildren(\'animal\');\n\n for (let i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// "Goat"\n// "Leopard"\n// "Zebra"\nReturns the first of the element's children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.
\n', + itemtype: 'method', + name: 'getChild', + params: [ + { + name: 'name', + description: 'element name or index
\n', + type: 'String|Integer' + } + ], + return: { + description: '', + type: 'p5.XML' + }, + example: [ + '<animal\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// "Goat"\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// "Leopard"\nAppends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag's name, or as a\nreference to an existing p5.XML object.\nA reference to the newly created child is returned as an p5.XML object.
\n', + itemtype: 'method', + name: 'addChild', + params: [ + { + name: 'node', + description: + 'a p5.XML Object which will be the child to be added
\n', + type: 'p5.XML' + } + ], + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let child = new p5.XML();\n child.setName(\'animal\');\n child.setAttribute(\'id\', \'3\');\n child.setAttribute(\'species\', \'Ornithorhynchus anatinus\');\n child.setContent(\'Platypus\');\n xml.addChild(child);\n\n let animals = xml.getChildren(\'animal\');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// "Goat"\n// "Leopard"\n// "Zebra"\nRemoves the element specified by name or index.
\n', + itemtype: 'method', + name: 'removeChild', + params: [ + { + name: 'name', + description: 'element name or index
\n', + type: 'String|Integer' + } + ], + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n xml.removeChild(\'animal\');\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// "Leopard"\n// "Zebra"\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n xml.removeChild(1);\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// "Goat"\n// "Zebra"\nCounts the specified element's number of attributes, returned as an Number.
\n', + itemtype: 'method', + name: 'getAttributeCount', + return: { + description: '', + type: 'Integer' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\nGets all of the specified element's attributes, and returns them as an\narray of Strings.
\n', + itemtype: 'method', + name: 'listAttributes', + return: { + description: 'an array of strings containing the names of attributes', + type: 'String[]' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// ["id", "species"]\nChecks whether or not an element has the specified attribute.
\n', + itemtype: 'method', + name: 'hasAttribute', + params: [ + { + name: 'the', + description: 'attribute to be checked
\n', + type: 'String' + } + ], + return: { + description: 'true if attribute found else false', + type: 'Boolean' + }, + example: [ + '\n\n // The following short XML file called "mammals.xml" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id="0" species="Capra hircus">Goat</animal>\n // <animal id="1" species="Panthera pardus">Leopard</animal>\n // <animal id="2" species="Equus zebra">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML(\'assets/mammals.xml\');\n }\n\n function setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.hasAttribute(\'species\'));\n print(firstChild.hasAttribute(\'color\'));\n }\n\n // Sketch prints:\n // true\n // false\n Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, the value 0 is returned.
\n', + itemtype: 'method', + name: 'getNum', + params: [ + { + name: 'name', + description: 'the non-null full name of the attribute
\n', + type: 'String' + }, + { + name: 'defaultValue', + description: 'the default value of the attribute
\n', + type: 'Number', + optional: true + } + ], + return: { + description: '', + type: 'Number' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getNum(\'id\'));\n}\n\n// Sketch prints:\n// 0\nReturns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, null is returned.
\n', + itemtype: 'method', + name: 'getString', + params: [ + { + name: 'name', + description: 'the non-null full name of the attribute
\n', + type: 'String' + }, + { + name: 'defaultValue', + description: 'the default value of the attribute
\n', + type: 'Number', + optional: true + } + ], + return: { + description: '', + type: 'String' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getString(\'species\'));\n}\n\n// Sketch prints:\n// "Capra hircus"\nSets the content of an element's attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.
\n', + itemtype: 'method', + name: 'setAttribute', + params: [ + { + name: 'name', + description: 'the full name of the attribute
\n', + type: 'String' + }, + { + name: 'value', + description: 'the value of the attribute
\n', + type: 'Number|String|Boolean' + } + ], + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getString(\'species\'));\n firstChild.setAttribute(\'species\', \'Jamides zebra\');\n print(firstChild.getString(\'species\'));\n}\n\n// Sketch prints:\n// "Capra hircus"\n// "Jamides zebra"\nReturns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.
\n', + itemtype: 'method', + name: 'getContent', + params: [ + { + name: 'defaultValue', + description: 'value returned if no content is found
\n', + type: 'String', + optional: true + } + ], + return: { + description: '', + type: 'String' + }, + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// "Goat"\nSets the element's content.
\n', + itemtype: 'method', + name: 'setContent', + params: [ + { + name: 'text', + description: 'the new content
\n', + type: 'String' + } + ], + example: [ + '\n\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n let firstChild = xml.getChild(\'animal\');\n print(firstChild.getContent());\n firstChild.setContent(\'Mountain Goat\');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// "Goat"\n// "Mountain Goat"\nSerializes the element into a string. This function is useful for preparing\nthe content to be sent over a http request or saved to file.
\n', + itemtype: 'method', + name: 'serialize', + return: { + description: 'Serialized string of the element', + type: 'String' + }, + example: [ + '\n\nlet xml;\n\nfunction preload() {\n xml = loadXML(\'assets/mammals.xml\');\n}\n\nfunction setup() {\n print(xml.serialize());\n}\n\n// Sketch prints:\n// \n// Goat \n// Leopard \n// Zebra \n// \nCalculates the absolute value (magnitude) of a number. Maps to Math.abs().\nThe absolute value of a number is always positive.
\n', + itemtype: 'method', + name: 'abs', + params: [ + { + name: 'n', + description: 'number to compute
\n', + type: 'Number' + } + ], + return: { + description: 'absolute value of given number', + type: 'Number' + }, + example: [ + '\n\nfunction setup() {\n let x = -3;\n let y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\nCalculates the closest int value that is greater than or equal to the\nvalue of the parameter. Maps to Math.ceil(). For example, ceil(9.03)\nreturns the value 10.
\n', + itemtype: 'method', + name: 'ceil', + params: [ + { + name: 'n', + description: 'number to round up
\n', + type: 'Number' + } + ], + return: { + description: 'rounded up number', + type: 'Integer' + }, + example: [ + '\n\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the ceiling of the mapped number.\n let bx = ceil(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\nConstrains a value between a minimum and maximum value.
\n', + itemtype: 'method', + name: 'constrain', + params: [ + { + name: 'n', + description: 'number to constrain
\n', + type: 'Number' + }, + { + name: 'low', + description: 'minimum limit
\n', + type: 'Number' + }, + { + name: 'high', + description: 'maximum limit
\n', + type: 'Number' + } + ], + return: { + description: 'constrained number', + type: 'Number' + }, + example: [ + '\n\nfunction draw() {\n background(200);\n\n let leftWall = 25;\n let rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n let xm = mouseX;\n let xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n}\nCalculates the distance between two points, in either two or three dimensions.
\n', + itemtype: 'method', + name: 'dist', + return: { + description: 'distance between the two points', + type: 'Number' + }, + example: [ + "\n\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n let x1 = 10;\n let y1 = 90;\n let x2 = mouseX;\n let y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n let d = int(dist(x1, y1, x2, y2));\n\n // Let's write d along the line we are drawing!\n push();\n translate((x1 + x2) / 2, (y1 + y2) / 2);\n rotate(atan2(y2 - y1, x2 - x1));\n text(nfc(d, 1), 0, -5);\n pop();\n // Fancy!\n}\nx-coordinate of the first point
\n', + type: 'Number' + }, + { + name: 'y1', + description: 'y-coordinate of the first point
\n', + type: 'Number' + }, + { + name: 'x2', + description: 'x-coordinate of the second point
\n', + type: 'Number' + }, + { + name: 'y2', + description: 'y-coordinate of the second point
\n', + type: 'Number' + } + ], + return: { + description: 'distance between the two points', + type: 'Number' + } + }, + { + line: 163, + params: [ + { + name: 'x1', + description: '', + type: 'Number' + }, + { + name: 'y1', + description: '', + type: 'Number' + }, + { + name: 'z1', + description: 'z-coordinate of the first point
\n', + type: 'Number' + }, + { + name: 'x2', + description: '', + type: 'Number' + }, + { + name: 'y2', + description: '', + type: 'Number' + }, + { + name: 'z2', + description: 'z-coordinate of the second point
\n', + type: 'Number' + } + ], + return: { + description: 'distance between the two points', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/calculation.js', + line: 184, + description: + 'Returns Euler's number e (2.71828...) raised to the power of the n\nparameter. Maps to Math.exp().
\n', + itemtype: 'method', + name: 'exp', + params: [ + { + name: 'n', + description: 'exponent to raise
\n', + type: 'Number' + } + ], + return: { + description: 'e^n', + type: 'Number' + }, + example: [ + "\n\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n let xValue = map(mouseX, 0, width, 0, 2);\n let yValue = exp(xValue);\n\n let y = map(yValue, 0, 8, height, 0);\n\n let legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n}\nCalculates the closest int value that is less than or equal to the\nvalue of the parameter. Maps to Math.floor().
\n', + itemtype: 'method', + name: 'floor', + params: [ + { + name: 'n', + description: 'number to round down
\n', + type: 'Number' + } + ], + return: { + description: 'rounded down number', + type: 'Integer' + }, + example: [ + '\n\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the floor of the mapped number.\n let bx = floor(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\nCalculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, and 1.0 is equal to the second point. If the\nvalue of amt is more than 1.0 or less than 0.0, the number will be\ncalculated accordingly in the ratio of the two given numbers. The lerp\nfunction is convenient for creating motion along a straight\npath and for drawing dotted lines.
\n', + itemtype: 'method', + name: 'lerp', + params: [ + { + name: 'start', + description: 'first value
\n', + type: 'Number' + }, + { + name: 'stop', + description: 'second value
\n', + type: 'Number' + }, + { + name: 'amt', + description: 'number
\n', + type: 'Number' + } + ], + return: { + description: 'lerped value', + type: 'Number' + }, + example: [ + '\n\nfunction setup() {\n background(200);\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n let y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\nCalculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().
\n', + itemtype: 'method', + name: 'log', + params: [ + { + name: 'n', + description: 'number greater than 0
\n', + type: 'Number' + } + ], + return: { + description: 'natural logarithm of n', + type: 'Number' + }, + example: [ + "\n\nfunction draw() {\n background(200);\n let maxX = 2.8;\n let maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n let xValue = map(mouseX, 0, width, 0, maxX);\n let yValue, y;\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n let legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n}\nCalculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no "start" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).
\n', + itemtype: 'method', + name: 'mag', + params: [ + { + name: 'a', + description: 'first value
\n', + type: 'Number' + }, + { + name: 'b', + description: 'second value
\n', + type: 'Number' + } + ], + return: { + description: 'magnitude of vector from (0,0) to (a,b)', + type: 'Number' + }, + example: [ + '\n\nfunction setup() {\n let x1 = 20;\n let x2 = 80;\n let y1 = 30;\n let y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints "36.05551275463989"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints "85.44003745317531"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints "72.80109889280519"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints "106.3014581273465"\n}\nRe-maps a number from one range to another.\n
\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).
the incoming value to be converted
\n', + type: 'Number' + }, + { + name: 'start1', + description: 'lower bound of the value's current range
\n', + type: 'Number' + }, + { + name: 'stop1', + description: 'upper bound of the value's current range
\n', + type: 'Number' + }, + { + name: 'start2', + description: 'lower bound of the value's target range
\n', + type: 'Number' + }, + { + name: 'stop2', + description: 'upper bound of the value's target range
\n', + type: 'Number' + }, + { + name: 'withinBounds', + description: 'constrain the value to the newly mapped range
\n', + type: 'Boolean', + optional: true + } + ], + return: { + description: 'remapped number', + type: 'Number' + }, + example: [ + '\n\nlet value = 25;\nlet m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n let x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n let x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\nDetermines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.
\n', + itemtype: 'method', + name: 'max', + return: { + description: 'maximum Number', + type: 'Number' + }, + example: [ + "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\nNumber to compare
\n', + type: 'Number' + }, + { + name: 'n1', + description: 'Number to compare
\n', + type: 'Number' + } + ], + return: { + description: 'maximum Number', + type: 'Number' + } + }, + { + line: 508, + params: [ + { + name: 'nums', + description: 'Numbers to compare
\n', + type: 'Number[]' + } + ], + return: { + description: '', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/calculation.js', + line: 522, + description: + 'Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.
\n', + itemtype: 'method', + name: 'min', + return: { + description: 'minimum Number', + type: 'Number' + }, + example: [ + "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\nNumber to compare
\n', + type: 'Number' + }, + { + name: 'n1', + description: 'Number to compare
\n', + type: 'Number' + } + ], + return: { + description: 'minimum Number', + type: 'Number' + } + }, + { + line: 558, + params: [ + { + name: 'nums', + description: 'Numbers to compare
\n', + type: 'Number[]' + } + ], + return: { + description: '', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/calculation.js', + line: 572, + description: + 'Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the example above.)
\n', + itemtype: 'method', + name: 'norm', + params: [ + { + name: 'value', + description: 'incoming value to be normalized
\n', + type: 'Number' + }, + { + name: 'start', + description: 'lower bound of the value's current range
\n', + type: 'Number' + }, + { + name: 'stop', + description: 'upper bound of the value's current range
\n', + type: 'Number' + } + ], + return: { + description: 'normalized number', + type: 'Number' + }, + example: [ + "\n\nfunction draw() {\n background(200);\n let currentNum = mouseX;\n let lowerBound = 0;\n let upperBound = width; //100;\n let normalized = norm(currentNum, lowerBound, upperBound);\n let lineY = 70;\n stroke(3);\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n let s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n let guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n let normalY = 40;\n let normalX = 20;\n text(normalized, normalX, normalY);\n}\nFacilitates exponential expressions. The pow() function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n3 × 3 × 3 × 3 × 3 and pow(3, -5) is equivalent to 1 /\n3 × 3 × 3 × 3 × 3. Maps to\nMath.pow().
\n', + itemtype: 'method', + name: 'pow', + params: [ + { + name: 'n', + description: 'base of the exponential expression
\n', + type: 'Number' + }, + { + name: 'e', + description: 'power by which to raise the base
\n', + type: 'Number' + } + ], + return: { + description: 'n^e', + type: 'Number' + }, + example: [ + '\n\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n let eSize = 3; // Original Size\n let eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n}\nCalculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().
\n', + itemtype: 'method', + name: 'round', + params: [ + { + name: 'n', + description: 'number to round
\n', + type: 'Number' + } + ], + return: { + description: 'rounded number', + type: 'Integer' + }, + example: [ + '\n\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n // Round the mapped number.\n let bx = round(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\nSquares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.
\n', + itemtype: 'method', + name: 'sq', + params: [ + { + name: 'n', + description: 'number to square
\n', + type: 'Number' + } + ], + return: { + description: 'squared number', + type: 'Number' + }, + example: [ + "\n\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = map(mouseX, 0, width, 0, 10);\n let y1 = 80;\n let x2 = sq(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n let spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n}\nCalculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().
\n', + itemtype: 'method', + name: 'sqrt', + params: [ + { + name: 'n', + description: 'non-negative number to square root
\n', + type: 'Number' + } + ], + return: { + description: 'square root of number', + type: 'Number' + }, + example: [ + "\n\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = mouseX;\n let y1 = 80;\n let x2 = sqrt(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n let spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n}\nCreates a new p5.Vector (the datatype for storing vectors). This provides a\ntwo or three dimensional vector, specifically a Euclidean (also known as\ngeometric) vector. A vector is an entity that has both magnitude and\ndirection.
\n', + itemtype: 'method', + name: 'createVector', + params: [ + { + name: 'x', + description: 'x component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'y', + description: 'y component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'z component of the vector
\n', + type: 'Number', + optional: true + } + ], + return: { + description: '', + type: 'p5.Vector' + }, + example: [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255, 102, 204);\n}\n\nfunction draw() {\n background(255);\n pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));\n scale(0.75);\n sphere();\n}\nReturns the Perlin noise value at specified coordinates. Perlin noise is\na random sequence generator producing a more natural ordered, harmonic\nsuccession of numbers compared to the standard random() function.\nIt was invented by Ken Perlin in the 1980s and been used since in\ngraphical applications to produce procedural textures, natural motion,\nshapes, terrains etc.
The main difference to the\nrandom() function is that Perlin noise is defined in an infinite\nn-dimensional space where each pair of coordinates corresponds to a\nfixed semi-random value (fixed only for the lifespan of the program; see\nthe noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,\ndepending on the number of coordinates given. The resulting value will\nalways be between 0.0 and 1.0. The noise value can be animated by moving\nthrough the noise space as demonstrated in the example above. The 2nd\nand 3rd dimension can also be interpreted as time.
The actual\nnoise is structured similar to an audio signal, in respect to the\nfunction's use of frequencies. Similar to the concept of harmonics in\nphysics, perlin noise is computed over several octaves which are added\ntogether for the final result.
Another way to adjust the\ncharacter of the resulting sequence is the scale of the input\ncoordinates. As the function works within an infinite space the value of\nthe coordinates doesn't matter as such, only the distance between\nsuccessive coordinates does (eg. when using noise() within a\nloop). As a general rule the smaller the difference between coordinates,\nthe smoother the resulting noise sequence will be. Steps of 0.005-0.03\nwork best for most applications, but this will differ depending on use.
x-coordinate in noise space
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y-coordinate in noise space
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'z-coordinate in noise space
\n', + type: 'Number', + optional: true + } + ], + return: { + description: + 'Perlin noise value (between 0 and 1) at specified\n coordinates', + type: 'Number' + }, + example: [ + '\n\nlet xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\nlet noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (let x=0; x < width; x++) {\n let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n\nAdjusts the character and level of detail produced by the Perlin noise\n function. Similar to harmonics in physics, noise is computed over\n several octaves. Lower octaves contribute more to the output signal and\n as such define the overall intensity of the noise, whereas higher octaves\n create finer grained details in the noise sequence.\n
\n By default, noise is computed over 4 octaves with each octave contributing\n exactly half than its predecessor, starting at 50% strength for the 1st\n octave. This falloff amount can be changed by adding an additional function\n parameter. Eg. a falloff factor of 0.75 means each octave will now have\n 75% impact (25% less) of the previous lower octave. Any value between\n 0.0 and 1.0 is valid, however note that values greater than 0.5 might\n result in greater than 1.0 values returned by noise().\n
\n By changing these parameters, the signal created by the noise()\n function can be adapted to fit very specific needs and characteristics.
number of octaves to be used by the noise
\n', + type: 'Number' + }, + { + name: 'falloff', + description: 'falloff factor for each octave
\n', + type: 'Number' + } + ], + example: [ + '\n\n let noiseVal;\n let noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n \n Sets the seed value for noise(). By default, noise()\nproduces different results each time the program is run. Set the\nvalue parameter to a constant to return the same pseudo-random\nnumbers each time the software is run.
\n', + itemtype: 'method', + name: 'noiseSeed', + params: [ + { + name: 'seed', + description: 'the seed value
\n', + type: 'Number' + } + ], + example: [ + '\nlet xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\nThe x component of the vector
\n', + itemtype: 'property', + name: 'x', + type: 'Number', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 70, + description: 'The y component of the vector
\n', + itemtype: 'property', + name: 'y', + type: 'Number', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 75, + description: 'The z component of the vector
\n', + itemtype: 'property', + name: 'z', + type: 'Number', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 82, + description: + 'Returns a string representation of a vector v by calling String(v)\nor v.toString(). This method is useful for logging vectors in the\nconsole.
\n', + itemtype: 'method', + name: 'toString', + return: { + description: '', + type: 'String' + }, + example: [ + '\n\nfunction setup() {\n let v = createVector(20, 30);\n print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"\n}\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, \'black\');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nSets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Vector, or the values from a float array.
\n', + itemtype: 'method', + name: 'set', + chainable: 1, + example: [ + "\n\nfunction setup() {\n let v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n let v1 = createVector(0, 0, 0);\n let arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n\n\nlet v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe x component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'y', + description: 'the y component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'the z component of the vector
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 191, + params: [ + { + name: 'value', + description: 'the vector to set
\n', + type: 'p5.Vector|Number[]' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 215, + description: + 'Gets a copy of the vector, returns a p5.Vector object.
\n', + itemtype: 'method', + name: 'copy', + return: { + description: 'the copy of the p5.Vector object', + type: 'p5.Vector' + }, + example: [ + '\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints "true"\n\nAdds x, y, and z components to a vector, adds one vector to another, or\nadds two independent vectors together. The version of the method that adds\ntwo vectors together is a static method and returns a p5.Vector, the others\nacts directly on the vector. See the examples for more context.
\n', + itemtype: 'method', + name: 'add', + chainable: 1, + example: [ + "\n\nlet v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nlet v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n let v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe x component of the vector to be added
\n', + type: 'Number' + }, + { + name: 'y', + description: 'the y component of the vector to be added
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'the z component of the vector to be added
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 304, + params: [ + { + name: 'value', + description: 'the vector to add
\n', + type: 'p5.Vector|Number[]' + } + ], + chainable: 1 + }, + { + line: 1557, + params: [ + { + name: 'v1', + description: + 'a p5.Vector to add
\n', + type: 'p5.Vector' + }, + { + name: 'v2', + description: + 'a p5.Vector to add
\n', + type: 'p5.Vector' + }, + { + name: 'target', + description: 'the vector to receive the result
\n', + type: 'p5.Vector' + } + ], + static: 1 + }, + { + line: 1564, + params: [ + { + name: 'v1', + description: '', + type: 'p5.Vector' + }, + { + name: 'v2', + description: '', + type: 'p5.Vector' + } + ], + static: 1, + return: { + description: 'the resulting p5.Vector', + type: 'p5.Vector' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 328, + description: + 'Subtracts x, y, and z components from a vector, subtracts one vector from\nanother, or subtracts two independent vectors. The version of the method\nthat subtracts two vectors is a static method and returns a p5.Vector, the\nother acts directly on the vector. See the examples for more context.
\n', + itemtype: 'method', + name: 'sub', + chainable: 1, + example: [ + "\n\nlet v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n\n\n// Static method\nlet v1 = createVector(2, 3, 4);\nlet v2 = createVector(1, 2, 3);\n\nlet v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n let v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe x component of the vector to subtract
\n', + type: 'Number' + }, + { + name: 'y', + description: 'the y component of the vector to subtract
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'the z component of the vector to subtract
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 394, + params: [ + { + name: 'value', + description: 'the vector to subtract
\n', + type: 'p5.Vector|Number[]' + } + ], + chainable: 1 + }, + { + line: 1587, + params: [ + { + name: 'v1', + description: + 'a p5.Vector to subtract from
\n', + type: 'p5.Vector' + }, + { + name: 'v2', + description: + 'a p5.Vector to subtract
\n', + type: 'p5.Vector' + }, + { + name: 'target', + description: 'if undefined a new vector will be created
\n', + type: 'p5.Vector' + } + ], + static: 1 + }, + { + line: 1594, + params: [ + { + name: 'v1', + description: '', + type: 'p5.Vector' + }, + { + name: 'v2', + description: '', + type: 'p5.Vector' + } + ], + static: 1, + return: { + description: 'the resulting p5.Vector', + type: 'p5.Vector' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 418, + description: + 'Multiply the vector by a scalar. The static version of this method\ncreates a new p5.Vector while the non static version acts on the vector\ndirectly. See the examples for more context.
\n', + itemtype: 'method', + name: 'mult', + chainable: 1, + example: [ + "\n\nlet v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, -2, 2, true);\n let v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe number to multiply with the vector
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 1615, + params: [ + { + name: 'v', + description: 'the vector to multiply
\n', + type: 'p5.Vector' + }, + { + name: 'n', + description: '', + type: 'Number' + }, + { + name: 'target', + description: 'if undefined a new vector will be created
\n', + type: 'p5.Vector' + } + ], + static: 1 + }, + { + line: 1622, + params: [ + { + name: 'v', + description: '', + type: 'p5.Vector' + }, + { + name: 'n', + description: '', + type: 'Number' + } + ], + static: 1, + return: { + description: 'the resulting new p5.Vector', + type: 'p5.Vector' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 493, + description: + 'Divide the vector by a scalar. The static version of this method creates a\nnew p5.Vector while the non static version acts on the vector directly.\nSee the examples for more context.
\n', + itemtype: 'method', + name: 'div', + chainable: 1, + example: [ + "\n\nlet v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nlet v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 100);\n let v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, 10, 0.5, true);\n let v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe number to divide the vector by
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 1642, + params: [ + { + name: 'v', + description: 'the vector to divide
\n', + type: 'p5.Vector' + }, + { + name: 'n', + description: '', + type: 'Number' + }, + { + name: 'target', + description: 'if undefined a new vector will be created
\n', + type: 'p5.Vector' + } + ], + static: 1 + }, + { + line: 1649, + params: [ + { + name: 'v', + description: '', + type: 'p5.Vector' + }, + { + name: 'n', + description: '', + type: 'Number' + } + ], + static: 1, + return: { + description: 'the resulting new p5.Vector', + type: 'p5.Vector' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 571, + description: + 'Calculates the magnitude (length) of the vector and returns the result as\na float (this is simply the equation sqrt(xx + yy + z*z).)
\n', + itemtype: 'method', + name: 'mag', + return: { + description: 'magnitude of the vector', + type: 'Number' + }, + example: [ + '\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, \'black\');\n\n noStroke();\n text(\'vector length: \' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n\nlet v = createVector(20.0, 30.0, 40.0);\nlet m = v.mag();\nprint(m); // Prints "53.85164807134504"\n\nthe vector to return the magnitude of
\n', + type: 'p5.Vector' + } + ], + static: 1, + return: { + description: 'the magnitude of vecT', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 619, + description: + 'Calculates the squared magnitude of the vector and returns the result\nas a float (this is simply the equation (xx + yy + z*z).)\nFaster if the real length is not required in the\ncase of comparing vectors, etc.
\n', + itemtype: 'method', + name: 'magSq', + return: { + description: 'squared magnitude of the vector', + type: 'Number' + }, + example: [ + '\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints "56"\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, \'black\');\n\n noStroke();\n text(\'vector length squared: \' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nCalculates the dot product of two vectors. The version of the method\nthat computes the dot product of two independent vectors is a static\nmethod. See the examples for more context.
\n', + itemtype: 'method', + name: 'dot', + return: { + description: 'the dot product', + type: 'Number' + }, + example: [ + '\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints "20"\n\n\n//Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints "10"\n\nx component of the vector
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'z component of the vector
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'the dot product', + type: 'Number' + } + }, + { + line: 704, + params: [ + { + name: 'value', + description: + 'value component of the vector or a p5.Vector
\n', + type: 'p5.Vector' + } + ], + return: { + description: '', + type: 'Number' + } + }, + { + line: 1669, + params: [ + { + name: 'v1', + description: + 'the first p5.Vector
\n', + type: 'p5.Vector' + }, + { + name: 'v2', + description: + 'the second p5.Vector
\n', + type: 'p5.Vector' + } + ], + static: 1, + return: { + description: 'the dot product', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 716, + description: + 'Calculates and returns a vector composed of the cross product between\ntwo vectors. Both the static and non static methods return a new p5.Vector.\nSee the examples for more context.
\n', + itemtype: 'method', + name: 'cross', + return: { + description: + 'p5.Vector composed of cross product', + type: 'p5.Vector' + }, + example: [ + '\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v\'s components are [0, 0, 0]\n\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n\np5.Vector to be crossed
\n', + type: 'p5.Vector' + } + ], + return: { + description: + 'p5.Vector composed of cross product', + type: 'p5.Vector' + } + }, + { + line: 1683, + params: [ + { + name: 'v1', + description: + 'the first p5.Vector
\n', + type: 'p5.Vector' + }, + { + name: 'v2', + description: + 'the second p5.Vector
\n', + type: 'p5.Vector' + } + ], + static: 1, + return: { + description: 'the cross product', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 757, + description: + 'Calculates the Euclidean distance between two points (considering a\npoint as a vector object).
\n', + itemtype: 'method', + name: 'dist', + return: { + description: 'the distance', + type: 'Number' + }, + example: [ + "\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe x, y, and z coordinates of a p5.Vector
\n', + type: 'p5.Vector' + } + ], + return: { + description: 'the distance', + type: 'Number' + } + }, + { + line: 1698, + params: [ + { + name: 'v1', + description: + 'the first p5.Vector
\n', + type: 'p5.Vector' + }, + { + name: 'v2', + description: + 'the second p5.Vector
\n', + type: 'p5.Vector' + } + ], + static: 1, + return: { + description: 'the distance', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 828, + description: + 'Normalize the vector to length 1 (make it a unit vector).
\n', + itemtype: 'method', + name: 'normalize', + return: { + description: 'normalized p5.Vector', + type: 'p5.Vector' + }, + example: [ + "\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nLimit the magnitude of this vector to the value used for the max\nparameter.
\n', + itemtype: 'method', + name: 'limit', + params: [ + { + name: 'max', + description: 'the maximum magnitude for the vector
\n', + type: 'Number' + } + ], + chainable: 1, + example: [ + "\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nSet the magnitude of this vector to the value used for the len\nparameter.
\n', + itemtype: 'method', + name: 'setMag', + params: [ + { + name: 'len', + description: 'the new length for this vector
\n', + type: 'Number' + } + ], + chainable: 1, + example: [ + "\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n let length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nCalculate the angle of rotation for this vector (only 2D vectors)
\n', + itemtype: 'method', + name: 'heading', + return: { + description: 'the angle of rotation', + type: 'Number' + }, + example: [ + "\n\nfunction setup() {\n let v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n let myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nRotate the vector by an angle (only 2D vectors), magnitude remains the\nsame
\n', + itemtype: 'method', + name: 'rotate', + params: [ + { + name: 'angle', + description: 'the angle of rotation
\n', + type: 'Number' + } + ], + chainable: 1, + example: [ + "\n\nlet v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n\n\nlet angle = 0;\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nCalculates and returns the angle (in radians) between two vectors.
\n', + itemtype: 'method', + name: 'angleBetween', + params: [ + { + name: 'value', + description: + 'the x, y, and z components of a p5.Vector
\n', + type: 'p5.Vector' + } + ], + return: { + description: 'the angle between (in radians)', + type: 'Number' + }, + example: [ + "\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n\n\nfunction draw() {\n background(240);\n let v0 = createVector(50, 50);\n\n let v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n let angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nLinear interpolate the vector to another vector
\n', + itemtype: 'method', + name: 'lerp', + chainable: 1, + example: [ + "\n\nlet v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n\n\nlet v1 = createVector(0, 0, 0);\nlet v2 = createVector(100, 100, 0);\n\nlet v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n\n\nlet step = 0.01;\nlet amount = 0;\n\nfunction draw() {\n background(240);\n let v0 = createVector(0, 0);\n\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n let v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nthe x component
\n', + type: 'Number' + }, + { + name: 'y', + description: 'the y component
\n', + type: 'Number' + }, + { + name: 'z', + description: 'the z component
\n', + type: 'Number' + }, + { + name: 'amt', + description: + 'the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 1273, + params: [ + { + name: 'v', + description: + 'the p5.Vector to lerp to
\n', + type: 'p5.Vector' + }, + { + name: 'amt', + description: '', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 1713, + params: [ + { + name: 'v1', + description: '', + type: 'p5.Vector' + }, + { + name: 'v2', + description: '', + type: 'p5.Vector' + }, + { + name: 'amt', + description: '', + type: 'Number' + }, + { + name: 'target', + description: 'if undefined a new vector will be created
\n', + type: 'p5.Vector' + } + ], + static: 1 + }, + { + line: 1721, + params: [ + { + name: 'v1', + description: '', + type: 'p5.Vector' + }, + { + name: 'v2', + description: '', + type: 'p5.Vector' + }, + { + name: 'amt', + description: '', + type: 'Number' + } + ], + static: 1, + return: { + description: 'the lerped value', + type: 'Number' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 1289, + description: + 'Return a representation of this vector as a float array. This is only\nfor temporary use. If used in any other fashion, the contents should be\ncopied by using the p5.Vector.copy() method to copy into your own\narray.
\n', + itemtype: 'method', + name: 'array', + return: { + description: 'an Array with the 3 values', + type: 'Number[]' + }, + example: [ + '\n\nfunction setup() {\n let v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n\n\nlet v = createVector(10.0, 20.0, 30.0);\nlet f = v.array();\nprint(f[0]); // Prints "10.0"\nprint(f[1]); // Prints "20.0"\nprint(f[2]); // Prints "30.0"\n\nEquality check against a p5.Vector
\n', + itemtype: 'method', + name: 'equals', + return: { + description: 'whether the vectors are equals', + type: 'Boolean' + }, + example: [ + '\n\nlet v1 = createVector(5, 10, 20);\nlet v2 = createVector(5, 10, 20);\nlet v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n\n\nlet v1 = createVector(10.0, 20.0, 30.0);\nlet v2 = createVector(10.0, 20.0, 30.0);\nlet v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n\nthe x component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'y', + description: 'the y component of the vector
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'the z component of the vector
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'whether the vectors are equals', + type: 'Boolean' + } + }, + { + line: 1351, + params: [ + { + name: 'value', + description: 'the vector to compare
\n', + type: 'p5.Vector|Array' + } + ], + return: { + description: '', + type: 'Boolean' + } + } + ] + }, + { + file: 'src/math/p5.Vector.js', + line: 1376, + description: 'Make a new 2D vector from an angle
\n', + itemtype: 'method', + name: 'fromAngle', + static: 1, + params: [ + { + name: 'angle', + description: + 'the desired angle, in radians (unaffected by angleMode)
\n', + type: 'Number' + }, + { + name: 'length', + description: 'the length of the new vector (defaults to 1)
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'the new p5.Vector object', + type: 'p5.Vector' + }, + example: [ + "\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n let myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n let readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n let v = p5.Vector.fromAngle(radians(myDegrees), 30);\n let vx = v.x;\n let vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n\nMake a new 3D vector from a pair of ISO spherical angles
\n', + itemtype: 'method', + name: 'fromAngles', + static: 1, + params: [ + { + name: 'theta', + description: 'the polar angle, in radians (zero is up)
\n', + type: 'Number' + }, + { + name: 'phi', + description: + 'the azimuthal angle, in radians\n (zero is out of the screen)
\n', + type: 'Number' + }, + { + name: 'length', + description: 'the length of the new vector (defaults to 1)
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'the new p5.Vector object', + type: 'p5.Vector' + }, + example: [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n let t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n\nMake a new 2D unit vector from a random angle
\n', + itemtype: 'method', + name: 'random2D', + static: 1, + return: { + description: 'the new p5.Vector object', + type: 'p5.Vector' + }, + example: [ + "\n\nlet v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\nMake a new random 3D unit vector.
\n', + itemtype: 'method', + name: 'random3D', + static: 1, + return: { + description: 'the new p5.Vector object', + type: 'p5.Vector' + }, + example: [ + '\n\nlet v = p5.Vector.random3D();\n// May make v\'s attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n\nMultiplies a vector by a scalar and returns a new vector.
\n', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 1639, + description: + 'Divides a vector by a scalar and returns a new vector.
\n', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 1666, + description: 'Calculates the dot product of two vectors.
\n', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 1680, + description: 'Calculates the cross product of two vectors.
\n', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 1694, + description: + 'Calculates the Euclidean distance between two points (considering a\npoint as a vector object).
\n', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/p5.Vector.js', + line: 1709, + description: + 'Linear interpolate a vector to another vector and return the result as a\nnew vector.
\n', + class: 'p5.Vector', + module: 'Math', + submodule: 'Vector' + }, + { + file: 'src/math/random.js', + line: 37, + description: + 'Sets the seed value for random().
\nBy default, random() produces different results each time the program\nis run. Set the seed parameter to a constant to return the same\npseudo-random numbers each time the software is run.
\n', + itemtype: 'method', + name: 'randomSeed', + params: [ + { + name: 'seed', + description: 'the seed value
\n', + type: 'Number' + } + ], + example: [ + '\n\nrandomSeed(99);\nfor (let i = 0; i < 100; i++) {\n let r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n\nReturn a random floating-point number.
\nTakes either 0, 1 or 2 arguments.
\nIf no argument is given, returns a random number from 0\nup to (but not including) 1.
\nIf one argument is given and it is a number, returns a random number from 0\nup to (but not including) the number.
\nIf one argument is given and it is an array, returns a random element from\nthat array.
\nIf two arguments are given, returns a random number from the\nfirst argument up to (but not including) the second argument.
\n', + itemtype: 'method', + name: 'random', + return: { + description: 'the random number', + type: 'Number' + }, + example: [ + "\n\nfor (let i = 0; i < 100; i++) {\n let r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\n\n\nfor (let i = 0; i < 100; i++) {\n let r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\n\n\n// Get a random element from an array using the random(Array) syntax\nlet words = ['apple', 'bear', 'cat', 'dog'];\nlet word = random(words); // select random word\ntext(word, 10, 50); // draw the word\n\nthe lower bound (inclusive)
\n', + type: 'Number', + optional: true + }, + { + name: 'max', + description: 'the upper bound (exclusive)
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'the random number', + type: 'Number' + } + }, + { + line: 121, + params: [ + { + name: 'choices', + description: 'the array to choose from
\n', + type: 'Array' + } + ], + return: { + description: 'the random element from the array', + type: '*' + } + } + ] + }, + { + file: 'src/math/random.js', + line: 155, + description: + 'Returns a random number fitting a Gaussian, or\n normal, distribution. There is theoretically no minimum or maximum\n value that randomGaussian() might return. Rather, there is\n just a very low probability that values far from the mean will be\n returned; and a higher probability that numbers near the mean will\n be returned.\n
\n Takes either 0, 1 or 2 arguments.
\n If no args, returns a mean of 0 and standard deviation of 1.
\n If one arg, that arg is the mean (standard deviation is 1).
\n If two args, first is mean, second is standard deviation.
the mean
\n', + type: 'Number' + }, + { + name: 'sd', + description: 'the standard deviation
\n', + type: 'Number' + } + ], + return: { + description: 'the random number', + type: 'Number' + }, + example: [ + '\n\n for (let y = 0; y < 100; y++) {\n let x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n \n \n let distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (let i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (let i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n let dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n }\n \n The inverse of cos(), returns the arc cosine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned in\nthe range 0 to PI (3.1415927).
\n', + itemtype: 'method', + name: 'acos', + params: [ + { + name: 'value', + description: 'the value whose arc cosine is to be returned
\n', + type: 'Number' + } + ], + return: { + description: 'the arc cosine of the given value', + type: 'Number' + }, + example: [ + "\n\nlet a = PI;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n\nlet a = PI + PI / 4.0;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n\nThe inverse of sin(), returns the arc sine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned\nin the range -PI/2 to PI/2.
\n', + itemtype: 'method', + name: 'asin', + params: [ + { + name: 'value', + description: 'the value whose arc sine is to be returned
\n', + type: 'Number' + } + ], + return: { + description: 'the arc sine of the given value', + type: 'Number' + }, + example: [ + "\n\nlet a = PI + PI / 3;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n\nlet a = PI + PI / 3.0;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\nThe inverse of tan(), returns the arc tangent of a value. This function\nexpects the values in the range of -Infinity to Infinity (exclusive) and\nvalues are returned in the range -PI/2 to PI/2.
\n', + itemtype: 'method', + name: 'atan', + params: [ + { + name: 'value', + description: 'the value whose arc tangent is to be returned
\n', + type: 'Number' + } + ], + return: { + description: 'the arc tangent of the given value', + type: 'Number' + }, + example: [ + "\n\nlet a = PI + PI / 3;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n\n\nlet a = PI + PI / 3.0;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n\nCalculates the angle (in radians) from a specified point to the coordinate\norigin as measured from the positive x-axis. Values are returned as a\nfloat in the range from PI to -PI. The atan2() function is most often used\nfor orienting geometry to the position of the cursor.\n
\nNote: The y-coordinate of the point is the first parameter, and the\nx-coordinate is the second parameter, due the the structure of calculating\nthe tangent.
y-coordinate of the point
\n', + type: 'Number' + }, + { + name: 'x', + description: 'x-coordinate of the point
\n', + type: 'Number' + } + ], + return: { + description: 'the arc tangent of the given point', + type: 'Number' + }, + example: [ + '\n\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n\nCalculates the cosine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\n', + itemtype: 'method', + name: 'cos', + params: [ + { + name: 'angle', + description: 'the angle
\n', + type: 'Number' + } + ], + return: { + description: 'the cosine of the angle', + type: 'Number' + }, + example: [ + '\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\n\nCalculates the sine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\n', + itemtype: 'method', + name: 'sin', + params: [ + { + name: 'angle', + description: 'the angle
\n', + type: 'Number' + } + ], + return: { + description: 'the sine of the angle', + type: 'Number' + }, + example: [ + '\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\n\nCalculates the tangent of an angle. This function takes into account\nthe current angleMode. Values are returned in the range of all real numbers.
\n', + itemtype: 'method', + name: 'tan', + params: [ + { + name: 'angle', + description: 'the angle
\n', + type: 'Number' + } + ], + return: { + description: 'the tangent of the angle', + type: 'Number' + }, + example: [ + '\n\nlet a = 0.0;\nlet inc = TWO_PI / 50.0;\nfor (let i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n'
+ ],
+ alt:
+ 'vertical black lines end down and up from center to form spike pattern',
+ class: 'p5',
+ module: 'Math',
+ submodule: 'Trigonometry'
+ },
+ {
+ file: 'src/math/trigonometry.js',
+ line: 242,
+ description:
+ 'Converts a radian measurement to its corresponding value in degrees.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent angleMode.
\n', + itemtype: 'method', + name: 'degrees', + params: [ + { + name: 'radians', + description: 'the radians value to convert to degrees
\n', + type: 'Number' + } + ], + return: { + description: 'the converted angle', + type: 'Number' + }, + example: [ + "\n\nlet rad = PI / 4;\nlet deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n\nConverts a degree measurement to its corresponding value in radians.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent angleMode.
\n', + itemtype: 'method', + name: 'radians', + params: [ + { + name: 'degrees', + description: 'the degree value to convert to radians
\n', + type: 'Number' + } + ], + return: { + description: 'the converted angle', + type: 'Number' + }, + example: [ + "\n\nlet deg = 45.0;\nlet rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n\nSets the current mode of p5 to given mode. Default mode is RADIANS.
\n', + itemtype: 'method', + name: 'angleMode', + params: [ + { + name: 'mode', + description: 'either RADIANS or DEGREES
\n', + type: 'Constant' + } + ], + example: [ + '\n\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // variable a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n\nSets the current alignment for drawing text. Accepts two\narguments: horizAlign (LEFT, CENTER, or RIGHT) and\nvertAlign (TOP, BOTTOM, CENTER, or BASELINE).
\nThe horizAlign parameter is in reference to the x value\nof the text() function, while the vertAlign parameter is\nin reference to the y value.
\nSo if you write textAlign(LEFT), you are aligning the left\nedge of your text to the x value you give in text(). If you\nwrite textAlign(RIGHT, TOP), you are aligning the right edge\nof your text to the x value and the top of edge of the text\nto the y value.
\n', + itemtype: 'method', + name: 'textAlign', + chainable: 1, + example: [ + "\n\ntextSize(16);\ntextAlign(RIGHT);\ntext('ABCD', 50, 30);\ntextAlign(CENTER);\ntext('EFGH', 50, 50);\ntextAlign(LEFT);\ntext('IJKL', 50, 70);\n\n\ntextSize(16);\nstrokeWeight(0.5);\n\nline(0, 12, width, 12);\ntextAlign(CENTER, TOP);\ntext('TOP', 0, 12, width);\n\nline(0, 37, width, 37);\ntextAlign(CENTER, CENTER);\ntext('CENTER', 0, 37, width);\n\nline(0, 62, width, 62);\ntextAlign(CENTER, BASELINE);\ntext('BASELINE', 0, 62, width);\n\nline(0, 87, width, 87);\ntextAlign(CENTER, BOTTOM);\ntext('BOTTOM', 0, 87, width);\n\nhorizontal alignment, either LEFT,\n CENTER, or RIGHT
\n', + type: 'Constant' + }, + { + name: 'vertAlign', + description: + 'vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE
\n', + type: 'Constant', + optional: true + } + ], + chainable: 1 + }, + { + line: 73, + params: [], + return: { + description: '', + type: 'Object' + } + } + ] + }, + { + file: 'src/typography/attributes.js', + line: 82, + description: + 'Sets/gets the spacing, in pixels, between lines of text. This\nsetting will be used in all subsequent calls to the text() function.
\n', + itemtype: 'method', + name: 'textLeading', + chainable: 1, + example: [ + '\n\n// Text to display. The "\\n" is a "new line" character\nlet lines = \'L1\\nL2\\nL3\';\ntextSize(12);\n\ntextLeading(10); // Set leading to 10\ntext(lines, 10, 25);\n\ntextLeading(20); // Set leading to 20\ntext(lines, 40, 25);\n\ntextLeading(30); // Set leading to 30\ntext(lines, 70, 25);\n\nthe size in pixels for spacing between lines
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 111, + params: [], + return: { + description: '', + type: 'Number' + } + } + ] + }, + { + file: 'src/typography/attributes.js', + line: 120, + description: + 'Sets/gets the current font size. This size will be used in all subsequent\ncalls to the text() function. Font size is measured in pixels.
\n', + itemtype: 'method', + name: 'textSize', + chainable: 1, + example: [ + "\n\ntextSize(12);\ntext('Font Size 12', 10, 30);\ntextSize(14);\ntext('Font Size 14', 10, 60);\ntextSize(16);\ntext('Font Size 16', 10, 90);\n\nthe size of the letters in units of pixels
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 143, + params: [], + return: { + description: '', + type: 'Number' + } + } + ] + }, + { + file: 'src/typography/attributes.js', + line: 152, + description: + 'Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.
\n', + itemtype: 'method', + name: 'textStyle', + chainable: 1, + example: [ + "\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 15);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 40);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 65);\ntextStyle(BOLDITALIC);\ntext('Font Style Bold Italic', 10, 90);\n\nstyling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC
\n', + type: 'Constant' + } + ], + chainable: 1 + }, + { + line: 180, + params: [], + return: { + description: '', + type: 'String' + } + } + ] + }, + { + file: 'src/typography/attributes.js', + line: 189, + description: + 'Calculates and returns the width of any character or text string.
\n', + itemtype: 'method', + name: 'textWidth', + params: [ + { + name: 'theText', + description: 'the String of characters to measure
\n', + type: 'String' + } + ], + return: { + description: '', + type: 'Number' + }, + example: [ + "\n\ntextSize(28);\n\nlet aChar = 'P';\nlet cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nlet aString = 'p5.js';\nlet sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n\nReturns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.
\n', + itemtype: 'method', + name: 'textAscent', + return: { + description: '', + type: 'Number' + }, + example: [ + "\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n\nReturns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.
\n', + itemtype: 'method', + name: 'textDescent', + return: { + description: '', + type: 'Number' + }, + example: [ + "\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet desc = textDescent() * scalar; // Calc ascent\nline(0, base + desc, width, base + desc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext('dp', 40, base); // Draw text on baseline\n\nHelper function to measure ascent and descent.
\n', + class: 'p5', + module: 'Typography', + submodule: 'Attributes' + }, + { + file: 'src/typography/loading_displaying.js', + line: 14, + description: + 'Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n
\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading fonts from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
name of the file or url to load
\n', + type: 'String' + }, + { + name: 'callback', + description: + 'function to be executed after\n loadFont() completes
\n', + type: 'Function', + optional: true + }, + { + name: 'onError', + description: + 'function to be executed if\n an error occurs
\n', + type: 'Function', + optional: true + } + ], + return: { + description: 'p5.Font object', + type: 'p5.Font' + }, + example: [ + "\n\nCalling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.
\n\n\nlet myFont;\nfunction preload() {\n myFont = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n\nfunction setup() {\n loadFont('assets/inconsolata.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\nYou can also use the font filename string (without the file extension) to style other HTML\nelements.
\n\n\nfunction preload() {\n loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n let myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Inconsolata');\n}\nDraws text to the screen. Displays the information specified in the first\nparameter on the screen in the position specified by the additional\nparameters. A default font will be used unless a font is set with the\ntextFont() function and a default size will be used unless a font is set\nwith textSize(). Change the color of the text with the fill() function.\nChange the outline of the text with the stroke() and strokeWeight()\nfunctions.\n
\nThe text displays in relation to the textAlign() function, which gives the\noption to draw to the left, right, and center of the coordinates.\n
\nThe x2 and y2 parameters define a rectangular area to display within and\nmay only be used with string data. When these parameters are specified,\nthey are interpreted based on the current rectMode() setting. Text that\ndoes not fit completely within the rectangle specified will not be drawn\nto the screen. If x2 and y2 are not specified, the baseline alignment is the\ndefault, which means that the text will be drawn upwards from x and y.\n
\nWEBGL: Only opentype/truetype fonts are supported. You must load a font using the\nloadFont() method (see the example above).\nstroke() currently has no effect in webgl mode.
the alphanumeric\n symbols to be displayed
\n', + type: 'String|Object|Array|Number|Boolean' + }, + { + name: 'x', + description: 'x-coordinate of text
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y-coordinate of text
\n', + type: 'Number' + }, + { + name: 'x2', + description: + 'by default, the width of the text box,\n see rectMode() for more info
\n', + type: 'Number', + optional: true + }, + { + name: 'y2', + description: + 'by default, the height of the text box,\n see rectMode() for more info
\n', + type: 'Number', + optional: true + } + ], + chainable: 1, + example: [ + "\n\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n\n\nlet s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n\n\nlet inconsolata;\nfunction preload() {\n inconsolata = loadFont('assets/inconsolata.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(inconsolata);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n let time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n\nSets the current font that will be drawn with the text() function.\n
\nWEBGL: Only fonts loaded via loadFont() are supported.
\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n\n\nlet fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n\na font loaded via loadFont(), or a String\nrepresenting a web safe font (a font\nthat is generally available across all systems)
\n', + type: 'Object|String' + }, + { + name: 'size', + description: 'the font size to use
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/typography/p5.Font.js', + line: 23, + description: 'Underlying opentype font implementation
\n', + itemtype: 'property', + name: 'font', + class: 'p5.Font', + module: 'Typography', + submodule: 'Loading & Displaying' + }, + { + file: 'src/typography/p5.Font.js', + line: 30, + description: + 'Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)
\n', + itemtype: 'method', + name: 'textBounds', + params: [ + { + name: 'line', + description: 'a line of text
\n', + type: 'String' + }, + { + name: 'x', + description: 'x-position
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y-position
\n', + type: 'Number' + }, + { + name: 'fontSize', + description: 'font size to use (optional) Default is 12.
\n', + type: 'Number', + optional: true + }, + { + name: 'options', + description: + 'opentype options (optional)\n opentype fonts contains alignment and baseline options.\n Default is 'LEFT' and 'alphabetic'
\n', + type: 'Object', + optional: true + } + ], + return: { + description: 'a rectangle object with properties: x, y, w, h', + type: 'Object' + }, + example: [ + "\n\nlet font;\nlet textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n let bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n}\n\nComputes an array of points following the path for specified text
\n', + itemtype: 'method', + name: 'textToPoints', + params: [ + { + name: 'txt', + description: 'a line of text
\n', + type: 'String' + }, + { + name: 'x', + description: 'x-position
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y-position
\n', + type: 'Number' + }, + { + name: 'fontSize', + description: 'font size to use (optional)
\n', + type: 'Number' + }, + { + name: 'options', + description: + 'an (optional) object that can contain:
\n
sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
\nlet font;\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nlet points;\nlet bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (let i = 0; i < points.length; i++) {\n let p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n\nAdds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().
\n', + itemtype: 'method', + name: 'append', + deprecated: true, + deprecationMessage: + 'Use array.push(value) instead.', + params: [ + { + name: 'array', + description: 'Array to append
\n', + type: 'Array' + }, + { + name: 'value', + description: 'to be added to the Array
\n', + type: 'Any' + } + ], + return: { + description: 'the array that was appended to', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let myArray = ['Mango', 'Apple', 'Papaya'];\n print(myArray); // ['Mango', 'Apple', 'Papaya']\n\n append(myArray, 'Peach');\n print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']\n}\nCopies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use concat().\n
\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).\n
\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.
\nlet src = ['A', 'B', 'C'];\nlet dst = [1, 2, 3];\nlet srcPosition = 1;\nlet dstPosition = 0;\nlet length = 2;\n\nprint(src); // ['A', 'B', 'C']\nprint(dst); // [ 1 , 2 , 3 ]\n\narrayCopy(src, srcPosition, dst, dstPosition, length);\nprint(dst); // ['B', 'C', 3]\nthe source Array
\n', + type: 'Array' + }, + { + name: 'srcPosition', + description: 'starting position in the source Array
\n', + type: 'Integer' + }, + { + name: 'dst', + description: 'the destination Array
\n', + type: 'Array' + }, + { + name: 'dstPosition', + description: 'starting position in the destination Array
\n', + type: 'Integer' + }, + { + name: 'length', + description: 'number of Array elements to be copied
\n', + type: 'Integer' + } + ] + }, + { + line: 73, + params: [ + { + name: 'src', + description: '', + type: 'Array' + }, + { + name: 'dst', + description: '', + type: 'Array' + }, + { + name: 'length', + description: '', + type: 'Integer', + optional: true + } + ] + } + ] + }, + { + file: 'src/utilities/array_functions.js', + line: 112, + description: + 'Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.
\n', + itemtype: 'method', + name: 'concat', + deprecated: true, + deprecationMessage: + 'Use arr1.concat(arr2) instead.', + params: [ + { + name: 'a', + description: 'first Array to concatenate
\n', + type: 'Array' + }, + { + name: 'b', + description: 'second Array to concatenate
\n', + type: 'Array' + } + ], + return: { + description: 'concatenated array', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let arr1 = ['A', 'B', 'C'];\n let arr2 = [1, 2, 3];\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1,2,3]\n\n let arr3 = concat(arr1, arr2);\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1, 2, 3]\n print(arr3); // ['A','B','C', 1, 2, 3]\n}\nReverses the order of an array, maps to Array.reverse()
\n', + itemtype: 'method', + name: 'reverse', + deprecated: true, + deprecationMessage: + 'Use array.reverse() instead.', + params: [ + { + name: 'list', + description: 'Array to reverse
\n', + type: 'Array' + } + ], + return: { + description: 'the reversed list', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A','B','C']\n\n reverse(myArray);\n print(myArray); // ['C','B','A']\n}\nDecreases an array by one element and returns the shortened array,\nmaps to Array.pop().
\n', + itemtype: 'method', + name: 'shorten', + deprecated: true, + deprecationMessage: + 'Use array.pop() instead.', + params: [ + { + name: 'list', + description: 'Array to shorten
\n', + type: 'Array' + } + ], + return: { + description: 'shortened Array', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A', 'B', 'C']\n let newArray = shorten(myArray);\n print(myArray); // ['A','B','C']\n print(newArray); // ['A','B']\n}\nRandomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.
\n", + itemtype: 'method', + name: 'shuffle', + params: [ + { + name: 'array', + description: 'Array to shuffle
\n', + type: 'Array' + }, + { + name: 'bool', + description: 'modify passed array
\n', + type: 'Boolean', + optional: true + } + ], + return: { + description: 'shuffled Array', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let regularArr = ['ABC', 'def', createVector(), TAU, Math.E];\n print(regularArr);\n shuffle(regularArr, true); // force modifications to passed array\n print(regularArr);\n\n // By default shuffle() returns a shuffled cloned array:\n let newArr = shuffle(regularArr);\n print(regularArr);\n print(newArr);\n}\nSorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.
\n', + itemtype: 'method', + name: 'sort', + deprecated: true, + deprecationMessage: + 'Use array.sort() instead.', + params: [ + { + name: 'list', + description: 'Array to sort
\n', + type: 'Array' + }, + { + name: 'count', + description: 'number of elements to sort, starting from 0
\n', + type: 'Integer', + optional: true + } + ], + return: { + description: 'the sorted list', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let words = ['banana', 'apple', 'pear', 'lime'];\n print(words); // ['banana', 'apple', 'pear', 'lime']\n let count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ['apple', 'banana', 'lime', 'pear']\n}\n\nfunction setup() {\n let numbers = [2, 6, 1, 5, 14, 9, 8, 12];\n print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]\n let count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\nInserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)
\n', + itemtype: 'method', + name: 'splice', + deprecated: true, + deprecationMessage: + 'Use array.splice() instead.', + params: [ + { + name: 'list', + description: 'Array to splice into
\n', + type: 'Array' + }, + { + name: 'value', + description: 'value to be spliced in
\n', + type: 'Any' + }, + { + name: 'position', + description: 'in the array from which to insert data
\n', + type: 'Integer' + } + ], + return: { + description: 'the list', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let myArray = [0, 1, 2, 3, 4];\n let insArray = ['A', 'B', 'C'];\n print(myArray); // [0, 1, 2, 3, 4]\n print(insArray); // ['A','B','C']\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,'A','B','C',3,4]\n}\nExtracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.
\n', + itemtype: 'method', + name: 'subset', + deprecated: true, + deprecationMessage: + 'Use array.slice() instead.', + params: [ + { + name: 'list', + description: 'Array to extract from
\n', + type: 'Array' + }, + { + name: 'start', + description: 'position to begin
\n', + type: 'Integer' + }, + { + name: 'count', + description: 'number of values to extract
\n', + type: 'Integer', + optional: true + } + ], + return: { + description: 'Array of extracted elements', + type: 'Array' + }, + example: [ + "\n\nfunction setup() {\n let myArray = [1, 2, 3, 4, 5];\n print(myArray); // [1, 2, 3, 4, 5]\n\n let sub1 = subset(myArray, 0, 3);\n let sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\nConverts a string to its floating point representation. The contents of a\nstring must resemble a number, or NaN (not a number) will be returned.\nFor example, float("1234.56") evaluates to 1234.56, but float("giraffe")\nwill return NaN.
\nWhen an array of values is passed in, then an array of floats of the same\nlength is returned.
\n', + itemtype: 'method', + name: 'float', + params: [ + { + name: 'str', + description: 'float string to parse
\n', + type: 'String' + } + ], + return: { + description: 'floating point representation of string', + type: 'Number' + }, + example: [ + "\n\nlet str = '20';\nlet diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n\nprint(float('10.31')); // 10.31\nprint(float('Infinity')); // Infinity\nprint(float('-Infinity')); // -Infinity\nConverts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.
\n', + itemtype: 'method', + name: 'int', + return: { + description: 'integer representation of value', + type: 'Number' + }, + example: [ + "\n\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\nprint(int(Infinity)); // Infinity\nprint(int('-Infinity')); // -Infinity\nvalue to parse
\n', + type: 'String|Boolean|Number' + }, + { + name: 'radix', + description: 'the radix to convert to (default: 10)
\n', + type: 'Integer', + optional: true + } + ], + return: { + description: 'integer representation of value', + type: 'Number' + } + }, + { + line: 67, + params: [ + { + name: 'ns', + description: 'values to parse
\n', + type: 'Array' + } + ], + return: { + description: 'integer representation of values', + type: 'Number[]' + } + } + ] + }, + { + file: 'src/utilities/conversion.js', + line: 88, + description: + 'Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.
\n', + itemtype: 'method', + name: 'str', + params: [ + { + name: 'n', + description: 'value to parse
\n', + type: 'String|Boolean|Number|Array' + } + ], + return: { + description: 'string representation of value', + type: 'String' + }, + example: [ + '\n\nprint(str(\'10\')); // "10"\nprint(str(10.31)); // "10.31"\nprint(str(-10)); // "-10"\nprint(str(true)); // "true"\nprint(str(false)); // "false"\nprint(str([true, \'10.3\', 9.8])); // [ "true", "10.3", "9.8" ]\nConverts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value "true" evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.
\n', + itemtype: 'method', + name: 'boolean', + params: [ + { + name: 'n', + description: 'value to parse
\n', + type: 'String|Boolean|Number|Array' + } + ], + return: { + description: 'boolean representation of value', + type: 'Boolean' + }, + example: [ + "\n\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, true]\nConverts a number, string representation of a number, or boolean to its byte\nrepresentation. A byte can be only a whole number between -128 and 127, so\nwhen a value outside of this range is converted, it wraps around to the\ncorresponding byte representation. When an array of number, string or boolean\nvalues is passed in, then an array of bytes the same length is returned.
\n', + itemtype: 'method', + name: 'byte', + return: { + description: 'byte representation of value', + type: 'Number' + }, + example: [ + "\n\nprint(byte(127)); // 127\nprint(byte(128)); // -128\nprint(byte(23.4)); // 23\nprint(byte('23.4')); // 23\nprint(byte('hello')); // NaN\nprint(byte(true)); // 1\nprint(byte([0, 255, '100'])); // [0, -1, 100]\nvalue to parse
\n', + type: 'String|Boolean|Number' + } + ], + return: { + description: 'byte representation of value', + type: 'Number' + } + }, + { + line: 168, + params: [ + { + name: 'ns', + description: 'values to parse
\n', + type: 'Array' + } + ], + return: { + description: 'array of byte representation of values', + type: 'Number[]' + } + } + ] + }, + { + file: 'src/utilities/conversion.js', + line: 182, + description: + 'Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.
\n', + itemtype: 'method', + name: 'char', + return: { + description: 'string representation of value', + type: 'String' + }, + example: [ + '\n\nprint(char(65)); // "A"\nprint(char(\'65\')); // "A"\nprint(char([65, 66, 67])); // [ "A", "B", "C" ]\nprint(join(char([65, 66, 67]), \'\')); // "ABC"\nvalue to parse
\n', + type: 'String|Number' + } + ], + return: { + description: 'string representation of value', + type: 'String' + } + }, + { + line: 201, + params: [ + { + name: 'ns', + description: 'values to parse
\n', + type: 'Array' + } + ], + return: { + description: 'array of string representation of values', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/conversion.js', + line: 216, + description: + 'Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.
\n', + itemtype: 'method', + name: 'unchar', + return: { + description: 'integer representation of value', + type: 'Number' + }, + example: [ + "\n\nprint(unchar('A')); // 65\nprint(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]\nprint(unchar(split('ABC', ''))); // [ 65, 66, 67 ]\nvalue to parse
\n', + type: 'String' + } + ], + return: { + description: 'integer representation of value', + type: 'Number' + } + }, + { + line: 232, + params: [ + { + name: 'ns', + description: 'values to parse
\n', + type: 'Array' + } + ], + return: { + description: 'integer representation of values', + type: 'Number[]' + } + } + ] + }, + { + file: 'src/utilities/conversion.js', + line: 245, + description: + 'Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.
\n', + itemtype: 'method', + name: 'hex', + return: { + description: 'hexadecimal string representation of value', + type: 'String' + }, + example: [ + '\n\nprint(hex(255)); // "000000FF"\nprint(hex(255, 6)); // "0000FF"\nprint(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]\nprint(Infinity); // "FFFFFFFF"\nprint(-Infinity); // "00000000"\nvalue to parse
\n', + type: 'Number' + }, + { + name: 'digits', + description: '', + type: 'Number', + optional: true + } + ], + return: { + description: 'hexadecimal string representation of value', + type: 'String' + } + }, + { + line: 265, + params: [ + { + name: 'ns', + description: 'array of values to parse
\n', + type: 'Number[]' + }, + { + name: 'digits', + description: '', + type: 'Number', + optional: true + } + ], + return: { + description: 'hexadecimal string representation of values', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/conversion.js', + line: 295, + description: + 'Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.
\n', + itemtype: 'method', + name: 'unhex', + return: { + description: 'integer representation of hexadecimal value', + type: 'Number' + }, + example: [ + "\n\nprint(unhex('A')); // 10\nprint(unhex('FF')); // 255\nprint(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]\nvalue to parse
\n', + type: 'String' + } + ], + return: { + description: 'integer representation of hexadecimal value', + type: 'Number' + } + }, + { + line: 311, + params: [ + { + name: 'ns', + description: 'values to parse
\n', + type: 'Array' + } + ], + return: { + description: 'integer representations of hexadecimal value', + type: 'Number[]' + } + } + ] + }, + { + file: 'src/utilities/string_functions.js', + line: 13, + description: + 'Combines an array of Strings into one String, each separated by the\ncharacter(s) used for the separator parameter. To join arrays of ints or\nfloats, it's necessary to first convert them to Strings using nf() or\nnfs().
\n', + itemtype: 'method', + name: 'join', + params: [ + { + name: 'list', + description: 'array of Strings to be joined
\n', + type: 'Array' + }, + { + name: 'separator', + description: 'String to be placed between each item
\n', + type: 'String' + } + ], + return: { + description: 'joined String', + type: 'String' + }, + example: [ + "\n\nlet array = ['Hello', 'world!'];\nlet separator = ' ';\nlet message = join(array, separator);\ntext(message, 5, 50);\n\nThis function is used to apply a regular expression to a piece of text,\nand return matching groups (elements found inside parentheses) as a\nString array. If there are no matches, a null value will be returned.\nIf no groups are specified in the regular expression, but the sequence\nmatches, an array of length 1 (with the matched text as the first element\nof the array) will be returned.\n
\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, an array is returned.\n
\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nElement [0] of a regular expression match returns the entire matching\nstring, and the match groups start at element [1] (the first group is [1],\nthe second [2], and so on).
the String to be searched
\n', + type: 'String' + }, + { + name: 'regexp', + description: 'the regexp to be used for matching
\n', + type: 'String' + } + ], + return: { + description: 'Array of Strings found', + type: 'String[]' + }, + example: [ + "\n\nlet string = 'Hello p5js*!';\nlet regexp = 'p5js\\\\*';\nlet m = match(string, regexp);\ntext(m, 5, 50);\n\nThis function is used to apply a regular expression to a piece of text,\nand return a list of matching groups (elements found inside parentheses)\nas a two-dimensional String array. If there are no matches, a null value\nwill be returned. If no groups are specified in the regular expression,\nbut the sequence matches, a two dimensional array is still returned, but\nthe second dimension is only of length one.\n
\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, a 2D array is returned.\n
\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nAssuming a loop with counter variable i, element [i][0] of a regular\nexpression match returns the entire matching string, and the match groups\nstart at element [i][1] (the first group is [i][1], the second [i][2],\nand so on).
the String to be searched
\n', + type: 'String' + }, + { + name: 'regexp', + description: 'the regexp to be used for matching
\n', + type: 'String' + } + ], + return: { + description: '2d Array of Strings found', + type: 'String[]' + }, + example: [ + "\n\nlet string = 'Hello p5js*! Hello world!';\nlet regexp = 'Hello';\nmatchAll(string, regexp);\n\nUtility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.\nThe values for the digits, left, and right parameters should always\nbe positive integers.\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.
\n', + itemtype: 'method', + name: 'nf', + return: { + description: 'formatted String', + type: 'String' + }, + example: [ + "\n\nlet myFont;\nfunction preload() {\n myFont = loadFont('assets/fonts/inconsolata.ttf');\n}\nfunction setup() {\n background(200);\n let num1 = 321;\n let num2 = -1321;\n\n noStroke();\n fill(0);\n textFont(myFont);\n textSize(22);\n\n text(nf(num1, 4, 2), 10, 30);\n text(nf(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\nthe Number to format
\n', + type: 'Number|String' + }, + { + name: 'left', + description: + 'number of digits to the left of the\n decimal point
\n', + type: 'Integer|String', + optional: true + }, + { + name: 'right', + description: + 'number of digits to the right of the\n decimal point
\n', + type: 'Integer|String', + optional: true + } + ], + return: { + description: 'formatted String', + type: 'String' + } + }, + { + line: 178, + params: [ + { + name: 'nums', + description: 'the Numbers to format
\n', + type: 'Array' + }, + { + name: 'left', + description: '', + type: 'Integer|String', + optional: true + }, + { + name: 'right', + description: '', + type: 'Integer|String', + optional: true + } + ], + return: { + description: 'formatted Strings', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/string_functions.js', + line: 239, + description: + 'Utility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.
\n', + itemtype: 'method', + name: 'nfc', + return: { + description: 'formatted String', + type: 'String' + }, + example: [ + '\n\nfunction setup() {\n background(200);\n let num = 11253106.115;\n let numArr = [1, 1, 2];\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfc(num, 4), 10, 30);\n text(nfc(numArr, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\nthe Number to format
\n', + type: 'Number|String' + }, + { + name: 'right', + description: + 'number of digits to the right of the\n decimal point
\n', + type: 'Integer|String', + optional: true + } + ], + return: { + description: 'formatted String', + type: 'String' + } + }, + { + line: 277, + params: [ + { + name: 'nums', + description: 'the Numbers to format
\n', + type: 'Array' + }, + { + name: 'right', + description: '', + type: 'Integer|String', + optional: true + } + ], + return: { + description: 'formatted Strings', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/string_functions.js', + line: 313, + description: + 'Utility function for formatting numbers into strings. Similar to nf() but\nputs a "+" in front of positive numbers and a "-" in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.
\n', + itemtype: 'method', + name: 'nfp', + return: { + description: 'formatted String', + type: 'String' + }, + example: [ + '\n\nfunction setup() {\n background(200);\n let num1 = 11253106.115;\n let num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfp(num1, 4, 2), 10, 30);\n text(nfp(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\nthe Number to format
\n', + type: 'Number' + }, + { + name: 'left', + description: + 'number of digits to the left of the decimal\n point
\n', + type: 'Integer', + optional: true + }, + { + name: 'right', + description: + 'number of digits to the right of the\n decimal point
\n', + type: 'Integer', + optional: true + } + ], + return: { + description: 'formatted String', + type: 'String' + } + }, + { + line: 354, + params: [ + { + name: 'nums', + description: 'the Numbers to format
\n', + type: 'Number[]' + }, + { + name: 'left', + description: '', + type: 'Integer', + optional: true + }, + { + name: 'right', + description: '', + type: 'Integer', + optional: true + } + ], + return: { + description: 'formatted Strings', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/string_functions.js', + line: 375, + description: + 'Utility function for formatting numbers into strings. Similar to nf() but\nputs an additional "_" (space) in front of positive numbers just in case to align it with negative\nnumbers which includes "-" (minus) sign.\nThe main usecase of nfs() can be seen when one wants to align the digits (place values) of a non-negative\nnumber with some negative number (See the example to get a clear picture).\nThere are two versions: one for formatting float, and one for formatting int.\nThe values for the digits, left, and right parameters should always be positive integers.\n(IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.
\n', + itemtype: 'method', + name: 'nfs', + return: { + description: 'formatted String', + type: 'String' + }, + example: [ + "\n\nlet myFont;\nfunction preload() {\n myFont = loadFont('assets/fonts/inconsolata.ttf');\n}\nfunction setup() {\n background(200);\n let num1 = 321;\n let num2 = -1321;\n\n noStroke();\n fill(0);\n textFont(myFont);\n textSize(22);\n\n // nfs() aligns num1 (positive number) with num2 (negative number) by\n // adding a blank space in front of the num1 (positive number)\n // [left = 4] in num1 add one 0 in front, to align the digits with num2\n // [right = 2] in num1 and num2 adds two 0's after both numbers\n // To see the differences check the example of nf() too.\n text(nfs(num1, 4, 2), 10, 30);\n text(nfs(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\nthe Number to format
\n', + type: 'Number' + }, + { + name: 'left', + description: + 'number of digits to the left of the decimal\n point
\n', + type: 'Integer', + optional: true + }, + { + name: 'right', + description: + 'number of digits to the right of the\n decimal point
\n', + type: 'Integer', + optional: true + } + ], + return: { + description: 'formatted String', + type: 'String' + } + }, + { + line: 432, + params: [ + { + name: 'nums', + description: 'the Numbers to format
\n', + type: 'Array' + }, + { + name: 'left', + description: '', + type: 'Integer', + optional: true + }, + { + name: 'right', + description: '', + type: 'Integer', + optional: true + } + ], + return: { + description: 'formatted Strings', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/string_functions.js', + line: 453, + description: + 'The split() function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.
\nThe splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.
\n', + itemtype: 'method', + name: 'split', + params: [ + { + name: 'value', + description: 'the String to be split
\n', + type: 'String' + }, + { + name: 'delim', + description: 'the String used to separate the data
\n', + type: 'String' + } + ], + return: { + description: 'Array of Strings', + type: 'String[]' + }, + example: [ + "\n\nlet names = 'Pat,Xio,Alex';\nlet splitString = split(names, ',');\ntext(splitString[0], 5, 30);\ntext(splitString[1], 5, 50);\ntext(splitString[2], 5, 70);\n\nThe splitTokens() function splits a String at one or many character\ndelimiters or "tokens." The delim parameter specifies the character or\ncharacters to be used as a boundary.\n
\nIf no delim characters are specified, any whitespace character is used to\nsplit. Whitespace characters include tab (\\t), line feed (\\n), carriage\nreturn (\\r), form feed (\\f), and space.
the String to be split
\n', + type: 'String' + }, + { + name: 'delim', + description: + 'list of individual Strings that will be used as\n separators
\n', + type: 'String', + optional: true + } + ], + return: { + description: 'Array of Strings', + type: 'String[]' + }, + example: [ + '\n\nfunction setup() {\n let myStr = \'Mango, Banana, Lime\';\n let myStrArr = splitTokens(myStr, \',\');\n\n print(myStrArr); // prints : ["Mango"," Banana"," Lime"]\n}\n\nRemoves whitespace characters from the beginning and end of a String. In\naddition to standard whitespace characters such as space, carriage return,\nand tab, this function also removes the Unicode "nbsp" character.
\n', + itemtype: 'method', + name: 'trim', + return: { + description: 'a trimmed String', + type: 'String' + }, + example: [ + "\n\nlet string = trim(' No new lines\\n ');\ntext(string + ' here', 2, 50);\n\na String to be trimmed
\n', + type: 'String' + } + ], + return: { + description: 'a trimmed String', + type: 'String' + } + }, + { + line: 560, + params: [ + { + name: 'strs', + description: 'an Array of Strings to be trimmed
\n', + type: 'Array' + } + ], + return: { + description: 'an Array of trimmed Strings', + type: 'String[]' + } + } + ] + }, + { + file: 'src/utilities/time_date.js', + line: 10, + description: + 'p5.js communicates with the clock on your computer. The day() function\nreturns the current day as a value from 1 - 31.
\n', + itemtype: 'method', + name: 'day', + return: { + description: 'the current day', + type: 'Integer' + }, + example: [ + "\n\nlet d = day();\ntext('Current day: \\n' + d, 5, 50);\n\np5.js communicates with the clock on your computer. The hour() function\nreturns the current hour as a value from 0 - 23.
\n', + itemtype: 'method', + name: 'hour', + return: { + description: 'the current hour', + type: 'Integer' + }, + example: [ + "\n\nlet h = hour();\ntext('Current hour:\\n' + h, 5, 50);\n\np5.js communicates with the clock on your computer. The minute() function\nreturns the current minute as a value from 0 - 59.
\n', + itemtype: 'method', + name: 'minute', + return: { + description: 'the current minute', + type: 'Integer' + }, + example: [ + "\n\nlet m = minute();\ntext('Current minute: \\n' + m, 5, 50);\n\nReturns the number of milliseconds (thousandths of a second) since\nstarting the program. This information is often used for timing events and\nanimation sequences.
\n', + itemtype: 'method', + name: 'millis', + return: { + description: 'the number of milliseconds since starting the program', + type: 'Number' + }, + example: [ + "\n\nlet millisecond = millis();\ntext('Milliseconds \\nrunning: \\n' + millisecond, 5, 40);\n\np5.js communicates with the clock on your computer. The month() function\nreturns the current month as a value from 1 - 12.
\n', + itemtype: 'method', + name: 'month', + return: { + description: 'the current month', + type: 'Integer' + }, + example: [ + "\n\nlet m = month();\ntext('Current month: \\n' + m, 5, 50);\n\np5.js communicates with the clock on your computer. The second() function\nreturns the current second as a value from 0 - 59.
\n', + itemtype: 'method', + name: 'second', + return: { + description: 'the current second', + type: 'Integer' + }, + example: [ + "\n\nlet s = second();\ntext('Current second: \\n' + s, 5, 50);\n\np5.js communicates with the clock on your computer. The year() function\nreturns the current year as an integer (2014, 2015, 2016, etc).
\n', + itemtype: 'method', + name: 'year', + return: { + description: 'the current year', + type: 'Integer' + }, + example: [ + "\n\nlet y = year();\ntext('Current year: \\n' + y, 5, 50);\n\nDraw a plane with given a width and height
\n', + itemtype: 'method', + name: 'plane', + params: [ + { + name: 'width', + description: 'width of the plane
\n', + type: 'Number', + optional: true + }, + { + name: 'height', + description: 'height of the plane
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: + 'Optional number of triangle\n subdivisions in x-dimension
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: + 'Optional number of triangle\n subdivisions in y-dimension
\n', + type: 'Integer', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw a plane\n// with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n\nDraw a box with given width, height and depth
\n', + itemtype: 'method', + name: 'box', + params: [ + { + name: 'width', + description: 'width of the box
\n', + type: 'Number', + optional: true + }, + { + name: 'Height', + description: 'height of the box
\n', + type: 'Number', + optional: true + }, + { + name: 'depth', + description: 'depth of the box
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: + 'Optional number of triangle\n subdivisions in x-dimension
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: + 'Optional number of triangle\n subdivisions in y-dimension
\n', + type: 'Integer', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw a spinning box\n// with width, height and depth of 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(50);\n}\n\nDraw a sphere with given radius.
\nDetailX and detailY determines the number of subdivisions in the x-dimension\nand the y-dimension of a sphere. More subdivisions make the sphere seem\nsmoother. The recommended maximum values are both 24. Using a value greater\nthan 24 may cause a warning or slow down the browser.
\n', + itemtype: 'method', + name: 'sphere', + params: [ + { + name: 'radius', + description: 'radius of circle
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: 'optional number of subdivisions in x-dimension
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: 'optional number of subdivisions in y-dimension
\n', + type: 'Integer', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw a sphere with radius 40\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(205, 102, 94);\n sphere(40);\n}\n\n\nlet detailX;\n// slide to see how detailX works\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 24, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n sphere(40, detailX.value(), 16);\n}\n\n\nlet detailY;\n// slide to see how detailY works\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(3, 16, 3);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n sphere(40, 16, detailY.value());\n}\n\nDraw a cylinder with given radius and height
\nDetailX and detailY determines the number of subdivisions in the x-dimension\nand the y-dimension of a cylinder. More subdivisions make the cylinder seem smoother.\nThe recommended maximum value for detailX is 24. Using a value greater than 24\nmay cause a warning or slow down the browser.
\n', + itemtype: 'method', + name: 'cylinder', + params: [ + { + name: 'radius', + description: 'radius of the surface
\n', + type: 'Number', + optional: true + }, + { + name: 'height', + description: 'height of the cylinder
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: + 'number of subdivisions in x-dimension;\n default is 24
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: + 'number of subdivisions in y-dimension;\n default is 1
\n', + type: 'Integer', + optional: true + }, + { + name: 'bottomCap', + description: 'whether to draw the bottom of the cylinder
\n', + type: 'Boolean', + optional: true + }, + { + name: 'topCap', + description: 'whether to draw the top of the cylinder
\n', + type: 'Boolean', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw a spinning cylinder\n// with radius 20 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(20, 50);\n}\n\n\n// slide to see how detailX works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 24, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n cylinder(20, 75, detailX.value(), 1);\n}\n\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(1, 16, 1);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n cylinder(20, 75, 16, detailY.value());\n}\n\nDraw a cone with given radius and height
\nDetailX and detailY determine the number of subdivisions in the x-dimension and\nthe y-dimension of a cone. More subdivisions make the cone seem smoother. The\nrecommended maximum value for detailX is 24. Using a value greater than 24\nmay cause a warning or slow down the browser.
\n', + itemtype: 'method', + name: 'cone', + params: [ + { + name: 'radius', + description: 'radius of the bottom surface
\n', + type: 'Number', + optional: true + }, + { + name: 'height', + description: 'height of the cone
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: + 'number of segments,\n the more segments the smoother geometry\n default is 24
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: + 'number of segments,\n the more segments the smoother geometry\n default is 1
\n', + type: 'Integer', + optional: true + }, + { + name: 'cap', + description: 'whether to draw the base of the cone
\n', + type: 'Boolean', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw a spinning cone\n// with radius 40 and height 70\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(40, 70);\n}\n\n\n// slide to see how detailx works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 16, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n cone(30, 65, detailX.value(), 16);\n}\n\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(3, 16, 3);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n cone(30, 65, 16, detailY.value());\n}\n\nDraw an ellipsoid with given radius
\nDetailX and detailY determine the number of subdivisions in the x-dimension and\nthe y-dimension of a cone. More subdivisions make the ellipsoid appear to be smoother.\nAvoid detail number above 150, it may crash the browser.
\n', + itemtype: 'method', + name: 'ellipsoid', + params: [ + { + name: 'radiusx', + description: 'x-radius of ellipsoid
\n', + type: 'Number', + optional: true + }, + { + name: 'radiusy', + description: 'y-radius of ellipsoid
\n', + type: 'Number', + optional: true + }, + { + name: 'radiusz', + description: 'z-radius of ellipsoid
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: + 'number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: + 'number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.
\n', + type: 'Integer', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw an ellipsoid\n// with radius 30, 40 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(205, 105, 94);\n ellipsoid(30, 40, 40);\n}\n\n\n// slide to see how detailX works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(2, 24, 12);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n ellipsoid(30, 40, 40, detailX.value(), 8);\n}\n\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(2, 24, 6);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 105, 9);\n rotateY(millis() / 1000);\n ellipsoid(30, 40, 40, 12, detailY.value());\n}\n\nDraw a torus with given radius and tube radius
\nDetailX and detailY determine the number of subdivisions in the x-dimension and\nthe y-dimension of a torus. More subdivisions make the torus appear to be smoother.\nThe default and maximum values for detailX and detailY are 24 and 16, respectively.\nSetting them to relatively small values like 4 and 6 allows you to create new\nshapes other than a torus.
\n', + itemtype: 'method', + name: 'torus', + params: [ + { + name: 'radius', + description: 'radius of the whole ring
\n', + type: 'Number', + optional: true + }, + { + name: 'tubeRadius', + description: 'radius of the tube
\n', + type: 'Number', + optional: true + }, + { + name: 'detailX', + description: + 'number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24
\n', + type: 'Integer', + optional: true + }, + { + name: 'detailY', + description: + 'number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16
\n', + type: 'Integer', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n// draw a spinning torus\n// with ring radius 30 and tube radius 15\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(30, 15);\n}\n\n\n// slide to see how detailX works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 24, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n torus(30, 15, detailX.value(), 12);\n}\n\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(3, 16, 3);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n torus(30, 15, 16, detailY.value());\n}\n\nAllows movement around a 3D sketch using a mouse or trackpad. Left-clicking\nand dragging will rotate the camera position about the center of the sketch,\nright-clicking and dragging will pan the camera position without rotation,\nand using the mouse wheel (scrolling) will move the camera closer or further\nfrom the center of the sketch. This function can be called with parameters\ndictating sensitivity to mouse movement along the X and Y axes. Calling\nthis function without parameters is equivalent to calling orbitControl(1,1).\nTo reverse direction of movement in either axis, enter a negative number\nfor sensitivity.
\n', + itemtype: 'method', + name: 'orbitControl', + params: [ + { + name: 'sensitivityX', + description: 'sensitivity to mouse movement along X axis
\n', + type: 'Number', + optional: true + }, + { + name: 'sensitivityY', + description: 'sensitivity to mouse movement along Y axis
\n', + type: 'Number', + optional: true + }, + { + name: 'sensitivityZ', + description: 'sensitivity to scroll movement along Z axis
\n', + type: 'Number', + optional: true + } + ], + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n}\nfunction draw() {\n background(200);\n orbitControl();\n rotateY(0.5);\n box(30, 50);\n}\n\ndebugMode() helps visualize 3D space by adding a grid to indicate where the\n‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z\ndirections. This function can be called without parameters to create a\ndefault grid and axes icon, or it can be called according to the examples\nabove to customize the size and position of the grid and/or axes icon. The\ngrid is drawn using the most recently set stroke color and weight. To\nspecify these parameters, add a call to stroke() and strokeWeight()\njust before the end of the draw() loop.
\nBy default, the grid will run through the origin (0,0,0) of the sketch\nalong the XZ plane\nand the axes icon will be offset from the origin. Both the grid and axes\nicon will be sized according to the current canvas size. Note that because the\ngrid runs parallel to the default camera view, it is often helpful to use\ndebugMode along with orbitControl to allow full view of the grid.
\n', + itemtype: 'method', + name: 'debugMode', + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode();\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n // Press the spacebar to turn debugMode off!\n if (keyIsDown(32)) {\n noDebugMode();\n }\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(GRID);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(AXES);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(GRID, 100, 10, 0, 0, 0);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0);\n}\n\nfunction draw() {\n noStroke();\n background(200);\n orbitControl();\n box(15, 30);\n // set the stroke color and weight for the grid!\n stroke(255, 0, 150);\n strokeWeight(0.8);\n}\n\neither GRID or AXES
\n', + type: 'Constant' + } + ] + }, + { + line: 283, + params: [ + { + name: 'mode', + description: '', + type: 'Constant' + }, + { + name: 'gridSize', + description: 'size of one side of the grid
\n', + type: 'Number', + optional: true + }, + { + name: 'gridDivisions', + description: 'number of divisions in the grid
\n', + type: 'Number', + optional: true + }, + { + name: 'xOff', + description: 'X axis offset from origin (0,0,0)
\n', + type: 'Number', + optional: true + }, + { + name: 'yOff', + description: 'Y axis offset from origin (0,0,0)
\n', + type: 'Number', + optional: true + }, + { + name: 'zOff', + description: 'Z axis offset from origin (0,0,0)
\n', + type: 'Number', + optional: true + } + ] + }, + { + line: 293, + params: [ + { + name: 'mode', + description: '', + type: 'Constant' + }, + { + name: 'axesSize', + description: 'size of axes icon
\n', + type: 'Number', + optional: true + }, + { + name: 'xOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'yOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'zOff', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 302, + params: [ + { + name: 'gridSize', + description: '', + type: 'Number', + optional: true + }, + { + name: 'gridDivisions', + description: '', + type: 'Number', + optional: true + }, + { + name: 'gridXOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'gridYOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'gridZOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'axesSize', + description: '', + type: 'Number', + optional: true + }, + { + name: 'axesXOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'axesYOff', + description: '', + type: 'Number', + optional: true + }, + { + name: 'axesZOff', + description: '', + type: 'Number', + optional: true + } + ] + } + ] + }, + { + file: 'src/webgl/interaction.js', + line: 353, + description: 'Turns off debugMode() in a 3D sketch.
\n', + itemtype: 'method', + name: 'noDebugMode', + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode();\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n // Press the spacebar to turn debugMode off!\n if (keyIsDown(32)) {\n noDebugMode();\n }\n}\n\nCreates an ambient light with a color
\n', + itemtype: 'method', + name: 'ambientLight', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(40);\n}\n\nred or hue value relative to\n the current color range
\n', + type: 'Number' + }, + { + name: 'v2', + description: + 'green or saturation value\n relative to the current color range
\n', + type: 'Number' + }, + { + name: 'v3', + description: + 'blue or brightness value\n relative to the current color range
\n', + type: 'Number' + }, + { + name: 'alpha', + description: 'the alpha value
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 44, + params: [ + { + name: 'value', + description: 'a color string
\n', + type: 'String' + } + ], + chainable: 1 + }, + { + line: 50, + params: [ + { + name: 'gray', + description: 'a gray value
\n', + type: 'Number' + }, + { + name: 'alpha', + description: '', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 57, + params: [ + { + name: 'values', + description: + 'an array containing the red,green,blue &\n and alpha components of the color
\n', + type: 'Number[]' + } + ], + chainable: 1 + }, + { + line: 64, + params: [ + { + name: 'color', + description: 'the ambient light color
\n', + type: 'p5.Color' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/light.js', + line: 85, + description: + 'Set's the color of the specular highlight when using a specular material and\nspecular light.
\nThis method can be combined with specularMaterial() and shininess()\nfunctions to set specular highlights. The default color is white, ie\n(255, 255, 255), which is used if this method is not called before\nspecularMaterial(). If this method is called without specularMaterial(),\nThere will be no effect.
\nNote: specularColor is equivalent to the processing function\nlightSpecular.
\n', + itemtype: 'method', + name: 'specularColor', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n}\n\nfunction draw() {\n background(0);\n shininess(20);\n ambientLight(50);\n specularColor(255, 0, 0);\n pointLight(255, 0, 0, 0, -50, 50);\n specularColor(0, 255, 0);\n pointLight(0, 255, 0, 0, 50, 50);\n specularMaterial(255);\n sphere(40);\n}\n\nred or hue value relative to\n the current color range
\n', + type: 'Number' + }, + { + name: 'v2', + description: + 'green or saturation value\n relative to the current color range
\n', + type: 'Number' + }, + { + name: 'v3', + description: + 'blue or brightness value\n relative to the current color range
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 132, + params: [ + { + name: 'value', + description: 'a color string
\n', + type: 'String' + } + ], + chainable: 1 + }, + { + line: 138, + params: [ + { + name: 'gray', + description: 'a gray value
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 144, + params: [ + { + name: 'values', + description: + 'an array containing the red,green,blue &\n and alpha components of the color
\n', + type: 'Number[]' + } + ], + chainable: 1 + }, + { + line: 151, + params: [ + { + name: 'color', + description: 'the ambient light color
\n', + type: 'p5.Color' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/light.js', + line: 170, + description: + 'Creates a directional light with a color and a direction
\n', + itemtype: 'method', + name: 'directionalLight', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n let dirX = (mouseX / width - 0.5) * 2;\n let dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, -1);\n noStroke();\n sphere(40);\n}\n\nred or hue value (depending on the current\ncolor mode),
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'green or saturation value
\n', + type: 'Number' + }, + { + name: 'v3', + description: 'blue or brightness value
\n', + type: 'Number' + }, + { + name: 'position', + description: 'the direction of the light
\n', + type: 'p5.Vector' + } + ], + chainable: 1 + }, + { + line: 202, + params: [ + { + name: 'color', + description: + 'color Array, CSS color string,\n or p5.Color value
\n', + type: 'Number[]|String|p5.Color' + }, + { + name: 'x', + description: 'x axis direction
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y axis direction
\n', + type: 'Number' + }, + { + name: 'z', + description: 'z axis direction
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 212, + params: [ + { + name: 'color', + description: '', + type: 'Number[]|String|p5.Color' + }, + { + name: 'position', + description: '', + type: 'p5.Vector' + } + ], + chainable: 1 + }, + { + line: 219, + params: [ + { + name: 'v1', + description: '', + type: 'Number' + }, + { + name: 'v2', + description: '', + type: 'Number' + }, + { + name: 'v3', + description: '', + type: 'Number' + }, + { + name: 'x', + description: '', + type: 'Number' + }, + { + name: 'y', + description: '', + type: 'Number' + }, + { + name: 'z', + description: '', + type: 'Number' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/light.js', + line: 272, + description: + 'Creates a point light with a color and a light position
\n', + itemtype: 'method', + name: 'pointLight', + chainable: 1, + example: [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n noStroke();\n sphere(40);\n}\n\nred or hue value (depending on the current\ncolor mode),
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'green or saturation value
\n', + type: 'Number' + }, + { + name: 'v3', + description: 'blue or brightness value
\n', + type: 'Number' + }, + { + name: 'x', + description: 'x axis position
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y axis position
\n', + type: 'Number' + }, + { + name: 'z', + description: 'z axis position
\n', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 313, + params: [ + { + name: 'v1', + description: '', + type: 'Number' + }, + { + name: 'v2', + description: '', + type: 'Number' + }, + { + name: 'v3', + description: '', + type: 'Number' + }, + { + name: 'position', + description: 'the position of the light
\n', + type: 'p5.Vector' + } + ], + chainable: 1 + }, + { + line: 322, + params: [ + { + name: 'color', + description: + 'color Array, CSS color string,\nor p5.Color value
\n', + type: 'Number[]|String|p5.Color' + }, + { + name: 'x', + description: '', + type: 'Number' + }, + { + name: 'y', + description: '', + type: 'Number' + }, + { + name: 'z', + description: '', + type: 'Number' + } + ], + chainable: 1 + }, + { + line: 332, + params: [ + { + name: 'color', + description: '', + type: 'Number[]|String|p5.Color' + }, + { + name: 'position', + description: '', + type: 'p5.Vector' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/light.js', + line: 378, + description: + 'Sets the default ambient and directional light. The defaults are ambientLight(128, 128, 128) and directionalLight(128, 128, 128, 0, 0, -1). Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop.
\n', + itemtype: 'method', + name: 'lights', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n lights();\n rotateX(millis() / 1000);\n rotateY(millis() / 1000);\n rotateZ(millis() / 1000);\n box();\n}\n\nSets the falloff rates for point lights. It affects only the elements which are created after it in the code.\nThe default value is lightFalloff(1.0, 0.0, 0.0), and the parameters are used to calculate the falloff with the following equation:
\nd = distance from light position to vertex position
\nfalloff = 1 / (CONSTANT + d * LINEAR + ( d * d ) * QUADRATIC)
\n', + itemtype: 'method', + name: 'lightFalloff', + params: [ + { + name: 'constant', + description: 'constant value for determining falloff
\n', + type: 'Number' + }, + { + name: 'linear', + description: 'linear value for determining falloff
\n', + type: 'Number' + }, + { + name: 'quadratic', + description: 'quadratic value for determining falloff
\n', + type: 'Number' + } + ], + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n}\nfunction draw() {\n background(0);\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n translate(-25, 0, 0);\n lightFalloff(1, 0, 0);\n pointLight(250, 250, 250, locX, locY, 50);\n sphere(20);\n translate(50, 0, 0);\n lightFalloff(0.9, 0.01, 0);\n pointLight(250, 250, 250, locX, locY, 50);\n sphere(20);\n}\n\nCreates a spotlight with a given color, position, direction of light,\nangle and concentration. Here, angle refers to the opening or aperture\nof the cone of the spotlight, and concentration is used to focus the\nlight towards the center. Both angle and concentration are optional, but if\nyou want to provide concentration, you will also have to specify the angle.
\n', + itemtype: 'method', + name: 'spotLight', + chainable: 1, + example: [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('perPixelLighting', true);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n ambientLight(50);\n spotLight(0, 250, 0, locX, locY, 100, 0, 0, -1, Math.PI / 16);\n noStroke();\n sphere(40);\n}\n\nred or hue value (depending on the current\ncolor mode),
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'green or saturation value
\n', + type: 'Number' + }, + { + name: 'v3', + description: 'blue or brightness value
\n', + type: 'Number' + }, + { + name: 'x', + description: 'x axis position
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y axis position
\n', + type: 'Number' + }, + { + name: 'z', + description: 'z axis position
\n', + type: 'Number' + }, + { + name: 'rx', + description: 'x axis direction of light
\n', + type: 'Number' + }, + { + name: 'ry', + description: 'y axis direction of light
\n', + type: 'Number' + }, + { + name: 'rz', + description: 'z axis direction of light
\n', + type: 'Number' + }, + { + name: 'angle', + description: + 'optional parameter for angle. Defaults to PI/3
\n', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: + 'optional parameter for concentration. Defaults to 100
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 547, + params: [ + { + name: 'color', + description: + 'color Array, CSS color string,\nor p5.Color value
\n', + type: 'Number[]|String|p5.Color' + }, + { + name: 'position', + description: 'the position of the light
\n', + type: 'p5.Vector' + }, + { + name: 'direction', + description: 'the direction of the light
\n', + type: 'p5.Vector' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 556, + params: [ + { + name: 'v1', + description: '', + type: 'Number' + }, + { + name: 'v2', + description: '', + type: 'Number' + }, + { + name: 'v3', + description: '', + type: 'Number' + }, + { + name: 'position', + description: '', + type: 'p5.Vector' + }, + { + name: 'direction', + description: '', + type: 'p5.Vector' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 566, + params: [ + { + name: 'color', + description: '', + type: 'Number[]|String|p5.Color' + }, + { + name: 'x', + description: '', + type: 'Number' + }, + { + name: 'y', + description: '', + type: 'Number' + }, + { + name: 'z', + description: '', + type: 'Number' + }, + { + name: 'direction', + description: '', + type: 'p5.Vector' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 576, + params: [ + { + name: 'color', + description: '', + type: 'Number[]|String|p5.Color' + }, + { + name: 'position', + description: '', + type: 'p5.Vector' + }, + { + name: 'rx', + description: '', + type: 'Number' + }, + { + name: 'ry', + description: '', + type: 'Number' + }, + { + name: 'rz', + description: '', + type: 'Number' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 586, + params: [ + { + name: 'v1', + description: '', + type: 'Number' + }, + { + name: 'v2', + description: '', + type: 'Number' + }, + { + name: 'v3', + description: '', + type: 'Number' + }, + { + name: 'x', + description: '', + type: 'Number' + }, + { + name: 'y', + description: '', + type: 'Number' + }, + { + name: 'z', + description: '', + type: 'Number' + }, + { + name: 'direction', + description: '', + type: 'p5.Vector' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 598, + params: [ + { + name: 'v1', + description: '', + type: 'Number' + }, + { + name: 'v2', + description: '', + type: 'Number' + }, + { + name: 'v3', + description: '', + type: 'Number' + }, + { + name: 'position', + description: '', + type: 'p5.Vector' + }, + { + name: 'rx', + description: '', + type: 'Number' + }, + { + name: 'ry', + description: '', + type: 'Number' + }, + { + name: 'rz', + description: '', + type: 'Number' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + }, + { + line: 610, + params: [ + { + name: 'color', + description: '', + type: 'Number[]|String|p5.Color' + }, + { + name: 'x', + description: '', + type: 'Number' + }, + { + name: 'y', + description: '', + type: 'Number' + }, + { + name: 'z', + description: '', + type: 'Number' + }, + { + name: 'rx', + description: '', + type: 'Number' + }, + { + name: 'ry', + description: '', + type: 'Number' + }, + { + name: 'rz', + description: '', + type: 'Number' + }, + { + name: 'angle', + description: '', + type: 'Number', + optional: true + }, + { + name: 'conc', + description: '', + type: 'Number', + optional: true + } + ] + } + ] + }, + { + file: 'src/webgl/light.js', + line: 835, + description: + 'This function will remove all the lights from the sketch for the\nsubsequent materials rendered. It affects all the subsequent methods.\nCalls to lighting methods made after noLights() will re-enable lights\nin the sketch.
\n', + itemtype: 'method', + name: 'noLights', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n\n ambientLight(150, 0, 0);\n translate(-25, 0, 0);\n ambientMaterial(250);\n sphere(20);\n\n noLights();\n ambientLight(0, 150, 0);\n translate(50, 0, 0);\n ambientMaterial(250);\n sphere(20);\n}\n\nLoad a 3d model from an OBJ or STL file.\n
\nloadModel() should be placed inside of preload().\nThis allows the model to load fully before the rest of your code is run.\n
\nOne of the limitations of the OBJ and STL format is that it doesn't have a built-in\nsense of scale. This means that models exported from different programs might\nbe very different sizes. If your model isn't displaying, try calling\nloadModel() with the normalized parameter set to true. This will resize the\nmodel to a scale appropriate for p5. You can also make additional changes to\nthe final size of your model with the scale() function.
Also, the support for colored STL files is not present. STL files with color will be\nrendered without color properties.
\n', + itemtype: 'method', + name: 'loadModel', + return: { + description: 'the p5.Geometry object', + type: 'p5.Geometry' + }, + example: [ + "\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n\n\n//draw a spinning teapot\nlet teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n\nPath of the model to be loaded
\n', + type: 'String' + }, + { + name: 'normalize', + description: + 'If true, scale the model to a\n standardized size when loading
\n', + type: 'Boolean' + }, + { + name: 'successCallback', + description: + 'Function to be called\n once the model is loaded. Will be passed\n the 3D model object.
\n', + type: 'function(p5.Geometry)', + optional: true + }, + { + name: 'failureCallback', + description: + 'called with event error if\n the model fails to load.
\n', + type: 'Function(Event)', + optional: true + } + ], + return: { + description: 'the p5.Geometry object', + type: 'p5.Geometry' + } + }, + { + line: 94, + params: [ + { + name: 'path', + description: '', + type: 'String' + }, + { + name: 'successCallback', + description: '', + type: 'function(p5.Geometry)', + optional: true + }, + { + name: 'failureCallback', + description: '', + type: 'Function(Event)', + optional: true + } + ], + return: { + description: 'the p5.Geometry object', + type: 'p5.Geometry' + } + } + ] + }, + { + file: 'src/webgl/loading.js', + line: 170, + description: + 'Parse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:
\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5
\nf 4 3 2 1
\n', + class: 'p5', + module: 'Shape', + submodule: '3D Models' + }, + { + file: 'src/webgl/loading.js', + line: 279, + description: + 'STL files can be of two types, ASCII and Binary,
\nWe need to convert the arrayBuffer to an array of strings,\nto parse it as an ASCII file.
\n', + class: 'p5', + module: 'Shape', + submodule: '3D Models' + }, + { + file: 'src/webgl/loading.js', + line: 306, + description: + 'This function checks if the file is in ASCII format or in Binary format
\nIt is done by searching keyword solid at the start of the file.
An ASCII STL data must begin with solid as the first six bytes.\nHowever, ASCII STLs lacking the SPACE after the d are known to be\nplentiful. So, check the first 5 bytes for solid.
Several encodings, such as UTF-8, precede the text with up to 5 bytes:\nhttps://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding\nSearch for solid to start anywhere after those prefixes.
This function matches the query at the provided offset
This function parses the Binary STL files.\nhttps://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL
\nCurrently there is no support for the colors provided in STL files.
\n', + class: 'p5', + module: 'Shape', + submodule: '3D Models' + }, + { + file: 'src/webgl/loading.js', + line: 435, + description: + 'ASCII STL file starts with solid 'nameOfFile'\nThen contain the normal of the face, starting with facet normal\nNext contain a keyword indicating the start of face vertex, outer loop\nNext comes the three vertex, starting with vertex x y z\nVertices ends with endloop\nFace ends with endfacet\nNext face starts with facet normal\nThe end of the file is indicated by endsolid
Render a 3d model to the screen.
\n', + itemtype: 'method', + name: 'model', + params: [ + { + name: 'model', + description: 'Loaded 3d model to be rendered
\n', + type: 'p5.Geometry' + } + ], + example: [ + "\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n\nLoads a custom shader from the provided vertex and fragment\nshader paths. The shader files are loaded asynchronously in the\nbackground, so this method should be used in preload().
\nFor now, there are three main types of shaders. p5 will automatically\nsupply appropriate vertices, normals, colors, and lighting attributes\nif the parameters defined in the shader match the names.
\n', + itemtype: 'method', + name: 'loadShader', + params: [ + { + name: 'vertFilename', + description: + 'path to file containing vertex shader\nsource code
\n', + type: 'String' + }, + { + name: 'fragFilename', + description: + 'path to file containing fragment shader\nsource code
\n', + type: 'String' + }, + { + name: 'callback', + description: + 'callback to be executed after loadShader\ncompletes. On success, the Shader object is passed as the first argument.
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'callback to be executed when an error\noccurs inside loadShader. On error, the error is passed as the first\nargument.
\n', + type: 'Function', + optional: true + } + ], + return: { + description: + 'a shader object created from the provided\nvertex and fragment shader files.', + type: 'p5.Shader' + }, + example: [ + "\n\nlet mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\nsource code for the vertex shader
\n', + type: 'String' + }, + { + name: 'fragSrc', + description: 'source code for the fragment shader
\n', + type: 'String' + } + ], + return: { + description: + 'a shader object created from the provided\nvertex and fragment shaders.', + type: 'p5.Shader' + }, + example: [ + "\n\n// the 'varying's are shared between both vertex & fragment shaders\nlet varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nlet vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nlet fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +\n '}';\n\nlet mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\nThe shader() function lets the user provide a custom shader\nto fill in shapes in WEBGL mode. Users can create their\nown shaders by loading vertex and fragment shaders with\nloadShader().
\n', + itemtype: 'method', + name: 'shader', + chainable: 1, + params: [ + { + name: 's', + description: + 'the desired p5.Shader to use for rendering\nshapes.
\n', + type: 'p5.Shader', + optional: true + } + ], + example: [ + "\n\n// Click within the image to toggle\n// the shader used by the quad shape\n// Note: for an alternative approach to the same example,\n// involving changing uniforms please refer to:\n// https://p5js.org/reference/#/p5.Shader/setUniform\n\nlet redGreen;\nlet orangeBlue;\nlet showRedGreen = false;\n\nfunction preload() {\n // note that we are using two instances\n // of the same vertex and fragment shaders\n redGreen = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');\n orangeBlue = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // initialize the colors for redGreen shader\n shader(redGreen);\n redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);\n redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);\n\n // initialize the colors for orangeBlue shader\n shader(orangeBlue);\n orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);\n orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);\n\n noStroke();\n}\n\nfunction draw() {\n // update the offset values for each shader,\n // moving orangeBlue in vertical and redGreen\n // in horizontal direction\n orangeBlue.setUniform('offset', [0, sin(millis() / 2000) + 1]);\n redGreen.setUniform('offset', [sin(millis() / 2000), 1]);\n\n if (showRedGreen === true) {\n shader(redGreen);\n } else {\n shader(orangeBlue);\n }\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\nfunction mouseClicked() {\n showRedGreen = !showRedGreen;\n}\n\nThis function restores the default shaders in WEBGL mode. Code that runs\nafter resetShader() will not be affected by previously defined\nshaders. Should be run after shader().
\n', + itemtype: 'method', + name: 'resetShader', + chainable: 1, + class: 'p5', + module: 'Lights, Camera', + submodule: 'Material' + }, + { + file: 'src/webgl/material.js', + line: 283, + description: + 'Normal material for geometry. You can view all\npossible materials in this\nexample.
\n', + itemtype: 'method', + name: 'normalMaterial', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(40);\n}\n\nTexture for geometry. You can view other possible materials in this\nexample.
\n', + itemtype: 'method', + name: 'texture', + params: [ + { + name: 'tex', + description: + '2-dimensional graphics\n to render as texture
\n', + type: 'p5.Image|p5.MediaElement|p5.Graphics' + } + ], + chainable: 1, + example: [ + "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(200, 200, 200);\n}\n\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(75);\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n rotateX(0.5);\n noStroke();\n plane(50);\n}\n\n\nlet vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n rect(-40, -40, 80, 80);\n}\n\nfunction mousePressed() {\n vid.loop();\n}\n\nSets the coordinate space for texture mapping. The default mode is IMAGE\nwhich refers to the actual coordinates of the image.\nNORMAL refers to a normalized space of values ranging from 0 to 1.\nThis function only works in WEBGL mode.
\nWith IMAGE, if an image is 100 x 200 pixels, mapping the image onto the entire\nsize of a quad would require the points (0,0) (100, 0) (100,200) (0,200).\nThe same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).
\n', + itemtype: 'method', + name: 'textureMode', + params: [ + { + name: 'mode', + description: 'either IMAGE or NORMAL
\n', + type: 'Constant' + } + ], + example: [ + "\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n texture(img);\n textureMode(NORMAL);\n beginShape();\n vertex(-50, -50, 0, 0);\n vertex(50, -50, 1, 0);\n vertex(50, 50, 1, 1);\n vertex(-50, 50, 0, 1);\n endShape();\n}\n\nSets the global texture wrapping mode. This controls how textures behave\nwhen their uv's go outside of the 0 - 1 range. There are three options:\nCLAMP, REPEAT, and MIRROR.
\nCLAMP causes the pixels at the edge of the texture to extend to the bounds\nREPEAT causes the texture to tile repeatedly until reaching the bounds\nMIRROR works similarly to REPEAT but it flips the texture with every new tile
\nREPEAT & MIRROR are only available if the texture\nis a power of two size (128, 256, 512, 1024, etc.).
\nThis method will affect all textures in your sketch until a subsequent\ntextureWrap call is made.
\nIf only one argument is provided, it will be applied to both the\nhorizontal and vertical axes.
\n', + itemtype: 'method', + name: 'textureWrap', + params: [ + { + name: 'wrapX', + description: 'either CLAMP, REPEAT, or MIRROR
\n', + type: 'Constant' + }, + { + name: 'wrapY', + description: 'either CLAMP, REPEAT, or MIRROR
\n', + type: 'Constant', + optional: true + } + ], + example: [ + "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textureWrap(MIRROR);\n}\n\nfunction draw() {\n background(0);\n\n let dX = mouseX;\n let dY = mouseY;\n\n let u = lerp(1.0, 2.0, dX);\n let v = lerp(1.0, 2.0, dY);\n\n scale(width / 2);\n\n texture(img);\n\n beginShape(TRIANGLES);\n vertex(-1, -1, 0, 0, 0);\n vertex(1, -1, 0, u, 0);\n vertex(1, 1, 0, u, v);\n\n vertex(1, 1, 0, u, v);\n vertex(-1, 1, 0, 0, v);\n vertex(-1, -1, 0, 0, 0);\n endShape();\n}\n\nAmbient material for geometry with a given color. You can view all\npossible materials in this\nexample.
\n', + itemtype: 'method', + name: 'ambientMaterial', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(200);\n ambientMaterial(70, 130, 230);\n sphere(40);\n}\n\ngray value, red or hue value\n (depending on the current color mode),
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'green or saturation value
\n', + type: 'Number', + optional: true + }, + { + name: 'v3', + description: 'blue or brightness value
\n', + type: 'Number', + optional: true + }, + { + name: 'a', + description: 'opacity
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 605, + params: [ + { + name: 'color', + description: 'color, color Array, or CSS color string
\n', + type: 'Number[]|String|p5.Color' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/material.js', + line: 625, + description: + 'Sets the emissive color of the material used for geometry drawn to\nthe screen. This is a misnomer in the sense that the material does not\nactually emit light that effects surrounding polygons. Instead,\nit gives the appearance that the object is glowing. An emissive material\nwill display at full strength even if there is no light for it to reflect.
\n', + itemtype: 'method', + name: 'emissiveMaterial', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(0);\n emissiveMaterial(130, 230, 0);\n sphere(40);\n}\n\ngray value, red or hue value\n (depending on the current color mode),
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'green or saturation value
\n', + type: 'Number', + optional: true + }, + { + name: 'v3', + description: 'blue or brightness value
\n', + type: 'Number', + optional: true + }, + { + name: 'a', + description: 'opacity
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 657, + params: [ + { + name: 'color', + description: 'color, color Array, or CSS color string
\n', + type: 'Number[]|String|p5.Color' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/material.js', + line: 677, + description: + 'Specular material for geometry with a given color. You can view all\npossible materials in this\nexample.
\n', + itemtype: 'method', + name: 'specularMaterial', + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(50);\n pointLight(250, 250, 250, 100, 100, 30);\n specularMaterial(250);\n sphere(40);\n}\n\ngray value, red or hue value\n (depending on the current color mode),
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'green or saturation value
\n', + type: 'Number', + optional: true + }, + { + name: 'v3', + description: 'blue or brightness value
\n', + type: 'Number', + optional: true + }, + { + name: 'a', + description: 'opacity
\n', + type: 'Number', + optional: true + } + ], + chainable: 1 + }, + { + line: 709, + params: [ + { + name: 'color', + description: 'color Array, or CSS color string
\n', + type: 'Number[]|String|p5.Color' + } + ], + chainable: 1 + } + ] + }, + { + file: 'src/webgl/material.js', + line: 729, + description: + 'Sets the amount of gloss in the surface of shapes.\nUsed in combination with specularMaterial() in setting\nthe material properties of shapes. The default and minimum value is 1.
\n', + itemtype: 'method', + name: 'shininess', + params: [ + { + name: 'shine', + description: + 'Degree of Shininess.\n Defaults to 1.
\n', + type: 'Number' + } + ], + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n ambientLight(60, 60, 60);\n pointLight(255, 255, 255, locX, locY, 50);\n specularMaterial(250);\n translate(-25, 0, 0);\n shininess(1);\n sphere(20);\n translate(50, 0, 0);\n shininess(20);\n sphere(20);\n}\n\nSets the camera position for a 3D sketch. Parameters for this function define\nthe position for the camera, the center of the sketch (where the camera is\npointing), and an up direction (the orientation of the camera).
\nThis function simulates the movements of the camera, allowing objects to be\nviewed from various angles. Remember, it does not move the objects themselves\nbut the camera instead. For example when centerX value is positive, the camera\nis rotating to the right side of the sketch, so the object would seem like\nmoving to the left.
\nSee this example to view the position of your camera.
\nWhen called with no arguments, this function creates a default camera\nequivalent to\ncamera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);
\n', + itemtype: 'method', + name: 'camera', + params: [ + { + name: 'x', + description: 'camera position value on x axis
\n', + type: 'Number', + optional: true + }, + { + name: 'y', + description: 'camera position value on y axis
\n', + type: 'Number', + optional: true + }, + { + name: 'z', + description: 'camera position value on z axis
\n', + type: 'Number', + optional: true + }, + { + name: 'centerX', + description: 'x coordinate representing center of the sketch
\n', + type: 'Number', + optional: true + }, + { + name: 'centerY', + description: 'y coordinate representing center of the sketch
\n', + type: 'Number', + optional: true + }, + { + name: 'centerZ', + description: 'z coordinate representing center of the sketch
\n', + type: 'Number', + optional: true + }, + { + name: 'upX', + description: + 'x component of direction 'up' from camera
\n', + type: 'Number', + optional: true + }, + { + name: 'upY', + description: + 'y component of direction 'up' from camera
\n', + type: 'Number', + optional: true + }, + { + name: 'upZ', + description: + 'z component of direction 'up' from camera
\n', + type: 'Number', + optional: true + } + ], + chainable: 1, + example: [ + '\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(204);\n //move the camera away from the plane by a sin wave\n camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);\n plane(10, 10);\n}\n\n\n//move slider to see changes!\n//sliders control the first 6 parameters of camera()\nlet sliderGroup = [];\nlet X;\nlet Y;\nlet Z;\nlet centerX;\nlet centerY;\nlet centerZ;\nlet h = 20;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n //create sliders\n for (var i = 0; i < 6; i++) {\n if (i === 2) {\n sliderGroup[i] = createSlider(10, 400, 200);\n } else {\n sliderGroup[i] = createSlider(-400, 400, 0);\n }\n h = map(i, 0, 6, 5, 85);\n sliderGroup[i].position(10, height + h);\n sliderGroup[i].style('width', '80px');\n }\n}\n\nfunction draw() {\n background(60);\n // assigning sliders' value to each parameters\n X = sliderGroup[0].value();\n Y = sliderGroup[1].value();\n Z = sliderGroup[2].value();\n centerX = sliderGroup[3].value();\n centerY = sliderGroup[4].value();\n centerZ = sliderGroup[5].value();\n camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);\n stroke(255);\n fill(255, 102, 94);\n box(85);\n}\n\nSets a perspective projection for the camera in a 3D sketch. This projection\nrepresents depth through foreshortening: objects that are close to the camera\nappear their actual size while those that are further away from the camera\nappear smaller. The parameters to this function define the viewing frustum\n(the truncated pyramid within which objects are seen by the camera) through\nvertical field of view, aspect ratio (usually width/height), and near and far\nclipping planes.
\nWhen called with no arguments, the defaults\nprovided are equivalent to\nperspective(PI/3.0, width/height, eyeZ/10.0, eyeZ10.0), where eyeZ\nis equal to ((height/2.0) / tan(PI60.0/360.0));
\n', + itemtype: 'method', + name: 'perspective', + params: [ + { + name: 'fovy', + description: + 'camera frustum vertical field of view,\n from bottom to top of view, in angleMode units
\n', + type: 'Number', + optional: true + }, + { + name: 'aspect', + description: 'camera frustum aspect ratio
\n', + type: 'Number', + optional: true + }, + { + name: 'near', + description: 'frustum near plane length
\n', + type: 'Number', + optional: true + }, + { + name: 'far', + description: 'frustum far plane length
\n', + type: 'Number', + optional: true + } + ], + chainable: 1, + example: [ + '\n\n//drag the mouse to look around!\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n perspective(PI / 3.0, width / height, 0.1, 500);\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(-0.3);\n rotateY(-0.2);\n translate(0, 0, -50);\n\n push();\n translate(-15, 0, sin(frameCount / 30) * 95);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 95);\n box(30);\n pop();\n}\n\nSets an orthographic projection for the camera in a 3D sketch and defines a\nbox-shaped viewing frustum within which objects are seen. In this projection,\nall objects with the same dimension appear the same size, regardless of\nwhether they are near or far from the camera. The parameters to this\nfunction specify the viewing frustum where left and right are the minimum and\nmaximum x values, top and bottom are the minimum and maximum y values, and near\nand far are the minimum and maximum z values. If no parameters are given, the\ndefault is used: ortho(-width/2, width/2, -height/2, height/2).
\n', + itemtype: 'method', + name: 'ortho', + params: [ + { + name: 'left', + description: 'camera frustum left plane
\n', + type: 'Number', + optional: true + }, + { + name: 'right', + description: 'camera frustum right plane
\n', + type: 'Number', + optional: true + }, + { + name: 'bottom', + description: 'camera frustum bottom plane
\n', + type: 'Number', + optional: true + }, + { + name: 'top', + description: 'camera frustum top plane
\n', + type: 'Number', + optional: true + }, + { + name: 'near', + description: 'camera frustum near plane
\n', + type: 'Number', + optional: true + }, + { + name: 'far', + description: 'camera frustum far plane
\n', + type: 'Number', + optional: true + } + ], + chainable: 1, + example: [ + "\n\n//drag the mouse to look around!\n//there's no vanishing point\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(0.2);\n rotateY(-0.2);\n push();\n translate(-15, 0, sin(frameCount / 30) * 65);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 65);\n box(30);\n pop();\n}\n\nSets a perspective matrix as defined by the parameters.
\nA frustum is a geometric form: a pyramid with its top\ncut off. With the viewer's eye at the imaginary top of\nthe pyramid, the six planes of the frustum act as clipping\nplanes when rendering a 3D view. Thus, any form inside the\nclipping planes is visible; anything outside\nthose planes is not visible.
\nSetting the frustum changes the perspective of the scene being rendered.\nThis can be achieved more simply in many cases by using\nperspective().
\n', + itemtype: 'method', + name: 'frustum', + params: [ + { + name: 'left', + description: 'camera frustum left plane
\n', + type: 'Number', + optional: true + }, + { + name: 'right', + description: 'camera frustum right plane
\n', + type: 'Number', + optional: true + }, + { + name: 'bottom', + description: 'camera frustum bottom plane
\n', + type: 'Number', + optional: true + }, + { + name: 'top', + description: 'camera frustum top plane
\n', + type: 'Number', + optional: true + }, + { + name: 'near', + description: 'camera frustum near plane
\n', + type: 'Number', + optional: true + }, + { + name: 'far', + description: 'camera frustum far plane
\n', + type: 'Number', + optional: true + } + ], + chainable: 1, + example: [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200);\n}\nfunction draw() {\n background(200);\n orbitControl();\n strokeWeight(10);\n stroke(0, 0, 255);\n noFill();\n\n rotateY(-0.2);\n rotateX(-0.3);\n push();\n translate(-15, 0, sin(frameCount / 30) * 25);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 25);\n box(30);\n pop();\n}\n\nCreates a new p5.Camera object and tells the\nrenderer to use that camera.\nReturns the p5.Camera object.
\n', + itemtype: 'method', + name: 'createCamera', + return: { + description: 'The newly created camera object.', + type: 'p5.Camera' + }, + class: 'p5', + module: 'Lights, Camera', + submodule: 'Camera' + }, + { + file: 'src/webgl/p5.Camera.js', + line: 408, + description: + 'Sets a perspective projection for a p5.Camera object and sets parameters\nfor that projection according to perspective()\nsyntax.
\n', + itemtype: 'method', + name: 'perspective', + class: 'p5.Camera', + module: 'Lights, Camera', + submodule: 'Camera' + }, + { + file: 'src/webgl/p5.Camera.js', + line: 488, + description: + 'Sets an orthographic projection for a p5.Camera object and sets parameters\nfor that projection according to ortho() syntax.
\n', + itemtype: 'method', + name: 'ortho', + class: 'p5.Camera', + module: 'Lights, Camera', + submodule: 'Camera' + }, + { + file: 'src/webgl/p5.Camera.js', + line: 547, + itemtype: 'method', + name: 'frustum', + class: 'p5.Camera', + module: 'Lights, Camera', + submodule: 'Camera' + }, + { + file: 'src/webgl/p5.Camera.js', + line: 652, + description: + 'Panning rotates the camera view to the left and right.
\n', + itemtype: 'method', + name: 'pan', + params: [ + { + name: 'angle', + description: + 'amount to rotate camera in current\nangleMode units.\nGreater than 0 values rotate counterclockwise (to the left).
\n', + type: 'Number' + } + ], + example: [ + "\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\nTilting rotates the camera view up and down.
\n', + itemtype: 'method', + name: 'tilt', + params: [ + { + name: 'angle', + description: + 'amount to rotate camera in current\nangleMode units.\nGreater than 0 values rotate counterclockwise (to the left).
\n', + type: 'Number' + } + ], + example: [ + "\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n\nReorients the camera to look at a position in world space.
\n', + itemtype: 'method', + name: 'lookAt', + params: [ + { + name: 'x', + description: 'x position of a point in world space
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y position of a point in world space
\n', + type: 'Number' + }, + { + name: 'z', + description: 'z position of a point in world space
\n', + type: 'Number' + } + ], + example: [ + '\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\nSets a camera's position and orientation. This is equivalent to calling\ncamera() on a p5.Camera object.
\n', + itemtype: 'method', + name: 'camera', + class: 'p5.Camera', + module: 'Lights, Camera', + submodule: 'Camera' + }, + { + file: 'src/webgl/p5.Camera.js', + line: 917, + description: + 'Move camera along its local axes while maintaining current camera orientation.
\n', + itemtype: 'method', + name: 'move', + params: [ + { + name: 'x', + description: + 'amount to move along camera's left-right axis
\n', + type: 'Number' + }, + { + name: 'y', + description: 'amount to move along camera's up-down axis
\n', + type: 'Number' + }, + { + name: 'z', + description: + 'amount to move along camera's forward-backward axis
\n', + type: 'Number' + } + ], + example: [ + '\n\n// see the camera move along its own axes while maintaining its orientation\nlet cam;\nlet delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n\nSet camera position in world-space while maintaining current camera\norientation.
\n', + itemtype: 'method', + name: 'setPosition', + params: [ + { + name: 'x', + description: 'x position of a point in world space
\n', + type: 'Number' + }, + { + name: 'y', + description: 'y position of a point in world space
\n', + type: 'Number' + }, + { + name: 'z', + description: 'z position of a point in world space
\n', + type: 'Number' + } + ], + example: [ + "\n\n// press '1' '2' or '3' keys to set camera position\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n\nSets rendererGL's current camera to a p5.Camera object. Allows switching\nbetween multiple cameras.
\n', + itemtype: 'method', + name: 'setCamera', + params: [ + { + name: 'cam', + description: 'p5.Camera object
\n', + type: 'p5.Camera' + } + ], + example: [ + '\n\nlet cam1, cam2;\nlet currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\ncomputes smooth normals per vertex as an average of each\nface.
\n', + itemtype: 'method', + name: 'computeNormals', + chainable: 1, + class: 'p5.Geometry', + module: 'Lights, Camera', + submodule: 'Material' + }, + { + file: 'src/webgl/p5.Geometry.js', + line: 153, + description: + 'Averages the vertex normals. Used in curved\nsurfaces
\n', + itemtype: 'method', + name: 'averageNormals', + chainable: 1, + class: 'p5.Geometry', + module: 'Lights, Camera', + submodule: 'Material' + }, + { + file: 'src/webgl/p5.Geometry.js', + line: 174, + description: + 'Averages pole normals. Used in spherical primitives
\n', + itemtype: 'method', + name: 'averagePoleNormals', + chainable: 1, + class: 'p5.Geometry', + module: 'Lights, Camera', + submodule: 'Material' + }, + { + file: 'src/webgl/p5.Geometry.js', + line: 267, + description: + 'Modifies all vertices to be centered within the range -100 to 100.
\n', + itemtype: 'method', + name: 'normalize', + chainable: 1, + class: 'p5.Geometry', + module: 'Lights, Camera', + submodule: 'Material' + }, + { + file: 'src/webgl/p5.RendererGL.js', + line: 279, + description: + 'Set attributes for the WebGL Drawing context.\nThis is a way of adjusting how the WebGL\nrenderer works to fine-tune the display and performance.\n
\nNote that this will reinitialize the drawing context\nif called after the WebGL canvas is made.\n
\nIf an object is passed as the parameter, all attributes\nnot declared in the object will be set to defaults.\n
\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true\n
\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n\nfunction setup() {\n setAttributes('antialias', true);\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nlet lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n let t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (let i = 0; i < lights.length; i++) {\n let light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 24, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n\nName of attribute
\n', + type: 'String' + }, + { + name: 'value', + description: 'New value of named attribute
\n', + type: 'Boolean' + } + ] + }, + { + line: 418, + params: [ + { + name: 'obj', + description: 'object with key-value pairs
\n', + type: 'Object' + } + ] + } + ] + }, + { + file: 'src/webgl/p5.Shader.js', + line: 281, + description: + 'Wrapper around gl.uniform functions.\nAs we store uniform info in the shader we can use that\nto do type checking on the supplied data and call\nthe appropriate function.
\n', + itemtype: 'method', + name: 'setUniform', + chainable: 1, + params: [ + { + name: 'uniformName', + description: 'the name of the uniform in the\nshader program
\n', + type: 'String' + }, + { + name: 'data', + description: + 'the data to be associated\nwith that uniform; type varies (could be a single numerical value, array,\nmatrix, or texture / sampler reference)
\n', + type: 'Object|Number|Boolean|Number[]' + } + ], + example: [ + "\n\n// Click within the image to toggle the value of uniforms\n// Note: for an alternative approach to the same example,\n// involving toggling between shaders please refer to:\n// https://p5js.org/reference/#/p5/shader\n\nlet grad;\nlet showRedGreen = false;\n\nfunction preload() {\n // note that we are using two instances\n // of the same vertex and fragment shaders\n grad = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n shader(grad);\n noStroke();\n}\n\nfunction draw() {\n // update the offset values for each scenario,\n // moving the \"grad\" shader in either vertical or\n // horizontal direction each with differing colors\n\n if (showRedGreen === true) {\n grad.setUniform('colorCenter', [1, 0, 0]);\n grad.setUniform('colorBackground', [0, 1, 0]);\n grad.setUniform('offset', [sin(millis() / 2000), 1]);\n } else {\n grad.setUniform('colorCenter', [1, 0.5, 0]);\n grad.setUniform('colorBackground', [0.226, 0, 0.615]);\n grad.setUniform('offset', [0, sin(millis() / 2000) + 1]);\n }\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\nfunction mouseClicked() {\n showRedGreen = !showRedGreen;\n}\n\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound
\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors
\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE
\nSome of the many audio libraries & resources that inspire p5.sound:
\nTONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js
\nbuzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/
\nBoris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0
\nwavesurfer.js https://github.com/katspaugh/wavesurfer.js
\nWeb Audio Components by Jordan Santell https://github.com/web-audio-components
\nWilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound
\nWeb Audio API: http://w3.org/TR/webaudio/
\nDetermine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats
\n', + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 363, + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 740, + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 810, + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1005, + description: + "Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.
\n\nSome browsers require users to startAudioContext\nwith a user gesture, such as touchStarted in the example below.
", + itemtype: 'method', + name: 'getAudioContext', + return: { + description: 'AudioContext for this sketch', + type: 'Object' + }, + example: [ + "\n\n function draw() {\n background(255);\n textAlign(CENTER);\n\n if (getAudioContext().state !== 'running') {\n text('click to start audio', width/2, height/2);\n } else {\n text('audio is enabled', width/2, height/2);\n }\n }\n\n function touchStarted() {\n if (getAudioContext().state !== 'running') {\n getAudioContext().resume();\n }\n let synth = new p5.MonoSynth();\n synth.play('A4', 0.5, 0, 0.2);\n }\n\nIt is a good practice to give users control over starting audio playback.\nThis practice is enforced by Google Chrome\'s autoplay policy as of r70\n(info), iOS Safari, and other browsers.\n
\n\n\nuserStartAudio() starts the Audio Context on a user gesture. It utilizes\nthe StartAudioContext library by\nYotam Mann (MIT Licence, 2016). Read more at https://github.com/tambien/StartAudioContext.\n
\n\nStarting the audio context on a user gesture can be as simple as userStartAudio().\nOptional parameters let you decide on a specific element that will start the audio context,\nand/or call a function once the audio context is started.
This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.
\n', + type: 'Element|Array', + optional: true + }, + { + name: 'callback', + description: + 'Callback to invoke when the AudioContext has started
\n', + type: 'Function', + optional: true + } + ], + return: { + description: + "Returns a Promise which is resolved when\n the AudioContext state is 'running'", + type: 'Promise' + }, + itemtype: 'method', + name: 'userStartAudio', + example: [ + "\n\nfunction setup() {\n let myDiv = createDiv('click to start audio');\n myDiv.position(0, 0);\n\n let mySynth = new p5.MonoSynth();\n\n // This won't play until the context has started\n mySynth.play('A6');\n\n // Start the audio context on a click/touch event\n userStartAudio().then(function() {\n myDiv.remove();\n });\n}\nMaster contains AudioContext and the master sound output.
\n', + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1132, + description: + 'Returns a number representing the master amplitude (volume) for sound\nin this sketch.
\n', + itemtype: 'method', + name: 'getMasterVolume', + return: { + description: + 'Master amplitude (volume) for sound in this sketch.\n Should be between 0.0 (silence) and 1.0.', + type: 'Number' + }, + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1143, + description: + "Scale the output of all sound in this sketch
\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide arampTime parameter. For more\ncomplex fades, see the Envelope class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
\nHow This Works: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer's output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.
\n\nIf no value is provided, returns a Web Audio API Gain Node
", + itemtype: 'method', + name: 'masterVolume', + params: [ + { + name: 'volume', + description: + 'Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
\n', + type: 'Number|Object' + }, + { + name: 'rampTime', + description: 'Fade for t seconds
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'Schedule this event to happen at\n t seconds in the future
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.sound', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1185, + description: + 'p5.soundOut is the p5.sound master output. It sends output to\nthe destination of this window's web audio context. It contains\nWeb Audio API nodes including a dyanmicsCompressor (.limiter),\nand Gain Nodes for .input and .output.
Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system's sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.
\n', + itemtype: 'method', + name: 'sampleRate', + return: { + description: 'samplerate samples per second', + type: 'Number' + }, + class: 'p5', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1226, + description: + 'Returns the closest MIDI note value for\na given frequency.
\n', + itemtype: 'method', + name: 'freqToMidi', + params: [ + { + name: 'frequency', + description: + 'A freqeuncy, for example, the "A"\n above Middle C is 440Hz
\n', + type: 'Number' + } + ], + return: { + description: 'MIDI note value', + type: 'Number' + }, + class: 'p5', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1240, + description: + 'Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.
\n', + itemtype: 'method', + name: 'midiToFreq', + params: [ + { + name: 'midiNote', + description: 'The number of a MIDI note
\n', + type: 'Number' + } + ], + return: { + description: 'Frequency value of the given MIDI note', + type: 'Number' + }, + example: [ + "\n\nlet notes = [60, 64, 67, 72];\nlet i = 0;\n\nfunction setup() {\n osc = new p5.Oscillator('Triangle');\n osc.start();\n frameRate(1);\n}\n\nfunction draw() {\n let freq = midiToFreq(notes[i]);\n osc.freq(freq);\n i++;\n if (i >= notes.length){\n i = 0;\n }\n}\nList the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client's web browser.\nHere is a free online file\nconverter.
\n', + itemtype: 'method', + name: 'soundFormats', + params: [ + { + name: 'formats', + description: + 'i.e. 'mp3', 'wav', 'ogg'
\n', + type: 'String', + optional: true, + multiple: true + } + ], + example: [ + "\n\nfunction preload() {\n // set the global sound formats\n soundFormats('mp3', 'ogg');\n\n // load either beatbox.mp3, or .ogg, depending on browser\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n mySound.play();\n}\nUsed by Osc and Envelope to chain signal math
\n', + class: 'p5', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1763, + description: + 'loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n\nlocal server is recommended when loading external files.
\n', + itemtype: 'method', + name: 'loadSound', + params: [ + { + name: 'path', + description: + 'Path to the sound file, or an array with\n paths to soundfiles in multiple formats\n i.e. ['sound.ogg', 'sound.mp3'].\n Alternately, accepts an object: either\n from the HTML5 File API, or a p5.File.
\n', + type: 'String|Array' + }, + { + name: 'successCallback', + description: 'Name of a function to call once file loads
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'Name of a function to call if there is\n an error loading the file.
\n', + type: 'Function', + optional: true + }, + { + name: 'whileLoading', + description: + 'Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.
\n', + type: 'Function', + optional: true + } + ], + return: { + description: 'Returns a p5.SoundFile', + type: 'SoundFile' + }, + example: [ + "\n\nfunction preload() {\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\nReturns true if the sound file finished loading successfully.
\n', + itemtype: 'method', + name: 'isLoaded', + return: { + description: '', + type: 'Boolean' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 1932, + description: 'Play the p5.SoundFile
\n', + itemtype: 'method', + name: 'play', + params: [ + { + name: 'startTime', + description: + '(optional) schedule playback to start (in seconds from now).
\n', + type: 'Number', + optional: true + }, + { + name: 'rate', + description: '(optional) playback rate
\n', + type: 'Number', + optional: true + }, + { + name: 'amp', + description: + '(optional) amplitude (volume)\n of playback
\n', + type: 'Number', + optional: true + }, + { + name: 'cueStart', + description: '(optional) cue start time in seconds
\n', + type: 'Number', + optional: true + }, + { + name: 'duration', + description: '(optional) duration of playback in seconds
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2022, + description: + 'p5.SoundFile has two play modes: restart and\nsustain. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. With untilDone, a sound will play only if it's\nnot already playing. Sustain is the default mode.
'restart' or 'sustain' or 'untilDone'
\n', + type: 'String' + } + ], + example: [ + "\n\nlet mySound;\nfunction preload(){\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\nfunction mouseClicked() {\n mySound.playMode('sustain');\n mySound.play();\n}\nfunction keyPressed() {\n mySound.playMode('restart');\n mySound.play();\n}\n\n Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.
\nAfter pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().
\n', + itemtype: 'method', + name: 'pause', + params: [ + { + name: 'startTime', + description: + '(optional) schedule event to occur\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + example: [ + "\n\nlet soundFile;\n\nfunction preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');\n}\nfunction setup() {\n background(0, 255, 0);\n soundFile.setVolume(0.1);\n soundFile.loop();\n}\nfunction keyTyped() {\n if (key == 'p') {\n soundFile.pause();\n background(255, 0, 0);\n }\n}\n\nfunction keyReleased() {\n if (key == 'p') {\n soundFile.play();\n background(0, 255, 0);\n }\n}\n\nLoop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.
\n', + itemtype: 'method', + name: 'loop', + params: [ + { + name: 'startTime', + description: + '(optional) schedule event to occur\n seconds from now
\n', + type: 'Number', + optional: true + }, + { + name: 'rate', + description: '(optional) playback rate
\n', + type: 'Number', + optional: true + }, + { + name: 'amp', + description: '(optional) playback volume
\n', + type: 'Number', + optional: true + }, + { + name: 'cueLoopStart', + description: '(optional) startTime in seconds
\n', + type: 'Number', + optional: true + }, + { + name: 'duration', + description: '(optional) loop duration in seconds
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2138, + description: + 'Set a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.
\n', + itemtype: 'method', + name: 'setLoop', + params: [ + { + name: 'Boolean', + description: 'set looping to true or false
\n', + type: 'Boolean' + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2159, + description: + 'Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.
\n', + itemtype: 'method', + name: 'isLooping', + return: { + description: '', + type: 'Boolean' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2174, + description: + 'Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).
\n', + itemtype: 'method', + name: 'isPlaying', + return: { + description: '', + type: 'Boolean' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2184, + description: + 'Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).
\n', + itemtype: 'method', + name: 'isPaused', + return: { + description: '', + type: 'Boolean' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2194, + description: 'Stop soundfile playback.
\n', + itemtype: 'method', + name: 'stop', + params: [ + { + name: 'startTime', + description: + '(optional) schedule event to occur\n in seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2239, + description: + 'Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime parameter. For more\ncomplex fades, see the Envelope class.
Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
\n', + itemtype: 'method', + name: 'setVolume', + params: [ + { + name: 'volume', + description: + 'Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
\n', + type: 'Number|Object' + }, + { + name: 'rampTime', + description: 'Fade for t seconds
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'Schedule this event to happen at\n t seconds in the future
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2280, + description: + 'Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).
\n', + itemtype: 'method', + name: 'pan', + params: [ + { + name: 'panValue', + description: 'Set the stereo panner
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + example: [ + "\n\n\n let ball = {};\n let soundFile;\n\n function preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/beatbox.mp3');\n }\n\n function draw() {\n background(0);\n ball.x = constrain(mouseX, 0, width);\n ellipse(ball.x, height/2, 20, 20)\n }\n\n function mousePressed(){\n // map the ball's x location to a panning degree\n // between -1.0 (left) and 1.0 (right)\n let panning = map(ball.x, 0., width,-1.0, 1.0);\n soundFile.pan(panning);\n soundFile.play();\n }\n Returns the current stereo pan position (-1.0 to 1.0)
\n', + itemtype: 'method', + name: 'getPan', + return: { + description: + 'Returns the stereo pan setting of the Oscillator\n as a number between -1.0 (left) and 1.0 (right).\n 0.0 is center and default.', + type: 'Number' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2330, + description: + 'Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.
\n', + itemtype: 'method', + name: 'rate', + params: [ + { + name: 'playbackRate', + description: + 'Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.
\n', + type: 'Number', + optional: true + } + ], + example: [ + "\n\nlet song;\n\nfunction preload() {\n song = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n song.loop();\n}\n\nfunction draw() {\n background(200);\n\n // Set the rate to a range between 0.1 and 4\n // Changing the rate also alters the pitch\n let speed = map(mouseY, 0.1, height, 0, 2);\n speed = constrain(speed, 0.01, 4);\n song.rate(speed);\n\n // Draw a circle to show what is going on\n stroke(0);\n fill(51, 100);\n ellipse(mouseX, 100, 48, 48);\n}\n\n \n Returns the duration of a sound file in seconds.
\n', + itemtype: 'method', + name: 'duration', + return: { + description: 'The duration of the soundFile in seconds.', + type: 'Number' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2417, + description: + 'Return the current position of the p5.SoundFile playhead, in seconds.\nTime is relative to the normal buffer direction, so if reverseBuffer\nhas been called, currentTime will count backwards.
Move the playhead of the song to a position, in seconds. Start timing\nand playback duration. If none are given, will reset the file to play\nentire duration from start to finish.
\n', + itemtype: 'method', + name: 'jump', + params: [ + { + name: 'cueTime', + description: 'cueTime of the soundFile in seconds.
\n', + type: 'Number' + }, + { + name: 'duration', + description: 'duration in seconds.
\n', + type: 'Number' + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2451, + description: + 'Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.
\n', + itemtype: 'method', + name: 'channels', + return: { + description: '[channels]', + type: 'Number' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2461, + description: 'Return the sample rate of the sound file.
\n', + itemtype: 'method', + name: 'sampleRate', + return: { + description: '[sampleRate]', + type: 'Number' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2470, + description: + 'Return the number of samples in a sound file.\nEqual to sampleRate * duration.
\n', + itemtype: 'method', + name: 'frames', + return: { + description: '[sampleCount]', + type: 'Number' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2480, + description: + 'Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile's\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, 'length', which determines size of the array.\nLarger arrays result in more precise waveform visualizations.
\nInspired by Wavesurfer.js.
\n', + itemtype: 'method', + name: 'getPeaks', + params: [ + { + name: 'length', + description: + 'length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'Array of peaks.', + type: 'Float32Array' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2532, + description: + 'Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).
\n', + itemtype: 'method', + name: 'reverseBuffer', + example: [ + "\n\nlet drum;\n\nfunction preload() {\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n drum.reverseBuffer();\n drum.play();\n}\n\n \n Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.
\n', + itemtype: 'method', + name: 'onended', + params: [ + { + name: 'callback', + description: + 'function to call when the\n soundfile has ended.
\n', + type: 'Function' + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2625, + description: + 'Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe master output. Most p5sound objects connect to the master\noutput when they are created.
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'object', + description: 'Audio object that accepts an input
\n', + type: 'Object', + optional: true + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2646, + description: 'Disconnects the output of this p5sound object.
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2656, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2661, + description: + 'Reset the source for this SoundFile to a\nnew path (URL).
\n', + itemtype: 'method', + name: 'setPath', + params: [ + { + name: 'path', + description: 'path to audio file
\n', + type: 'String' + }, + { + name: 'callback', + description: 'Callback
\n', + type: 'Function' + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2674, + description: 'Replace the current Audio Buffer with a new Buffer.
\n', + itemtype: 'method', + name: 'setBuffer', + params: [ + { + name: 'buf', + description: + 'Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.
\n', + type: 'Array' + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2741, + description: + 'processPeaks returns an array of timestamps where it thinks there is a beat.
\nThis is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.
\nThe process involves running the soundfile through a lowpass filter, and finding all of the\npeaks above the initial threshold. If the total number of peaks are below the minimum number of peaks,\nit decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached.
\n', + itemtype: 'method', + name: 'processPeaks', + params: [ + { + name: 'callback', + description: 'a function to call once this data is returned
\n', + type: 'Function' + }, + { + name: 'initThreshold', + description: 'initial threshold defaults to 0.9
\n', + type: 'Number', + optional: true + }, + { + name: 'minThreshold', + description: 'minimum threshold defaults to 0.22
\n', + type: 'Number', + optional: true + }, + { + name: 'minPeaks', + description: 'minimum number of peaks defaults to 200
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'Array of timestamped peaks', + type: 'Array' + }, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2934, + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 2943, + description: + 'Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\nAccepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\nTime will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n', + itemtype: 'method', + name: 'addCue', + params: [ + { + name: 'time', + description: + 'Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.
\n', + type: 'Number' + }, + { + name: 'callback', + description: + 'Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.
\n', + type: 'Function' + }, + { + name: 'value', + description: + 'An object to be passed as the\n second parameter to the\n callback function.
\n', + type: 'Object', + optional: true + } + ], + return: { + description: + 'id ID of this cue,\n useful for removeCue(id)', + type: 'Number' + }, + example: [ + '\n\nlet mySound;\nfunction preload() {\n mySound = loadSound(\'assets/beat.mp3\');\n}\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text(\'click to play\', width/2, height/2);\n\n // schedule calls to changeText\n mySound.addCue(0.50, changeText, "hello" );\n mySound.addCue(1.00, changeText, "p5" );\n mySound.addCue(1.50, changeText, "what" );\n mySound.addCue(2.00, changeText, "do" );\n mySound.addCue(2.50, changeText, "you" );\n mySound.addCue(3.00, changeText, "want" );\n mySound.addCue(4.00, changeText, "to" );\n mySound.addCue(5.00, changeText, "make" );\n mySound.addCue(6.00, changeText, "?" );\n}\n\nfunction changeText(val) {\n background(0);\n text(val, width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (mySound.isPlaying() ) {\n mySound.stop();\n } else {\n mySound.play();\n }\n }\n}\nRemove a callback based on its ID. The ID is returned by the\naddCue method.
\n', + itemtype: 'method', + name: 'removeCue', + params: [ + { + name: 'id', + description: 'ID of the cue, as returned by addCue
\n', + type: 'Number' + } + ], + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3040, + description: + 'Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n', + itemtype: 'method', + name: 'clearCues', + class: 'p5.SoundFile', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3065, + description: + 'Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device. To upload a file to a server, see\ngetBlob
\n', + itemtype: 'method', + name: 'save', + params: [ + { + name: 'fileName', + description: 'name of the resulting .wav file.
\n', + type: 'String', + optional: true + } + ], + example: [ + "\n\n let inp, button, mySound;\n let fileName = 'cool';\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n function setup() {\n btn = createButton('click to save file');\n btn.position(0, 0);\n btn.mouseClicked(handleMouseClick);\n }\n\n function handleMouseClick() {\n mySound.save(fileName);\n }\nThis method is useful for sending a SoundFile to a server. It returns the\n.wav-encoded audio data as a "Blob".\nA Blob is a file-like data object that can be uploaded to a server\nwith an http request. We'll\nuse the httpDo options object to send a POST request with some\nspecific options: we encode the request as multipart/form-data,\nand attach the blob as one of the form values using FormData.
\n\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n\n function setup() {\n noCanvas();\n let soundBlob = mySound.getBlob();\n\n // Now we can send the blob to a server...\n let serverUrl = 'https://jsonplaceholder.typicode.com/posts';\n let httpRequestOptions = {\n method: 'POST',\n body: new FormData().append('soundBlob', soundBlob),\n headers: new Headers({\n 'Content-Type': 'multipart/form-data'\n })\n };\n httpDo(serverUrl, httpRequestOptions);\n\n // We can also create an `ObjectURL` pointing to the Blob\n let blobUrl = URL.createObjectURL(soundBlob);\n\n // The `Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).
\n', + itemtype: 'method', + name: 'setInput', + params: [ + { + name: 'snd', + description: + 'set the sound source\n (optional, defaults to\n master output)
\n', + type: 'SoundObject|undefined', + optional: true + }, + { + name: 'smoothing', + description: + 'a range between 0.0 and 1.0\n to smooth amplitude readings
\n', + type: 'Number|undefined', + optional: true + } + ], + example: [ + "\n\nfunction preload(){\n sound1 = loadSound('assets/beat.mp3');\n sound2 = loadSound('assets/drum.mp3');\n}\nfunction setup(){\n amplitude = new p5.Amplitude();\n sound1.play();\n sound2.play();\n amplitude.setInput(sound2);\n}\nfunction draw() {\n background(0);\n fill(255);\n let level = amplitude.getLevel();\n let size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound1.stop();\n sound2.stop();\n}\nReturns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.
\n', + itemtype: 'method', + name: 'getLevel', + params: [ + { + name: 'channel', + description: + 'Optionally return only channel 0 (left) or 1 (right)
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'Amplitude as a number between 0.0 and 1.0', + type: 'Number' + }, + example: [ + "\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n amplitude = new p5.Amplitude();\n sound.play();\n}\nfunction draw() {\n background(0);\n fill(255);\n let level = amplitude.getLevel();\n let size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound.stop();\n}\nDetermines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.
\n', + itemtype: 'method', + name: 'toggleNormalize', + params: [ + { + name: 'boolean', + description: 'set normalize to true (1) or false (0)
\n', + type: 'Boolean', + optional: true + } + ], + class: 'p5.Amplitude', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3425, + description: + 'Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.
\n', + itemtype: 'method', + name: 'smooth', + params: [ + { + name: 'set', + description: 'smoothing from 0.0 <= 1
\n', + type: 'Number' + } + ], + class: 'p5.Amplitude', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3599, + description: + 'Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.
\n', + itemtype: 'method', + name: 'setInput', + params: [ + { + name: 'source', + description: 'p5.sound object (or web audio API source node)
\n', + type: 'Object', + optional: true + } + ], + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3618, + description: + 'Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.
\n', + itemtype: 'method', + name: 'waveform', + params: [ + { + name: 'bins', + description: + 'Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n', + type: 'Number', + optional: true + }, + { + name: 'precision', + description: + 'If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.
\n', + type: 'String', + optional: true + } + ], + return: { + description: + 'Array Array of amplitude values (-1 to 1)\n over time. Array length = bins.', + type: 'Array' + }, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3661, + description: + 'Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\ngetEnergy().
Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n', + type: 'Number', + optional: true + }, + { + name: 'scale', + description: + 'If "dB," returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.
\n', + type: 'Number', + optional: true + } + ], + return: { + description: + 'spectrum Array of energy (amplitude/volume)\n values across the frequency spectrum.\n Lowest energy (silence) = 0, highest\n possible is 255.', + type: 'Array' + }, + example: [ + "\n\nlet osc;\nlet fft;\n\nfunction setup(){\n createCanvas(100,100);\n osc = new p5.Oscillator();\n osc.amp(0);\n osc.start();\n fft = new p5.FFT();\n}\n\nfunction draw(){\n background(0);\n\n let freq = map(mouseX, 0, 800, 20, 15000);\n freq = constrain(freq, 1, 20000);\n osc.freq(freq);\n\n let spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n let x = map(i, 0, spectrum.length, 0, width);\n let h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h );\n }\n\n stroke(255);\n text('Freq: ' + round(freq)+'Hz', 10, 10);\n\n isMouseOverCanvas();\n}\n\n// only play sound when mouse is over canvas\nfunction isMouseOverCanvas() {\n let mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n osc.amp(0.5, 0.2);\n } else {\n osc.amp(0, 0.2);\n }\n}\nReturns the amount of energy (volume) at a specific\n\nfrequency, or the average amount of energy between two\nfrequencies. Accepts Number(s) corresponding\nto frequency (in Hz), or a String corresponding to predefined\nfrequency ranges ("bass", "lowMid", "mid", "highMid", "treble").\nReturns a range between 0 (no energy/volume at that frequency) and\n255 (maximum energy).\nNOTE: analyze() must be called prior to getEnergy(). Analyze()\ntells the FFT to analyze frequency data, and getEnergy() uses\nthe results determine the value at a specific frequency or\nrange of frequencies.
\n', + itemtype: 'method', + name: 'getEnergy', + params: [ + { + name: 'frequency1', + description: + 'Will return a value representing\n energy at this frequency. Alternately,\n the strings "bass", "lowMid" "mid",\n "highMid", and "treble" will return\n predefined frequency ranges.
\n', + type: 'Number|String' + }, + { + name: 'frequency2', + description: + 'If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.
\n', + type: 'Number', + optional: true + } + ], + return: { + description: + 'Energy Energy (volume/amplitude) from\n 0 and 255.', + type: 'Number' + }, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3835, + description: + 'Returns the\n\nspectral centroid of the input signal.\nNOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.
\n', + itemtype: 'method', + name: 'getCentroid', + return: { + description: + 'Spectral Centroid Frequency Frequency of the spectral centroid in Hz.', + type: 'Number' + }, + example: [ + '\n\n\n\nfunction setup(){\ncnv = createCanvas(100,100);\nsound = new p5.AudioIn();\nsound.start();\nfft = new p5.FFT();\nsound.connect(fft);\n}\n\n\nfunction draw(){\n\nvar centroidplot = 0.0;\nvar spectralCentroid = 0;\n\n\nbackground(0);\nstroke(0,255,0);\nvar spectrum = fft.analyze();\nfill(0,255,0); // spectrum is green\n\n//draw the spectrum\nfor (var i = 0; i< spectrum.length; i++){\n var x = map(log(i), 0, log(spectrum.length), 0, width);\n var h = map(spectrum[i], 0, 255, 0, height);\n var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));\n rect(x, height, rectangle_width, -h )\n}\n\nvar nyquist = 22050;\n\n// get the centroid\nspectralCentroid = fft.getCentroid();\n\n// the mean_freq_index calculation is for the display.\nvar mean_freq_index = spectralCentroid/(nyquist/spectrum.length);\n\ncentroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);\n\n\nstroke(255,0,0); // the line showing where the centroid is will be red\n\nrect(centroidplot, 0, width / spectrum.length, height)\nnoStroke();\nfill(255,255,255); // text is white\ntext("centroid: ", 10, 20);\ntext(round(spectralCentroid)+" Hz", 10, 40);\n}\n Smooth FFT analysis by averaging with the last analysis frame.
\n', + itemtype: 'method', + name: 'smooth', + params: [ + { + name: 'smoothing', + description: + '0.0 < smoothing < 1.0.\n Defaults to 0.8.
\n', + type: 'Number' + } + ], + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3937, + description: + 'Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\nNOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.
\n', + itemtype: 'method', + name: 'linAverages', + params: [ + { + name: 'N', + description: 'Number of returned frequency groups
\n', + type: 'Number' + } + ], + return: { + description: + 'linearAverages Array of average amplitude values for each group', + type: 'Array' + }, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3967, + description: + 'Returns an array of average amplitude values of the spectrum, for a given\nset of \nOctave Bands\nNOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.
\n', + itemtype: 'method', + name: 'logAverages', + params: [ + { + name: 'octaveBands', + description: 'Array of Octave Bands objects for grouping
\n', + type: 'Array' + } + ], + return: { + description: + 'logAverages Array of average amplitude values for each group', + type: 'Array' + }, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 3997, + description: + 'Calculates and Returns the 1/N\nOctave Bands\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.
\n', + itemtype: 'method', + name: 'getOctaveBands', + params: [ + { + name: 'N', + description: + 'Specifies the 1/N type of generated octave bands
\n', + type: 'Number' + }, + { + name: 'fCtr0', + description: 'Minimum central frequency for the lowest band
\n', + type: 'Number' + } + ], + return: { + description: + 'octaveBands Array of octave band objects with their bounds', + type: 'Array' + }, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4055, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4076, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4135, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4453, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4625, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4783, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4824, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 4881, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5049, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5097, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5128, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5149, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5169, + class: 'p5.FFT', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5268, + description: 'Fade to value, for smooth transitions
\n', + itemtype: 'method', + name: 'fade', + params: [ + { + name: 'value', + description: 'Value to set this signal
\n', + type: 'Number' + }, + { + name: 'secondsFromNow', + description: 'Length of fade, in seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Signal', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5279, + description: + 'Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.
\n', + itemtype: 'method', + name: 'setInput', + params: [ + { + name: 'input', + description: '', + type: 'Object' + } + ], + class: 'p5.Signal', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5293, + description: + 'Add a constant value to this audio signal,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalAdd.
\n', + itemtype: 'method', + name: 'add', + params: [ + { + name: 'number', + description: '', + type: 'Number' + } + ], + return: { + description: 'object', + type: 'p5.Signal' + }, + class: 'p5.Signal', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5312, + description: + 'Multiply this signal by a constant value,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalMult.
\n', + itemtype: 'method', + name: 'mult', + params: [ + { + name: 'number', + description: 'to multiply
\n', + type: 'Number' + } + ], + return: { + description: 'object', + type: 'p5.Signal' + }, + class: 'p5.Signal', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5331, + description: + 'Scale this signal value to a given range,\nand return the result as an audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalScale.
\n', + itemtype: 'method', + name: 'scale', + params: [ + { + name: 'number', + description: 'to multiply
\n', + type: 'Number' + }, + { + name: 'inMin', + description: 'input range minumum
\n', + type: 'Number' + }, + { + name: 'inMax', + description: 'input range maximum
\n', + type: 'Number' + }, + { + name: 'outMin', + description: 'input range minumum
\n', + type: 'Number' + }, + { + name: 'outMax', + description: 'input range maximum
\n', + type: 'Number' + } + ], + return: { + description: 'object', + type: 'p5.Signal' + }, + class: 'p5.Signal', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5465, + description: + 'Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.
\n', + itemtype: 'method', + name: 'start', + params: [ + { + name: 'time', + description: 'startTime in seconds from now.
\n', + type: 'Number', + optional: true + }, + { + name: 'frequency', + description: 'frequency in Hz.
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5505, + description: + 'Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.
\n', + itemtype: 'method', + name: 'stop', + params: [ + { + name: 'secondsFromNow', + description: 'Time, in seconds from now.
\n', + type: 'Number' + } + ], + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5521, + description: + 'Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.
\n', + itemtype: 'method', + name: 'amp', + params: [ + { + name: 'vol', + description: + 'between 0 and 1.0\n or a modulating signal/oscillator
\n', + type: 'Number|Object' + }, + { + name: 'rampTime', + description: 'create a fade that lasts rampTime
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + return: { + description: + "gain If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's\n gain/amplitude/volume)", + type: 'AudioParam' + }, + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5556, + description: + 'Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.
\n', + itemtype: 'method', + name: 'freq', + params: [ + { + name: 'Frequency', + description: + 'Frequency in Hz\n or modulating signal/oscillator
\n', + type: 'Number|Object' + }, + { + name: 'rampTime', + description: 'Ramp time (in seconds)
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'Schedule this event to happen\n at x seconds from now
\n', + type: 'Number', + optional: true + } + ], + return: { + description: + "Frequency If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's frequency", + type: 'AudioParam' + }, + example: [ + '\n\nlet osc = new p5.Oscillator(300);\nosc.start();\nosc.freq(40, 10);\nSet type to 'sine', 'triangle', 'sawtooth' or 'square'.
\n', + itemtype: 'method', + name: 'setType', + params: [ + { + name: 'type', + description: + ''sine', 'triangle', 'sawtooth' or 'square'.
\n', + type: 'String' + } + ], + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5627, + description: 'Connect to a p5.sound / Web Audio object.
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: 'A p5.sound or Web Audio object
\n', + type: 'Object' + } + ], + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5644, + description: 'Disconnect all outputs
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5661, + description: 'Pan between Left (-1) and Right (1)
\n', + itemtype: 'method', + name: 'pan', + params: [ + { + name: 'panning', + description: 'Number between -1 and 1
\n', + type: 'Number' + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number' + } + ], + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5693, + description: + 'Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator's current frequency.
\n', + itemtype: 'method', + name: 'phase', + params: [ + { + name: 'phase', + description: 'float between 0.0 and 1.0
\n', + type: 'Number' + } + ], + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5747, + description: + 'Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.
\n', + itemtype: 'method', + name: 'add', + params: [ + { + name: 'number', + description: 'Constant number to add
\n', + type: 'Number' + } + ], + return: { + description: + 'Oscillator Returns this oscillator\n with scaled output', + type: 'p5.Oscillator' + }, + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5764, + description: + 'Multiply the p5.Oscillator's output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.
\n', + itemtype: 'method', + name: 'mult', + params: [ + { + name: 'number', + description: 'Constant number to multiply
\n', + type: 'Number' + } + ], + return: { + description: + 'Oscillator Returns this oscillator\n with multiplied output', + type: 'p5.Oscillator' + }, + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5780, + description: + 'Scale this oscillator's amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.
\n', + itemtype: 'method', + name: 'scale', + params: [ + { + name: 'inMin', + description: 'input range minumum
\n', + type: 'Number' + }, + { + name: 'inMax', + description: 'input range maximum
\n', + type: 'Number' + }, + { + name: 'outMin', + description: 'input range minumum
\n', + type: 'Number' + }, + { + name: 'outMax', + description: 'input range maximum
\n', + type: 'Number' + } + ], + return: { + description: + 'Oscillator Returns this oscillator\n with scaled output', + type: 'p5.Oscillator' + }, + class: 'p5.Oscillator', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 5879, + class: 'p5.SqrOsc', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6082, + class: 'p5.SqrOsc', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6369, + description: 'Time until envelope reaches attackLevel
\n', + itemtype: 'property', + name: 'attackTime', + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6374, + description: 'Level once attack is complete.
\n', + itemtype: 'property', + name: 'attackLevel', + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6379, + description: 'Time until envelope reaches decayLevel.
\n', + itemtype: 'property', + name: 'decayTime', + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6384, + description: + 'Level after decay. The envelope will sustain here until it is released.
\n', + itemtype: 'property', + name: 'decayLevel', + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6389, + description: 'Duration of the release portion of the envelope.
\n', + itemtype: 'property', + name: 'releaseTime', + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6394, + description: 'Level at the end of the release.
\n', + itemtype: 'property', + name: 'releaseLevel', + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6430, + description: + 'Reset the envelope with a series of time/value pairs.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'attackTime', + description: + 'Time (in seconds) before level\n reaches attackLevel
\n', + type: 'Number' + }, + { + name: 'attackLevel', + description: + 'Typically an amplitude between\n 0.0 and 1.0
\n', + type: 'Number' + }, + { + name: 'decayTime', + description: 'Time
\n', + type: 'Number' + }, + { + name: 'decayLevel', + description: + 'Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)
\n', + type: 'Number' + }, + { + name: 'releaseTime', + description: 'Release Time (in seconds)
\n', + type: 'Number' + }, + { + name: 'releaseLevel', + description: 'Amplitude
\n', + type: 'Number' + } + ], + example: [ + "\n\nlet t1 = 0.1; // attack time in seconds\nlet l1 = 0.7; // attack level 0.0 to 1.0\nlet t2 = 0.3; // decay time in seconds\nlet l2 = 0.1; // decay level 0.0 to 1.0\nlet t3 = 0.2; // sustain time in seconds\nlet l3 = 0.5; // sustain level 0.0 to 1.0\n// release level defaults to zero\n\nlet env;\nlet triOsc;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope(t1, l1, t2, l2, t3, l3);\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env); // give the env control of the triOsc's amp\n triOsc.start();\n}\n\n// mouseClick triggers envelope if over canvas\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(triOsc);\n }\n}\nSet values like a traditional\n\nADSR envelope\n.
\n', + itemtype: 'method', + name: 'setADSR', + params: [ + { + name: 'attackTime', + description: + 'Time (in seconds before envelope\n reaches Attack Level
\n', + type: 'Number' + }, + { + name: 'decayTime', + description: + 'Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n', + type: 'Number', + optional: true + }, + { + name: 'susRatio', + description: + 'Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n', + type: 'Number', + optional: true + } + ], + example: [ + "\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n env.play();\n}\nSet max (attackLevel) and min (releaseLevel) of envelope.
\n', + itemtype: 'method', + name: 'setRange', + params: [ + { + name: 'aLevel', + description: 'attack level (defaults to 1)
\n', + type: 'Number' + }, + { + name: 'rLevel', + description: 'release level (defaults to 0)
\n', + type: 'Number' + } + ], + example: [ + "\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n env.play();\n}\nAssign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Envelope will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.
\n', + itemtype: 'method', + name: 'setInput', + params: [ + { + name: 'inputs', + description: + 'A p5.sound object or\n Web Audio Param.
\n', + type: 'Object', + optional: true, + multiple: true + } + ], + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6648, + description: + 'Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.
\n', + itemtype: 'method', + name: 'setExp', + params: [ + { + name: 'isExp', + description: 'true is exponential, false is linear
\n', + type: 'Boolean' + } + ], + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 6666, + description: + 'Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Envelope will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.
\n', + itemtype: 'method', + name: 'play', + params: [ + { + name: 'unit', + description: + 'A p5.sound object or\n Web Audio Param.
\n', + type: 'Object' + }, + { + name: 'startTime', + description: 'time from now (in seconds) at which to play
\n', + type: 'Number', + optional: true + }, + { + name: 'sustainTime', + description: 'time to sustain before releasing the envelope
\n', + type: 'Number', + optional: true + } + ], + example: [ + "\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\n}\nTrigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a \nWeb Audio Param.
\n', + itemtype: 'method', + name: 'triggerAttack', + params: [ + { + name: 'unit', + description: 'p5.sound Object or Web Audio Param
\n', + type: 'Object' + }, + { + name: 'secondsFromNow', + description: 'time from now (in seconds)
\n', + type: 'Number' + } + ], + example: [ + "\n\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.3;\nlet susPercent = 0.4;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack() {\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\nTrigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n', + itemtype: 'method', + name: 'triggerRelease', + params: [ + { + name: 'unit', + description: 'p5.sound Object or Web Audio Param
\n', + type: 'Object' + }, + { + name: 'secondsFromNow', + description: 'time to trigger the release
\n', + type: 'Number' + } + ], + example: [ + "\n\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.3;\nlet susPercent = 0.4;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack() {\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\nExponentially ramp to a value using the first two\nvalues from setADSR(attackTime, decayTime)\nas \ntime constants for simple exponential ramps.\nIf the value is higher than current value, it uses attackTime,\nwhile a decrease uses decayTime.
p5.sound Object or Web Audio Param
\n', + type: 'Object' + }, + { + name: 'secondsFromNow', + description: 'When to trigger the ramp
\n', + type: 'Number' + }, + { + name: 'v', + description: 'Target value
\n', + type: 'Number' + }, + { + name: 'v2', + description: 'Second target value (optional)
\n', + type: 'Number', + optional: true + } + ], + example: [ + "\n\nlet env, osc, amp, cnv;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet attackLevel = 1;\nlet decayLevel = 0;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n fill(0,255,0);\n noStroke();\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime);\n\n osc = new p5.Oscillator();\n osc.amp(env);\n osc.start();\n\n amp = new p5.Amplitude();\n\n cnv.mousePressed(triggerRamp);\n}\n\nfunction triggerRamp() {\n env.ramp(osc, 0, attackLevel, decayLevel);\n}\n\nfunction draw() {\n background(20,20,20);\n text('click me', 10, 20);\n let h = map(amp.getLevel(), 0, 0.4, 0, height);;\n\n rect(0, height, width, -h);\n}\nAdd a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.
\n', + itemtype: 'method', + name: 'add', + params: [ + { + name: 'number', + description: 'Constant number to add
\n', + type: 'Number' + } + ], + return: { + description: + 'Envelope Returns this envelope\n with scaled output', + type: 'p5.Envelope' + }, + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7054, + description: + 'Multiply the p5.Envelope's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.
\n', + itemtype: 'method', + name: 'mult', + params: [ + { + name: 'number', + description: 'Constant number to multiply
\n', + type: 'Number' + } + ], + return: { + description: + 'Envelope Returns this envelope\n with scaled output', + type: 'p5.Envelope' + }, + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7070, + description: + 'Scale this envelope's amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.
\n', + itemtype: 'method', + name: 'scale', + params: [ + { + name: 'inMin', + description: 'input range minumum
\n', + type: 'Number' + }, + { + name: 'inMax', + description: 'input range maximum
\n', + type: 'Number' + }, + { + name: 'outMin', + description: 'input range minumum
\n', + type: 'Number' + }, + { + name: 'outMax', + description: 'input range maximum
\n', + type: 'Number' + } + ], + return: { + description: + 'Envelope Returns this envelope\n with scaled output', + type: 'p5.Envelope' + }, + class: 'p5.Envelope', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7178, + description: + 'Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).
\n', + itemtype: 'method', + name: 'width', + params: [ + { + name: 'width', + description: + 'Width between the pulses (0 to 1.0,\n defaults to 0)
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Pulse', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7365, + description: + 'Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.
\n', + itemtype: 'method', + name: 'setType', + params: [ + { + name: 'type', + description: + ''white', 'pink' or 'brown'
\n', + type: 'String', + optional: true + } + ], + class: 'p5.Noise', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7478, + itemtype: 'property', + name: 'input', + type: 'GainNode', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7482, + itemtype: 'property', + name: 'output', + type: 'GainNode', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7486, + itemtype: 'property', + name: 'stream', + type: 'MediaStream|null', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7490, + itemtype: 'property', + name: 'mediaStream', + type: 'MediaStreamAudioSourceNode|null', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7494, + itemtype: 'property', + name: 'currentSource', + type: 'Number|null', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7498, + description: + 'Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables access.
\n', + itemtype: 'property', + name: 'enabled', + type: 'Boolean', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7505, + description: + 'Input amplitude, connect to it by default but not to master out
\n', + itemtype: 'property', + name: 'amplitude', + type: 'p5.Amplitude', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7518, + description: + 'Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound's output. So you won't hear\nanything unless you use the connect() method.
Certain browsers limit access to the user's microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won't provide mic access.
\n', + itemtype: 'method', + name: 'start', + params: [ + { + name: 'successCallback', + description: + 'Name of a function to call on\n success.
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.
\n', + type: 'Function', + optional: true + } + ], + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7571, + description: + 'Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.
\n', + itemtype: 'method', + name: 'stop', + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7587, + description: + 'Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).
An object that accepts audio input,\n such as an FFT
\n', + type: 'Object', + optional: true + } + ], + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7608, + description: + 'Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.
Read the Amplitude (volume level) of an AudioIn. The AudioIn\nclass contains its own instance of the Amplitude class to help\nmake it easy to get a microphone's volume level. Accepts an\noptional smoothing value (0.0 < 1.0). NOTE: AudioIn must\n.start() before using .getLevel().
Smoothing is 0.0 by default.\n Smooths values based on previous values.
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'Volume level (between 0.0 and 1.0)', + type: 'Number' + }, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7640, + description: + 'Set amplitude (volume) of a mic input between 0 and 1.0.
between 0 and 1.0
\n', + type: 'Number' + }, + { + name: 'time', + description: 'ramp time (optional)
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7659, + description: + 'Returns a list of available input sources. This is a wrapper\nfor <a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n "https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n\n\n', + itemtype: 'method', + name: 'getSources', + params: [ + { + name: 'successCallback', + description: + 'and it returns a Promise.
\n
This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'This optional callback receives the error\n message as its argument.
\n', + type: 'Function', + optional: true + } + ], + return: { + description: + 'Returns a Promise that can be used in place of the callbacks, similar\n to the enumerateDevices() method', + type: 'Promise' + }, + example: [ + '\n\n let audiograb;\n\n function setup(){\n //new audioIn\n audioGrab = new p5.AudioIn();\n\n audioGrab.getSources(function(deviceList) {\n //print out the array of available sources\n console.log(deviceList);\n //set the source to the first item in the deviceList array\n audioGrab.setSource(0);\n });\n }\n Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n<a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n\n\n', + itemtype: 'method', + name: 'setSource', + params: [ + { + name: 'num', + description: 'navigator.mediaDevices.enumerateDevices().
\n
position of input source in the array
\n', + type: 'Number' + } + ], + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7750, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7766, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7790, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7816, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7838, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7860, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7906, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7937, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 7955, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8292, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8314, + class: 'p5.AudioIn', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8390, + description: + 'In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter
\n', + class: 'p5.Effect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8403, + description: 'Set the output volume of the filter.
\n', + itemtype: 'method', + name: 'amp', + params: [ + { + name: 'vol', + description: 'amplitude between 0 and 1.0
\n', + type: 'Number', + optional: true + }, + { + name: 'rampTime', + description: 'create a fade that lasts until rampTime
\n', + type: 'Number', + optional: true + }, + { + name: 'tFromNow', + description: + 'schedule this event to happen in tFromNow seconds
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Effect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8420, + description: + 'Link effects together in a chain
Example usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments
Chain together multiple sound objects
\n', + type: 'Object', + optional: true + } + ], + class: 'p5.Effect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8437, + description: 'Adjust the dry/wet value.
\n', + itemtype: 'method', + name: 'drywet', + params: [ + { + name: 'fade', + description: 'The desired drywet value (0 - 1.0)
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Effect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8449, + description: + 'Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: '', + type: 'Object' + } + ], + class: 'p5.Effect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8460, + description: 'Disconnect all output.
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.Effect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8578, + description: + 'The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.
\n', + itemtype: 'property', + name: 'biquadFilter', + type: 'DelayNode', + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8596, + description: + 'Filter an audio signal according to a set\nof filter parameters.
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'Signal', + description: 'An object that outputs audio
\n', + type: 'Object' + }, + { + name: 'freq', + description: 'Frequency in Hz, from 10 to 22050
\n', + type: 'Number', + optional: true + }, + { + name: 'res', + description: + 'Resonance/Width of the filter frequency\n from 0.001 to 1000
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8610, + description: 'Set the frequency and the resonance of the filter.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'freq', + description: 'Frequency in Hz, from 10 to 22050
\n', + type: 'Number', + optional: true + }, + { + name: 'res', + description: 'Resonance (Q) from 0.001 to 1000
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8627, + description: + 'Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).
\n', + itemtype: 'method', + name: 'freq', + params: [ + { + name: 'freq', + description: 'Filter Frequency
\n', + type: 'Number' + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'value Returns the current frequency value', + type: 'Number' + }, + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8651, + description: + 'Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.
\n', + itemtype: 'method', + name: 'res', + params: [ + { + name: 'res', + description: + 'Resonance/Width of filter freq\n from 0.001 to 1000
\n', + type: 'Number' + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'value Returns the current res value', + type: 'Number' + }, + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8673, + description: + 'Controls the gain attribute of a Biquad Filter.\nThis is distinctly different from .amp() which is inherited from p5.Effect\n.amp() controls the volume via the output gain node\np5.Filter.gain() controls the gain parameter of a Biquad Filter node.
\n', + itemtype: 'method', + name: 'gain', + params: [ + { + name: 'gain', + description: '', + type: 'Number' + } + ], + return: { + description: 'Returns the current or updated gain value', + type: 'Number' + }, + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8694, + description: + 'Toggle function. Switches between the specified type and allpass
\n', + itemtype: 'method', + name: 'toggle', + return: { + description: '[Toggle value]', + type: 'Boolean' + }, + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8709, + description: + 'Set the type of a p5.Filter. Possible types include:\n"lowpass" (default), "highpass", "bandpass",\n"lowshelf", "highshelf", "peaking", "notch",\n"allpass".
\n', + itemtype: 'method', + name: 'setType', + params: [ + { + name: 't', + description: '', + type: 'String' + } + ], + class: 'p5.Filter', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 8916, + description: + 'The p5.EQ is built with abstracted p5.Filter objects.\nTo modify any bands, use methods of the \np5.Filter API, especially gain and freq.\nBands are stored in an array, with indices 0 - 3, or 0 - 7
Process an input by connecting it to the EQ
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'src', + description: 'Audio source
\n', + type: 'Object' + } + ], + class: 'p5.EQ', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9039, + description: + '\nWeb Audio Spatial Panner Node
\nProperties include
\n\n\npanningModel: "equal power" or "HRTF"
\n
\n\ndistanceModel: "linear", "inverse", or "exponential"
\n
Connect an audio sorce
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'src', + description: 'Input source
\n', + type: 'Object' + } + ], + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9071, + description: 'Set the X,Y,Z position of the Panner
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'xVal', + description: '', + type: 'Number' + }, + { + name: 'yVal', + description: '', + type: 'Number' + }, + { + name: 'zVal', + description: '', + type: 'Number' + }, + { + name: 'time', + description: '', + type: 'Number' + } + ], + return: { + description: 'Updated x, y, z values as an array', + type: 'Array' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9090, + description: 'Getter and setter methods for position coordinates
\n', + itemtype: 'method', + name: 'positionX', + return: { + description: 'updated coordinate value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9095, + description: 'Getter and setter methods for position coordinates
\n', + itemtype: 'method', + name: 'positionY', + return: { + description: 'updated coordinate value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9100, + description: 'Getter and setter methods for position coordinates
\n', + itemtype: 'method', + name: 'positionZ', + return: { + description: 'updated coordinate value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9138, + description: 'Set the X,Y,Z position of the Panner
\n', + itemtype: 'method', + name: 'orient', + params: [ + { + name: 'xVal', + description: '', + type: 'Number' + }, + { + name: 'yVal', + description: '', + type: 'Number' + }, + { + name: 'zVal', + description: '', + type: 'Number' + }, + { + name: 'time', + description: '', + type: 'Number' + } + ], + return: { + description: 'Updated x, y, z values as an array', + type: 'Array' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9157, + description: 'Getter and setter methods for orient coordinates
\n', + itemtype: 'method', + name: 'orientX', + return: { + description: 'updated coordinate value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9162, + description: 'Getter and setter methods for orient coordinates
\n', + itemtype: 'method', + name: 'orientY', + return: { + description: 'updated coordinate value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9167, + description: 'Getter and setter methods for orient coordinates
\n', + itemtype: 'method', + name: 'orientZ', + return: { + description: 'updated coordinate value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9205, + description: 'Set the rolloff factor and max distance
\n', + itemtype: 'method', + name: 'setFalloff', + params: [ + { + name: 'maxDistance', + description: '', + type: 'Number', + optional: true + }, + { + name: 'rolloffFactor', + description: '', + type: 'Number', + optional: true + } + ], + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9215, + description: 'Maxium distance between the source and the listener
\n', + itemtype: 'method', + name: 'maxDist', + params: [ + { + name: 'maxDistance', + description: '', + type: 'Number' + } + ], + return: { + description: 'updated value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9227, + description: + 'How quickly the volume is reduced as the source moves away from the listener
\n', + itemtype: 'method', + name: 'rollof', + params: [ + { + name: 'rolloffFactor', + description: '', + type: 'Number' + } + ], + return: { + description: 'updated value', + type: 'Number' + }, + class: 'p5.Panner3D', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9532, + description: + 'The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n', + itemtype: 'property', + name: 'leftDelay', + type: 'DelayNode', + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9540, + description: + 'The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n', + itemtype: 'property', + name: 'rightDelay', + type: 'DelayNode', + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9572, + description: + 'Add delay to an audio signal according to a set\nof delay parameters.
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'Signal', + description: 'An object that outputs audio
\n', + type: 'Object' + }, + { + name: 'delayTime', + description: + 'Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.
\n', + type: 'Number', + optional: true + }, + { + name: 'feedback', + description: + 'sends the delay back through itself\n in a loop that decreases in volume\n each time.
\n', + type: 'Number', + optional: true + }, + { + name: 'lowPass', + description: + 'Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9607, + description: + 'Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.
\n', + itemtype: 'method', + name: 'delayTime', + params: [ + { + name: 'delayTime', + description: 'Time (in seconds) of the delay
\n', + type: 'Number' + } + ], + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9626, + description: + 'Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5
\n', + itemtype: 'method', + name: 'feedback', + params: [ + { + name: 'feedback', + description: + '0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param
\n', + type: 'Number|Object' + } + ], + return: { + description: 'Feedback value', + type: 'Number' + }, + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9654, + description: + 'Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.
\n', + itemtype: 'method', + name: 'filter', + params: [ + { + name: 'cutoffFreq', + description: + 'A lowpass filter will cut off any\n frequencies higher than the filter frequency.
\n', + type: 'Number|Object' + }, + { + name: 'res', + description: + 'Resonance of the filter frequency\n cutoff, or an object (i.e. a p5.Oscillator)\n that can be used to modulate this parameter.\n High numbers (i.e. 15) will produce a resonance,\n low numbers (i.e. .2) will produce a slope.
\n', + type: 'Number|Object' + } + ], + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9671, + description: + 'Choose a preset type of delay. 'pingPong' bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.
\n', + itemtype: 'method', + name: 'setType', + params: [ + { + name: 'type', + description: ''pingPong' (1) or 'default' (0)
\n', + type: 'String|Number' + } + ], + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9704, + description: 'Set the output level of the delay effect.
\n', + itemtype: 'method', + name: 'amp', + params: [ + { + name: 'volume', + description: 'amplitude between 0 and 1.0
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'create a fade that lasts rampTime
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9713, + description: 'Send output to a p5.sound or web audio object
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: '', + type: 'Object' + } + ], + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9719, + description: 'Disconnect all output.
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.Delay', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9812, + description: + 'Connect a source to the reverb, and assign reverb parameters.
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'src', + description: + 'p5.sound / Web Audio object with a sound\n output.
\n', + type: 'Object' + }, + { + name: 'seconds', + description: + 'Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
\n', + type: 'Number', + optional: true + }, + { + name: 'decayRate', + description: + 'Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
\n', + type: 'Number', + optional: true + }, + { + name: 'reverse', + description: 'Play the reverb backwards or forwards.
\n', + type: 'Boolean', + optional: true + } + ], + class: 'p5.Reverb', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9841, + description: + 'Set the reverb settings. Similar to .process(), but without\nassigning a new input.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'seconds', + description: + 'Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
\n', + type: 'Number', + optional: true + }, + { + name: 'decayRate', + description: + 'Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
\n', + type: 'Number', + optional: true + }, + { + name: 'reverse', + description: 'Play the reverb backwards or forwards.
\n', + type: 'Boolean', + optional: true + } + ], + class: 'p5.Reverb', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9869, + description: 'Set the output level of the reverb effect.
\n', + itemtype: 'method', + name: 'amp', + params: [ + { + name: 'volume', + description: 'amplitude between 0 and 1.0
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'create a fade that lasts rampTime
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Reverb', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9878, + description: 'Send output to a p5.sound or web audio object
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: '', + type: 'Object' + } + ], + class: 'p5.Reverb', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9884, + description: 'Disconnect all output.
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.Reverb', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9975, + description: + 'Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.
\n', + itemtype: 'property', + name: 'convolverNode', + type: 'ConvolverNode', + class: 'p5.Convolver', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 9998, + description: + 'Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.
\n', + itemtype: 'method', + name: 'createConvolver', + params: [ + { + name: 'path', + description: 'path to a sound file
\n', + type: 'String' + }, + { + name: 'callback', + description: + 'function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.
\n', + type: 'Function', + optional: true + }, + { + name: 'errorCallback', + description: + 'function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.
\n', + type: 'Function', + optional: true + } + ], + return: { + description: '', + type: 'p5.Convolver' + }, + example: [ + "\n\nlet cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\nConnect a source to the reverb, and assign reverb parameters.
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'src', + description: + 'p5.sound / Web Audio object with a sound\n output.
\n', + type: 'Object' + } + ], + example: [ + "\n\nlet cVerb, sound;\nfunction preload() {\n soundFormats('ogg', 'mp3');\n\n cVerb = createConvolver('assets/concrete-tunnel.mp3');\n\n sound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with (i.e. connect to) cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\nIf you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the toggleImpulse(id) method.
Load and assign a new Impulse Response to the p5.Convolver.\nThe impulse is added to the .impulses array. Previous\nimpulses can be accessed with the .toggleImpulse(id)\nmethod.
path to a sound file
\n', + type: 'String' + }, + { + name: 'callback', + description: 'function (optional)
\n', + type: 'Function' + }, + { + name: 'errorCallback', + description: 'function (optional)
\n', + type: 'Function' + } + ], + class: 'p5.Convolver', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10180, + description: + 'Similar to .addImpulse, except that the .impulses\nArray is reset to save memory. A new .impulses\narray is created with this impulse as the only item.
path to a sound file
\n', + type: 'String' + }, + { + name: 'callback', + description: 'function (optional)
\n', + type: 'Function' + }, + { + name: 'errorCallback', + description: 'function (optional)
\n', + type: 'Function' + } + ], + class: 'p5.Convolver', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10198, + description: + 'If you have used .addImpulse() to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the .impulses Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the .impulses\n Array (Number).
\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an .audioBuffer (type:\nWeb Audio \nAudioBuffer) and a .name, a String that corresponds\nwith the original filename.
Identify the impulse by its original filename\n (String), or by its position in the\n .impulses Array (Number).
Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.
\n', + itemtype: 'method', + name: 'setBPM', + params: [ + { + name: 'BPM', + description: 'Beats Per Minute
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'Seconds from now
\n', + type: 'Number' + } + ], + class: 'p5.Convolver', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10550, + description: + 'Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction's requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.
\n', + itemtype: 'property', + name: 'sequence', + type: 'Array', + class: 'p5.Phrase', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10638, + description: 'Set the tempo of this part, in Beats Per Minute.
\n', + itemtype: 'method', + name: 'setBPM', + params: [ + { + name: 'BPM', + description: 'Beats Per Minute
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'Seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10648, + description: + 'Returns the tempo, in Beats Per Minute, of this part.
\n', + itemtype: 'method', + name: 'getBPM', + return: { + description: '', + type: 'Number' + }, + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10657, + description: + 'Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.
\n', + itemtype: 'method', + name: 'start', + params: [ + { + name: 'time', + description: 'seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10673, + description: + 'Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.
\n', + itemtype: 'method', + name: 'loop', + params: [ + { + name: 'time', + description: 'seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10690, + description: 'Tell the part to stop looping.
\n', + itemtype: 'method', + name: 'noLoop', + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10702, + description: + 'Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again.
\n', + itemtype: 'method', + name: 'stop', + params: [ + { + name: 'time', + description: 'seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10712, + description: + 'Pause the part. Playback will resume\nfrom the current step.
\n', + itemtype: 'method', + name: 'pause', + params: [ + { + name: 'time', + description: 'seconds from now
\n', + type: 'Number' + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10724, + description: 'Add a p5.Phrase to this Part.
\n', + itemtype: 'method', + name: 'addPhrase', + params: [ + { + name: 'phrase', + description: 'reference to a p5.Phrase
\n', + type: 'p5.Phrase' + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10745, + description: + 'Remove a phrase from this part, based on the name it was\ngiven when it was created.
\n', + itemtype: 'method', + name: 'removePhrase', + params: [ + { + name: 'phraseName', + description: '', + type: 'String' + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10759, + description: + 'Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
\n', + itemtype: 'method', + name: 'getPhrase', + params: [ + { + name: 'phraseName', + description: '', + type: 'String' + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10773, + description: + 'Find all sequences with the specified name, and replace their patterns with the specified array.
\n', + itemtype: 'method', + name: 'replaceSequence', + params: [ + { + name: 'phraseName', + description: '', + type: 'String' + }, + { + name: 'sequence', + description: + 'Array of values to pass into the callback\n at each step of the phrase.
\n', + type: 'Array' + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10800, + description: + 'Set the function that will be called at every step. This will clear the previous function.
\n', + itemtype: 'method', + name: 'onStep', + params: [ + { + name: 'callback', + description: + 'The name of the callback\n you want to fire\n on every beat/tatum.
\n', + type: 'Function' + } + ], + class: 'p5.Part', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10853, + description: 'Start playback of the score.
\n', + itemtype: 'method', + name: 'start', + class: 'p5.Score', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10862, + description: 'Stop playback of the score.
\n', + itemtype: 'method', + name: 'stop', + class: 'p5.Score', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10872, + description: 'Pause playback of the score.
\n', + itemtype: 'method', + name: 'pause', + class: 'p5.Score', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10880, + description: 'Loop playback of the score.
\n', + itemtype: 'method', + name: 'loop', + class: 'p5.Score', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10889, + description: + 'Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.
\n', + itemtype: 'method', + name: 'noLoop', + class: 'p5.Score', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10914, + description: 'Set the tempo for all parts in the score
\n', + itemtype: 'method', + name: 'setBPM', + params: [ + { + name: 'BPM', + description: 'Beats Per Minute
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'Seconds from now
\n', + type: 'Number' + } + ], + class: 'p5.Score', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10982, + description: + 'musicalTimeMode uses Tone.Time convention\ntrue if string, false if number
\n', + itemtype: 'property', + name: 'musicalTimeMode', + type: 'Boolean', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10989, + description: + 'musicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string
\n', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 10996, + description: + 'Set a limit to the number of loops to play. defaults to Infinity
\n', + itemtype: 'property', + name: 'maxIterations', + type: 'Number', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11005, + description: + 'Do not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded
\nThe callback should only be called until maxIterations is reached
\n', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11019, + description: 'Start the loop
\n', + itemtype: 'method', + name: 'start', + params: [ + { + name: 'timeFromNow', + description: 'schedule a starting time
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11032, + description: 'Stop the loop
\n', + itemtype: 'method', + name: 'stop', + params: [ + { + name: 'timeFromNow', + description: 'schedule a stopping time
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11045, + description: 'Pause the loop
\n', + itemtype: 'method', + name: 'pause', + params: [ + { + name: 'timeFromNow', + description: 'schedule a pausing time
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11058, + description: + 'Synchronize loops. Use this method to start two more more loops in synchronization\nor to start a loop in synchronization with a loop that is already playing\nThis method will schedule the implicit loop in sync with the explicit master loop\ni.e. loopToStart.syncedStart(loopToSyncWith)
\n', + itemtype: 'method', + name: 'syncedStart', + params: [ + { + name: 'otherLoop', + description: 'a p5.SoundLoop to sync with
\n', + type: 'Object' + }, + { + name: 'timeFromNow', + description: + 'Start the loops in sync after timeFromNow seconds
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11139, + description: + 'Getters and Setters, setting any paramter will result in a change in the clock's\nfrequency, that will be reflected after the next callback\nbeats per minute (defaults to 60)
\n', + itemtype: 'property', + name: 'bpm', + type: 'Number', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11157, + description: + 'number of quarter notes in a measure (defaults to 4)
\n', + itemtype: 'property', + name: 'timeSignature', + type: 'Number', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11173, + description: 'length of the loops interval
\n', + itemtype: 'property', + name: 'interval', + type: 'Number|String', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11187, + description: 'how many times the callback has been called so far
\n', + itemtype: 'property', + name: 'iterations', + type: 'Number', + readonly: '', + class: 'p5.SoundLoop', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11228, + description: + 'The p5.Compressor is built with a Web Audio Dynamics Compressor Node\n
\n', + itemtype: 'property', + name: 'compressor', + type: 'AudioNode', + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11239, + description: + 'Performs the same function as .connect, but also accepts\noptional parameters to set compressor's audioParams
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'src', + description: 'Sound source to be connected
\n', + type: 'Object' + }, + { + name: 'attack', + description: + 'The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n', + type: 'Number', + optional: true + }, + { + name: 'knee', + description: + 'A decibel value representing the range above the \n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40
\n', + type: 'Number', + optional: true + }, + { + name: 'ratio', + description: + 'The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n', + type: 'Number', + optional: true + }, + { + name: 'threshold', + description: + 'The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n', + type: 'Number', + optional: true + }, + { + name: 'release', + description: + 'The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11262, + description: 'Set the paramters of a compressor.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'attack', + description: + 'The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n', + type: 'Number' + }, + { + name: 'knee', + description: + 'A decibel value representing the range above the \n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40
\n', + type: 'Number' + }, + { + name: 'ratio', + description: + 'The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n', + type: 'Number' + }, + { + name: 'threshold', + description: + 'The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n', + type: 'Number' + }, + { + name: 'release', + description: + 'The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n', + type: 'Number' + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11294, + description: 'Get current attack or set value w/ time ramp
\n', + itemtype: 'method', + name: 'attack', + params: [ + { + name: 'attack', + description: + 'Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n', + type: 'Number', + optional: true + }, + { + name: 'time', + description: + 'Assign time value to schedule the change in value
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11314, + description: 'Get current knee or set value w/ time ramp
\n', + itemtype: 'method', + name: 'knee', + params: [ + { + name: 'knee', + description: + 'A decibel value representing the range above the \n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40
\n', + type: 'Number', + optional: true + }, + { + name: 'time', + description: + 'Assign time value to schedule the change in value
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11334, + description: 'Get current ratio or set value w/ time ramp
\n', + itemtype: 'method', + name: 'ratio', + params: [ + { + name: 'ratio', + description: + 'The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n', + type: 'Number', + optional: true + }, + { + name: 'time', + description: + 'Assign time value to schedule the change in value
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11353, + description: 'Get current threshold or set value w/ time ramp
\n', + itemtype: 'method', + name: 'threshold', + params: [ + { + name: 'threshold', + description: + 'The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n', + type: 'Number' + }, + { + name: 'time', + description: + 'Assign time value to schedule the change in value
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11372, + description: 'Get current release or set value w/ time ramp
\n', + itemtype: 'method', + name: 'release', + params: [ + { + name: 'release', + description: + 'The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n', + type: 'Number' + }, + { + name: 'time', + description: + 'Assign time value to schedule the change in value
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11392, + description: 'Return the current reduction value
\n', + itemtype: 'method', + name: 'reduction', + return: { + description: + 'Value of the amount of gain reduction that is applied to the signal', + type: 'Number' + }, + class: 'p5.Compressor', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11508, + description: + 'Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.
\n', + itemtype: 'method', + name: 'setInput', + params: [ + { + name: 'unit', + description: + 'p5.sound object or a web audio unit\n that outputs sound
\n', + type: 'Object', + optional: true + } + ], + class: 'p5.SoundRecorder', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11529, + description: + 'Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.
\n', + itemtype: 'method', + name: 'record', + params: [ + { + name: 'soundFile', + description: 'p5.SoundFile
\n', + type: 'p5.SoundFile' + }, + { + name: 'duration', + description: 'Time (in seconds)
\n', + type: 'Number', + optional: true + }, + { + name: 'callback', + description: + 'The name of a function that will be\n called once the recording completes
\n', + type: 'Function', + optional: true + } + ], + class: 'p5.SoundRecorder', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11562, + description: + 'Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.
\n', + itemtype: 'method', + name: 'stop', + class: 'p5.SoundRecorder', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11635, + description: + 'Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device.\nFor uploading audio to a server, use\np5.SoundFile.saveBlob.
p5.SoundFile that you wish to save
\n', + type: 'p5.SoundFile' + }, + { + name: 'fileName', + description: 'name of the resulting .wav file.
\n', + type: 'String' + } + ], + class: 'p5', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11761, + description: 'isDetected is set to true when a peak is detected.
\n', + itemtype: 'attribute', + name: 'isDetected', + type: 'Boolean', + default: 'false', + class: 'p5.PeakDetect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11774, + description: + 'The update method is run in the draw loop.
\nAccepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.
\n', + itemtype: 'method', + name: 'update', + params: [ + { + name: 'fftObject', + description: 'A p5.FFT object
\n', + type: 'p5.FFT' + } + ], + class: 'p5.PeakDetect', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11805, + description: + 'onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.
\n', + itemtype: 'method', + name: 'onPeak', + params: [ + { + name: 'callback', + description: + 'Name of a function that will\n be called when a peak is\n detected.
\n', + type: 'Function' + }, + { + name: 'val', + description: + 'Optional value to pass\n into the function when\n a peak is detected.
\n', + type: 'Object', + optional: true + } + ], + example: [ + "\n\nlet cnv, soundFile, fft, peakDetect;\nlet ellipseWidth = 0;\n\nfunction preload() {\n soundFile = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n cnv = createCanvas(100,100);\n textAlign(CENTER);\n\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n setupSound();\n\n // when a beat is detected, call triggerBeat()\n peakDetect.onPeak(triggerBeat);\n}\n\nfunction draw() {\n background(0);\n fill(255);\n text('click to play', width/2, height/2);\n\n fft.analyze();\n peakDetect.update(fft);\n\n ellipseWidth *= 0.95;\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// this function is called by peakDetect.onPeak\nfunction triggerBeat() {\n ellipseWidth = 50;\n}\n\n// mouseclick starts/stops sound\nfunction setupSound() {\n cnv.mouseClicked( function() {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n });\n}\nConnect a source to the gain node.
\n', + itemtype: 'method', + name: 'setInput', + params: [ + { + name: 'src', + description: + 'p5.sound / Web Audio object with a sound\n output.
\n', + type: 'Object' + } + ], + class: 'p5.Gain', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11964, + description: 'Send output to a p5.sound or web audio object
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: '', + type: 'Object' + } + ], + class: 'p5.Gain', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11974, + description: 'Disconnect all output.
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.Gain', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 11984, + description: 'Set the output level of the gain node.
\n', + itemtype: 'method', + name: 'amp', + params: [ + { + name: 'volume', + description: 'amplitude between 0 and 1.0
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'create a fade that lasts rampTime
\n', + type: 'Number', + optional: true + }, + { + name: 'timeFromNow', + description: + 'schedule this event to happen\n seconds from now
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.Gain', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12042, + description: 'Connect to p5 objects or Web Audio Nodes
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: '', + type: 'Object' + } + ], + class: 'p5.AudioVoice', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12051, + description: 'Disconnect from soundOut
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.AudioVoice', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12131, + description: + 'Play tells the MonoSynth to start playing a note. This method schedules\nthe calling of .triggerAttack and .triggerRelease.
\n', + itemtype: 'method', + name: 'play', + params: [ + { + name: 'note', + description: + 'the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz.
\n', + type: 'String | Number' + }, + { + name: 'velocity', + description: + 'velocity of the note to play (ranging from 0 to 1)
\n', + type: 'Number', + optional: true + }, + { + name: 'secondsFromNow', + description: 'time from now (in seconds) at which to play
\n', + type: 'Number', + optional: true + }, + { + name: 'sustainTime', + description: 'time to sustain before releasing the envelope
\n', + type: 'Number', + optional: true + } + ], + example: [ + '\n\nlet monoSynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n monoSynth = new p5.MonoSynth();\n\n textAlign(CENTER);\n text(\'click to play\', width/2, height/2);\n}\n\nfunction playSynth() {\n // time from now (in seconds)\n let time = 0;\n // note duration (in seconds)\n let dur = 1/6;\n // note velocity (volume, from 0 to 1)\n let v = random();\n\n monoSynth.play("Fb3", v, 0, dur);\n monoSynth.play("Gb3", v, time += dur, dur);\n\n background(random(255), random(255), 255);\n text(\'click to play\', width/2, height/2);\n}\nTrigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n', + params: [ + { + name: 'note', + description: + 'the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz
\n', + type: 'String | Number' + }, + { + name: 'velocity', + description: + 'velocity of the note to play (ranging from 0 to 1)
\n', + type: 'Number', + optional: true + }, + { + name: 'secondsFromNow', + description: 'time from now (in seconds) at which to play
\n', + type: 'Number', + optional: true + } + ], + itemtype: 'method', + name: 'triggerAttack', + example: [ + '\n\nlet monoSynth = new p5.MonoSynth();\n\nfunction mousePressed() {\n monoSynth.triggerAttack("E3");\n}\n\nfunction mouseReleased() {\n monoSynth.triggerRelease();\n}\nTrigger the release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n', + params: [ + { + name: 'secondsFromNow', + description: 'time to trigger the release
\n', + type: 'Number' + } + ], + itemtype: 'method', + name: 'triggerRelease', + example: [ + '\n\nlet monoSynth = new p5.MonoSynth();\n\nfunction mousePressed() {\n monoSynth.triggerAttack("E3");\n}\n\nfunction mouseReleased() {\n monoSynth.triggerRelease();\n}\nSet values like a traditional\n\nADSR envelope\n.
\n', + itemtype: 'method', + name: 'setADSR', + params: [ + { + name: 'attackTime', + description: + 'Time (in seconds before envelope\n reaches Attack Level
\n', + type: 'Number' + }, + { + name: 'decayTime', + description: + 'Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n', + type: 'Number', + optional: true + }, + { + name: 'susRatio', + description: + 'Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12260, + description: 'Getters and Setters
\n', + itemtype: 'property', + name: 'attack', + type: 'Number', + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12264, + itemtype: 'property', + name: 'decay', + type: 'Number', + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12267, + itemtype: 'property', + name: 'sustain', + type: 'Number', + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12270, + itemtype: 'property', + name: 'release', + type: 'Number', + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12307, + description: 'MonoSynth amp
\n', + itemtype: 'method', + name: 'amp', + params: [ + { + name: 'vol', + description: 'desired volume
\n', + type: 'Number' + }, + { + name: 'rampTime', + description: 'Time to reach new volume
\n', + type: 'Number', + optional: true + } + ], + return: { + description: 'new volume value', + type: 'Number' + }, + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12321, + description: 'Connect to a p5.sound / Web Audio object.
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: 'A p5.sound or Web Audio object
\n', + type: 'Object' + } + ], + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12331, + description: 'Disconnect all outputs
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12341, + description: + 'Get rid of the MonoSynth and free up its resources / memory.
\n', + itemtype: 'method', + name: 'dispose', + class: 'p5.MonoSynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12411, + description: + 'An object that holds information about which notes have been played and\nwhich notes are currently being played. New notes are added as keys\non the fly. While a note has been attacked, but not released, the value of the\nkey is the audiovoice which is generating that note. When notes are released,\nthe value of the key becomes undefined.
\n', + itemtype: 'property', + name: 'notes', + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12423, + description: + 'A PolySynth must have at least 1 voice, defaults to 8
\n', + itemtype: 'property', + name: 'polyvalue', + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12428, + description: + 'Monosynth that generates the sound for each note that is triggered. The\np5.PolySynth defaults to using the p5.MonoSynth as its voice.
\n', + itemtype: 'property', + name: 'AudioVoice', + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12459, + description: + 'Play a note by triggering noteAttack and noteRelease with sustain time
\n', + itemtype: 'method', + name: 'play', + params: [ + { + name: 'note', + description: + 'midi note to play (ranging from 0 to 127 - 60 being a middle C)
\n', + type: 'Number', + optional: true + }, + { + name: 'velocity', + description: + 'velocity of the note to play (ranging from 0 to 1)
\n', + type: 'Number', + optional: true + }, + { + name: 'secondsFromNow', + description: 'time from now (in seconds) at which to play
\n', + type: 'Number', + optional: true + }, + { + name: 'sustainTime', + description: 'time to sustain before releasing the envelope
\n', + type: 'Number', + optional: true + } + ], + example: [ + '\n\nlet polySynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n polySynth = new p5.PolySynth();\n\n textAlign(CENTER);\n text(\'click to play\', width/2, height/2);\n}\n\nfunction playSynth() {\n // note duration (in seconds)\n let dur = 0.1;\n\n // time from now (in seconds)\n let time = 0;\n\n // velocity (volume, from 0 to 1)\n let vel = 0.1;\n\n polySynth.play("G2", vel, 0, dur);\n polySynth.play("C3", vel, 0, dur);\n polySynth.play("G3", vel, 0, dur);\n\n background(random(255), random(255), 255);\n text(\'click to play\', width/2, height/2);\n}\nnoteADSR sets the envelope for a specific note that has just been triggered.\nUsing this method modifies the envelope of whichever audiovoice is being used\nto play the desired note. The envelope should be reset before noteRelease is called\nin order to prevent the modified envelope from being used on other notes.
\n', + itemtype: 'method', + name: 'noteADSR', + params: [ + { + name: 'note', + description: 'Midi note on which ADSR should be set.
\n', + type: 'Number', + optional: true + }, + { + name: 'attackTime', + description: + 'Time (in seconds before envelope\n reaches Attack Level
\n', + type: 'Number', + optional: true + }, + { + name: 'decayTime', + description: + 'Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n', + type: 'Number', + optional: true + }, + { + name: 'susRatio', + description: + 'Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12533, + description: + 'Set the PolySynths global envelope. This method modifies the envelopes of each\nmonosynth so that all notes are played with this envelope.
\n', + itemtype: 'method', + name: 'setADSR', + params: [ + { + name: 'attackTime', + description: + 'Time (in seconds before envelope\n reaches Attack Level
\n', + type: 'Number', + optional: true + }, + { + name: 'decayTime', + description: + 'Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n', + type: 'Number', + optional: true + }, + { + name: 'susRatio', + description: + 'Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n', + type: 'Number', + optional: true + } + ], + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12557, + description: + 'Trigger the Attack, and Decay portion of a MonoSynth.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n', + itemtype: 'method', + name: 'noteAttack', + params: [ + { + name: 'note', + description: 'midi note on which attack should be triggered.
\n', + type: 'Number', + optional: true + }, + { + name: 'velocity', + description: + 'velocity of the note to play (ranging from 0 to 1)/
\n', + type: 'Number', + optional: true + }, + { + name: 'secondsFromNow', + description: 'time from now (in seconds)
\n', + type: 'Number', + optional: true + } + ], + example: [ + '\n\nlet polySynth = new p5.PolySynth();\nlet pitches = ["G", "D", "G", "C"];\nlet octaves = [2, 3, 4];\n\nfunction mousePressed() {\n // play a chord: multiple notes at the same time\n for (let i = 0; i < 4; i++) {\n let note = random(pitches) + random(octaves);\n polySynth.noteAttack(note, 0.1);\n }\n}\n\nfunction mouseReleased() {\n // release all voices\n polySynth.noteRelease();\n}\nTrigger the Release of an AudioVoice note. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n', + itemtype: 'method', + name: 'noteRelease', + params: [ + { + name: 'note', + description: + 'midi note on which attack should be triggered.\n If no value is provided, all notes will be released.
\n', + type: 'Number', + optional: true + }, + { + name: 'secondsFromNow', + description: 'time to trigger the release
\n', + type: 'Number', + optional: true + } + ], + example: [ + '\n\nlet pitches = ["G", "D", "G", "C"];\nlet octaves = [2, 3, 4];\nlet polySynth = new p5.PolySynth();\n\nfunction mousePressed() {\n // play a chord: multiple notes at the same time\n for (let i = 0; i < 4; i++) {\n let note = random(pitches) + random(octaves);\n polySynth.noteAttack(note, 0.1);\n }\n}\n\nfunction mouseReleased() {\n // release all voices\n polySynth.noteRelease();\n}\nConnect to a p5.sound / Web Audio object.
\n', + itemtype: 'method', + name: 'connect', + params: [ + { + name: 'unit', + description: 'A p5.sound or Web Audio object
\n', + type: 'Object' + } + ], + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12722, + description: 'Disconnect all outputs
\n', + itemtype: 'method', + name: 'disconnect', + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12732, + description: + 'Get rid of the MonoSynth and free up its resources / memory.
\n', + itemtype: 'method', + name: 'dispose', + class: 'p5.PolySynth', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12800, + description: + 'The p5.Distortion is built with a\n\nWeb Audio WaveShaper Node.
\n', + itemtype: 'property', + name: 'WaveShaperNode', + type: 'AudioNode', + class: 'p5.Distortion', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12815, + description: + 'Process a sound source, optionally specify amount and oversample values.
\n', + itemtype: 'method', + name: 'process', + params: [ + { + name: 'amount', + description: + 'Unbounded distortion amount.\n Normal values range from 0-1.
\n', + type: 'Number', + optional: true, + optdefault: '0.25' + }, + { + name: 'oversample', + description: ''none', '2x', or '4x'.
\n', + type: 'String', + optional: true, + optdefault: "'none'" + } + ], + class: 'p5.Distortion', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12827, + description: + 'Set the amount and oversample of the waveshaper distortion.
\n', + itemtype: 'method', + name: 'set', + params: [ + { + name: 'amount', + description: + 'Unbounded distortion amount.\n Normal values range from 0-1.
\n', + type: 'Number', + optional: true, + optdefault: '0.25' + }, + { + name: 'oversample', + description: ''none', '2x', or '4x'.
\n', + type: 'String', + optional: true, + optdefault: "'none'" + } + ], + class: 'p5.Distortion', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12845, + description: + 'Return the distortion amount, typically between 0-1.
\n', + itemtype: 'method', + name: 'getAmount', + return: { + description: + 'Unbounded distortion amount.\n Normal values range from 0-1.', + type: 'Number' + }, + class: 'p5.Distortion', + module: 'p5.sound', + submodule: 'p5.sound' + }, + { + file: 'lib/addons/p5.sound.js', + line: 12855, + description: 'Return the oversampling.
\n', + itemtype: 'method', + name: 'getOversample', + return: { + description: "Oversample can either be 'none', '2x', or '4x'.", + type: 'String' + }, + class: 'p5.Distortion', + module: 'p5.sound', + submodule: 'p5.sound' + } + ], + warnings: [ + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:14' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:59' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:89' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:132' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:330' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:361' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:398' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:489' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:519' + }, + { + message: 'unknown tag: alt', + line: ' src/color/creating_reading.js:559' + }, + { + message: 'unknown tag: alt', + line: ' src/color/p5.Color.js:50' + }, + { + message: 'unknown tag: alt', + line: ' src/color/p5.Color.js:251' + }, + { + message: 'unknown tag: alt', + line: ' src/color/p5.Color.js:280' + }, + { + message: 'unknown tag: alt', + line: ' src/color/p5.Color.js:309' + }, + { + message: 'unknown tag: alt', + line: ' src/color/p5.Color.js:338' + }, + { + message: 'unknown tag: alt', + line: ' src/color/p5.Color.js:775' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:13' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:179' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:218' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:339' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:496' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:537' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:577' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:749' + }, + { + message: 'unknown tag: alt', + line: ' src/color/setting.js:829' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:100' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:211' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:271' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:301' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:357' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:432' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:499' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:582' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/2d_primitives.js:636' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:12' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:82' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:117' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:186' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:222' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:259' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/attributes.js:326' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:11' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:94' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:137' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:192' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:271' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:362' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:404' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/curves.js:500' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:20' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:68' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:268' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:268' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:268' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:396' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:441' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:506' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:566' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:652' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:718' + }, + { + message: 'unknown tag: alt', + line: ' src/core/shape/vertex.js:811' + }, + { + message: 'unknown tag: alt', + line: ' src/core/constants.js:58' + }, + { + message: 'unknown tag: alt', + line: ' src/core/constants.js:77' + }, + { + message: 'unknown tag: alt', + line: ' src/core/constants.js:96' + }, + { + message: 'unknown tag: alt', + line: ' src/core/constants.js:115' + }, + { + message: 'unknown tag: alt', + line: ' src/core/constants.js:134' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:20' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:51' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:78' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:129' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:161' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:230' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:333' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:358' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:377' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:396' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:412' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:428' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:506' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:557' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/core/environment.js:592' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/core/environment.js:611' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:611' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:666' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:695' + }, + { + message: 'unknown tag: alt', + line: ' src/core/environment.js:715' + }, + { + message: 'unknown tag: alt', + line: ' src/core/main.js:41' + }, + { + message: 'unknown tag: alt', + line: ' src/core/main.js:82' + }, + { + message: 'unknown tag: alt', + line: ' src/core/main.js:113' + }, + { + message: 'unknown tag: alt', + line: ' src/core/main.js:406' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:46' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:111' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:151' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:186' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:247' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:296' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:362' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:416' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:472' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:530' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:573' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:615' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:663' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:703' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:752' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Element.js:790' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Graphics.js:63' + }, + { + message: 'unknown tag: alt', + line: ' src/core/p5.Graphics.js:115' + }, + { + message: 'unknown tag: alt', + line: ' src/core/rendering.js:15' + }, + { + message: 'unknown tag: alt', + line: ' src/core/rendering.js:115' + }, + { + message: 'unknown tag: alt', + line: ' src/core/rendering.js:170' + }, + { + message: 'unknown tag: alt', + line: ' src/core/rendering.js:193' + }, + { + message: 'unknown tag: alt', + line: ' src/core/rendering.js:232' + }, + { + message: 'unknown tag: alt', + line: ' src/core/structure.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/core/structure.js:72' + }, + { + message: 'unknown tag: alt', + line: ' src/core/structure.js:120' + }, + { + message: 'unknown tag: alt', + line: ' src/core/structure.js:211' + }, + { + message: 'unknown tag: alt', + line: ' src/core/structure.js:303' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:11' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:148' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:174' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:214' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:244' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:274' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:304' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:379' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:419' + }, + { + message: 'unknown tag: alt', + line: ' src/core/transform.js:459' + }, + { + message: 'unknown tag: alt', + line: ' src/data/local_storage.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/data/local_storage.js:91' + }, + { + message: 'unknown tag: alt', + line: ' src/dom/dom.js:226' + }, + { + message: 'unknown tag: alt', + line: ' src/dom/dom.js:294' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/dom/dom.js:1418' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/dom/dom.js:1480' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/dom/dom.js:1584' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/dom/dom.js:1623' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/dom/dom.js:1717' + }, + { + message: 'unknown tag: alt', + line: ' src/dom/dom.js:2076' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:21' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:44' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:67' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:133' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:164' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:195' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:231' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:276' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:320' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:378' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:417' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:460' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:504' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:536' + }, + { + message: 'unknown tag: alt', + line: ' src/events/acceleration.js:595' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:37' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:66' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:107' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:194' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:246' + }, + { + message: 'unknown tag: alt', + line: ' src/events/keyboard.js:310' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:12' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:44' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:82' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:109' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:136' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:169' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:201' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:240' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:279' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:320' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:362' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:401' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:494' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:549' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:630' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:712' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:790' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:860' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:945' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:999' + }, + { + message: 'unknown tag: alt', + line: ' src/events/mouse.js:1046' + }, + { + message: 'unknown tag: alt', + line: ' src/events/touch.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/events/touch.js:71' + }, + { + message: 'unknown tag: alt', + line: ' src/events/touch.js:151' + }, + { + message: 'unknown tag: alt', + line: ' src/events/touch.js:224' + }, + { + message: 'unknown tag: alt', + line: ' src/image/image.js:22' + }, + { + message: 'unknown tag: alt', + line: ' src/image/image.js:102' + }, + { + message: 'unknown tag: alt', + line: ' src/image/image.js:249' + }, + { + message: 'unknown tag: alt', + line: ' src/image/loading_displaying.js:16' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/image/loading_displaying.js:234' + }, + { + message: 'unknown tag: alt', + line: ' src/image/loading_displaying.js:251' + }, + { + message: 'unknown tag: alt', + line: ' src/image/loading_displaying.js:422' + }, + { + message: 'unknown tag: alt', + line: ' src/image/loading_displaying.js:522' + }, + { + message: 'unknown tag: alt', + line: ' src/image/loading_displaying.js:588' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:88' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:115' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:152' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:258' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:294' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:345' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:400' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:438' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:550' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:606' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:669' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:705' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:827' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:869' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:910' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:942' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:987' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:1023' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:1061' + }, + { + message: 'unknown tag: alt', + line: ' src/image/p5.Image.js:1098' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:12' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:81' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:175' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:310' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:489' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:577' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:614' + }, + { + message: 'unknown tag: alt', + line: ' src/image/pixels.js:688' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:18' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:183' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:294' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:604' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/io/files.js:715' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:715' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:1523' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:1581' + }, + { + message: 'unknown tag: alt', + line: ' src/io/files.js:1649' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:85' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:149' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:197' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:243' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:292' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:357' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:552' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:605' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:647' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:906' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:971' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1021' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1067' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1112' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1159' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1204' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1257' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.Table.js:1321' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.TableRow.js:40' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.TableRow.js:102' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.TableRow.js:146' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.TableRow.js:191' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.TableRow.js:239' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.TableRow.js:295' + }, + { + message: 'unknown tag: alt', + line: ' src/io/p5.XML.js:9' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:34' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:74' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:119' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:184' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:234' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:273' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:321' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:377' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:416' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:472' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:522' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:572' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:625' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:660' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:699' + }, + { + message: 'unknown tag: alt', + line: ' src/math/calculation.js:744' + }, + { + message: 'unknown tag: alt', + line: ' src/math/math.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/math/noise.js:36' + }, + { + message: 'unknown tag: alt', + line: ' src/math/noise.js:180' + }, + { + message: 'unknown tag: alt', + line: ' src/math/noise.js:246' + }, + { + message: 'unknown tag: alt', + line: ' src/math/p5.Vector.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/math/random.js:37' + }, + { + message: 'unknown tag: alt', + line: ' src/math/random.js:67' + }, + { + message: 'unknown tag: alt', + line: ' src/math/random.js:155' + }, + { + message: 'unknown tag: alt', + line: ' src/math/trigonometry.js:122' + }, + { + message: 'unknown tag: alt', + line: ' src/math/trigonometry.js:158' + }, + { + message: 'unknown tag: alt', + line: ' src/math/trigonometry.js:186' + }, + { + message: 'unknown tag: alt', + line: ' src/math/trigonometry.js:214' + }, + { + message: 'unknown tag: alt', + line: ' src/math/trigonometry.js:290' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/math/trigonometry.js:326' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/math/trigonometry.js:341' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/math/trigonometry.js:356' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/attributes.js:11' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/attributes.js:82' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/attributes.js:120' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/attributes.js:152' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/attributes.js:189' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/loading_displaying.js:14' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/loading_displaying.js:138' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/loading_displaying.js:225' + }, + { + message: 'unknown tag: alt', + line: ' src/typography/p5.Font.js:30' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/conversion.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:13' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:42' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:130' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:239' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:313' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:375' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:453' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/string_functions.js:540' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:30' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:50' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:70' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:91' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:113' + }, + { + message: 'unknown tag: alt', + line: ' src/utilities/time_date.js:133' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/3d_primitives.js:13' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:11' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:145' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:145' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:145' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:145' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:145' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/interaction.js:353' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:10' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:85' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:170' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:272' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:378' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:409' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:495' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/light.js:835' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/loading.js:12' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/loading.js:12' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/loading.js:579' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:12' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/webgl/material.js:111' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:111' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:179' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:283' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:321' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:422' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:422' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:501' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:574' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:625' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:677' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/material.js:729' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:13' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:112' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:173' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:230' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:319' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:652' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:711' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:769' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:917' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:989' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Camera.js:1254' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/webgl/p5.RendererGL.Retained.js:38' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.RendererGL.js:279' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.RendererGL.js:548' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.RendererGL.js:590' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.RendererGL.js:692' + }, + { + message: 'unknown tag: alt', + line: ' src/webgl/p5.Shader.js:281' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:115' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/webgl/text.js:158' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:191' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:203' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:236' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:250' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:388' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' src/webgl/text.js:388' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:456' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:471' + }, + { + message: 'replacing incorrect tag: function with method', + line: ' src/webgl/text.js:556' + }, + { + message: 'replacing incorrect tag: params with param', + line: ' lib/addons/p5.sound.js:2480' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' lib/addons/p5.sound.js:2480' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' lib/addons/p5.sound.js:3094' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' lib/addons/p5.sound.js:7659' + }, + { + message: 'replacing incorrect tag: returns with return', + line: ' lib/addons/p5.sound.js:9626' + }, + { + message: + "Missing item type\nConversions adapted fromGeneric class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.
\nCSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don\'t bother with the\nquotes.
\nFile names should end with .csv if they\'re comma separated.
\nA rough "spec" for CSV can be found\nhere.
\nTo load files, use the loadTable method.
\nTo save tables to your computer, use the save method\n or the saveTable method.
\n\nPossible options include:\n
+ * noStroke();
+ * let c = color(0, 126, 255, 102);
+ * fill(c);
+ * rect(15, 15, 35, 70);
+ * let value = alpha(c); // Sets 'value' to 102
+ * fill(value);
+ * rect(50, 15, 35, 70);
+ *
+ *
+ * let c = color(175, 100, 220); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let blueValue = blue(c); // Get blue in 'c'
+ * print(blueValue); // Prints "220.0"
+ * fill(0, 0, blueValue); // Use 'blueValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // Sets 'value' to 255
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color('hsb(60, 100%, 50%)');
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // A 'value' of 50% is 127.5
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ * let c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * noStroke(); // Don't draw a stroke around shapes
+ * rect(30, 20, 55, 55); // Draw rectangle
+ *
+ *
+ * let c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * noStroke(); // Don't draw a stroke around shapes
+ * ellipse(25, 25, 80, 80); // Draw left circle
+ *
+ * // Using only one value with color()
+ * // generates a grayscale value.
+ * c = color(65); // Update 'c' with grayscale value
+ * fill(c); // Use updated 'c' as fill color
+ * ellipse(75, 75, 80, 80); // Draw right circle
+ *
+ *
+ * // Named SVG & CSS colors may be used,
+ * let c = color('magenta');
+ * fill(c); // Use 'c' as fill color
+ * noStroke(); // Don't draw a stroke around shapes
+ * rect(20, 20, 60, 60); // Draw rectangle
+ *
+ *
+ * // as can hex color codes:
+ * noStroke(); // Don't draw a stroke around shapes
+ * let c = color('#0f0');
+ * fill(c); // Use 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw rectangle
+ *
+ * c = color('#00ff00');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ * // RGB and RGBA color strings are also supported:
+ * // these all set to the same color (solid blue)
+ * let c;
+ * noStroke(); // Don't draw a stroke around shapes
+ * c = color('rgb(0,0,255)');
+ * fill(c); // Use 'c' as fill color
+ * rect(10, 10, 35, 35); // Draw rectangle
+ *
+ * c = color('rgb(0%, 0%, 100%)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 35, 35); // Draw rectangle
+ *
+ * c = color('rgba(0, 0, 255, 1)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(10, 55, 35, 35); // Draw rectangle
+ *
+ * c = color('rgba(0%, 0%, 100%, 1)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 55, 35, 35); // Draw rectangle
+ *
+ *
+ * // HSL color is also supported and can be specified
+ * // by value
+ * let c;
+ * noStroke(); // Don't draw a stroke around shapes
+ * c = color('hsl(160, 100%, 50%)');
+ * fill(c); // Use 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw rectangle
+ *
+ * c = color('hsla(160, 100%, 50%, 0.5)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ * // HSB color is also supported and can be specified
+ * // by value
+ * let c;
+ * noStroke(); // Don't draw a stroke around shapes
+ * c = color('hsb(160, 100%, 50%)');
+ * fill(c); // Use 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw rectangle
+ *
+ * c = color('hsba(160, 100%, 50%, 0.5)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ * let c; // Declare color 'c'
+ * noStroke(); // Don't draw a stroke around shapes
+ *
+ * // If no colorMode is specified, then the
+ * // default of RGB with scale of 0-255 is used.
+ * c = color(50, 55, 100); // Create a color for 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw left rect
+ *
+ * colorMode(HSB, 100); // Use HSB with scale of 0-100
+ * c = color(50, 55, 100); // Update 'c' with new color
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw right rect
+ *
+ *
+ * let c = color(20, 75, 200); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let greenValue = green(c); // Get green in 'c'
+ * print(greenValue); // Print "75.0"
+ * fill(0, greenValue, 0); // Use 'greenValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = hue(c); // Sets 'value' to "0"
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ * colorMode(RGB);
+ * stroke(255);
+ * background(51);
+ * let from = color(218, 165, 32);
+ * let to = color(72, 61, 139);
+ * colorMode(RGB); // Try changing to HSB.
+ * let interA = lerpColor(from, to, 0.33);
+ * let interB = lerpColor(from, to, 0.66);
+ * fill(from);
+ * rect(10, 20, 20, 60);
+ * fill(interA);
+ * rect(30, 20, 20, 60);
+ * fill(interB);
+ * rect(50, 20, 20, 60);
+ * fill(to);
+ * rect(70, 20, 20, 60);
+ *
+ *
+ * noStroke();
+ * colorMode(HSL);
+ * let c = color(156, 100, 50, 1);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = lightness(c); // Sets 'value' to 50
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ * let c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let redValue = red(c); // Get red in 'c'
+ * print(redValue); // Print "255.0"
+ * fill(redValue, 0, 0); // Use 'redValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ * colorMode(RGB, 255); // Sets the range for red, green, and blue to 255
+ * let c = color(127, 255, 0);
+ * colorMode(RGB, 1); // Sets the range for red, green, and blue to 1
+ * let myColor = red(c);
+ * print(myColor); // 0.4980392156862745
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = saturation(c); // Sets 'value' to 126
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ * let myColor;
+ * function setup() {
+ * createCanvas(200, 200);
+ * stroke(255);
+ * myColor = color(100, 100, 250);
+ * fill(myColor);
+ * }
+ *
+ * function draw() {
+ * rotate(HALF_PI);
+ * text(myColor.toString(), 0, -5);
+ * text(myColor.toString('#rrggbb'), 0, -30);
+ * text(myColor.toString('rgba%'), 0, -55);
+ * }
+ *
+ *
+ * let backgroundColor;
+ *
+ * function setup() {
+ * backgroundColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * backgroundColor.setRed(128 + 128 * sin(millis() / 1000));
+ * background(backgroundColor);
+ * }
+ *
+ *
+ * let backgroundColor;
+ *
+ * function setup() {
+ * backgroundColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));
+ * background(backgroundColor);
+ * }
+ *
+ *
+ * let backgroundColor;
+ *
+ * function setup() {
+ * backgroundColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));
+ * background(backgroundColor);
+ * }
+ *
+ *
+ * let squareColor;
+ *
+ * function setup() {
+ * ellipseMode(CORNERS);
+ * strokeWeight(4);
+ * squareColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ *
+ * noFill();
+ * stroke(0);
+ * ellipse(10, 10, width - 10, height - 10);
+ *
+ * squareColor.setAlpha(128 + 128 * sin(millis() / 1000));
+ * fill(squareColor);
+ * noStroke();
+ * rect(13, 13, width - 26, height - 26);
+ * }
+ *
+ *
+ * // todo
+ *
+ *
+ * // Grayscale integer value
+ * background(51);
+ *
+ *
+ * // R, G & B integer values
+ * background(255, 204, 0);
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * background(255, 204, 100);
+ *
+ *
+ * // Named SVG/CSS color string
+ * background('red');
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * background('#fae');
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * background('#222222');
+ *
+ *
+ * // integer RGB notation
+ * background('rgb(0,255,0)');
+ *
+ *
+ * // integer RGBA notation
+ * background('rgba(0,255,0, 0.25)');
+ *
+ *
+ * // percentage RGB notation
+ * background('rgb(100%,0%,10%)');
+ *
+ *
+ * // percentage RGBA notation
+ * background('rgba(100%,0%,100%,0.5)');
+ *
+ *
+ * // p5 Color object
+ * background(color(0, 0, 255));
+ *
+ *
+ * // Clear the screen on mouse press.
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * ellipse(mouseX, mouseY, 20, 20);
+ * }
+ *
+ * function mousePressed() {
+ * clear();
+ * }
+ *
+ *
+ * noStroke();
+ * colorMode(RGB, 100);
+ * for (let i = 0; i < 100; i++) {
+ * for (let j = 0; j < 100; j++) {
+ * stroke(i, j, 0);
+ * point(i, j);
+ * }
+ * }
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 100);
+ * for (let i = 0; i < 100; i++) {
+ * for (let j = 0; j < 100; j++) {
+ * stroke(i, j, 100);
+ * point(i, j);
+ * }
+ * }
+ *
+ *
+ * colorMode(RGB, 255);
+ * let c = color(127, 255, 0);
+ *
+ * colorMode(RGB, 1);
+ * let myColor = c._getRed();
+ * text(myColor, 10, 10, 80, 80);
+ *
+ *
+ * noFill();
+ * colorMode(RGB, 255, 255, 255, 1);
+ * background(255);
+ *
+ * strokeWeight(4);
+ * stroke(255, 0, 10, 0.3);
+ * ellipse(40, 40, 50, 50);
+ * ellipse(50, 50, 40, 40);
+ *
+ *
+ * // Grayscale integer value
+ * fill(51);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // R, G & B integer values
+ * fill(255, 204, 0);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * fill(255, 204, 100);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // Named SVG/CSS color string
+ * fill('red');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * fill('#fae');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * fill('#222222');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // integer RGB notation
+ * fill('rgb(0,255,0)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // integer RGBA notation
+ * fill('rgba(0,255,0, 0.25)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // percentage RGB notation
+ * fill('rgb(100%,0%,10%)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // percentage RGBA notation
+ * fill('rgba(100%,0%,100%,0.5)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // p5 Color object
+ * fill(color(0, 0, 255));
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * rect(15, 10, 55, 55);
+ * noFill();
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * noFill();
+ * stroke(100, 100, 240);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(45, 45, 45);
+ * }
+ *
+ *
+ * noStroke();
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * fill(240, 150, 150);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(45, 45, 45);
+ * }
+ *
+ *
+ * // Grayscale integer value
+ * strokeWeight(4);
+ * stroke(51);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // R, G & B integer values
+ * stroke(255, 204, 0);
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * strokeWeight(4);
+ * stroke(255, 204, 100);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // Named SVG/CSS color string
+ * stroke('red');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * stroke('#fae');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * stroke('#222222');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // integer RGB notation
+ * stroke('rgb(0,255,0)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // integer RGBA notation
+ * stroke('rgba(0,255,0,0.25)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // percentage RGB notation
+ * stroke('rgb(100%,0%,10%)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // percentage RGBA notation
+ * stroke('rgba(100%,0%,100%,0.5)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * // p5 Color object
+ * stroke(color(0, 0, 255));
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * background(100, 100, 250);
+ * fill(250, 100, 100);
+ * rect(20, 20, 60, 60);
+ * erase();
+ * ellipse(25, 30, 30);
+ * noErase();
+ *
+ *
+ * background(150, 250, 150);
+ * fill(100, 100, 250);
+ * rect(20, 20, 60, 60);
+ * strokeWeight(5);
+ * erase(150, 255);
+ * triangle(50, 10, 70, 50, 90, 10);
+ * noErase();
+ *
+ *
+ * function setup() {
+ * smooth();
+ * createCanvas(100, 100, WEBGL);
+ * // Make a <p> element and put it behind the canvas
+ * let p = createP('I am a dom element');
+ * p.center();
+ * p.style('font-size', '20px');
+ * p.style('text-align', 'center');
+ * p.style('z-index', '-9999');
+ * }
+ *
+ * function draw() {
+ * background(250, 250, 150);
+ * fill(15, 195, 185);
+ * noStroke();
+ * sphere(30);
+ * erase();
+ * rotateY(frameCount * 0.02);
+ * translate(0, 0, 40);
+ * torus(15, 5);
+ * noErase();
+ * }
+ *
+ *
+ * background(235, 145, 15);
+ * noStroke();
+ * fill(30, 45, 220);
+ * rect(30, 10, 10, 80);
+ * erase();
+ * ellipse(50, 50, 60);
+ * noErase();
+ * rect(70, 10, 10, 80);
+ *
+ *
+ * arc(50, 50, 80, 80, 0, HALF_PI);
+ *
+ * arc(50, 50, 80, 80, 0, PI);
+ *
+ * arc(50, 50, 80, 80, 0, QUARTER_PI);
+ *
+ * arc(50, 50, 80, 80, 0, TAU);
+ *
+ * arc(50, 50, 80, 80, 0, TWO_PI);
+ *
+ * function setup() {
+ * angleMode(DEGREES);
+ * }
+ *
+ * function setup() {
+ * angleMode(RADIANS);
+ * }
+ *
+ * let x = 10;
+ * print('The value of x is ' + x);
+ * // prints "The value of x is 10"
+ *
+ * function setup() {
+ * frameRate(30);
+ * textSize(30);
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(frameCount, width / 2, height / 2);
+ * }
+
+ * let rectX = 0;
+ * let fr = 30; //starting FPS
+ * let clr;
+ *
+ * function setup() {
+ * background(200);
+ * frameRate(fr); // Attempt to refresh at starting FPS
+ * clr = color(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rectX = rectX + 1 * (deltaTime / 50); // Move Rectangle in relation to deltaTime
+ *
+ * if (rectX >= width) {
+ * // If you go off screen.
+ * if (fr === 30) {
+ * clr = color(0, 0, 255);
+ * fr = 10;
+ * frameRate(fr); // make frameRate 10 FPS
+ * } else {
+ * clr = color(255, 0, 0);
+ * fr = 30;
+ * frameRate(fr); // make frameRate 30 FPS
+ * }
+ * rectX = 0;
+ * }
+ * fill(clr);
+ * rect(rectX, 40, 20, 20);
+ * }
+ *
+ * // To demonstrate, put two windows side by side.
+ * // Click on the window that the p5 sketch isn't in!
+ * function draw() {
+ * background(200);
+ * noStroke();
+ * fill(0, 200, 0);
+ * ellipse(25, 25, 50, 50);
+ *
+ * if (!focused) {
+ // or "if (focused === false)"
+ * stroke(200, 0, 0);
+ * line(0, 0, 100, 100);
+ * line(100, 0, 0, 100);
+ * }
+ * }
+ *
+ * // Move the mouse across the quadrants
+ * // to see the cursor change
+ * function draw() {
+ * line(width / 2, 0, width / 2, height);
+ * line(0, height / 2, width, height / 2);
+ * if (mouseX < 50 && mouseY < 50) {
+ * cursor(CROSS);
+ * } else if (mouseX > 50 && mouseY < 50) {
+ * cursor('progress');
+ * } else if (mouseX > 50 && mouseY > 50) {
+ * cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');
+ * } else {
+ * cursor('grab');
+ * }
+ * }
+ *
+ * let rectX = 0;
+ * let fr = 30; //starting FPS
+ * let clr;
+ *
+ * function setup() {
+ * background(200);
+ * frameRate(fr); // Attempt to refresh at starting FPS
+ * clr = color(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rectX = rectX += 1; // Move Rectangle
+ *
+ * if (rectX >= width) {
+ // If you go off screen.
+ * if (fr === 30) {
+ * clr = color(0, 0, 255);
+ * fr = 10;
+ * frameRate(fr); // make frameRate 10 FPS
+ * } else {
+ * clr = color(255, 0, 0);
+ * fr = 30;
+ * frameRate(fr); // make frameRate 30 FPS
+ * }
+ * rectX = 0;
+ * }
+ * fill(clr);
+ * rect(rectX, 40, 20, 20);
+ * }
+ *
+ * function setup() {
+ * noCursor();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * ellipse(mouseX, mouseY, 10, 10);
+ * }
+ *
+ * createCanvas(displayWidth, displayHeight);
+ *
+ * createCanvas(displayWidth, displayHeight);
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ * function setup() {
+ * createCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * function draw() {
+ * background(0, 100, 200);
+ * }
+ *
+ * function windowResized() {
+ * resizeCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * // Clicking in the box toggles fullscreen on and off.
+ * function setup() {
+ * background(200);
+ * }
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {
+ * let fs = fullscreen();
+ * fullscreen(!fs);
+ * }
+ * }
+ *
+ *
+ * function setup() {
+ * pixelDensity(1);
+ * createCanvas(100, 100);
+ * background(200);
+ * ellipse(width / 2, height / 2, 50, 50);
+ * }
+ *
+ *
+ * function setup() {
+ * pixelDensity(3.0);
+ * createCanvas(100, 100);
+ * background(200);
+ * ellipse(width / 2, height / 2, 50, 50);
+ * }
+ *
+ *
+ * function setup() {
+ * let density = displayDensity();
+ * pixelDensity(density);
+ * createCanvas(100, 100);
+ * background(200);
+ * ellipse(width / 2, height / 2, 50, 50);
+ * }
+ *
+ *
+ * let url;
+ * let x = 100;
+ *
+ * function setup() {
+ * fill(0);
+ * noStroke();
+ * url = getURL();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(url, x, height / 2);
+ * x--;
+ * }
+ *
+ *
+ * function setup() {
+ * let urlPath = getURLPath();
+ * for (let i = 0; i < urlPath.length; i++) {
+ * text(urlPath[i], 10, i * 20 + 20);
+ * }
+ * }
+ *
+ * // Example: http://p5js.org?year=2014&month=May&day=15
+ *
+ * function setup() {
+ * let params = getURLParams();
+ * text(params.day, 10, 20);
+ * text(params.month, 10, 40);
+ * text(params.year, 10, 60);
+ * }
+ *
+ *
+ * let img;
+ * let c;
+ * function preload() {
+ * // preload() runs once
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * // setup() waits until preload() is done
+ * img.loadPixels();
+ * // get color of middle pixel
+ * c = img.get(img.width / 2, img.height / 2);
+ * }
+ *
+ * function draw() {
+ * background(c);
+ * image(img, 25, 25, 50, 50);
+ * }
+ *
+ * let a = 0;
+ *
+ * function setup() {
+ * background(0);
+ * noStroke();
+ * fill(102);
+ * }
+ *
+ * function draw() {
+ * rect(a++ % width, 10, 2, 80);
+ * }
+ *
+ * let yPos = 0;
+ * function setup() {
+ * // setup() runs once
+ * frameRate(30);
+ * }
+ * function draw() {
+ * // draw() loops forever, until stopped
+ * background(204);
+ * yPos = yPos - 1;
+ * if (yPos < 0) {
+ * yPos = height;
+ * }
+ * line(0, yPos, width, yPos);
+ * }
+ *
+ * function draw() {
+ * ellipse(50, 50, 10, 10);
+ * }
+ *
+ * function mousePressed() {
+ * remove(); // remove whole sketch on mouse press
+ * }
+ *
+ * p5.disableFriendlyErrors = true;
+ *
+ * function setup() {
+ * createCanvas(100, 50);
+ * }
+ *
+ * function setup() {
+ * let c = createCanvas(50, 50);
+ * c.elt.style.border = '5px solid red';
+ * }
+ *
+ * function draw() {
+ * background(220);
+ * }
+ *
+ *
+ * // in the html file:
+ * // <div id="myContainer"></div>
+ *
+ * // in the js file:
+ * let cnv = createCanvas(100, 100);
+ * cnv.parent('myContainer');
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div1.parent(div0); // use p5.Element
+ *
+ * let div0 = createDiv('this is the parent');
+ * div0.id('apples');
+ * let div1 = createDiv('this is the child');
+ * div1.parent('apples'); // use id
+ *
+ * let elt = document.getElementById('myParentDiv');
+ * let div1 = createDiv('this is the child');
+ * div1.parent(elt); // use element from page
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector ID to
+ * // the canvas element.
+ * cnv.id('mycanvas');
+ * }
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector class 'small'
+ * // to the canvas element.
+ * cnv.class('small');
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mousePressed(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any click anywhere
+ * function mousePressed() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.doubleClicked(changeGray); // attach listener for
+ * // canvas double click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any double click anywhere
+ * function doubleClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is double clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseWheel(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // anywhere on screen
+ * function mouseWheel() {
+ * g = g + 10;
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // over canvas only
+ * function changeSize(event) {
+ * if (event.deltaY > 0) {
+ * d = d + 10;
+ * } else {
+ * d = d - 10;
+ * }
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseReleased(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released
+ * function mouseReleased() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released while on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ *
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseClicked(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked anywhere
+ * function mouseClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * let cnv;
+ * let d = 30;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseMoved(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * fill(200);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires when mouse moves anywhere on
+ * // page
+ * function mouseMoved() {
+ * g = g + 5;
+ * if (g > 255) {
+ * g = 0;
+ * }
+ * }
+ *
+ * // this function fires when mouse moves over canvas
+ * function changeSize() {
+ * d = d + 2;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ * let cnv;
+ * let d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOver(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ * let cnv;
+ * let d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOut(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchStarted(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchStarted() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ * let cnv;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchMoved(changeGray); // attach listener for
+ * // canvas click only
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchEnded(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchEnded() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ * // To test this sketch, simply drag a
+ * // file over the canvas
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragOver(dragOverCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged over the canvas
+ * function dragOverCallback() {
+ * background(240);
+ * text('Dragged over', width / 2, height / 2);
+ * }
+ *
+ * // To test this sketch, simply drag a file
+ * // over and then out of the canvas area
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragLeave(dragLeaveCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged out of the canvas
+ * function dragLeaveCallback() {
+ * background(240);
+ * text('Dragged off', width / 2, height / 2);
+ * }
+ *
+ * let pg;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(0);
+ * pg = createGraphics(50, 100);
+ * pg.fill(0);
+ * frameRate(5);
+ * }
+ * function draw() {
+ * image(pg, width / 2, 0);
+ * pg.background(255);
+ * // p5.Graphics object behave a bit differently in some cases
+ * // The normal canvas on the left resets the translate
+ * // with every loop through draw()
+ * // the graphics object on the right doesn't automatically reset
+ * // so translate() is additive and it moves down the screen
+ * rect(0, 0, width / 2, 5);
+ * pg.rect(0, 0, width / 2, 5);
+ * translate(0, 5, 0);
+ * pg.translate(0, 5, 0);
+ * }
+ * function mouseClicked() {
+ * // if you click you will see that
+ * // reset() resets the translate back to the initial state
+ * // of the Graphics object
+ * pg.reset();
+ * }
+ *
+ * let bg;
+ * function setup() {
+ * bg = createCanvas(100, 100);
+ * bg.background(0);
+ * image(bg, 0, 0);
+ * bg.remove();
+ * }
+ *
+ * let bg;
+ * function setup() {
+ * pixelDensity(1);
+ * createCanvas(100, 100);
+ * stroke(255);
+ * fill(0);
+ *
+ * // create and draw the background image
+ * bg = createGraphics(100, 100);
+ * bg.background(200);
+ * bg.ellipse(50, 50, 80, 80);
+ * }
+ * function draw() {
+ * let t = millis() / 1000;
+ * // draw the background
+ * if (bg) {
+ * image(bg, frameCount % 100, 0);
+ * image(bg, frameCount % 100 - 100, 0);
+ * }
+ * // draw the foreground
+ * let p = p5.Vector.fromAngle(t, 35).add(50, 50);
+ * ellipse(p.x, p.y, 30);
+ * }
+ * function mouseClicked() {
+ * // remove the background
+ * if (bg) {
+ * bg.remove();
+ * bg = null;
+ * }
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 50);
+ * background(153);
+ * line(0, 0, width, height);
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * function draw() {
+ * background(0, 100, 200);
+ * }
+ *
+ * function windowResized() {
+ * resizeCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * function setup() {
+ * noCanvas();
+ * }
+ *
+ *
+ * let pg;
+ * function setup() {
+ * createCanvas(100, 100);
+ * pg = createGraphics(100, 100);
+ * }
+ * function draw() {
+ * background(200);
+ * pg.background(100);
+ * pg.noStroke();
+ * pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);
+ * image(pg, 50, 50);
+ * image(pg, 0, 0, 50, 50);
+ * }
+ *
+ * BLEND - linear interpolation of colours: C =
+ * A\*factor + B. This is the default blending mode.ADD - sum of A and BDARKEST - only the darkest colour succeeds: C =
+ * min(A\*factor, B).LIGHTEST - only the lightest colour succeeds: C =
+ * max(A\*factor, B).DIFFERENCE - subtract colors from underlying image.EXCLUSION - similar to DIFFERENCE, but less
+ * extreme.MULTIPLY - multiply the colors, result will always be
+ * darker.SCREEN - opposite multiply, uses inverse values of the
+ * colors.REPLACE - the pixels entirely replace the others and
+ * don't utilize alpha (transparency) values.REMOVE - removes pixels from B with the alpha strength of A.OVERLAY - mix of MULTIPLY and SCREEN
+ * . Multiplies dark values, and screens light values. (2D)HARD_LIGHT - SCREEN when greater than 50%
+ * gray, MULTIPLY when lower. (2D)SOFT_LIGHT - mix of DARKEST and
+ * LIGHTEST. Works like OVERLAY, but not as harsh. (2D)
+ * DODGE - lightens light tones and increases contrast,
+ * ignores darks. (2D)BURN - darker areas are applied, increasing contrast,
+ * ignores lights. (2D)SUBTRACT - remainder of A and B (3D)
+ * blendMode(LIGHTEST);
+ * strokeWeight(30);
+ * stroke(80, 150, 255);
+ * line(25, 25, 75, 75);
+ * stroke(255, 50, 50);
+ * line(75, 25, 25, 75);
+ *
+ *
+ * blendMode(MULTIPLY);
+ * strokeWeight(30);
+ * stroke(80, 150, 255);
+ * line(25, 25, 75, 75);
+ * stroke(255, 50, 50);
+ * line(75, 25, 25, 75);
+ *
+ *
+ * arc(50, 55, 50, 50, 0, HALF_PI);
+ * noFill();
+ * arc(50, 55, 60, 60, HALF_PI, PI);
+ * arc(50, 55, 70, 70, PI, PI + QUARTER_PI);
+ * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI);
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);
+ *
+ *
+ * ellipse(56, 46, 55, 55);
+ *
+ *
+ * // Draw a circle at location (30, 30) with a diameter of 20.
+ * circle(30, 30, 20);
+ *
+ *
+ * line(30, 20, 85, 75);
+ *
+ *
+ * line(30, 20, 85, 20);
+ * stroke(126);
+ * line(85, 20, 85, 75);
+ * stroke(255);
+ * line(85, 75, 30, 75);
+ *
+ *
+ * point(30, 20);
+ * point(85, 20);
+ * point(85, 75);
+ * point(30, 75);
+ *
+ *
+ * stroke('purple'); // Change the color
+ * strokeWeight(10); // Make the points 10 pixels in size
+ * point(30, 20);
+ * point(85, 20);
+ * point(85, 75);
+ * point(30, 75);
+ *
+ *
+ * let a = createVector(10, 10);
+ * point(a);
+ * let b = createVector(10, 20);
+ * point(b);
+ * point(createVector(20, 10));
+ * point(createVector(20, 20));
+ *
+ *
+ * quad(38, 31, 86, 20, 69, 63, 30, 76);
+ *
+ *
+ * // Draw a rectangle at location (30, 20) with a width and height of 55.
+ * rect(30, 20, 55, 55);
+ *
+ *
+ * // Draw a rectangle with rounded corners, each having a radius of 20.
+ * rect(30, 20, 55, 55, 20);
+ *
+ *
+ * // Draw a rectangle with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * rect(30, 20, 55, 55, 20, 15, 10, 5);
+ *
+ *
+ * // Draw a square at location (30, 20) with a side size of 55.
+ * square(30, 20, 55);
+ *
+ *
+ * // Draw a square with rounded corners, each having a radius of 20.
+ * square(30, 20, 55, 20);
+ *
+ *
+ * // Draw a square with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * square(30, 20, 55, 20, 15, 10, 5);
+ *
+ *
+ * triangle(30, 75, 58, 20, 86, 75);
+ *
+ *
+ * ellipseMode(RADIUS); // Set ellipseMode to RADIUS
+ * fill(255); // Set fill to white
+ * ellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode
+ *
+ * ellipseMode(CENTER); // Set ellipseMode to CENTER
+ * fill(100); // Set fill to gray
+ * ellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode
+ *
+ *
+ * ellipseMode(CORNER); // Set ellipseMode is CORNER
+ * fill(255); // Set fill to white
+ * ellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode
+ *
+ * ellipseMode(CORNERS); // Set ellipseMode to CORNERS
+ * fill(100); // Set fill to gray
+ * ellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode
+ *
+ *
+ * background(0);
+ * noStroke();
+ * smooth();
+ * ellipse(30, 48, 36, 36);
+ * noSmooth();
+ * ellipse(70, 48, 36, 36);
+ *
+ *
+ * rectMode(CORNER); // Default rectMode is CORNER
+ * fill(255); // Set fill to white
+ * rect(25, 25, 50, 50); // Draw white rect using CORNER mode
+ *
+ * rectMode(CORNERS); // Set rectMode to CORNERS
+ * fill(100); // Set fill to gray
+ * rect(25, 25, 50, 50); // Draw gray rect using CORNERS mode
+ *
+ *
+ * rectMode(RADIUS); // Set rectMode to RADIUS
+ * fill(255); // Set fill to white
+ * rect(50, 50, 30, 30); // Draw white rect using RADIUS mode
+ *
+ * rectMode(CENTER); // Set rectMode to CENTER
+ * fill(100); // Set fill to gray
+ * rect(50, 50, 30, 30); // Draw gray rect using CENTER mode
+ *
+ *
+ * background(0);
+ * noStroke();
+ * smooth();
+ * ellipse(30, 48, 36, 36);
+ * noSmooth();
+ * ellipse(70, 48, 36, 36);
+ *
+ *
+ * strokeWeight(12.0);
+ * strokeCap(ROUND);
+ * line(20, 30, 80, 30);
+ * strokeCap(SQUARE);
+ * line(20, 50, 80, 50);
+ * strokeCap(PROJECT);
+ * line(20, 70, 80, 70);
+ *
+ *
+ * noFill();
+ * strokeWeight(10.0);
+ * strokeJoin(MITER);
+ * beginShape();
+ * vertex(35, 20);
+ * vertex(65, 50);
+ * vertex(35, 80);
+ * endShape();
+ *
+ *
+ * noFill();
+ * strokeWeight(10.0);
+ * strokeJoin(BEVEL);
+ * beginShape();
+ * vertex(35, 20);
+ * vertex(65, 50);
+ * vertex(35, 80);
+ * endShape();
+ *
+ *
+ * noFill();
+ * strokeWeight(10.0);
+ * strokeJoin(ROUND);
+ * beginShape();
+ * vertex(35, 20);
+ * vertex(65, 50);
+ * vertex(35, 80);
+ * endShape();
+ *
+ *
+ * strokeWeight(1); // Default
+ * line(20, 20, 80, 20);
+ * strokeWeight(4); // Thicker
+ * line(20, 40, 80, 40);
+ * strokeWeight(10); // Beastly
+ * line(20, 70, 80, 70);
+ *
+ *
+ * noFill();
+ * stroke(255, 102, 0);
+ * line(85, 20, 10, 10);
+ * line(90, 90, 15, 80);
+ * stroke(0, 0, 0);
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ *
+ *
+ * background(0, 0, 0);
+ * noFill();
+ * stroke(255);
+ * bezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noFill();
+ *
+ * bezierDetail(5);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // prettier-ignore
+ * bezier(-40, -40, 0,
+ * 90, -40, 0,
+ * -90, 40, 0,
+ * 40, 40, 0);
+ * }
+ *
+ *
+ * noFill();
+ * let x1 = 85,
+ x2 = 10,
+ x3 = 90,
+ x4 = 15;
+ * let y1 = 20,
+ y2 = 10,
+ y3 = 90,
+ y4 = 80;
+ * bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ * fill(255);
+ * let steps = 10;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(x1, x2, x3, x4, t);
+ * let y = bezierPoint(y1, y2, y3, y4, t);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * let steps = 6;
+ * fill(255);
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * // Get the location of the point
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * // Get the tangent points
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * // Calculate an angle from the tangent points
+ * let a = atan2(ty, tx);
+ * a += PI;
+ * stroke(255, 102, 0);
+ * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);
+ * // The following line of code makes a line
+ * // inverse of the above line
+ * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);
+ * stroke(0);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * stroke(255, 102, 0);
+ * let steps = 16;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * let a = atan2(ty, tx);
+ * a -= HALF_PI;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ * noFill();
+ * stroke(255, 102, 0);
+ * curve(5, 26, 5, 26, 73, 24, 73, 61);
+ * stroke(0);
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * stroke(255, 102, 0);
+ * curve(73, 24, 73, 61, 15, 65, 15, 65);
+ *
+ *
+ * // Define the curve points as JavaScript objects
+ * let p1 = { x: 5, y: 26 },
+ p2 = { x: 73, y: 24 };
+ * let p3 = { x: 73, y: 61 },
+ p4 = { x: 15, y: 65 };
+ * noFill();
+ * stroke(255, 102, 0);
+ * curve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
+ * stroke(0);
+ * curve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);
+ * stroke(255, 102, 0);
+ * curve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);
+ *
+ *
+ * noFill();
+ * stroke(255, 102, 0);
+ * curve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);
+ * stroke(0);
+ * curve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);
+ * stroke(255, 102, 0);
+ * curve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ *
+ * curveDetail(5);
+ * }
+ * function draw() {
+ * background(200);
+ *
+ * curve(250, 600, 0, -30, 40, 0, 30, 30, 0, -250, 600, 0);
+ * }
+ *
+ *
+ * // Move the mouse left and right to see the curve change
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * let t = map(mouseX, 0, width, -5, 5);
+ * curveTightness(t);
+ * beginShape();
+ * curveVertex(10, 26);
+ * curveVertex(10, 26);
+ * curveVertex(83, 24);
+ * curveVertex(83, 61);
+ * curveVertex(25, 65);
+ * curveVertex(25, 65);
+ * endShape();
+ * }
+ *
+ *
+ * noFill();
+ * curve(5, 26, 5, 26, 73, 24, 73, 61);
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * fill(255);
+ * ellipseMode(CENTER);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 5, 73, 73, t);
+ * let y = curvePoint(26, 26, 24, 61, t);
+ * ellipse(x, y, 5, 5);
+ * x = curvePoint(5, 73, 73, 15, t);
+ * y = curvePoint(26, 24, 61, 65, t);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ * noFill();
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 73, 73, 15, t);
+ * let y = curvePoint(26, 24, 61, 65, t);
+ * //ellipse(x, y, 5, 5);
+ * let tx = curveTangent(5, 73, 73, 15, t);
+ * let ty = curveTangent(26, 24, 61, 65, t);
+ * let a = atan2(ty, tx);
+ * a -= PI / 2.0;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ * translate(50, 50);
+ * stroke(255, 0, 0);
+ * beginShape();
+ * // Exterior part of shape, clockwise winding
+ * vertex(-40, -40);
+ * vertex(40, -40);
+ * vertex(40, 40);
+ * vertex(-40, 40);
+ * // Interior part of shape, counter-clockwise winding
+ * beginContour();
+ * vertex(-20, -20);
+ * vertex(-20, 20);
+ * vertex(20, 20);
+ * vertex(20, -20);
+ * endContour();
+ * endShape(CLOSE);
+ *
+ *
+ * beginShape();
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape(CLOSE);
+ *
+ *
+ * beginShape(POINTS);
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ * beginShape(LINES);
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ * noFill();
+ * beginShape();
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ * noFill();
+ * beginShape();
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape(CLOSE);
+ *
+ *
+ * beginShape(TRIANGLES);
+ * vertex(30, 75);
+ * vertex(40, 20);
+ * vertex(50, 75);
+ * vertex(60, 20);
+ * vertex(70, 75);
+ * vertex(80, 20);
+ * endShape();
+ *
+ *
+ * beginShape(TRIANGLE_STRIP);
+ * vertex(30, 75);
+ * vertex(40, 20);
+ * vertex(50, 75);
+ * vertex(60, 20);
+ * vertex(70, 75);
+ * vertex(80, 20);
+ * vertex(90, 75);
+ * endShape();
+ *
+ *
+ * beginShape(TRIANGLE_FAN);
+ * vertex(57.5, 50);
+ * vertex(57.5, 15);
+ * vertex(92, 50);
+ * vertex(57.5, 85);
+ * vertex(22, 50);
+ * vertex(57.5, 15);
+ * endShape();
+ *
+ *
+ * beginShape(QUADS);
+ * vertex(30, 20);
+ * vertex(30, 75);
+ * vertex(50, 75);
+ * vertex(50, 20);
+ * vertex(65, 20);
+ * vertex(65, 75);
+ * vertex(85, 75);
+ * vertex(85, 20);
+ * endShape();
+ *
+ *
+ * beginShape(QUAD_STRIP);
+ * vertex(30, 20);
+ * vertex(30, 75);
+ * vertex(50, 20);
+ * vertex(50, 75);
+ * vertex(65, 20);
+ * vertex(65, 75);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * endShape();
+ *
+ *
+ * beginShape();
+ * vertex(20, 20);
+ * vertex(40, 20);
+ * vertex(40, 40);
+ * vertex(60, 40);
+ * vertex(60, 60);
+ * vertex(20, 60);
+ * endShape(CLOSE);
+ *
+ *
+ * noFill();
+ * beginShape();
+ * vertex(30, 20);
+ * bezierVertex(80, 0, 80, 75, 30, 75);
+ * endShape();
+ *
+ *
+ * beginShape();
+ * vertex(30, 20);
+ * bezierVertex(80, 0, 80, 75, 30, 75);
+ * bezierVertex(50, 80, 60, 25, 30, 20);
+ * endShape();
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * }
+ * function draw() {
+ * orbitControl();
+ * background(50);
+ * strokeWeight(4);
+ * stroke(255);
+ * point(-25, 30);
+ * point(25, 30);
+ * point(25, -30);
+ * point(-25, -30);
+ *
+ * strokeWeight(1);
+ * noFill();
+ *
+ * beginShape();
+ * vertex(-25, 30);
+ * bezierVertex(25, 30, 25, -30, -25, -30);
+ * endShape();
+ *
+ * beginShape();
+ * vertex(-25, 30, 20);
+ * bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20);
+ * endShape();
+ * }
+ *
+ *
+ * strokeWeight(5);
+ * point(84, 91);
+ * point(68, 19);
+ * point(21, 17);
+ * point(32, 91);
+ * strokeWeight(1);
+ *
+ * noFill();
+ * beginShape();
+ * curveVertex(84, 91);
+ * curveVertex(84, 91);
+ * curveVertex(68, 19);
+ * curveVertex(21, 17);
+ * curveVertex(32, 91);
+ * curveVertex(32, 91);
+ * endShape();
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * }
+ * function draw() {
+ * orbitControl();
+ * background(50);
+ * strokeWeight(4);
+ * stroke(255);
+ *
+ * point(-25, 25);
+ * point(-25, 25);
+ * point(-25, -25);
+ * point(25, -25);
+ * point(25, 25);
+ * point(25, 25);
+ *
+ * strokeWeight(1);
+ * noFill();
+ *
+ * beginShape();
+ * curveVertex(-25, 25);
+ * curveVertex(-25, 25);
+ * curveVertex(-25, -25);
+ * curveVertex(25, -25);
+ * curveVertex(25, 25);
+ * curveVertex(25, 25);
+ * endShape();
+ *
+ * beginShape();
+ * curveVertex(-25, 25, 20);
+ * curveVertex(-25, 25, 20);
+ * curveVertex(-25, -25, 20);
+ * curveVertex(25, -25, 20);
+ * curveVertex(25, 25, 20);
+ * curveVertex(25, 25, 20);
+ * endShape();
+ * }
+ *
+ *
+ * translate(50, 50);
+ * stroke(255, 0, 0);
+ * beginShape();
+ * // Exterior part of shape, clockwise winding
+ * vertex(-40, -40);
+ * vertex(40, -40);
+ * vertex(40, 40);
+ * vertex(-40, 40);
+ * // Interior part of shape, counter-clockwise winding
+ * beginContour();
+ * vertex(-20, -20);
+ * vertex(-20, 20);
+ * vertex(20, 20);
+ * vertex(20, -20);
+ * endContour();
+ * endShape(CLOSE);
+ *
+ *
+ * noFill();
+ *
+ * beginShape();
+ * vertex(20, 20);
+ * vertex(45, 20);
+ * vertex(45, 80);
+ * endShape(CLOSE);
+ *
+ * beginShape();
+ * vertex(50, 20);
+ * vertex(75, 20);
+ * vertex(75, 80);
+ * endShape();
+ *
+ *
+ * strokeWeight(5);
+ * point(20, 20);
+ * point(80, 20);
+ * point(50, 50);
+ *
+ * noFill();
+ * strokeWeight(1);
+ * beginShape();
+ * vertex(20, 20);
+ * quadraticVertex(80, 20, 50, 50);
+ * endShape();
+ *
+ *
+ * strokeWeight(5);
+ * point(20, 20);
+ * point(80, 20);
+ * point(50, 50);
+ *
+ * point(20, 80);
+ * point(80, 80);
+ * point(80, 60);
+ *
+ * noFill();
+ * strokeWeight(1);
+ * beginShape();
+ * vertex(20, 20);
+ * quadraticVertex(80, 20, 50, 50);
+ * quadraticVertex(20, 80, 80, 80);
+ * vertex(80, 60);
+ * endShape();
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * }
+ * function draw() {
+ * orbitControl();
+ * background(50);
+ * strokeWeight(4);
+ * stroke(255);
+ *
+ * point(-35, -35);
+ * point(35, -35);
+ * point(0, 0);
+ * point(-35, 35);
+ * point(35, 35);
+ * point(35, 10);
+ *
+ * strokeWeight(1);
+ * noFill();
+ *
+ * beginShape();
+ * vertex(-35, -35);
+ * quadraticVertex(35, -35, 0, 0);
+ * quadraticVertex(-35, 35, 35, 35);
+ * vertex(35, 10);
+ * endShape();
+ *
+ * beginShape();
+ * vertex(-35, -35, 20);
+ * quadraticVertex(35, -35, 20, 0, 0, 20);
+ * quadraticVertex(-35, 35, 20, 35, 35, 20);
+ * vertex(35, 10, 20);
+ * endShape();
+ * }
+ *
+ *
+ * strokeWeight(3);
+ * beginShape(POINTS);
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ * createCanvas(100, 100, WEBGL);
+ * background(240, 240, 240);
+ * fill(237, 34, 93);
+ * noStroke();
+ * beginShape();
+ * vertex(0, 35);
+ * vertex(35, 0);
+ * vertex(0, -35);
+ * vertex(-35, 0);
+ * endShape();
+ *
+ *
+ * createCanvas(100, 100, WEBGL);
+ * background(240, 240, 240);
+ * fill(237, 34, 93);
+ * noStroke();
+ * beginShape();
+ * vertex(-10, 10);
+ * vertex(0, 35);
+ * vertex(10, 10);
+ * vertex(35, 0);
+ * vertex(10, -8);
+ * vertex(0, -35);
+ * vertex(-10, -8);
+ * vertex(-35, 0);
+ * endShape();
+ *
+ *
+ * strokeWeight(3);
+ * stroke(237, 34, 93);
+ * beginShape(LINES);
+ * vertex(10, 35);
+ * vertex(90, 35);
+ * vertex(10, 65);
+ * vertex(90, 65);
+ * vertex(35, 10);
+ * vertex(35, 90);
+ * vertex(65, 10);
+ * vertex(65, 90);
+ * endShape();
+ *
+ *
+ * // Click to change the number of sides.
+ * // In WebGL mode, custom shapes will only
+ * // display hollow fill sections when
+ * // all calls to vertex() use the same z-value.
+ *
+ * let sides = 3;
+ * let angle, px, py;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * fill(237, 34, 93);
+ * strokeWeight(3);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateZ(frameCount * 0.01);
+ * ngon(sides, 0, 0, 80);
+ * }
+ *
+ * function mouseClicked() {
+ * if (sides > 6) {
+ * sides = 3;
+ * } else {
+ * sides++;
+ * }
+ * }
+ *
+ * function ngon(n, x, y, d) {
+ * beginShape();
+ * for (let i = 0; i < n + 1; i++) {
+ * angle = TWO_PI / n * i;
+ * px = x + sin(angle) * d / 2;
+ * py = y - cos(angle) * d / 2;
+ * vertex(px, py, 0);
+ * }
+ * for (let i = 0; i < n + 1; i++) {
+ * angle = TWO_PI / n * i;
+ * px = x + sin(angle) * d / 4;
+ * py = y - cos(angle) * d / 4;
+ * vertex(px, py, 0);
+ * }
+ * endShape();
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * noLoop();
+ * }
+
+ * function draw() {
+ * line(10, 10, 90, 90);
+ * }
+ *
+ * let x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * noLoop();
+ * }
+ *
+ * function mouseReleased() {
+ * loop();
+ * }
+ *
+ * let x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * loop();
+ * }
+ *
+ * function mouseReleased() {
+ * noLoop();
+ * }
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * translate(50, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * translate(50, 0);
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ * let x = 0;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * x += 1;
+ * redraw();
+ * }
+ *
+ * let x = 0;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x += 1;
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * redraw(5);
+ * }
+ *
+ *
+ * @method applyMatrix
+ * @param {Number} a numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} b numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} c numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} d numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} e numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} f numbers which define the 2x3 matrix to be multiplied
+ * @chainable
+ * @example
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * let step = frameCount % 20;
+ * background(200);
+ * // Equivalent to translate(x, y);
+ * applyMatrix(1, 0, 0, 1, 40 + step, 50);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * let step = frameCount % 20;
+ * background(200);
+ * translate(50, 50);
+ * // Equivalent to scale(x, y);
+ * applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * let step = frameCount % 20;
+ * let angle = map(step, 0, 20, 0, TWO_PI);
+ * let cos_a = cos(angle);
+ * let sin_a = sin(angle);
+ * background(200);
+ * translate(50, 50);
+ * // Equivalent to rotate(angle);
+ * applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * let step = frameCount % 20;
+ * let angle = map(step, 0, 20, -PI / 4, PI / 4);
+ * background(200);
+ * translate(50, 50);
+ * // equivalent to shearX(angle);
+ * let shear_factor = 1 / tan(PI / 2 - angle);
+ * applyMatrix(1, 0, shear_factor, 1, 0, 0);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateY(PI / 6);
+ * stroke(153);
+ * box(35);
+ * let rad = millis() / 1000;
+ * // Set rotation angles
+ * let ct = cos(rad);
+ * let st = sin(rad);
+ * // Matrix for rotation around the Y axis
+ * // prettier-ignore
+ * applyMatrix( ct, 0.0, st, 0.0,
+ * 0.0, 1.0, 0.0, 0.0,
+ * -st, 0.0, ct, 0.0,
+ * 0.0, 0.0, 0.0, 1.0);
+ * stroke(255);
+ * box(50);
+ * }
+ *
+ *
+ * translate(50, 50);
+ * applyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);
+ * rect(0, 0, 20, 20);
+ * // Note that the translate is also reset.
+ * resetMatrix();
+ * rect(0, 0, 20, 20);
+ *
+ *
+ * translate(width / 2, height / 2);
+ * rotate(PI / 3.0);
+ * rect(-26, -26, 52, 52);
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(255);
+ * rotateX(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(255);
+ * rotateY(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(255);
+ * rotateZ(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ * rect(30, 20, 50, 50);
+ * scale(0.5);
+ * rect(30, 20, 50, 50);
+ *
+ *
+ * rect(30, 20, 50, 50);
+ * scale(0.5, 1.3);
+ * rect(30, 20, 50, 50);
+ *
+ *
+ * translate(width / 4, height / 4);
+ * shearX(PI / 4.0);
+ * rect(0, 0, 30, 30);
+ *
+ *
+ * translate(width / 4, height / 4);
+ * shearY(PI / 4.0);
+ * rect(0, 0, 30, 30);
+ *
+ *
+ * translate(30, 20);
+ * rect(0, 0, 55, 55);
+ *
+ *
+ * rect(0, 0, 55, 55); // Draw rect at original 0,0
+ * translate(30, 20);
+ * rect(0, 0, 55, 55); // Draw rect at new 0,0
+ * translate(14, 14);
+ * rect(0, 0, 55, 55); // Draw rect at new 0,0
+ *
+ *
+ * function draw() {
+ * background(200);
+ * rectMode(CENTER);
+ * translate(width / 2, height / 2);
+ * translate(p5.Vector.fromAngle(millis() / 1000, 40));
+ * rect(0, 0, 20, 20);
+ * }
+ *
+ *
+ * // Type to change the letter in the
+ * // center of the canvas.
+ * // If you reload the page, it will
+ * // still display the last key you entered
+ *
+ * let myText;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * myText = getItem('myText');
+ * if (myText === null) {
+ * myText = '';
+ * }
+ * }
+ *
+ * function draw() {
+ * textSize(40);
+ * background(255);
+ * text(myText, width / 2, height / 2);
+ * }
+ *
+ * function keyPressed() {
+ * myText = key;
+ * storeItem('myText', myText);
+ * }
+ *
+ * // Click the mouse to change
+ * // the color of the background
+ * // Once you have changed the color
+ * // it will stay changed even when you
+ * // reload the page.
+ *
+ * let myColor;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * myColor = getItem('myColor');
+ * }
+ *
+ * function draw() {
+ * if (myColor !== null) {
+ * background(myColor);
+ * }
+ * }
+ *
+ * function mousePressed() {
+ * myColor = color(random(255), random(255), random(255));
+ * storeItem('myColor', myColor);
+ * }
+ *
+ * function setup() {
+ * let myNum = 10;
+ * let myBool = false;
+ * storeItem('myNum', myNum);
+ * storeItem('myBool', myBool);
+ * print(getItem('myNum')); // logs 10 to the console
+ * print(getItem('myBool')); // logs false to the console
+ * clearStorage();
+ * print(getItem('myNum')); // logs null to the console
+ * print(getItem('myBool')); // logs null to the console
+ * }
+ *
+ * function setup() {
+ * let myVar = 10;
+ * storeItem('myVar', myVar);
+ * print(getItem('myVar')); // logs 10 to the console
+ * removeItem('myVar');
+ * print(getItem('myVar')); // logs null to the console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * print(myDictionary.hasKey('p5')); // logs true to console
+ *
+ * let anotherDictionary = createStringDict({ happy: 'coding' });
+ * print(anotherDictionary.hasKey('happy')); // logs true to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict(100, 42);
+ * print(myDictionary.hasKey(100)); // logs true to console
+ *
+ * let anotherDictionary = createNumberDict({ 200: 84 });
+ * print(anotherDictionary.hasKey(200)); // logs true to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict(1, 10);
+ * myDictionary.create(2, 20);
+ * myDictionary.create(3, 30);
+ * print(myDictionary.size()); // logs 3 to the console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * print(myDictionary.hasKey('p5')); // logs true to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * let myValue = myDictionary.get('p5');
+ * print(myValue === 'js'); // logs true to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * myDictionary.set('p5', 'JS');
+ * myDictionary.print(); // logs "key: p5 - value: JS" to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * myDictionary.create('happy', 'coding');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: js, key: happy - value: coding" to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * print(myDictionary.hasKey('p5')); // prints 'true'
+ * myDictionary.clear();
+ * print(myDictionary.hasKey('p5')); // prints 'false'
+ * }
+ *
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * myDictionary.create('happy', 'coding');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: js, key: happy - value: coding" to console
+ * myDictionary.remove('p5');
+ * myDictionary.print();
+ * // above logs "key: happy value: coding" to console
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createStringDict('p5', 'js');
+ * myDictionary.create('happy', 'coding');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: js, key: happy - value: coding" to console
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * createStringDict({
+ * john: 1940,
+ * paul: 1942,
+ * george: 1943,
+ * ringo: 1940
+ * }).saveTable('beatles');
+ * }
+ * }
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * createStringDict({
+ * john: 1940,
+ * paul: 1942,
+ * george: 1943,
+ * ringo: 1940
+ * }).saveJSON('beatles');
+ * }
+ * }
+ *
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict(2, 5);
+ * myDictionary.add(2, 2);
+ * print(myDictionary.get(2)); // logs 7 to console.
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict(2, 5);
+ * myDictionary.sub(2, 2);
+ * print(myDictionary.get(2)); // logs 3 to console.
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict(2, 4);
+ * myDictionary.mult(2, 2);
+ * print(myDictionary.get(2)); // logs 8 to console.
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict(2, 8);
+ * myDictionary.div(2, 2);
+ * print(myDictionary.get(2)); // logs 4 to console.
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
+ * let lowestValue = myDictionary.minValue(); // value is -10
+ * print(lowestValue);
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
+ * let highestValue = myDictionary.maxValue(); // value is 3
+ * print(highestValue);
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
+ * let lowestKey = myDictionary.minKey(); // value is 1.2
+ * print(lowestKey);
+ * }
+ *
+ * function setup() {
+ * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
+ * let highestKey = myDictionary.maxKey(); // value is 4
+ * print(highestKey);
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * //translates canvas 50px down
+ * select('canvas').position(100, 100);
+ * }
+ *
+ * // these are all valid calls to select()
+ * let a = select('#moo');
+ * let b = select('#blah', '#myContainer');
+ * let c, e;
+ * if (b) {
+ * c = select('#foo', b);
+ * }
+ * let d = document.getElementById('beep');
+ * if (d) {
+ * e = select('p', d);
+ * }
+ * [a, b, c, d, e]; // unused
+ *
+ * function setup() {
+ * createButton('btn');
+ * createButton('2nd btn');
+ * createButton('3rd btn');
+ * let buttons = selectAll('button');
+ *
+ * for (let i = 0; i < buttons.length; i++) {
+ * buttons[i].size(100, 100);
+ * }
+ * }
+ *
+ * // these are all valid calls to selectAll()
+ * let a = selectAll('.moo');
+ * a = selectAll('div');
+ * a = selectAll('button', '#myContainer');
+ *
+ * let d = select('#container');
+ * a = selectAll('p', d);
+ *
+ * let f = document.getElementById('beep');
+ * a = select('.blah', f);
+ *
+ * a; // unused
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * createDiv('this is some text');
+ * createP('this is a paragraph');
+ * }
+ * function mousePressed() {
+ * removeElements(); // this will remove the div and p, not canvas
+ * }
+ *
+ * let sel;
+ *
+ * function setup() {
+ * textAlign(CENTER);
+ * background(200);
+ * sel = createSelect();
+ * sel.position(10, 10);
+ * sel.option('pear');
+ * sel.option('kiwi');
+ * sel.option('grape');
+ * sel.changed(mySelectEvent);
+ * }
+ *
+ * function mySelectEvent() {
+ * let item = sel.value();
+ * background(200);
+ * text("it's a " + item + '!', 50, 50);
+ * }
+ *
+ * let checkbox;
+ * let cnv;
+ *
+ * function setup() {
+ * checkbox = createCheckbox(' fill');
+ * checkbox.changed(changeFill);
+ * cnv = createCanvas(100, 100);
+ * cnv.position(0, 30);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * ellipse(50, 50, 50, 50);
+ * }
+ *
+ * function changeFill() {
+ * if (checkbox.checked()) {
+ * fill(0);
+ * } else {
+ * noFill();
+ * }
+ * }
+ *
+ * // Open your console to see the output
+ * function setup() {
+ * let inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ * createDiv('this is some text');
+ *
+ * createP('this is some text');
+ *
+ * createSpan('this is some text');
+ *
+ * createImg(
+ * 'https://p5js.org/assets/img/asterisk-01.png',
+ * 'the p5 magenta asterisk'
+ * );
+ *
+ * createA('http://p5js.org/', 'this is a link');
+ *
+ * let slider;
+ * function setup() {
+ * slider = createSlider(0, 255, 100);
+ * slider.position(10, 10);
+ * slider.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * let val = slider.value();
+ * background(val);
+ * }
+ *
+ * let slider;
+ * function setup() {
+ * colorMode(HSB);
+ * slider = createSlider(0, 360, 60, 40);
+ * slider.position(10, 10);
+ * slider.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * let val = slider.value();
+ * background(val, 100, 100, 1);
+ * }
+ *
+ * let button;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(0);
+ * button = createButton('click me');
+ * button.position(19, 19);
+ * button.mousePressed(changeBG);
+ * }
+ *
+ * function changeBG() {
+ * let val = random(255);
+ * background(val);
+ * }
+ *
+ * let checkbox;
+ *
+ * function setup() {
+ * checkbox = createCheckbox('label', false);
+ * checkbox.changed(myCheckedEvent);
+ * }
+ *
+ * function myCheckedEvent() {
+ * if (this.checked()) {
+ * console.log('Checking!');
+ * } else {
+ * console.log('Unchecking!');
+ * }
+ * }
+ *
+ * let sel;
+ *
+ * function setup() {
+ * textAlign(CENTER);
+ * background(200);
+ * sel = createSelect();
+ * sel.position(10, 10);
+ * sel.option('pear');
+ * sel.option('kiwi');
+ * sel.option('grape');
+ * sel.changed(mySelectEvent);
+ * }
+ *
+ * function mySelectEvent() {
+ * let item = sel.value();
+ * background(200);
+ * text('It is a ' + item + '!', 50, 50);
+ * }
+ *
+ * let radio;
+ *
+ * function setup() {
+ * radio = createRadio();
+ * radio.option('black');
+ * radio.option('white');
+ * radio.option('gray');
+ * radio.style('width', '60px');
+ * textAlign(CENTER);
+ * fill(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * let val = radio.value();
+ * background(val);
+ * text(val, width / 2, height / 2);
+ * }
+ *
+ * let radio;
+ *
+ * function setup() {
+ * radio = createRadio();
+ * radio.option('apple', 1);
+ * radio.option('bread', 2);
+ * radio.option('juice', 3);
+ * radio.style('width', '60px');
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * let val = radio.value();
+ * if (val) {
+ * text('item cost is $' + val, width / 2, height / 2);
+ * }
+ * }
+ *
+ * let inp1, inp2;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background('grey');
+ * inp1 = createColorPicker('#ff0000');
+ * inp2 = createColorPicker(color('yellow'));
+ * inp1.input(setShade1);
+ * inp2.input(setShade2);
+ * setMidShade();
+ * }
+ *
+ * function setMidShade() {
+ * // Finding a shade between the two
+ * let commonShade = lerpColor(inp1.color(), inp2.color(), 0.5);
+ * fill(commonShade);
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * function setShade1() {
+ * setMidShade();
+ * console.log('You are choosing shade 1 to be : ', this.value());
+ * }
+ * function setShade2() {
+ * setMidShade();
+ * console.log('You are choosing shade 2 to be : ', this.value());
+ * }
+ *
+ *
+ * function setup() {
+ * let inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ * let input;
+ * let img;
+ *
+ * function setup() {
+ * input = createFileInput(handleFile);
+ * input.position(0, 0);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * if (img) {
+ * image(img, 0, 0, width, height);
+ * }
+ * }
+ *
+ * function handleFile(file) {
+ * print(file);
+ * if (file.type === 'image') {
+ * img = createImg(file.data, '');
+ * img.hide();
+ * } else {
+ * img = null;
+ * }
+ * }
+ *
+ * let vid;
+ * function setup() {
+ * noCanvas();
+ *
+ * vid = createVideo(
+ * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],
+ * vidLoad
+ * );
+ *
+ * vid.size(100, 100);
+ * }
+ *
+ * // This function is called when the video loads
+ * function vidLoad() {
+ * vid.loop();
+ * vid.volume(0);
+ * }
+ *
+ * let ele;
+ * function setup() {
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * // here we set the element to autoplay
+ * // The element will play as soon
+ * // as it is able to do so.
+ * ele.autoplay(true);
+ * }
+ * Creates a new HTML5 <video> element that contains the audio/video + * feed from a webcam. The element is separate from the canvas and is + * displayed by default. The element can be hidden using .hide(). The feed + * can be drawn onto the canvas using image(). The loadedmetadata property can + * be used to detect when the element has fully loaded (see second example).
+ *More specific properties of the feed can be passing in a Constraints object. + * See the + * W3C + * spec for possible properties. Note that not all of these are supported + * by all browsers.
+ *Security note: A new browser security specification requires that getUserMedia, + * which is behind createCapture(), only works when you're running the code locally, + * or on HTTPS. Learn more here + * and here.
+ * + * @method createCapture + * @param {String|Constant|Object} type type of capture, either VIDEO or + * AUDIO if none specified, default both, + * or a Constraints object + * @param {Function} [callback] function to be called once + * stream has loaded + * @return {p5.Element} capture video p5.Element + * @example + *
+ * let capture;
+ *
+ * function setup() {
+ * createCanvas(480, 480);
+ * capture = createCapture(VIDEO);
+ * capture.hide();
+ * }
+ *
+ * function draw() {
+ * image(capture, 0, 0, width, width * capture.height / capture.width);
+ * filter(INVERT);
+ * }
+ *
+ * function setup() {
+ * createCanvas(480, 120);
+ * let constraints = {
+ * video: {
+ * mandatory: {
+ * minWidth: 1280,
+ * minHeight: 720
+ * },
+ * optional: [{ maxFrameRate: 10 }]
+ * },
+ * audio: true
+ * };
+ * createCapture(constraints, function(stream) {
+ * console.log(stream);
+ * });
+ * }
+ *
+ * let capture;
+ *
+ * function setup() {
+ * createCanvas(640, 480);
+ * capture = createCapture(VIDEO);
+ * }
+ * function draw() {
+ * background(0);
+ * if (capture.loadedmetadata) {
+ * let c = capture.get(0, 0, 100, 100);
+ * image(c, 0, 0);
+ * }
+ * }
+ *
+ */
+ _main.default.prototype.createCapture = function() {
+ _main.default._validateParameters('createCapture', arguments);
+ var useVideo = true;
+ var useAudio = true;
+ var constraints;
+ var cb;
+ for (var i = 0; i < arguments.length; i++) {
+ if (arguments[i] === _main.default.prototype.VIDEO) {
+ useAudio = false;
+ } else if (arguments[i] === _main.default.prototype.AUDIO) {
+ useVideo = false;
+ } else if (_typeof(arguments[i]) === 'object') {
+ constraints = arguments[i];
+ } else if (typeof arguments[i] === 'function') {
+ cb = arguments[i];
+ }
+ }
+ if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
+ var elt = document.createElement('video');
+ // required to work in iOS 11 & up:
+ elt.setAttribute('playsinline', '');
+
+ if (!constraints) {
+ constraints = { video: useVideo, audio: useAudio };
+ }
+
+ navigator.mediaDevices.getUserMedia(constraints).then(
+ function(stream) {
+ try {
+ if ('srcObject' in elt) {
+ elt.srcObject = stream;
+ } else {
+ elt.src = window.URL.createObjectURL(stream);
+ }
+ } catch (err) {
+ elt.src = stream;
+ }
+ },
+ function(e) {
+ console.log(e);
+ }
+ );
+ } else {
+ throw 'getUserMedia not supported in this browser';
+ }
+ var c = addElement(elt, this, true);
+ c.loadedmetadata = false;
+ // set width and height onload metadata
+ elt.addEventListener('loadedmetadata', function() {
+ elt.play();
+ if (elt.width) {
+ c.width = elt.videoWidth = elt.width;
+ c.height = elt.videoHeight = elt.height;
+ } else {
+ c.width = c.elt.width = elt.videoWidth;
+ c.height = c.elt.height = elt.videoHeight;
+ }
+ c.loadedmetadata = true;
+ if (cb) {
+ cb(elt.srcObject);
+ }
+ });
+ return c;
+ };
+
+ /**
+ * Creates element with given tag in the DOM with given content.
+ *
+ * @method createElement
+ * @param {String} tag tag for the new element
+ * @param {String} [content] html content to be inserted into the element
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * createElement('h2', 'im an h2 p5.element!');
+ *
+ */
+ _main.default.prototype.createElement = function(tag, content) {
+ _main.default._validateParameters('createElement', arguments);
+ var elt = document.createElement(tag);
+ if (typeof content !== 'undefined') {
+ elt.innerHTML = content;
+ }
+ return addElement(elt, this);
+ };
+
+ // =============================================================================
+ // p5.Element additions
+ // =============================================================================
+ /**
+ *
+ * Adds specified class to the element.
+ *
+ * @for p5.Element
+ * @method addClass
+ * @param {String} class name of class to add
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('div');
+ * div.addClass('myClass');
+ *
+ */
+ _main.default.Element.prototype.addClass = function(c) {
+ if (this.elt.className) {
+ if (!this.hasClass(c)) {
+ this.elt.className = this.elt.className + ' ' + c;
+ }
+ } else {
+ this.elt.className = c;
+ }
+ return this;
+ };
+
+ /**
+ *
+ * Removes specified class from the element.
+ *
+ * @method removeClass
+ * @param {String} class name of class to remove
+ * @chainable
+ * @example
+ *
+ * // In this example, a class is set when the div is created
+ * // and removed when mouse is pressed. This could link up
+ * // with a CSS style rule to toggle style properties.
+ *
+ * let div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('myClass');
+ * }
+ *
+ * function mousePressed() {
+ * div.removeClass('myClass');
+ * }
+ *
+ */
+ _main.default.Element.prototype.removeClass = function(c) {
+ // Note: Removing a class that does not exist does NOT throw an error in classList.remove method
+ this.elt.classList.remove(c);
+ return this;
+ };
+
+ /**
+ *
+ * Checks if specified class already set to element
+ *
+ * @method hasClass
+ * @returns {boolean} a boolean value if element has specified class
+ * @param c {String} class name of class to check
+ * @example
+ *
+ * let div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('show');
+ * }
+ *
+ * function mousePressed() {
+ * if (div.hasClass('show')) {
+ * div.addClass('show');
+ * } else {
+ * div.removeClass('show');
+ * }
+ * }
+ *
+ */
+ _main.default.Element.prototype.hasClass = function(c) {
+ return this.elt.classList.contains(c);
+ };
+
+ /**
+ *
+ * Toggles element class
+ *
+ * @method toggleClass
+ * @param c {String} class name to toggle
+ * @chainable
+ * @example
+ *
+ * let div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('show');
+ * }
+ *
+ * function mousePressed() {
+ * div.toggleClass('show');
+ * }
+ *
+ */
+ _main.default.Element.prototype.toggleClass = function(c) {
+ // classList also has a toggle() method, but we cannot use that yet as support is unclear.
+ // See https://github.com/processing/p5.js/issues/3631
+ // this.elt.classList.toggle(c);
+ if (this.elt.classList.contains(c)) {
+ this.elt.classList.remove(c);
+ } else {
+ this.elt.classList.add(c);
+ }
+ return this;
+ };
+
+ /**
+ *
+ * Attaches the element as a child to the parent specified.
+ * Accepts either a string ID, DOM node, or p5.Element.
+ * If no argument is specified, an array of children DOM nodes is returned.
+ *
+ * @method child
+ * @returns {Node[]} an array of child nodes
+ * @example
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div0.child(div1); // use p5.Element
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div1.id('apples');
+ * div0.child('apples'); // use id
+ *
+ *
+ * // this example assumes there is a div already on the page
+ * // with id "myChildDiv"
+ * let div0 = createDiv('this is the parent');
+ * let elt = document.getElementById('myChildDiv');
+ * div0.child(elt); // use element from page
+ *
+ */
+ /**
+ * @method child
+ * @param {String|p5.Element} [child] the ID, DOM node, or p5.Element
+ * to add to the current element
+ * @chainable
+ */
+ _main.default.Element.prototype.child = function(c) {
+ if (typeof c === 'undefined') {
+ return this.elt.childNodes;
+ }
+ if (typeof c === 'string') {
+ if (c[0] === '#') {
+ c = c.substring(1);
+ }
+ c = document.getElementById(c);
+ } else if (c instanceof _main.default.Element) {
+ c = c.elt;
+ }
+ this.elt.appendChild(c);
+ return this;
+ };
+
+ /**
+ * Centers a p5 Element either vertically, horizontally,
+ * or both, relative to its parent or according to
+ * the body if the Element has no parent. If no argument is passed
+ * the Element is aligned both vertically and horizontally.
+ *
+ * @method center
+ * @param {String} [align] passing 'vertical', 'horizontal' aligns element accordingly
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let div = createDiv('').size(10, 10);
+ * div.style('background-color', 'orange');
+ * div.center();
+ * }
+ *
+ */
+ _main.default.Element.prototype.center = function(align) {
+ var style = this.elt.style.display;
+ var hidden = this.elt.style.display === 'none';
+ var parentHidden = this.parent().style.display === 'none';
+ var pos = { x: this.elt.offsetLeft, y: this.elt.offsetTop };
+
+ if (hidden) this.show();
+
+ this.elt.style.display = 'block';
+ this.position(0, 0);
+
+ if (parentHidden) this.parent().style.display = 'block';
+
+ var wOffset = Math.abs(this.parent().offsetWidth - this.elt.offsetWidth);
+ var hOffset = Math.abs(this.parent().offsetHeight - this.elt.offsetHeight);
+ var y = pos.y;
+ var x = pos.x;
+
+ if (align === 'both' || align === undefined) {
+ this.position(wOffset / 2, hOffset / 2);
+ } else if (align === 'horizontal') {
+ this.position(wOffset / 2, y);
+ } else if (align === 'vertical') {
+ this.position(x, hOffset / 2);
+ }
+
+ this.style('display', style);
+
+ if (hidden) this.hide();
+
+ if (parentHidden) this.parent().style.display = 'none';
+
+ return this;
+ };
+
+ /**
+ *
+ * If an argument is given, sets the inner HTML of the element,
+ * replacing any existing html. If true is included as a second
+ * argument, html is appended instead of replacing existing html.
+ * If no arguments are given, returns
+ * the inner HTML of the element.
+ *
+ * @for p5.Element
+ * @method html
+ * @returns {String} the inner HTML of the element
+ * @example
+ *
+ * let div = createDiv('').size(100, 100);
+ * div.html('hi');
+ *
+ *
+ * let div = createDiv('Hello ').size(100, 100);
+ * div.html('World', true);
+ *
+ */
+ /**
+ * @method html
+ * @param {String} [html] the HTML to be placed inside the element
+ * @param {boolean} [append] whether to append HTML to existing
+ * @chainable
+ */
+ _main.default.Element.prototype.html = function() {
+ if (arguments.length === 0) {
+ return this.elt.innerHTML;
+ } else if (arguments[1]) {
+ this.elt.innerHTML += arguments[0];
+ return this;
+ } else {
+ this.elt.innerHTML = arguments[0];
+ return this;
+ }
+ };
+
+ /**
+ *
+ * Sets the position of the element relative to (0, 0) of the
+ * window. Essentially, sets position:absolute and left and top
+ * properties of style. If no arguments given returns the x and y position
+ * of the element in an object.
+ *
+ * @method position
+ * @returns {Object} the x and y position of the element in an object
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // positions canvas 50px to the right and 100px
+ * // below upper left corner of the window
+ * cnv.position(50, 100);
+ * }
+ *
+ */
+ /**
+ * @method position
+ * @param {Number} [x] x-position relative to upper left of window
+ * @param {Number} [y] y-position relative to upper left of window
+ * @chainable
+ */
+ _main.default.Element.prototype.position = function() {
+ if (arguments.length === 0) {
+ return { x: this.elt.offsetLeft, y: this.elt.offsetTop };
+ } else {
+ this.elt.style.position = 'absolute';
+ this.elt.style.left = arguments[0] + 'px';
+ this.elt.style.top = arguments[1] + 'px';
+ this.x = arguments[0];
+ this.y = arguments[1];
+ return this;
+ }
+ };
+
+ /* Helper method called by p5.Element.style() */
+ _main.default.Element.prototype._translate = function() {
+ this.elt.style.position = 'absolute';
+ // save out initial non-translate transform styling
+ var transform = '';
+ if (this.elt.style.transform) {
+ transform = this.elt.style.transform.replace(/translate3d\(.*\)/g, '');
+ transform = transform.replace(/translate[X-Z]?\(.*\)/g, '');
+ }
+ if (arguments.length === 2) {
+ this.elt.style.transform =
+ 'translate(' + arguments[0] + 'px, ' + arguments[1] + 'px)';
+ } else if (arguments.length > 2) {
+ this.elt.style.transform =
+ 'translate3d(' +
+ arguments[0] +
+ 'px,' +
+ arguments[1] +
+ 'px,' +
+ arguments[2] +
+ 'px)';
+ if (arguments.length === 3) {
+ this.elt.parentElement.style.perspective = '1000px';
+ } else {
+ this.elt.parentElement.style.perspective = arguments[3] + 'px';
+ }
+ }
+ // add any extra transform styling back on end
+ this.elt.style.transform += transform;
+ return this;
+ };
+
+ /* Helper method called by p5.Element.style() */
+ _main.default.Element.prototype._rotate = function() {
+ // save out initial non-rotate transform styling
+ var transform = '';
+ if (this.elt.style.transform) {
+ transform = this.elt.style.transform.replace(/rotate3d\(.*\)/g, '');
+ transform = transform.replace(/rotate[X-Z]?\(.*\)/g, '');
+ }
+
+ if (arguments.length === 1) {
+ this.elt.style.transform = 'rotate(' + arguments[0] + 'deg)';
+ } else if (arguments.length === 2) {
+ this.elt.style.transform =
+ 'rotate(' + arguments[0] + 'deg, ' + arguments[1] + 'deg)';
+ } else if (arguments.length === 3) {
+ this.elt.style.transform = 'rotateX(' + arguments[0] + 'deg)';
+ this.elt.style.transform += 'rotateY(' + arguments[1] + 'deg)';
+ this.elt.style.transform += 'rotateZ(' + arguments[2] + 'deg)';
+ }
+ // add remaining transform back on
+ this.elt.style.transform += transform;
+ return this;
+ };
+
+ /**
+ * Sets the given style (css) property (1st arg) of the element with the
+ * given value (2nd arg). If a single argument is given, .style()
+ * returns the value of the given property; however, if the single argument
+ * is given in css syntax ('text-align:center'), .style() sets the css
+ * appropriately.
+ *
+ * @method style
+ * @param {String} property property to be set
+ * @returns {String} value of property
+ * @example
+ *
+ * let myDiv = createDiv('I like pandas.');
+ * myDiv.style('font-size', '18px');
+ * myDiv.style('color', '#ff0000');
+ *
+ *
+ * let col = color(25, 23, 200, 50);
+ * let button = createButton('button');
+ * button.style('background-color', col);
+ * button.position(10, 10);
+ *
+ *
+ * let myDiv;
+ * function setup() {
+ * background(200);
+ * myDiv = createDiv('I like gray.');
+ * myDiv.position(20, 20);
+ * }
+ *
+ * function draw() {
+ * myDiv.style('font-size', mouseX + 'px');
+ * }
+ *
+ */
+ /**
+ * @method style
+ * @param {String} property
+ * @param {String|Number|p5.Color} value value to assign to property
+ * @return {String} current value of property, if no value is given as second argument
+ * @chainable
+ */
+ _main.default.Element.prototype.style = function(prop, val) {
+ var self = this;
+
+ if (val instanceof _main.default.Color) {
+ val =
+ 'rgba(' +
+ val.levels[0] +
+ ',' +
+ val.levels[1] +
+ ',' +
+ val.levels[2] +
+ ',' +
+ val.levels[3] / 255 +
+ ')';
+ }
+
+ if (typeof val === 'undefined') {
+ // input provided as single line string
+ if (prop.indexOf(':') === -1) {
+ var styles = window.getComputedStyle(self.elt);
+ var style = styles.getPropertyValue(prop);
+ return style;
+ } else {
+ var attrs = prop.split(';');
+ for (var i = 0; i < attrs.length; i++) {
+ var parts = attrs[i].split(':');
+ if (parts[0] && parts[1]) {
+ this.elt.style[parts[0].trim()] = parts[1].trim();
+ }
+ }
+ }
+ } else {
+ // input provided as key,val pair
+ this.elt.style[prop] = val;
+ if (
+ prop === 'width' ||
+ prop === 'height' ||
+ prop === 'left' ||
+ prop === 'top'
+ ) {
+ var numVal = val.replace(/\D+/g, '');
+ this[prop] = parseInt(numVal, 10);
+ }
+ }
+ return this;
+ };
+
+ /**
+ *
+ * Adds a new attribute or changes the value of an existing attribute
+ * on the specified element. If no value is specified, returns the
+ * value of the given attribute, or null if attribute is not set.
+ *
+ * @method attribute
+ * @return {String} value of attribute
+ *
+ * @example
+ *
+ * let myDiv = createDiv('I like pandas.');
+ * myDiv.attribute('align', 'center');
+ *
+ */
+ /**
+ * @method attribute
+ * @param {String} attr attribute to set
+ * @param {String} value value to assign to attribute
+ * @chainable
+ */
+ _main.default.Element.prototype.attribute = function(attr, value) {
+ //handling for checkboxes and radios to ensure options get
+ //attributes not divs
+ if (
+ this.elt.firstChild != null &&
+ (this.elt.firstChild.type === 'checkbox' ||
+ this.elt.firstChild.type === 'radio')
+ ) {
+ if (typeof value === 'undefined') {
+ return this.elt.firstChild.getAttribute(attr);
+ } else {
+ for (var i = 0; i < this.elt.childNodes.length; i++) {
+ this.elt.childNodes[i].setAttribute(attr, value);
+ }
+ }
+ } else if (typeof value === 'undefined') {
+ return this.elt.getAttribute(attr);
+ } else {
+ this.elt.setAttribute(attr, value);
+ return this;
+ }
+ };
+
+ /**
+ *
+ * Removes an attribute on the specified element.
+ *
+ * @method removeAttribute
+ * @param {String} attr attribute to remove
+ * @chainable
+ *
+ * @example
+ *
+ * let button;
+ * let checkbox;
+ *
+ * function setup() {
+ * checkbox = createCheckbox('enable', true);
+ * checkbox.changed(enableButton);
+ * button = createButton('button');
+ * button.position(10, 10);
+ * }
+ *
+ * function enableButton() {
+ * if (this.checked()) {
+ * // Re-enable the button
+ * button.removeAttribute('disabled');
+ * } else {
+ * // Disable the button
+ * button.attribute('disabled', '');
+ * }
+ * }
+ *
+ */
+ _main.default.Element.prototype.removeAttribute = function(attr) {
+ if (
+ this.elt.firstChild != null &&
+ (this.elt.firstChild.type === 'checkbox' ||
+ this.elt.firstChild.type === 'radio')
+ ) {
+ for (var i = 0; i < this.elt.childNodes.length; i++) {
+ this.elt.childNodes[i].removeAttribute(attr);
+ }
+ }
+ this.elt.removeAttribute(attr);
+ return this;
+ };
+
+ /**
+ * Either returns the value of the element if no arguments
+ * given, or sets the value of the element.
+ *
+ * @method value
+ * @return {String|Number} value of the element
+ * @example
+ *
+ * // gets the value
+ * let inp;
+ * function setup() {
+ * inp = createInput('');
+ * }
+ *
+ * function mousePressed() {
+ * print(inp.value());
+ * }
+ *
+ *
+ * // sets the value
+ * let inp;
+ * function setup() {
+ * inp = createInput('myValue');
+ * }
+ *
+ * function mousePressed() {
+ * inp.value('myValue');
+ * }
+ *
+ */
+ /**
+ * @method value
+ * @param {String|Number} value
+ * @chainable
+ */
+ _main.default.Element.prototype.value = function() {
+ if (arguments.length > 0) {
+ this.elt.value = arguments[0];
+ return this;
+ } else {
+ if (this.elt.type === 'range') {
+ return parseFloat(this.elt.value);
+ } else return this.elt.value;
+ }
+ };
+
+ /**
+ *
+ * Shows the current element. Essentially, setting display:block for the style.
+ *
+ * @method show
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('div');
+ * div.style('display', 'none');
+ * div.show(); // turns display to block
+ *
+ */
+ _main.default.Element.prototype.show = function() {
+ this.elt.style.display = 'block';
+ return this;
+ };
+
+ /**
+ * Hides the current element. Essentially, setting display:none for the style.
+ *
+ * @method hide
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('this is a div');
+ * div.hide();
+ *
+ */
+ _main.default.Element.prototype.hide = function() {
+ this.elt.style.display = 'none';
+ return this;
+ };
+
+ /**
+ *
+ * Sets the width and height of the element. AUTO can be used to
+ * only adjust one dimension at a time. If no arguments are given, it
+ * returns the width and height of the element in an object. In case of
+ * elements which need to be loaded, such as images, it is recommended
+ * to call the function after the element has finished loading.
+ *
+ * @method size
+ * @return {Object} the width and height of the element in an object
+ * @example
+ *
+ * let div = createDiv('this is a div');
+ * div.size(100, 100);
+ * let img = createImg(
+ * 'assets/rockies.jpg',
+ * 'A tall mountain with a small forest and field in front of it on a sunny day',
+ * '',
+ * () => {
+ * img.size(10, AUTO);
+ * }
+ * );
+ *
+ */
+ /**
+ * @method size
+ * @param {Number|Constant} w width of the element, either AUTO, or a number
+ * @param {Number|Constant} [h] height of the element, either AUTO, or a number
+ * @chainable
+ */
+ _main.default.Element.prototype.size = function(w, h) {
+ if (arguments.length === 0) {
+ return { width: this.elt.offsetWidth, height: this.elt.offsetHeight };
+ } else {
+ var aW = w;
+ var aH = h;
+ var AUTO = _main.default.prototype.AUTO;
+ if (aW !== AUTO || aH !== AUTO) {
+ if (aW === AUTO) {
+ aW = h * this.width / this.height;
+ } else if (aH === AUTO) {
+ aH = w * this.height / this.width;
+ }
+ // set diff for cnv vs normal div
+ if (this.elt instanceof HTMLCanvasElement) {
+ var j = {};
+ var k = this.elt.getContext('2d');
+ var prop;
+ for (prop in k) {
+ j[prop] = k[prop];
+ }
+ this.elt.setAttribute('width', aW * this._pInst._pixelDensity);
+ this.elt.setAttribute('height', aH * this._pInst._pixelDensity);
+ this.elt.style.width = aW + 'px';
+ this.elt.style.height = aH + 'px';
+ this._pInst.scale(this._pInst._pixelDensity, this._pInst._pixelDensity);
+ for (prop in j) {
+ this.elt.getContext('2d')[prop] = j[prop];
+ }
+ } else {
+ this.elt.style.width = aW + 'px';
+ this.elt.style.height = aH + 'px';
+ this.elt.width = aW;
+ this.elt.height = aH;
+ }
+
+ this.width = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+
+ if (this._pInst && this._pInst._curElement) {
+ // main canvas associated with p5 instance
+ if (this._pInst._curElement.elt === this.elt) {
+ this._pInst._setProperty('width', this.elt.offsetWidth);
+ this._pInst._setProperty('height', this.elt.offsetHeight);
+ }
+ }
+ }
+ return this;
+ }
+ };
+
+ /**
+ * Removes the element and deregisters all listeners.
+ * @method remove
+ * @example
+ *
+ * let myDiv = createDiv('this is some text');
+ * myDiv.remove();
+ *
+ */
+ _main.default.Element.prototype.remove = function() {
+ // deregister events
+ for (var ev in this._events) {
+ this.elt.removeEventListener(ev, this._events[ev]);
+ }
+ if (this.elt && this.elt.parentNode) {
+ this.elt.parentNode.removeChild(this.elt);
+ }
+ delete this;
+ };
+
+ /**
+ * Registers a callback that gets called every time a file that is
+ * dropped on the element has been loaded.
+ * p5 will load every dropped file into memory and pass it as a p5.File object to the callback.
+ * Multiple files dropped at the same time will result in multiple calls to the callback.
+ *
+ * You can optionally pass a second callback which will be registered to the raw
+ * drop event.
+ * The callback will thus be provided the original
+ * DragEvent.
+ * Dropping multiple files at the same time will trigger the second callback once per drop,
+ * whereas the first callback will trigger for each loaded file.
+ *
+ * @method drop
+ * @param {Function} callback callback to receive loaded file, called for each file dropped.
+ * @param {Function} [fxn] callback triggered once when files are dropped with the drop event.
+ * @chainable
+ * @example
+ *
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('drop file', width / 2, height / 2);
+ * c.drop(gotFile);
+ * }
+ *
+ * function gotFile(file) {
+ * background(200);
+ * text('received file:', width / 2, height / 2);
+ * text(file.name, width / 2, height / 2 + 50);
+ * }
+ *
+ *
+ *
+ * let img;
+ *
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('drop image', width / 2, height / 2);
+ * c.drop(gotFile);
+ * }
+ *
+ * function draw() {
+ * if (img) {
+ * image(img, 0, 0, width, height);
+ * }
+ * }
+ *
+ * function gotFile(file) {
+ * img = createImg(file.data, '').hide();
+ * }
+ *
+ *
+ * @alt
+ * Canvas turns into whatever image is dragged/dropped onto it.
+ */
+ _main.default.Element.prototype.drop = function(callback, fxn) {
+ // Is the file stuff supported?
+ if (window.File && window.FileReader && window.FileList && window.Blob) {
+ if (!this._dragDisabled) {
+ this._dragDisabled = true;
+
+ var preventDefault = function preventDefault(evt) {
+ evt.preventDefault();
+ };
+
+ // If you want to be able to drop you've got to turn off
+ // a lot of default behavior.
+ // avoid `attachListener` here, since it overrides other handlers.
+ this.elt.addEventListener('dragover', preventDefault);
+
+ // If this is a drag area we need to turn off the default behavior
+ this.elt.addEventListener('dragleave', preventDefault);
+ }
+
+ // Deal with the files
+ _main.default.Element._attachListener(
+ 'drop',
+ function(evt) {
+ evt.preventDefault();
+ // Call the second argument as a callback that receives the raw drop event
+ if (typeof fxn === 'function') {
+ fxn.call(this, evt);
+ }
+ // A FileList
+ var files = evt.dataTransfer.files;
+
+ // Load each one and trigger the callback
+ for (var i = 0; i < files.length; i++) {
+ var f = files[i];
+ _main.default.File._load(f, callback);
+ }
+ },
+ this
+ );
+ } else {
+ console.log('The File APIs are not fully supported in this browser.');
+ }
+
+ return this;
+ };
+
+ // =============================================================================
+ // p5.MediaElement additions
+ // =============================================================================
+
+ /**
+ * Extends p5.Element to handle audio and video. In addition to the methods
+ * of p5.Element, it also contains methods for controlling media. It is not
+ * called directly, but p5.MediaElements are created by calling createVideo,
+ * createAudio, and createCapture.
+ *
+ * @class p5.MediaElement
+ * @constructor
+ * @param {String} elt DOM node that is wrapped
+ */
+ _main.default.MediaElement = function(elt, pInst) {
+ _main.default.Element.call(this, elt, pInst);
+
+ var self = this;
+ this.elt.crossOrigin = 'anonymous';
+
+ this._prevTime = 0;
+ this._cueIDCounter = 0;
+ this._cues = [];
+ this._pixelsState = this;
+ this._pixelDensity = 1;
+ this._modified = false;
+
+ /**
+ * Path to the media element source.
+ *
+ * @property src
+ * @return {String} src
+ * @example
+ *
+ * let ele;
+ *
+ * function setup() {
+ * background(250);
+ *
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * //We'll set up our example so that
+ * //when you click on the text,
+ * //an alert box displays the MediaElement's
+ * //src field.
+ * textAlign(CENTER);
+ * text('Click Me!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Show our p5.MediaElement's src field
+ * alert(ele.src);
+ * }
+ * }
+ *
+ */
+ Object.defineProperty(self, 'src', {
+ get: function get() {
+ var firstChildSrc = self.elt.children[0].src;
+ var srcVal = self.elt.src === window.location.href ? '' : self.elt.src;
+ var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc;
+ return ret;
+ },
+ set: function set(newValue) {
+ for (var i = 0; i < self.elt.children.length; i++) {
+ self.elt.removeChild(self.elt.children[i]);
+ }
+ var source = document.createElement('source');
+ source.src = newValue;
+ elt.appendChild(source);
+ self.elt.src = newValue;
+ self.modified = true;
+ }
+ });
+
+ // private _onended callback, set by the method: onended(callback)
+ self._onended = function() {};
+ self.elt.onended = function() {
+ self._onended(self);
+ };
+ };
+ _main.default.MediaElement.prototype = Object.create(
+ _main.default.Element.prototype
+ );
+
+ /**
+ * Play an HTML5 media element.
+ *
+ * @method play
+ * @chainable
+ * @example
+ *
+ * let ele;
+ *
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Here we call the play() function on
+ * //the p5.MediaElement we created above.
+ * //This will start the audio sample.
+ * ele.play();
+ *
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.play = function() {
+ if (this.elt.currentTime === this.elt.duration) {
+ this.elt.currentTime = 0;
+ }
+ var promise;
+ if (this.elt.readyState > 1) {
+ promise = this.elt.play();
+ } else {
+ // in Chrome, playback cannot resume after being stopped and must reload
+ this.elt.load();
+ promise = this.elt.play();
+ }
+ if (promise && promise.catch) {
+ promise.catch(function(e) {
+ console.log('WARN: Element play method raised an error asynchronously', e);
+ });
+ }
+ return this;
+ };
+
+ /**
+ * Stops an HTML5 media element (sets current time to zero).
+ *
+ * @method stop
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and stops a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //if the sample is currently playing
+ * //calling the stop() function on
+ * //our p5.MediaElement will stop
+ * //it and reset its current
+ * //time to 0 (i.e. it will start
+ * //at the beginning the next time
+ * //you play it)
+ * ele.stop();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to play!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.stop = function() {
+ this.elt.pause();
+ this.elt.currentTime = 0;
+ return this;
+ };
+
+ /**
+ * Pauses an HTML5 media element.
+ *
+ * @method pause
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and pauses a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //Calling pause() on our
+ * //p5.MediaElement will stop it
+ * //playing, but when we call the
+ * //loop() or play() functions
+ * //the sample will start from
+ * //where we paused it.
+ * ele.pause();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to resume!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.pause() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to pause!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.pause = function() {
+ this.elt.pause();
+ return this;
+ };
+
+ /**
+ * Set 'loop' to true for an HTML5 media element, and starts playing.
+ *
+ * @method loop
+ * @chainable
+ * @example
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsLooping = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (!sampleIsLooping) {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsLooping = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * } else {
+ * ele.stop();
+ *
+ * sampleIsLooping = false;
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.loop = function() {
+ this.elt.setAttribute('loop', true);
+ this.play();
+ return this;
+ };
+ /**
+ * Set 'loop' to false for an HTML5 media element. Element will stop
+ * when it reaches the end.
+ *
+ * @method noLoop
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and stops loop of sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * ele.noLoop();
+ * text('No more Loops!', width / 2, height / 2);
+ * } else {
+ * ele.loop();
+ * sampleIsPlaying = true;
+ * text('Click to stop looping!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ *
+ */
+ _main.default.MediaElement.prototype.noLoop = function() {
+ this.elt.setAttribute('loop', false);
+ return this;
+ };
+
+ /**
+ * Set HTML5 media element to autoplay or not.
+ *
+ * @method autoplay
+ * @param {Boolean} autoplay whether the element should autoplay
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.autoplay = function(val) {
+ this.elt.setAttribute('autoplay', val);
+ return this;
+ };
+
+ /**
+ * Sets volume for this HTML5 media element. If no argument is given,
+ * returns the current volume.
+ *
+ * @method volume
+ * @return {Number} current volume
+ *
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * // p5.MediaElement objects are usually created
+ * // by calling the createAudio(), createVideo(),
+ * // and createCapture() functions.
+ * // In this example we create
+ * // a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ * function mouseClicked() {
+ * // Here we call the volume() function
+ * // on the sound element to set its volume
+ * // Volume must be between 0.0 and 1.0
+ * ele.volume(0.2);
+ * ele.play();
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ *
+ *
+ * let audio;
+ * let counter = 0;
+ *
+ * function loaded() {
+ * audio.play();
+ * }
+ *
+ * function setup() {
+ * audio = createAudio('assets/lucky_dragons.mp3', loaded);
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (counter === 0) {
+ * background(0, 255, 0);
+ * text('volume(0.9)', width / 2, height / 2);
+ * } else if (counter === 1) {
+ * background(255, 255, 0);
+ * text('volume(0.5)', width / 2, height / 2);
+ * } else if (counter === 2) {
+ * background(255, 0, 0);
+ * text('volume(0.1)', width / 2, height / 2);
+ * }
+ * }
+ *
+ * function mousePressed() {
+ * counter++;
+ * if (counter === 0) {
+ * audio.volume(0.9);
+ * } else if (counter === 1) {
+ * audio.volume(0.5);
+ * } else if (counter === 2) {
+ * audio.volume(0.1);
+ * } else {
+ * counter = 0;
+ * audio.volume(0.9);
+ * }
+ * }
+ *
+ *
+ */
+ /**
+ * @method volume
+ * @param {Number} val volume between 0.0 and 1.0
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.volume = function(val) {
+ if (typeof val === 'undefined') {
+ return this.elt.volume;
+ } else {
+ this.elt.volume = val;
+ }
+ };
+
+ /**
+ * If no arguments are given, returns the current playback speed of the
+ * element. The speed parameter sets the speed where 2.0 will play the
+ * element twice as fast, 0.5 will play at half the speed, and -1 will play
+ * the element in normal speed in reverse.(Note that not all browsers support
+ * backward playback and even if they do, playback might not be smooth.)
+ *
+ * @method speed
+ * @return {Number} current playback speed of the element
+ *
+ * @example
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ * let button;
+ *
+ * function setup() {
+ * createCanvas(710, 400);
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * ele.loop();
+ * background(200);
+ *
+ * button = createButton('2x speed');
+ * button.position(100, 68);
+ * button.mousePressed(twice_speed);
+ *
+ * button = createButton('half speed');
+ * button.position(200, 68);
+ * button.mousePressed(half_speed);
+ *
+ * button = createButton('reverse play');
+ * button.position(300, 68);
+ * button.mousePressed(reverse_speed);
+ *
+ * button = createButton('STOP');
+ * button.position(400, 68);
+ * button.mousePressed(stop_song);
+ *
+ * button = createButton('PLAY!');
+ * button.position(500, 68);
+ * button.mousePressed(play_speed);
+ * }
+ *
+ * function twice_speed() {
+ * ele.speed(2);
+ * }
+ *
+ * function half_speed() {
+ * ele.speed(0.5);
+ * }
+ *
+ * function reverse_speed() {
+ * ele.speed(-1);
+ * }
+ *
+ * function stop_song() {
+ * ele.stop();
+ * }
+ *
+ * function play_speed() {
+ * ele.play();
+ * }
+ *
+ */
+ /**
+ * @method speed
+ * @param {Number} speed speed multiplier for element playback
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.speed = function(val) {
+ if (typeof val === 'undefined') {
+ return this.presetPlaybackRate || this.elt.playbackRate;
+ } else {
+ if (this.loadedmetadata) {
+ this.elt.playbackRate = val;
+ } else {
+ this.presetPlaybackRate = val;
+ }
+ }
+ };
+
+ /**
+ * If no arguments are given, returns the current time of the element.
+ * If an argument is given the current time of the element is set to it.
+ *
+ * @method time
+ * @return {Number} current time (in seconds)
+ *
+ * @example
+ *
+ * let ele;
+ * let beginning = true;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('start at beginning', width / 2, height / 2);
+ * }
+ *
+ * // this function fires with click anywhere
+ * function mousePressed() {
+ * if (beginning === true) {
+ * // here we start the sound at the beginning
+ * // time(0) is not necessary here
+ * // as this produces the same result as
+ * // play()
+ * ele.play().time(0);
+ * background(200);
+ * text('jump 2 sec in', width / 2, height / 2);
+ * beginning = false;
+ * } else {
+ * // here we jump 2 seconds into the sound
+ * ele.play().time(2);
+ * background(250);
+ * text('start at beginning', width / 2, height / 2);
+ * beginning = true;
+ * }
+ * }
+ *
+ */
+ /**
+ * @method time
+ * @param {Number} time time to jump to (in seconds)
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.time = function(val) {
+ if (typeof val === 'undefined') {
+ return this.elt.currentTime;
+ } else {
+ this.elt.currentTime = val;
+ return this;
+ }
+ };
+
+ /**
+ * Returns the duration of the HTML5 media element.
+ *
+ * @method duration
+ * @return {Number} duration
+ *
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/doorbell.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to know the duration!', 10, 25, 70, 80);
+ * }
+ * function mouseClicked() {
+ * ele.play();
+ * background(200);
+ * //ele.duration dislpays the duration
+ * text(ele.duration() + ' seconds', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.duration = function() {
+ return this.elt.duration;
+ };
+ _main.default.MediaElement.prototype.pixels = [];
+ _main.default.MediaElement.prototype._ensureCanvas = function() {
+ if (!this.canvas) {
+ this.canvas = document.createElement('canvas');
+ this.drawingContext = this.canvas.getContext('2d');
+ this.setModified(true);
+ }
+ if (this.loadedmetadata) {
+ // wait for metadata for w/h
+ if (this.canvas.width !== this.elt.width) {
+ this.canvas.width = this.elt.width;
+ this.canvas.height = this.elt.height;
+ this.width = this.canvas.width;
+ this.height = this.canvas.height;
+ }
+
+ this.drawingContext.drawImage(
+ this.elt,
+ 0,
+ 0,
+ this.canvas.width,
+ this.canvas.height
+ );
+
+ this.setModified(true);
+ }
+ };
+ _main.default.MediaElement.prototype.loadPixels = function() {
+ this._ensureCanvas();
+ return _main.default.Renderer2D.prototype.loadPixels.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.updatePixels = function(x, y, w, h) {
+ if (this.loadedmetadata) {
+ // wait for metadata
+ this._ensureCanvas();
+ _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h);
+ }
+ this.setModified(true);
+ return this;
+ };
+ _main.default.MediaElement.prototype.get = function() {
+ this._ensureCanvas();
+ return _main.default.Renderer2D.prototype.get.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype._getPixel = function() {
+ this.loadPixels();
+ return _main.default.Renderer2D.prototype._getPixel.apply(this, arguments);
+ };
+
+ _main.default.MediaElement.prototype.set = function(x, y, imgOrCol) {
+ if (this.loadedmetadata) {
+ // wait for metadata
+ this._ensureCanvas();
+ _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+ }
+ };
+ _main.default.MediaElement.prototype.copy = function() {
+ this._ensureCanvas();
+ _main.default.prototype.copy.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.mask = function() {
+ this.loadPixels();
+ this.setModified(true);
+ _main.default.Image.prototype.mask.apply(this, arguments);
+ };
+ /**
+ * helper method for web GL mode to figure out if the element
+ * has been modified and might need to be re-uploaded to texture
+ * memory between frames.
+ * @method isModified
+ * @private
+ * @return {boolean} a boolean indicating whether or not the
+ * image has been updated or modified since last texture upload.
+ */
+ _main.default.MediaElement.prototype.isModified = function() {
+ return this._modified;
+ };
+ /**
+ * helper method for web GL mode to indicate that an element has been
+ * changed or unchanged since last upload. gl texture upload will
+ * set this value to false after uploading the texture; or might set
+ * it to true if metadata has become available but there is no actual
+ * texture data available yet..
+ * @method setModified
+ * @param {boolean} val sets whether or not the element has been
+ * modified.
+ * @private
+ */
+ _main.default.MediaElement.prototype.setModified = function(value) {
+ this._modified = value;
+ };
+ /**
+ * Schedule an event to be called when the audio or video
+ * element reaches the end. If the element is looping,
+ * this will not be called. The element is passed in
+ * as the argument to the onended callback.
+ *
+ * @method onended
+ * @param {Function} callback function to call when the
+ * soundfile has ended. The
+ * media element will be passed
+ * in as the argument to the
+ * callback.
+ * @chainable
+ * @example
+ *
+ * function setup() {
+ * let audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ * audioEl.onended(sayDone);
+ * }
+ *
+ * function sayDone(elt) {
+ * alert('done playing ' + elt.src);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.onended = function(callback) {
+ this._onended = callback;
+ return this;
+ };
+
+ /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/
+
+ /**
+ * Send the audio output of this element to a specified audioNode or
+ * p5.sound object. If no element is provided, connects to p5's master
+ * output. That connection is established when this method is first called.
+ * All connections are removed by the .disconnect() method.
+ *
+ * This method is meant to be used with the p5.sound.js addon library.
+ *
+ * @method connect
+ * @param {AudioNode|Object} audioNode AudioNode from the Web Audio API,
+ * or an object from the p5.sound library
+ */
+ _main.default.MediaElement.prototype.connect = function(obj) {
+ var audioContext, masterOutput;
+
+ // if p5.sound exists, same audio context
+ if (typeof _main.default.prototype.getAudioContext === 'function') {
+ audioContext = _main.default.prototype.getAudioContext();
+ masterOutput = _main.default.soundOut.input;
+ } else {
+ try {
+ audioContext = obj.context;
+ masterOutput = audioContext.destination;
+ } catch (e) {
+ throw 'connect() is meant to be used with Web Audio API or p5.sound.js';
+ }
+ }
+
+ // create a Web Audio MediaElementAudioSourceNode if none already exists
+ if (!this.audioSourceNode) {
+ this.audioSourceNode = audioContext.createMediaElementSource(this.elt);
+
+ // connect to master output when this method is first called
+ this.audioSourceNode.connect(masterOutput);
+ }
+
+ // connect to object if provided
+ if (obj) {
+ if (obj.input) {
+ this.audioSourceNode.connect(obj.input);
+ } else {
+ this.audioSourceNode.connect(obj);
+ }
+ } else {
+ // otherwise connect to master output of p5.sound / AudioContext
+ this.audioSourceNode.connect(masterOutput);
+ }
+ };
+
+ /**
+ * Disconnect all Web Audio routing, including to master output.
+ * This is useful if you want to re-route the output through
+ * audio effects, for example.
+ *
+ * @method disconnect
+ */
+ _main.default.MediaElement.prototype.disconnect = function() {
+ if (this.audioSourceNode) {
+ this.audioSourceNode.disconnect();
+ } else {
+ throw 'nothing to disconnect';
+ }
+ };
+
+ /*** SHOW / HIDE CONTROLS ***/
+
+ /**
+ * Show the default MediaElement controls, as determined by the web browser.
+ *
+ * @method showControls
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to Show Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.showControls();
+ * background(200);
+ * text('Controls Shown', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.showControls = function() {
+ // must set style for the element to show on the page
+ this.elt.style['text-align'] = 'inherit';
+ this.elt.controls = true;
+ };
+
+ /**
+ * Hide the default mediaElement controls.
+ * @method hideControls
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * ele.showControls();
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to hide Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.hideControls();
+ * background(200);
+ * text('Controls hidden', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.hideControls = function() {
+ this.elt.controls = false;
+ };
+
+ /*** SCHEDULE EVENTS ***/
+
+ // Cue inspired by JavaScript setTimeout, and the
+ // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org
+ var Cue = function Cue(callback, time, id, val) {
+ this.callback = callback;
+ this.time = time;
+ this.id = id;
+ this.val = val;
+ };
+
+ /**
+ * Schedule events to trigger every time a MediaElement
+ * (audio/video) reaches a playback cue point.
+ *
+ * Accepts a callback function, a time (in seconds) at which to trigger
+ * the callback, and an optional parameter for the callback.
+ *
+ * Time will be passed as the first parameter to the callback function,
+ * and param will be the second parameter.
+ *
+ *
+ * @method addCue
+ * @param {Number} time Time in seconds, relative to this media
+ * element's playback. For example, to trigger
+ * an event every time playback reaches two
+ * seconds, pass in the number 2. This will be
+ * passed as the first parameter to
+ * the callback function.
+ * @param {Function} callback Name of a function that will be
+ * called at the given time. The callback will
+ * receive time and (optionally) param as its
+ * two parameters.
+ * @param {Object} [value] An object to be passed as the
+ * second parameter to the
+ * callback function.
+ * @return {Number} id ID of this cue,
+ * useful for removeCue(id)
+ * @example
+ *
+ * //
+ * //
+ * function setup() {
+ * noCanvas();
+ *
+ * let audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ *
+ * // schedule three calls to changeBackground
+ * audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * audioEl.addCue(5.0, changeBackground, color(255, 255, 0));
+ * }
+ *
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.addCue = function(time, callback, val) {
+ var id = this._cueIDCounter++;
+
+ var cue = new Cue(callback, time, id, val);
+ this._cues.push(cue);
+
+ if (!this.elt.ontimeupdate) {
+ this.elt.ontimeupdate = this._onTimeUpdate.bind(this);
+ }
+
+ return id;
+ };
+
+ /**
+ * Remove a callback based on its ID. The ID is returned by the
+ * addCue method.
+ * @method removeCue
+ * @param {Number} id ID of the cue, as returned by addCue
+ * @example
+ *
+ * let audioEl, id1, id2;
+ * function setup() {
+ * background(255, 255, 255);
+ * audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ * // schedule five calls to changeBackground
+ * id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * text('Click to remove first and last Cue!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * audioEl.removeCue(id1);
+ * audioEl.removeCue(id2);
+ * }
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.removeCue = function(id) {
+ for (var i = 0; i < this._cues.length; i++) {
+ if (this._cues[i].id === id) {
+ console.log(id);
+ this._cues.splice(i, 1);
+ }
+ }
+
+ if (this._cues.length === 0) {
+ this.elt.ontimeupdate = null;
+ }
+ };
+
+ /**
+ * Remove all of the callbacks that had originally been scheduled
+ * via the addCue method.
+ * @method clearCues
+ * @param {Number} id ID of the cue, as returned by addCue
+ * @example
+ *
+ * let audioEl;
+ * function setup() {
+ * background(255, 255, 255);
+ * audioEl = createAudio('assets/beat.mp3');
+ * //Show the default MediaElement controls, as determined by the web browser
+ * audioEl.showControls();
+ * // schedule calls to changeBackground
+ * background(200);
+ * text('Click to change Cue!', 10, 25, 70, 80);
+ * audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * }
+ * function mousePressed() {
+ * // here we clear the scheduled callbacks
+ * audioEl.clearCues();
+ * // then we add some more callbacks
+ * audioEl.addCue(1, changeBackground, color(2, 2, 2));
+ * audioEl.addCue(3, changeBackground, color(255, 255, 0));
+ * }
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.clearCues = function() {
+ this._cues = [];
+ this.elt.ontimeupdate = null;
+ };
+
+ // private method that checks for cues to be fired if events
+ // have been scheduled using addCue(callback, time).
+ _main.default.MediaElement.prototype._onTimeUpdate = function() {
+ var playbackTime = this.time();
+
+ for (var i = 0; i < this._cues.length; i++) {
+ var callbackTime = this._cues[i].time;
+ var val = this._cues[i].val;
+
+ if (this._prevTime < callbackTime && callbackTime <= playbackTime) {
+ // pass the scheduled callbackTime as parameter to the callback
+ this._cues[i].callback(val);
+ }
+ }
+
+ this._prevTime = playbackTime;
+ };
+
+ /**
+ * Base class for a file.
+ * Used for Element.drop and createFileInput.
+ *
+ * @class p5.File
+ * @constructor
+ * @param {File} file File that is wrapped
+ */
+ _main.default.File = function(file, pInst) {
+ /**
+ * Underlying File object. All normal File methods can be called on this.
+ *
+ * @property file
+ */
+ this.file = file;
+
+ this._pInst = pInst;
+
+ // Splitting out the file type into two components
+ // This makes determining if image or text etc simpler
+ var typeList = file.type.split('/');
+ /**
+ * File type (image, text, etc.)
+ *
+ * @property type
+ */
+ this.type = typeList[0];
+ /**
+ * File subtype (usually the file extension jpg, png, xml, etc.)
+ *
+ * @property subtype
+ */
+ this.subtype = typeList[1];
+ /**
+ * File name
+ *
+ * @property name
+ */
+ this.name = file.name;
+ /**
+ * File size
+ *
+ * @property size
+ */
+ this.size = file.size;
+
+ /**
+ * URL string containing image data.
+ *
+ * @property data
+ */
+ this.data = undefined;
+ };
+
+ _main.default.File._createLoader = function(theFile, callback) {
+ var reader = new FileReader();
+ reader.onload = function(e) {
+ var p5file = new _main.default.File(theFile);
+ p5file.data = e.target.result;
+ callback(p5file);
+ };
+ return reader;
+ };
+
+ _main.default.File._load = function(f, callback) {
+ // Text or data?
+ // This should likely be improved
+ if (/^text\//.test(f.type)) {
+ _main.default.File._createLoader(f, callback).readAsText(f);
+ } else if (!/^(video|audio)\//.test(f.type)) {
+ _main.default.File._createLoader(f, callback).readAsDataURL(f);
+ } else {
+ var file = new _main.default.File(f);
+ file.data = URL.createObjectURL(f);
+ callback(file);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 44: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Events
+ * @submodule Acceleration
+ * @for p5
+ * @requires core
+ */ /**
+ * The system variable deviceOrientation always contains the orientation of
+ * the device. The value of this variable will either be set 'landscape'
+ * or 'portrait'. If no data is available it will be set to 'undefined'.
+ * either LANDSCAPE or PORTRAIT.
+ *
+ * @property {Constant} deviceOrientation
+ * @readOnly
+ */ _main.default.prototype.deviceOrientation = undefined; /**
+ * The system variable accelerationX always contains the acceleration of the
+ * device along the x axis. Value is represented as meters per second squared.
+ *
+ * @property {Number} accelerationX
+ * @readOnly
+ * @example
+ *
+ *
+ * // Move a touchscreen device to register
+ * // acceleration changes.
+ * function draw() {
+ * background(220, 50);
+ * fill('magenta');
+ * ellipse(width / 2, height / 2, accelerationX);
+ * }
+ *
+ *
+ * @alt
+ * Magnitude of device acceleration is displayed as ellipse size
+ */
+ _main.default.prototype.accelerationX = 0;
+
+ /**
+ * The system variable accelerationY always contains the acceleration of the
+ * device along the y axis. Value is represented as meters per second squared.
+ *
+ * @property {Number} accelerationY
+ * @readOnly
+ * @example
+ *
+ *
+ * // Move a touchscreen device to register
+ * // acceleration changes.
+ * function draw() {
+ * background(220, 50);
+ * fill('magenta');
+ * ellipse(width / 2, height / 2, accelerationY);
+ * }
+ *
+ *
+ * @alt
+ * Magnitude of device acceleration is displayed as ellipse size
+ */
+ _main.default.prototype.accelerationY = 0;
+
+ /**
+ * The system variable accelerationZ always contains the acceleration of the
+ * device along the z axis. Value is represented as meters per second squared.
+ *
+ * @property {Number} accelerationZ
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move a touchscreen device to register
+ * // acceleration changes.
+ * function draw() {
+ * background(220, 50);
+ * fill('magenta');
+ * ellipse(width / 2, height / 2, accelerationZ);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Magnitude of device acceleration is displayed as ellipse size
+ */
+ _main.default.prototype.accelerationZ = 0;
+
+ /**
+ * The system variable pAccelerationX always contains the acceleration of the
+ * device along the x axis in the frame previous to the current frame. Value
+ * is represented as meters per second squared.
+ *
+ * @property {Number} pAccelerationX
+ * @readOnly
+ */
+ _main.default.prototype.pAccelerationX = 0;
+
+ /**
+ * The system variable pAccelerationY always contains the acceleration of the
+ * device along the y axis in the frame previous to the current frame. Value
+ * is represented as meters per second squared.
+ *
+ * @property {Number} pAccelerationY
+ * @readOnly
+ */
+ _main.default.prototype.pAccelerationY = 0;
+
+ /**
+ * The system variable pAccelerationZ always contains the acceleration of the
+ * device along the z axis in the frame previous to the current frame. Value
+ * is represented as meters per second squared.
+ *
+ * @property {Number} pAccelerationZ
+ * @readOnly
+ */
+ _main.default.prototype.pAccelerationZ = 0;
+
+ /**
+ * _updatePAccelerations updates the pAcceleration values
+ *
+ * @private
+ */
+ _main.default.prototype._updatePAccelerations = function() {
+ this._setProperty('pAccelerationX', this.accelerationX);
+ this._setProperty('pAccelerationY', this.accelerationY);
+ this._setProperty('pAccelerationZ', this.accelerationZ);
+ };
+
+ /**
+ * The system variable rotationX always contains the rotation of the
+ * device along the x axis. Value is represented as 0 to +/-180 degrees.
+ *
+ * Note: The order the rotations are called is important, ie. if used
+ * together, it must be called in the order Z-X-Y or there might be
+ * unexpected behaviour.
+ *
+ * @property {Number} rotationX
+ * @readOnly
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * //rotateZ(radians(rotationZ));
+ * rotateX(radians(rotationX));
+ * //rotateY(radians(rotationY));
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ */
+ _main.default.prototype.rotationX = 0;
+
+ /**
+ * The system variable rotationY always contains the rotation of the
+ * device along the y axis. Value is represented as 0 to +/-90 degrees.
+ *
+ * Note: The order the rotations are called is important, ie. if used
+ * together, it must be called in the order Z-X-Y or there might be
+ * unexpected behaviour.
+ *
+ * @property {Number} rotationY
+ * @readOnly
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * //rotateZ(radians(rotationZ));
+ * //rotateX(radians(rotationX));
+ * rotateY(radians(rotationY));
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ */
+ _main.default.prototype.rotationY = 0;
+
+ /**
+ * The system variable rotationZ always contains the rotation of the
+ * device along the z axis. Value is represented as 0 to 359 degrees.
+ *
+ * Unlike rotationX and rotationY, this variable is available for devices
+ * with a built-in compass only.
+ *
+ * Note: The order the rotations are called is important, ie. if used
+ * together, it must be called in the order Z-X-Y or there might be
+ * unexpected behaviour.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateZ(radians(rotationZ));
+ * //rotateX(radians(rotationX));
+ * //rotateY(radians(rotationY));
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ *
+ * @property {Number} rotationZ
+ * @readOnly
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ */
+ _main.default.prototype.rotationZ = 0;
+
+ /**
+ * The system variable pRotationX always contains the rotation of the
+ * device along the x axis in the frame previous to the current frame. Value
+ * is represented as 0 to +/-180 degrees.
+ *
+ * pRotationX can also be used with rotationX to determine the rotate
+ * direction of the device along the X-axis.
+ * @example
+ *
+ *
+ * // A simple if statement looking at whether
+ * // rotationX - pRotationX < 0 is true or not will be
+ * // sufficient for determining the rotate direction
+ * // in most cases.
+ *
+ * // Some extra logic is needed to account for cases where
+ * // the angles wrap around.
+ * let rotateDirection = 'clockwise';
+ *
+ * // Simple range conversion to make things simpler.
+ * // This is not absolutely necessary but the logic
+ * // will be different in that case.
+ *
+ * let rX = rotationX + 180;
+ * let pRX = pRotationX + 180;
+ *
+ * if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {
+ * rotateDirection = 'clockwise';
+ * } else if (rX - pRX < 0 || rX - pRX > 270) {
+ * rotateDirection = 'counter-clockwise';
+ * }
+ *
+ * print(rotateDirection);
+ *
+ *
+ *
+ * @alt
+ * no image to display.
+ *
+ *
+ * @property {Number} pRotationX
+ * @readOnly
+ */
+ _main.default.prototype.pRotationX = 0;
+
+ /**
+ * The system variable pRotationY always contains the rotation of the
+ * device along the y axis in the frame previous to the current frame. Value
+ * is represented as 0 to +/-90 degrees.
+ *
+ * pRotationY can also be used with rotationY to determine the rotate
+ * direction of the device along the Y-axis.
+ * @example
+ *
+ *
+ * // A simple if statement looking at whether
+ * // rotationY - pRotationY < 0 is true or not will be
+ * // sufficient for determining the rotate direction
+ * // in most cases.
+ *
+ * // Some extra logic is needed to account for cases where
+ * // the angles wrap around.
+ * let rotateDirection = 'clockwise';
+ *
+ * // Simple range conversion to make things simpler.
+ * // This is not absolutely necessary but the logic
+ * // will be different in that case.
+ *
+ * let rY = rotationY + 180;
+ * let pRY = pRotationY + 180;
+ *
+ * if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {
+ * rotateDirection = 'clockwise';
+ * } else if (rY - pRY < 0 || rY - pRY > 270) {
+ * rotateDirection = 'counter-clockwise';
+ * }
+ * print(rotateDirection);
+ *
+ *
+ *
+ * @alt
+ * no image to display.
+ *
+ *
+ * @property {Number} pRotationY
+ * @readOnly
+ */
+ _main.default.prototype.pRotationY = 0;
+
+ /**
+ * The system variable pRotationZ always contains the rotation of the
+ * device along the z axis in the frame previous to the current frame. Value
+ * is represented as 0 to 359 degrees.
+ *
+ * pRotationZ can also be used with rotationZ to determine the rotate
+ * direction of the device along the Z-axis.
+ * @example
+ *
+ *
+ * // A simple if statement looking at whether
+ * // rotationZ - pRotationZ < 0 is true or not will be
+ * // sufficient for determining the rotate direction
+ * // in most cases.
+ *
+ * // Some extra logic is needed to account for cases where
+ * // the angles wrap around.
+ * let rotateDirection = 'clockwise';
+ *
+ * if (
+ * (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||
+ * rotationZ - pRotationZ < -270
+ * ) {
+ * rotateDirection = 'clockwise';
+ * } else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {
+ * rotateDirection = 'counter-clockwise';
+ * }
+ * print(rotateDirection);
+ *
+ *
+ *
+ * @alt
+ * no image to display.
+ *
+ *
+ * @property {Number} pRotationZ
+ * @readOnly
+ */
+ _main.default.prototype.pRotationZ = 0;
+
+ var startAngleX = 0;
+ var startAngleY = 0;
+ var startAngleZ = 0;
+
+ var rotateDirectionX = 'clockwise';
+ var rotateDirectionY = 'clockwise';
+ var rotateDirectionZ = 'clockwise';
+
+ _main.default.prototype.pRotateDirectionX = undefined;
+ _main.default.prototype.pRotateDirectionY = undefined;
+ _main.default.prototype.pRotateDirectionZ = undefined;
+
+ _main.default.prototype._updatePRotations = function() {
+ this._setProperty('pRotationX', this.rotationX);
+ this._setProperty('pRotationY', this.rotationY);
+ this._setProperty('pRotationZ', this.rotationZ);
+ };
+
+ /**
+ * When a device is rotated, the axis that triggers the deviceTurned()
+ * method is stored in the turnAxis variable. The turnAxis variable is only defined within
+ * the scope of deviceTurned().
+ * @property {String} turnAxis
+ * @readOnly
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Rotate the device by 90 degrees in the
+ * // X-axis to change the value.
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceTurned() {
+ * if (turnAxis === 'X') {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device turns
+ * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns
+ */
+ _main.default.prototype.turnAxis = undefined;
+
+ var move_threshold = 0.5;
+ var shake_threshold = 30;
+
+ /**
+ * The setMoveThreshold() function is used to set the movement threshold for
+ * the deviceMoved() function. The default threshold is set to 0.5.
+ *
+ * @method setMoveThreshold
+ * @param {number} value The threshold value
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // You will need to move the device incrementally further
+ * // the closer the square's color gets to white in order to change the value.
+ *
+ * let value = 0;
+ * let threshold = 0.5;
+ * function setup() {
+ * setMoveThreshold(threshold);
+ * }
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * threshold = threshold + 0.1;
+ * if (value > 255) {
+ * value = 0;
+ * threshold = 30;
+ * }
+ * setMoveThreshold(threshold);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device moves
+ */
+
+ _main.default.prototype.setMoveThreshold = function(val) {
+ _main.default._validateParameters('setMoveThreshold', arguments);
+ move_threshold = val;
+ };
+
+ /**
+ * The setShakeThreshold() function is used to set the movement threshold for
+ * the deviceShaken() function. The default threshold is set to 30.
+ *
+ * @method setShakeThreshold
+ * @param {number} value The threshold value
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // You will need to shake the device more firmly
+ * // the closer the box's fill gets to white in order to change the value.
+ *
+ * let value = 0;
+ * let threshold = 30;
+ * function setup() {
+ * setShakeThreshold(threshold);
+ * }
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * threshold = threshold + 5;
+ * if (value > 255) {
+ * value = 0;
+ * threshold = 30;
+ * }
+ * setShakeThreshold(threshold);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device
+ * is being shaked
+ */
+
+ _main.default.prototype.setShakeThreshold = function(val) {
+ _main.default._validateParameters('setShakeThreshold', arguments);
+ shake_threshold = val;
+ };
+
+ /**
+ * The deviceMoved() function is called when the device is moved by more than
+ * the threshold value along X, Y or Z axis. The default threshold is set to 0.5.
+ * The threshold value can be changed using setMoveThreshold().
+ *
+ * @method deviceMoved
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Move the device around
+ * // to change the value.
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device moves
+ *
+ */
+
+ /**
+ * The deviceTurned() function is called when the device rotates by
+ * more than 90 degrees continuously.
+ *
+ * The axis that triggers the deviceTurned() method is stored in the turnAxis
+ * variable. The deviceTurned() method can be locked to trigger on any axis:
+ * X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.
+ *
+ * @method deviceTurned
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Rotate the device by 90 degrees
+ * // to change the value.
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceTurned() {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * // Run this example on a mobile device
+ * // Rotate the device by 90 degrees in the
+ * // X-axis to change the value.
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceTurned() {
+ * if (turnAxis === 'X') {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device turns
+ * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns
+ *
+ */
+
+ /**
+ * The deviceShaken() function is called when the device total acceleration
+ * changes of accelerationX and accelerationY values is more than
+ * the threshold value. The default threshold is set to 30.
+ * The threshold value can be changed using setShakeThreshold().
+ *
+ * @method deviceShaken
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Shake the device to change the value.
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceShaken() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device shakes
+ *
+ */
+
+ _main.default.prototype._ondeviceorientation = function(e) {
+ this._updatePRotations();
+ this._setProperty('rotationX', e.beta);
+ this._setProperty('rotationY', e.gamma);
+ this._setProperty('rotationZ', e.alpha);
+ this._handleMotion();
+ };
+ _main.default.prototype._ondevicemotion = function(e) {
+ this._updatePAccelerations();
+ this._setProperty('accelerationX', e.acceleration.x * 2);
+ this._setProperty('accelerationY', e.acceleration.y * 2);
+ this._setProperty('accelerationZ', e.acceleration.z * 2);
+ this._handleMotion();
+ };
+ _main.default.prototype._handleMotion = function() {
+ if (window.orientation === 90 || window.orientation === -90) {
+ this._setProperty('deviceOrientation', 'landscape');
+ } else if (window.orientation === 0) {
+ this._setProperty('deviceOrientation', 'portrait');
+ } else if (window.orientation === undefined) {
+ this._setProperty('deviceOrientation', 'undefined');
+ }
+ var deviceMoved = this.deviceMoved || window.deviceMoved;
+ if (typeof deviceMoved === 'function') {
+ if (
+ Math.abs(this.accelerationX - this.pAccelerationX) > move_threshold ||
+ Math.abs(this.accelerationY - this.pAccelerationY) > move_threshold ||
+ Math.abs(this.accelerationZ - this.pAccelerationZ) > move_threshold
+ ) {
+ deviceMoved();
+ }
+ }
+ var deviceTurned = this.deviceTurned || window.deviceTurned;
+ if (typeof deviceTurned === 'function') {
+ // The angles given by rotationX etc is from range -180 to 180.
+ // The following will convert them to 0 to 360 for ease of calculation
+ // of cases when the angles wrapped around.
+ // _startAngleX will be converted back at the end and updated.
+ var wRX = this.rotationX + 180;
+ var wPRX = this.pRotationX + 180;
+ var wSAX = startAngleX + 180;
+ if ((wRX - wPRX > 0 && wRX - wPRX < 270) || wRX - wPRX < -270) {
+ rotateDirectionX = 'clockwise';
+ } else if (wRX - wPRX < 0 || wRX - wPRX > 270) {
+ rotateDirectionX = 'counter-clockwise';
+ }
+ if (rotateDirectionX !== this.pRotateDirectionX) {
+ wSAX = wRX;
+ }
+ if (Math.abs(wRX - wSAX) > 90 && Math.abs(wRX - wSAX) < 270) {
+ wSAX = wRX;
+ this._setProperty('turnAxis', 'X');
+ deviceTurned();
+ }
+ this.pRotateDirectionX = rotateDirectionX;
+ startAngleX = wSAX - 180;
+
+ // Y-axis is identical to X-axis except for changing some names.
+ var wRY = this.rotationY + 180;
+ var wPRY = this.pRotationY + 180;
+ var wSAY = startAngleY + 180;
+ if ((wRY - wPRY > 0 && wRY - wPRY < 270) || wRY - wPRY < -270) {
+ rotateDirectionY = 'clockwise';
+ } else if (wRY - wPRY < 0 || wRY - this.pRotationY > 270) {
+ rotateDirectionY = 'counter-clockwise';
+ }
+ if (rotateDirectionY !== this.pRotateDirectionY) {
+ wSAY = wRY;
+ }
+ if (Math.abs(wRY - wSAY) > 90 && Math.abs(wRY - wSAY) < 270) {
+ wSAY = wRY;
+ this._setProperty('turnAxis', 'Y');
+ deviceTurned();
+ }
+ this.pRotateDirectionY = rotateDirectionY;
+ startAngleY = wSAY - 180;
+
+ // Z-axis is already in the range 0 to 360
+ // so no conversion is needed.
+ if (
+ (this.rotationZ - this.pRotationZ > 0 &&
+ this.rotationZ - this.pRotationZ < 270) ||
+ this.rotationZ - this.pRotationZ < -270
+ ) {
+ rotateDirectionZ = 'clockwise';
+ } else if (
+ this.rotationZ - this.pRotationZ < 0 ||
+ this.rotationZ - this.pRotationZ > 270
+ ) {
+ rotateDirectionZ = 'counter-clockwise';
+ }
+ if (rotateDirectionZ !== this.pRotateDirectionZ) {
+ startAngleZ = this.rotationZ;
+ }
+ if (
+ Math.abs(this.rotationZ - startAngleZ) > 90 &&
+ Math.abs(this.rotationZ - startAngleZ) < 270
+ ) {
+ startAngleZ = this.rotationZ;
+ this._setProperty('turnAxis', 'Z');
+ deviceTurned();
+ }
+ this.pRotateDirectionZ = rotateDirectionZ;
+ this._setProperty('turnAxis', undefined);
+ }
+ var deviceShaken = this.deviceShaken || window.deviceShaken;
+ if (typeof deviceShaken === 'function') {
+ var accelerationChangeX;
+ var accelerationChangeY;
+ // Add accelerationChangeZ if acceleration change on Z is needed
+ if (this.pAccelerationX !== null) {
+ accelerationChangeX = Math.abs(this.accelerationX - this.pAccelerationX);
+ accelerationChangeY = Math.abs(this.accelerationY - this.pAccelerationY);
+ }
+ if (accelerationChangeX + accelerationChangeY > shake_threshold) {
+ deviceShaken();
+ }
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 45: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Events
+ * @submodule Keyboard
+ * @for p5
+ * @requires core
+ */ /**
+ * The boolean system variable keyIsPressed is true if any key is pressed
+ * and false if no keys are pressed.
+ *
+ * @property {Boolean} keyIsPressed
+ * @readOnly
+ * @example
+ *
+ *
+ * function draw() {
+ * if (keyIsPressed === true) {
+ * fill(0);
+ * } else {
+ * fill(255);
+ * }
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 white rect that turns black on keypress.
+ *
+ */ _main.default.prototype.isKeyPressed = false;
+ _main.default.prototype.keyIsPressed = false; // khan
+ /**
+ * The system variable key always contains the value of the most recent
+ * key on the keyboard that was typed. To get the proper capitalization, it
+ * is best to use it within keyTyped(). For non-ASCII keys, use the keyCode
+ * variable.
+ *
+ * @property {String} key
+ * @readOnly
+ * @example
+ *
+ * // Click any key to display it!
+ * // (Not Guaranteed to be Case Sensitive)
+ * function setup() {
+ * fill(245, 123, 158);
+ * textSize(50);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(key, 33, 65); // Display last key pressed.
+ * }
+ *
+ *
+ * @alt
+ * canvas displays any key value that is pressed in pink font.
+ *
+ */
+ _main.default.prototype.key = '';
+
+ /**
+ * The variable keyCode is used to detect special keys such as BACKSPACE,
+ * DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,
+ * DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ * You can also check for custom keys by looking up the keyCode of any key
+ * on a site like this: keycode.info.
+ *
+ * @property {Integer} keyCode
+ * @readOnly
+ * @example
+ *
+ * let fillVal = 126;
+ * function draw() {
+ * fill(fillVal);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function keyPressed() {
+ * if (keyCode === UP_ARROW) {
+ * fillVal = 255;
+ * } else if (keyCode === DOWN_ARROW) {
+ * fillVal = 0;
+ * }
+ * return false; // prevent default
+ * }
+ *
+ *
+ * function draw() {}
+ * function keyPressed() {
+ * background('yellow');
+ * text(`${key} ${keyCode}`, 10, 40);
+ * print(key, ' ', keyCode);
+ * return false; // prevent default
+ * }
+ *
+ * @alt
+ * Grey rect center. turns white when up arrow pressed and black when down
+ * Display key pressed and its keyCode in a yellow box
+ */
+ _main.default.prototype.keyCode = 0;
+
+ /**
+ * The keyPressed() function is called once every time a key is pressed. The
+ * keyCode for the key that was pressed is stored in the keyCode variable.
+ *
+ * For non-ASCII keys, use the keyCode variable. You can check if the keyCode
+ * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,
+ * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ *
+ * For ASCII keys, the key that was pressed is stored in the key variable. However, it
+ * does not distinguish between uppercase and lowercase. For this reason, it
+ * is recommended to use keyTyped() to read the key variable, in which the
+ * case of the variable will be distinguished.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * may cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyPressed
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyPressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyPressed() {
+ * if (keyCode === LEFT_ARROW) {
+ * value = 255;
+ * } else if (keyCode === RIGHT_ARROW) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * function keyPressed() {
+ * // Do something
+ * return false; // prevent any default behaviour
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when key pressed and black when released
+ * black rect center. turns white when left arrow pressed and black when right.
+ *
+ */
+ _main.default.prototype._onkeydown = function(e) {
+ if (this._downKeys[e.which]) {
+ // prevent multiple firings
+ return;
+ }
+ this._setProperty('isKeyPressed', true);
+ this._setProperty('keyIsPressed', true);
+ this._setProperty('keyCode', e.which);
+ this._downKeys[e.which] = true;
+ this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which);
+ var keyPressed = this.keyPressed || window.keyPressed;
+ if (typeof keyPressed === 'function' && !e.charCode) {
+ var executeDefault = keyPressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+ /**
+ * The keyReleased() function is called once every time a key is released.
+ * See key and keyCode for more information.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyReleased
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * return false; // prevent any default behavior
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when key pressed and black when pressed again
+ *
+ */
+ _main.default.prototype._onkeyup = function(e) {
+ var keyReleased = this.keyReleased || window.keyReleased;
+ this._downKeys[e.which] = false;
+
+ if (!this._areDownKeys()) {
+ this._setProperty('isKeyPressed', false);
+ this._setProperty('keyIsPressed', false);
+ }
+
+ this._setProperty('_lastKeyCodeTyped', null);
+
+ this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which);
+ this._setProperty('keyCode', e.which);
+ if (typeof keyReleased === 'function') {
+ var executeDefault = keyReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The keyTyped() function is called once every time a key is pressed, but
+ * action keys such as Backspace, Delete, Ctrl, Shift, and Alt are ignored. If you are trying to detect
+ * a keyCode for one of these keys, use the keyPressed() function instead.
+ * The most recent key typed will be stored in the key variable.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * will cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default behaviors attached to various key
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method keyTyped
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyTyped() {
+ * if (key === 'a') {
+ * value = 255;
+ * } else if (key === 'b') {
+ * value = 0;
+ * }
+ * // uncomment to prevent any default behavior
+ * // return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when 'a' key typed and black when 'b' pressed
+ *
+ */
+ _main.default.prototype._onkeypress = function(e) {
+ if (e.which === this._lastKeyCodeTyped) {
+ // prevent multiple firings
+ return;
+ }
+ this._setProperty('_lastKeyCodeTyped', e.which); // track last keyCode
+ this._setProperty('key', String.fromCharCode(e.which));
+ var keyTyped = this.keyTyped || window.keyTyped;
+ if (typeof keyTyped === 'function') {
+ var executeDefault = keyTyped(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+ /**
+ * The onblur function is called when the user is no longer focused
+ * on the p5 element. Because the keyup events will not fire if the user is
+ * not focused on the element we must assume all keys currently down have
+ * been released.
+ */
+ _main.default.prototype._onblur = function(e) {
+ this._downKeys = {};
+ };
+
+ /**
+ * The keyIsDown() function checks if the key is currently down, i.e. pressed.
+ * It can be used if you have an object that moves, and you want several keys
+ * to be able to affect its behaviour simultaneously, such as moving a
+ * sprite diagonally. You can put in any number representing the keyCode of
+ * the key, or use any of the variable keyCode names listed
+ * here.
+ *
+ * @method keyIsDown
+ * @param {Number} code The key to check for.
+ * @return {Boolean} whether key is down or not
+ * @example
+ *
+ * let x = 100;
+ * let y = 100;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * fill(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * if (keyIsDown(LEFT_ARROW)) {
+ * x -= 5;
+ * }
+ *
+ * if (keyIsDown(RIGHT_ARROW)) {
+ * x += 5;
+ * }
+ *
+ * if (keyIsDown(UP_ARROW)) {
+ * y -= 5;
+ * }
+ *
+ * if (keyIsDown(DOWN_ARROW)) {
+ * y += 5;
+ * }
+ *
+ * clear();
+ * ellipse(x, y, 50, 50);
+ * }
+ *
+ *
+ *
+ * let diameter = 50;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * }
+ *
+ * function draw() {
+ * // 107 and 187 are keyCodes for "+"
+ * if (keyIsDown(107) || keyIsDown(187)) {
+ * diameter += 1;
+ * }
+ *
+ * // 109 and 189 are keyCodes for "-"
+ * if (keyIsDown(109) || keyIsDown(189)) {
+ * diameter -= 1;
+ * }
+ *
+ * clear();
+ * fill(255, 0, 0);
+ * ellipse(50, 50, diameter, diameter);
+ * }
+ *
+ *
+ * @alt
+ * 50x50 red ellipse moves left, right, up and down with arrow presses.
+ * 50x50 red ellipse gets bigger or smaller when + or - are pressed.
+ *
+ */
+ _main.default.prototype.keyIsDown = function(code) {
+ _main.default._validateParameters('keyIsDown', arguments);
+ return this._downKeys[code] || false;
+ };
+
+ /**
+ * The _areDownKeys function returns a boolean true if any keys pressed
+ * and a false if no keys are currently pressed.
+
+ * Helps avoid instances where multiple keys are pressed simultaneously and
+ * releasing a single key will then switch the
+ * keyIsPressed property to true.
+ * @private
+ **/
+ _main.default.prototype._areDownKeys = function() {
+ for (var key in this._downKeys) {
+ if (this._downKeys.hasOwnProperty(key) && this._downKeys[key] === true) {
+ return true;
+ }
+ }
+ return false;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 46: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Events
+ * @submodule Mouse
+ * @for p5
+ * @requires core
+ * @requires constants
+ */ /**
+ *
+ * The variable movedX contains the horizontal movement of the mouse since the last frame
+ * @property {Number} movedX
+ * @readOnly
+ * @example
+ *
+ *
+ * let x = 50;
+ * function setup() {
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (x > 48) {
+ * x -= 2;
+ * } else if (x < 48) {
+ * x += 2;
+ * }
+ * x += floor(movedX / 5);
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(x, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * box moves left and right according to mouse movement then slowly back towards the center
+ *
+ */ _main.default.prototype.movedX = 0;
+ /**
+ * The variable movedY contains the vertical movement of the mouse since the last frame
+ * @property {Number} movedY
+ * @readOnly
+ * @example
+ *
+ *
+ * let y = 50;
+ * function setup() {
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (y > 48) {
+ * y -= 2;
+ * } else if (y < 48) {
+ * y += 2;
+ * }
+ * y += floor(movedY / 5);
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(y, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * box moves up and down according to mouse movement then slowly back towards the center
+ *
+ */ _main.default.prototype.movedY = 0;
+ /*
+ * This is a flag which is false until the first time
+ * we receive a mouse event. The pmouseX and pmouseY
+ * values will match the mouseX and mouseY values until
+ * this interaction takes place.
+ */
+ _main.default.prototype._hasMouseInteracted = false;
+
+ /**
+ * The system variable mouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the canvas. The value at
+ * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.
+ * If touch is used instead of mouse input, mouseX will hold the x value
+ * of the most recent touch point.
+ *
+ * @property {Number} mouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, 0, mouseX, 100);
+ * }
+ *
+ *
+ *
+ * @alt
+ * horizontal black line moves left and right with mouse x-position
+ *
+ */
+ _main.default.prototype.mouseX = 0;
+
+ /**
+ * The system variable mouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the canvas. The value at
+ * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.
+ * If touch is used instead of mouse input, mouseY will hold the y value
+ * of the most recent touch point.
+ *
+ * @property {Number} mouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(0, mouseY, 100, mouseY);
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black line moves up and down with mouse y-position
+ *
+ */
+ _main.default.prototype.mouseY = 0;
+
+ /**
+ * The system variable pmouseX always contains the horizontal position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and
+ * (-width/2, -height/2) for WebGL. Note: pmouseX will be reset to the current mouseX
+ * value at the start of each touch event.
+ *
+ * @property {Number} pmouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas to leave a trail
+ * function setup() {
+ * //slow down the frameRate to make it more visible
+ * frameRate(10);
+ * }
+ *
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, mouseY, pmouseX, pmouseY);
+ * print(pmouseX + ' -> ' + mouseX);
+ * }
+ *
+ *
+ *
+ * @alt
+ * line trail is created from cursor movements. faster movement make longer line.
+ *
+ */
+ _main.default.prototype.pmouseX = 0;
+
+ /**
+ * The system variable pmouseY always contains the vertical position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and
+ * (-width/2, -height/2) for WebGL. Note: pmouseY will be reset to the current mouseY
+ * value at the start of each touch event.
+ *
+ * @property {Number} pmouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * //draw a square only if the mouse is not moving
+ * if (mouseY === pmouseY && mouseX === pmouseX) {
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * print(pmouseY + ' -> ' + mouseY);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect center, fuchsia background. rect flickers on mouse movement
+ *
+ */
+ _main.default.prototype.pmouseY = 0;
+
+ /**
+ * The system variable winMouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * let body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the horizontal mouse position
+ * //relative to the window
+ * myCanvas.position(winMouseX + 1, windowHeight / 2);
+ *
+ * //the y of the square is relative to the canvas
+ * rect(20, mouseY, 60, 60);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect y moves with mouse y and fuchsia canvas moves with mouse x
+ *
+ */
+ _main.default.prototype.winMouseX = 0;
+
+ /**
+ * The system variable winMouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * let body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the vertical mouse position
+ * //relative to the window
+ * myCanvas.position(windowWidth / 2, winMouseY + 1);
+ *
+ * //the x of the square is relative to the canvas
+ * rect(mouseX, 20, 60, 60);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect x moves with mouse x and fuchsia canvas y moves with mouse y
+ *
+ */
+ _main.default.prototype.winMouseY = 0;
+
+ /**
+ * The system variable pwinMouseX always contains the horizontal position
+ * of the mouse in the frame previous to the current frame, relative to
+ * (0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX
+ * value at the start of each touch event.
+ *
+ * @property {Number} pwinMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current x position is the horizontal mouse speed
+ * let speed = abs(winMouseX - pwinMouseX);
+ * //change the size of the circle
+ * //according to the horizontal speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ *
+ */
+ _main.default.prototype.pwinMouseX = 0;
+
+ /**
+ * The system variable pwinMouseY always contains the vertical position of
+ * the mouse in the frame previous to the current frame, relative to (0, 0)
+ * of the window. Note: pwinMouseY will be reset to the current winMouseY
+ * value at the start of each touch event.
+ *
+ * @property {Number} pwinMouseY
+ * @readOnly
+ *
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current y position is the vertical mouse speed
+ * let speed = abs(winMouseY - pwinMouseY);
+ * //change the size of the circle
+ * //according to the vertical speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ *
+ */
+ _main.default.prototype.pwinMouseY = 0;
+
+ /**
+ * Processing automatically tracks if the mouse button is pressed and which
+ * button is pressed. The value of the system variable mouseButton is either
+ * LEFT, RIGHT, or CENTER depending on which button was pressed last.
+ * Warning: different browsers may track mouseButton differently.
+ *
+ * @property {Constant} mouseButton
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * if (mouseIsPressed) {
+ * if (mouseButton === LEFT) {
+ * ellipse(50, 50, 50, 50);
+ * }
+ * if (mouseButton === RIGHT) {
+ * rect(25, 25, 50, 50);
+ * }
+ * if (mouseButton === CENTER) {
+ * triangle(23, 75, 50, 20, 78, 75);
+ * }
+ * }
+ *
+ * print(mouseButton);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black ellipse appears on center of fuchsia canvas on mouse click/press.
+ *
+ */
+ _main.default.prototype.mouseButton = 0;
+
+ /**
+ * The boolean system variable mouseIsPressed is true if the mouse is pressed
+ * and false if not.
+ *
+ * @property {Boolean} mouseIsPressed
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * if (mouseIsPressed) {
+ * ellipse(50, 50, 50, 50);
+ * } else {
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * print(mouseIsPressed);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect becomes ellipse with mouse click/press. fuchsia background.
+ *
+ */
+ _main.default.prototype.mouseIsPressed = false;
+
+ _main.default.prototype._updateNextMouseCoords = function(e) {
+ if (this._curElement !== null && (!e.touches || e.touches.length > 0)) {
+ var mousePos = getMousePos(this._curElement.elt, this.width, this.height, e);
+
+ this._setProperty('movedX', e.movementX);
+ this._setProperty('movedY', e.movementY);
+ this._setProperty('mouseX', mousePos.x);
+ this._setProperty('mouseY', mousePos.y);
+ this._setProperty('winMouseX', mousePos.winX);
+ this._setProperty('winMouseY', mousePos.winY);
+ }
+ if (!this._hasMouseInteracted) {
+ // For first draw, make previous and next equal
+ this._updateMouseCoords();
+ this._setProperty('_hasMouseInteracted', true);
+ }
+ };
+
+ _main.default.prototype._updateMouseCoords = function() {
+ this._setProperty('pmouseX', this.mouseX);
+ this._setProperty('pmouseY', this.mouseY);
+ this._setProperty('pwinMouseX', this.winMouseX);
+ this._setProperty('pwinMouseY', this.winMouseY);
+
+ this._setProperty('_pmouseWheelDeltaY', this._mouseWheelDeltaY);
+ };
+
+ function getMousePos(canvas, w, h, evt) {
+ if (evt && !evt.clientX) {
+ // use touches if touch and not mouse
+ if (evt.touches) {
+ evt = evt.touches[0];
+ } else if (evt.changedTouches) {
+ evt = evt.changedTouches[0];
+ }
+ }
+ var rect = canvas.getBoundingClientRect();
+ var sx = canvas.scrollWidth / w || 1;
+ var sy = canvas.scrollHeight / h || 1;
+ return {
+ x: (evt.clientX - rect.left) / sx,
+ y: (evt.clientY - rect.top) / sy,
+ winX: evt.clientX,
+ winY: evt.clientY,
+ id: evt.identifier
+ };
+ }
+
+ _main.default.prototype._setMouseButton = function(e) {
+ if (e.button === 1) {
+ this._setProperty('mouseButton', constants.CENTER);
+ } else if (e.button === 2) {
+ this._setProperty('mouseButton', constants.RIGHT);
+ } else {
+ this._setProperty('mouseButton', constants.LEFT);
+ }
+ };
+
+ /**
+ * The mouseMoved() function is called every time the mouse moves and a mouse
+ * button is not pressed.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseMoved
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Move the mouse across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseMoved() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect becomes lighter with mouse movements until white then resets
+ * no image displayed
+ *
+ */
+
+ /**
+ * The mouseDragged() function is called once every time the mouse moves and
+ * a mouse button is pressed. If no mouseDragged() function is defined, the
+ * touchMoved() function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseDragged
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Drag the mouse across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseDragged() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseDragged() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseDragged(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns lighter with mouse click and drag until white, resets
+ * no image displayed
+ *
+ */
+ _main.default.prototype._onmousemove = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._updateNextMouseCoords(e);
+ if (!this.mouseIsPressed) {
+ if (typeof context.mouseMoved === 'function') {
+ executeDefault = context.mouseMoved(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ } else {
+ if (typeof context.mouseDragged === 'function') {
+ executeDefault = context.mouseDragged(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.touchMoved === 'function') {
+ executeDefault = context.touchMoved(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ }
+ };
+
+ /**
+ * The mousePressed() function is called once after every time a mouse button
+ * is pressed. The mouseButton variable (see the related reference entry)
+ * can be used to determine which button has been pressed. If no
+ * mousePressed() function is defined, the touchStarted() function will be
+ * called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mousePressed
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mousePressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mousePressed() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mousePressed(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ *
+ */
+ _main.default.prototype._onmousedown = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', true);
+ this._setMouseButton(e);
+ this._updateNextMouseCoords(e);
+
+ if (typeof context.mousePressed === 'function') {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ // only safari needs this manual fallback for consistency
+ } else if (
+ navigator.userAgent.toLowerCase().includes('safari') &&
+ typeof context.touchStarted === 'function'
+ ) {
+ executeDefault = context.touchStarted(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The mouseReleased() function is called every time a mouse button is
+ * released. If no mouseReleased() function is defined, the touchEnded()
+ * function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ *
+ * @method mouseReleased
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseReleased() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseReleased(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ *
+ */
+ _main.default.prototype._onmouseup = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', false);
+ if (typeof context.mouseReleased === 'function') {
+ executeDefault = context.mouseReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.touchEnded === 'function') {
+ executeDefault = context.touchEnded(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ _main.default.prototype._ondragend = _main.default.prototype._onmouseup;
+ _main.default.prototype._ondragover = _main.default.prototype._onmousemove;
+
+ /**
+ * The mouseClicked() function is called once after a mouse button has been
+ * pressed and then released.
+ * Browsers handle clicks differently, so this function is only guaranteed to be
+ * run when the left mouse button is clicked. To handle other mouse buttons
+ * being pressed or released, see mousePressed() or mouseReleased().
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function mouseClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseClicked() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ *
+ */
+ _main.default.prototype._onclick = function(e) {
+ var context = this._isGlobal ? window : this;
+ if (typeof context.mouseClicked === 'function') {
+ var executeDefault = context.mouseClicked(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The doubleClicked() function is executed every time a event
+ * listener has detected a dblclick event which is a part of the
+ * DOM L3 specification. The doubleClicked event is fired when a
+ * pointing device button (usually a mouse's primary button)
+ * is clicked twice on a single element. For more info on the
+ * dblclick event refer to mozilla's documentation here:
+ * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick
+ *
+ * @method doubleClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been double clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function doubleClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function doubleClicked() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function doubleClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse doubleClick/press.
+ * no image displayed
+ */
+
+ _main.default.prototype._ondblclick = function(e) {
+ var context = this._isGlobal ? window : this;
+ if (typeof context.doubleClicked === 'function') {
+ var executeDefault = context.doubleClicked(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * For use with WebGL orbitControl.
+ * @property {Number} _mouseWheelDeltaY
+ * @readOnly
+ * @private
+ */
+ _main.default.prototype._mouseWheelDeltaY = 0;
+
+ /**
+ * For use with WebGL orbitControl.
+ * @property {Number} _pmouseWheelDeltaY
+ * @readOnly
+ * @private
+ */
+ _main.default.prototype._pmouseWheelDeltaY = 0;
+
+ /**
+ * The function mouseWheel() is executed every time a vertical mouse wheel
+ * event is detected either triggered by an actual mouse wheel or by a
+ * touchpad.
+ * The event.delta property returns the amount the mouse wheel
+ * have scrolled. The values can be positive or negative depending on the
+ * scroll direction (on OS X with "natural" scrolling enabled, the signs
+ * are inverted).
+ * Browsers may have different default behaviors attached to various
+ * mouse events. To prevent any default behavior for this event, add
+ * "return false" to the end of the method.
+ * Due to the current support of the "wheel" event on Safari, the function
+ * may only work as expected if "return false" is included while using Safari.
+ *
+ * @method mouseWheel
+ * @param {Object} [event] optional WheelEvent callback argument.
+ *
+ * @example
+ *
+ *
+ * let pos = 25;
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(25, pos, 50, 50);
+ * }
+ *
+ * function mouseWheel(event) {
+ * print(event.delta);
+ * //move the square according to the vertical scroll amount
+ * pos += event.delta;
+ * //uncomment to block page scrolling
+ * //return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect moves up and down with vertical scroll. fuchsia background
+ *
+ */
+ _main.default.prototype._onwheel = function(e) {
+ var context = this._isGlobal ? window : this;
+ this._setProperty('_mouseWheelDeltaY', e.deltaY);
+ if (typeof context.mouseWheel === 'function') {
+ e.delta = e.deltaY;
+ var executeDefault = context.mouseWheel(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The function requestPointerLock()
+ * locks the pointer to its current position and makes it invisible.
+ * Use movedX and movedY to get the difference the mouse was moved since
+ * the last call of draw
+ * Note that not all browsers support this feature
+ * This enables you to create experiences that aren't limited by the mouse moving out of the screen
+ * even if it is repeatedly moved into one direction.
+ * For example a first person perspective experience
+ *
+ * @method requestPointerLock
+ * @example
+ *
+ *
+ * let cam;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * requestPointerLock();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * cam.pan(-movedX * 0.001);
+ * cam.tilt(movedY * 0.001);
+ * sphere(25);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 3D scene moves according to mouse mouse movement in a first person perspective
+ *
+ */
+ _main.default.prototype.requestPointerLock = function() {
+ // pointer lock object forking for cross browser
+ var canvas = this._curElement.elt;
+ canvas.requestPointerLock =
+ canvas.requestPointerLock || canvas.mozRequestPointerLock;
+ if (!canvas.requestPointerLock) {
+ console.log('requestPointerLock is not implemented in this browser');
+ return false;
+ }
+ canvas.requestPointerLock();
+ return true;
+ };
+
+ /**
+ * The function exitPointerLock()
+ * exits a previously triggered pointer Lock
+ * for example to make ui elements usable etc
+ *
+ * @method exitPointerLock
+ * @example
+ *
+ *
+ * //click the canvas to lock the pointer
+ * //click again to exit (otherwise escape)
+ * let locked = false;
+ * function draw() {
+ * background(237, 34, 93);
+ * }
+ * function mouseClicked() {
+ * if (!locked) {
+ * locked = true;
+ * requestPointerLock();
+ * } else {
+ * exitPointerLock();
+ * locked = false;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * cursor gets locked / unlocked on mouse-click
+ *
+ */
+ _main.default.prototype.exitPointerLock = function() {
+ document.exitPointerLock();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 47: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Events
+ * @submodule Touch
+ * @for p5
+ * @requires core
+ */ /**
+ * The system variable touches[] contains an array of the positions of all
+ * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
+ * unique touch as it moves. Each element in the array is an object with x, y,
+ * and id properties.
+ *
+ * The touches[] array is not supported on Safari and IE on touch-based
+ * desktops (laptops).
+ *
+ * @property {Object[]} touches
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // On a touchscreen device, touch
+ * // the canvas using one or more fingers
+ * // at the same time
+ * function draw() {
+ * clear();
+ * let display = touches.length + ' touches';
+ * text(display, 5, 10);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Number of touches currently registered are displayed on the canvas
+ */ _main.default.prototype.touches = [];
+ _main.default.prototype._updateTouchCoords = function(e) {
+ if (this._curElement !== null) {
+ var touches = [];
+ for (var i = 0; i < e.touches.length; i++) {
+ touches[i] = getTouchInfo(
+ this._curElement.elt,
+ this.width,
+ this.height,
+ e,
+ i
+ );
+ }
+ this._setProperty('touches', touches);
+ }
+ };
+
+ function getTouchInfo(canvas, w, h, e) {
+ var i = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
+ var rect = canvas.getBoundingClientRect();
+ var sx = canvas.scrollWidth / w || 1;
+ var sy = canvas.scrollHeight / h || 1;
+ var touch = e.touches[i] || e.changedTouches[i];
+ return {
+ x: (touch.clientX - rect.left) / sx,
+ y: (touch.clientY - rect.top) / sy,
+ winX: touch.clientX,
+ winY: touch.clientY,
+ id: touch.identifier
+ };
+ }
+
+ /**
+ * The touchStarted() function is called once after every time a touch is
+ * registered. If no touchStarted() function is defined, the mousePressed()
+ * function will be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchStarted
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Touch within the image to change
+ * // the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchStarted() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function touchStarted() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchStarted(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns white with touch event.
+ * no image displayed
+ */
+ _main.default.prototype._ontouchstart = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', true);
+ this._updateTouchCoords(e);
+ this._updateNextMouseCoords(e);
+ this._updateMouseCoords(); // reset pmouseXY at the start of each touch event
+
+ if (typeof context.touchStarted === 'function') {
+ executeDefault = context.touchStarted(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ // only safari needs this manual fallback for consistency
+ } else if (
+ navigator.userAgent.toLowerCase().includes('safari') &&
+ typeof context.touchStarted === 'function'
+ ) {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The touchMoved() function is called every time a touch move is registered.
+ * If no touchMoved() function is defined, the mouseDragged() function will
+ * be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchMoved
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Move your finger across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function touchMoved() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns lighter with touch until white. resets
+ * no image displayed
+ *
+ */
+ _main.default.prototype._ontouchmove = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._updateTouchCoords(e);
+ this._updateNextMouseCoords(e);
+ if (typeof context.touchMoved === 'function') {
+ executeDefault = context.touchMoved(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.mouseDragged === 'function') {
+ executeDefault = context.mouseDragged(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The touchEnded() function is called every time a touch ends. If no
+ * touchEnded() function is defined, the mouseReleased() function will be
+ * called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchEnded
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Release touch within the image to
+ * // change the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchEnded() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function touchEnded() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchEnded(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns white with touch.
+ * no image displayed
+ *
+ */
+ _main.default.prototype._ontouchend = function(e) {
+ this._setProperty('mouseIsPressed', false);
+ this._updateTouchCoords(e);
+ this._updateNextMouseCoords(e);
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ if (typeof context.touchEnded === 'function') {
+ executeDefault = context.touchEnded(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.mouseReleased === 'function') {
+ executeDefault = context.mouseReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 48: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0; /*global ImageData:false */
+
+ /**
+ * This module defines the filters for use with image buffers.
+ *
+ * This module is basically a collection of functions stored in an object
+ * as opposed to modules. The functions are destructive, modifying
+ * the passed in canvas rather than creating a copy.
+ *
+ * Generally speaking users of this module will use the Filters.apply method
+ * on a canvas to create an effect.
+ *
+ * A number of functions are borrowed/adapted from
+ * http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
+ * or the java processing implementation.
+ */
+
+ var Filters = {};
+
+ /*
+ * Helper functions
+ */
+
+ /**
+ * Returns the pixel buffer for a canvas
+ *
+ * @private
+ *
+ * @param {Canvas|ImageData} canvas the canvas to get pixels from
+ * @return {Uint8ClampedArray} a one-dimensional array containing
+ * the data in thc RGBA order, with integer
+ * values between 0 and 255
+ */
+ Filters._toPixels = function(canvas) {
+ if (canvas instanceof ImageData) {
+ return canvas.data;
+ } else {
+ return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)
+ .data;
+ }
+ };
+
+ /**
+ * Returns a 32 bit number containing ARGB data at ith pixel in the
+ * 1D array containing pixels data.
+ *
+ * @private
+ *
+ * @param {Uint8ClampedArray} data array returned by _toPixels()
+ * @param {Integer} i index of a 1D Image Array
+ * @return {Integer} 32 bit integer value representing
+ * ARGB value.
+ */
+ Filters._getARGB = function(data, i) {
+ var offset = i * 4;
+ return (
+ ((data[offset + 3] << 24) & 0xff000000) |
+ ((data[offset] << 16) & 0x00ff0000) |
+ ((data[offset + 1] << 8) & 0x0000ff00) |
+ (data[offset + 2] & 0x000000ff)
+ );
+ };
+
+ /**
+ * Modifies pixels RGBA values to values contained in the data object.
+ *
+ * @private
+ *
+ * @param {Uint8ClampedArray} pixels array returned by _toPixels()
+ * @param {Int32Array} data source 1D array where each value
+ * represents ARGB values
+ */
+ Filters._setPixels = function(pixels, data) {
+ var offset = 0;
+ for (var i = 0, al = pixels.length; i < al; i++) {
+ offset = i * 4;
+ pixels[offset + 0] = (data[i] & 0x00ff0000) >>> 16;
+ pixels[offset + 1] = (data[i] & 0x0000ff00) >>> 8;
+ pixels[offset + 2] = data[i] & 0x000000ff;
+ pixels[offset + 3] = (data[i] & 0xff000000) >>> 24;
+ }
+ };
+
+ /**
+ * Returns the ImageData object for a canvas
+ * https://developer.mozilla.org/en-US/docs/Web/API/ImageData
+ *
+ * @private
+ *
+ * @param {Canvas|ImageData} canvas canvas to get image data from
+ * @return {ImageData} Holder of pixel data (and width and
+ * height) for a canvas
+ */
+ Filters._toImageData = function(canvas) {
+ if (canvas instanceof ImageData) {
+ return canvas;
+ } else {
+ return canvas
+ .getContext('2d')
+ .getImageData(0, 0, canvas.width, canvas.height);
+ }
+ };
+
+ /**
+ * Returns a blank ImageData object.
+ *
+ * @private
+ *
+ * @param {Integer} width
+ * @param {Integer} height
+ * @return {ImageData}
+ */
+ Filters._createImageData = function(width, height) {
+ Filters._tmpCanvas = document.createElement('canvas');
+ Filters._tmpCtx = Filters._tmpCanvas.getContext('2d');
+ return this._tmpCtx.createImageData(width, height);
+ };
+
+ /**
+ * Applys a filter function to a canvas.
+ *
+ * The difference between this and the actual filter functions defined below
+ * is that the filter functions generally modify the pixel buffer but do
+ * not actually put that data back to the canvas (where it would actually
+ * update what is visible). By contrast this method does make the changes
+ * actually visible in the canvas.
+ *
+ * The apply method is the method that callers of this module would generally
+ * use. It has been separated from the actual filters to support an advanced
+ * use case of creating a filter chain that executes without actually updating
+ * the canvas in between everystep.
+ *
+ * @private
+ * @param {HTMLCanvasElement} canvas [description]
+ * @param {function(ImageData,Object)} func [description]
+ * @param {Object} filterParam [description]
+ */
+ Filters.apply = function(canvas, func, filterParam) {
+ var pixelsState = canvas.getContext('2d');
+ var imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height);
+
+ //Filters can either return a new ImageData object, or just modify
+ //the one they received.
+ var newImageData = func(imageData, filterParam);
+ if (newImageData instanceof ImageData) {
+ pixelsState.putImageData(
+ newImageData,
+ 0,
+ 0,
+ 0,
+ 0,
+ canvas.width,
+ canvas.height
+ );
+ } else {
+ pixelsState.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
+ }
+ };
+
+ /*
+ * Filters
+ */
+
+ /**
+ * Converts the image to black and white pixels depending if they are above or
+ * below the threshold defined by the level parameter. The parameter must be
+ * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
+ *
+ * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
+ *
+ * @private
+ * @param {Canvas} canvas
+ * @param {Float} level
+ */
+ Filters.threshold = function(canvas, level) {
+ var pixels = Filters._toPixels(canvas);
+
+ if (level === undefined) {
+ level = 0.5;
+ }
+ var thresh = Math.floor(level * 255);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+ var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ var val = void 0;
+ if (gray >= thresh) {
+ val = 255;
+ } else {
+ val = 0;
+ }
+ pixels[i] = pixels[i + 1] = pixels[i + 2] = val;
+ }
+ };
+
+ /**
+ * Converts any colors in the image to grayscale equivalents.
+ * No parameter is used.
+ *
+ * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
+ *
+ * @private
+ * @param {Canvas} canvas
+ */
+ Filters.gray = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+
+ // CIE luminance for RGB
+ var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ pixels[i] = pixels[i + 1] = pixels[i + 2] = gray;
+ }
+ };
+
+ /**
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ * @private
+ * @param {Canvas} canvas
+ */
+ Filters.opaque = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ pixels[i + 3] = 255;
+ }
+
+ return pixels;
+ };
+
+ /**
+ * Sets each pixel to its inverse value. No parameter is used.
+ * @private
+ * @param {Canvas} canvas
+ */
+ Filters.invert = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ pixels[i] = 255 - pixels[i];
+ pixels[i + 1] = 255 - pixels[i + 1];
+ pixels[i + 2] = 255 - pixels[i + 2];
+ }
+ };
+
+ /**
+ * Limits each channel of the image to the number of colors specified as
+ * the parameter. The parameter can be set to values between 2 and 255, but
+ * results are most noticeable in the lower ranges.
+ *
+ * Adapted from java based processing implementation
+ *
+ * @private
+ * @param {Canvas} canvas
+ * @param {Integer} level
+ */
+ Filters.posterize = function(canvas, level) {
+ var pixels = Filters._toPixels(canvas);
+
+ if (level < 2 || level > 255) {
+ throw new Error(
+ 'Level must be greater than 2 and less than 255 for posterize'
+ );
+ }
+
+ var levels1 = level - 1;
+ for (var i = 0; i < pixels.length; i += 4) {
+ var rlevel = pixels[i];
+ var glevel = pixels[i + 1];
+ var blevel = pixels[i + 2];
+
+ pixels[i] = ((rlevel * level) >> 8) * 255 / levels1;
+ pixels[i + 1] = ((glevel * level) >> 8) * 255 / levels1;
+ pixels[i + 2] = ((blevel * level) >> 8) * 255 / levels1;
+ }
+ };
+
+ /**
+ * reduces the bright areas in an image
+ * @private
+ * @param {Canvas} canvas
+ *
+ */
+ Filters.dilate = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+ var currIdx = 0;
+ var maxIdx = pixels.length ? pixels.length / 4 : 0;
+ var out = new Int32Array(maxIdx);
+ var currRowIdx, maxRowIdx, colOrig, colOut, currLum;
+
+ var idxRight, idxLeft, idxUp, idxDown;
+ var colRight, colLeft, colUp, colDown;
+ var lumRight, lumLeft, lumUp, lumDown;
+
+ while (currIdx < maxIdx) {
+ currRowIdx = currIdx;
+ maxRowIdx = currIdx + canvas.width;
+ while (currIdx < maxRowIdx) {
+ colOrig = colOut = Filters._getARGB(pixels, currIdx);
+ idxLeft = currIdx - 1;
+ idxRight = currIdx + 1;
+ idxUp = currIdx - canvas.width;
+ idxDown = currIdx + canvas.width;
+
+ if (idxLeft < currRowIdx) {
+ idxLeft = currIdx;
+ }
+ if (idxRight >= maxRowIdx) {
+ idxRight = currIdx;
+ }
+ if (idxUp < 0) {
+ idxUp = 0;
+ }
+ if (idxDown >= maxIdx) {
+ idxDown = currIdx;
+ }
+ colUp = Filters._getARGB(pixels, idxUp);
+ colLeft = Filters._getARGB(pixels, idxLeft);
+ colDown = Filters._getARGB(pixels, idxDown);
+ colRight = Filters._getARGB(pixels, idxRight);
+
+ //compute luminance
+ currLum =
+ 77 * ((colOrig >> 16) & 0xff) +
+ 151 * ((colOrig >> 8) & 0xff) +
+ 28 * (colOrig & 0xff);
+ lumLeft =
+ 77 * ((colLeft >> 16) & 0xff) +
+ 151 * ((colLeft >> 8) & 0xff) +
+ 28 * (colLeft & 0xff);
+ lumRight =
+ 77 * ((colRight >> 16) & 0xff) +
+ 151 * ((colRight >> 8) & 0xff) +
+ 28 * (colRight & 0xff);
+ lumUp =
+ 77 * ((colUp >> 16) & 0xff) +
+ 151 * ((colUp >> 8) & 0xff) +
+ 28 * (colUp & 0xff);
+ lumDown =
+ 77 * ((colDown >> 16) & 0xff) +
+ 151 * ((colDown >> 8) & 0xff) +
+ 28 * (colDown & 0xff);
+
+ if (lumLeft > currLum) {
+ colOut = colLeft;
+ currLum = lumLeft;
+ }
+ if (lumRight > currLum) {
+ colOut = colRight;
+ currLum = lumRight;
+ }
+ if (lumUp > currLum) {
+ colOut = colUp;
+ currLum = lumUp;
+ }
+ if (lumDown > currLum) {
+ colOut = colDown;
+ currLum = lumDown;
+ }
+ out[currIdx++] = colOut;
+ }
+ }
+ Filters._setPixels(pixels, out);
+ };
+
+ /**
+ * increases the bright areas in an image
+ * @private
+ * @param {Canvas} canvas
+ *
+ */
+ Filters.erode = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+ var currIdx = 0;
+ var maxIdx = pixels.length ? pixels.length / 4 : 0;
+ var out = new Int32Array(maxIdx);
+ var currRowIdx, maxRowIdx, colOrig, colOut, currLum;
+ var idxRight, idxLeft, idxUp, idxDown;
+ var colRight, colLeft, colUp, colDown;
+ var lumRight, lumLeft, lumUp, lumDown;
+
+ while (currIdx < maxIdx) {
+ currRowIdx = currIdx;
+ maxRowIdx = currIdx + canvas.width;
+ while (currIdx < maxRowIdx) {
+ colOrig = colOut = Filters._getARGB(pixels, currIdx);
+ idxLeft = currIdx - 1;
+ idxRight = currIdx + 1;
+ idxUp = currIdx - canvas.width;
+ idxDown = currIdx + canvas.width;
+
+ if (idxLeft < currRowIdx) {
+ idxLeft = currIdx;
+ }
+ if (idxRight >= maxRowIdx) {
+ idxRight = currIdx;
+ }
+ if (idxUp < 0) {
+ idxUp = 0;
+ }
+ if (idxDown >= maxIdx) {
+ idxDown = currIdx;
+ }
+ colUp = Filters._getARGB(pixels, idxUp);
+ colLeft = Filters._getARGB(pixels, idxLeft);
+ colDown = Filters._getARGB(pixels, idxDown);
+ colRight = Filters._getARGB(pixels, idxRight);
+
+ //compute luminance
+ currLum =
+ 77 * ((colOrig >> 16) & 0xff) +
+ 151 * ((colOrig >> 8) & 0xff) +
+ 28 * (colOrig & 0xff);
+ lumLeft =
+ 77 * ((colLeft >> 16) & 0xff) +
+ 151 * ((colLeft >> 8) & 0xff) +
+ 28 * (colLeft & 0xff);
+ lumRight =
+ 77 * ((colRight >> 16) & 0xff) +
+ 151 * ((colRight >> 8) & 0xff) +
+ 28 * (colRight & 0xff);
+ lumUp =
+ 77 * ((colUp >> 16) & 0xff) +
+ 151 * ((colUp >> 8) & 0xff) +
+ 28 * (colUp & 0xff);
+ lumDown =
+ 77 * ((colDown >> 16) & 0xff) +
+ 151 * ((colDown >> 8) & 0xff) +
+ 28 * (colDown & 0xff);
+
+ if (lumLeft < currLum) {
+ colOut = colLeft;
+ currLum = lumLeft;
+ }
+ if (lumRight < currLum) {
+ colOut = colRight;
+ currLum = lumRight;
+ }
+ if (lumUp < currLum) {
+ colOut = colUp;
+ currLum = lumUp;
+ }
+ if (lumDown < currLum) {
+ colOut = colDown;
+ currLum = lumDown;
+ }
+
+ out[currIdx++] = colOut;
+ }
+ }
+ Filters._setPixels(pixels, out);
+ };
+
+ // BLUR
+
+ // internal kernel stuff for the gaussian blur filter
+ var blurRadius;
+ var blurKernelSize;
+ var blurKernel;
+ var blurMult;
+
+ /*
+ * Port of https://github.com/processing/processing/blob/
+ * master/core/src/processing/core/PImage.java#L1250
+ *
+ * Optimized code for building the blur kernel.
+ * further optimized blur code (approx. 15% for radius=20)
+ * bigger speed gains for larger radii (~30%)
+ * added support for various image types (ALPHA, RGB, ARGB)
+ * [toxi 050728]
+ */
+ function buildBlurKernel(r) {
+ var radius = (r * 3.5) | 0;
+ radius = radius < 1 ? 1 : radius < 248 ? radius : 248;
+
+ if (blurRadius !== radius) {
+ blurRadius = radius;
+ blurKernelSize = (1 + blurRadius) << 1;
+ blurKernel = new Int32Array(blurKernelSize);
+ blurMult = new Array(blurKernelSize);
+ for (var l = 0; l < blurKernelSize; l++) {
+ blurMult[l] = new Int32Array(256);
+ }
+
+ var bk, bki;
+ var bm, bmi;
+
+ for (var i = 1, radiusi = radius - 1; i < radius; i++) {
+ blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi;
+ bm = blurMult[radius + i];
+ bmi = blurMult[radiusi--];
+ for (var j = 0; j < 256; j++) {
+ bm[j] = bmi[j] = bki * j;
+ }
+ }
+ bk = blurKernel[radius] = radius * radius;
+ bm = blurMult[radius];
+
+ for (var k = 0; k < 256; k++) {
+ bm[k] = bk * k;
+ }
+ }
+ }
+
+ // Port of https://github.com/processing/processing/blob/
+ // master/core/src/processing/core/PImage.java#L1433
+ function blurARGB(canvas, radius) {
+ var pixels = Filters._toPixels(canvas);
+ var width = canvas.width;
+ var height = canvas.height;
+ var numPackedPixels = width * height;
+ var argb = new Int32Array(numPackedPixels);
+ for (var j = 0; j < numPackedPixels; j++) {
+ argb[j] = Filters._getARGB(pixels, j);
+ }
+ var sum, cr, cg, cb, ca;
+ var read, ri, ym, ymi, bk0;
+ var a2 = new Int32Array(numPackedPixels);
+ var r2 = new Int32Array(numPackedPixels);
+ var g2 = new Int32Array(numPackedPixels);
+ var b2 = new Int32Array(numPackedPixels);
+ var yi = 0;
+ buildBlurKernel(radius);
+ var x, y, i;
+ var bm;
+ for (y = 0; y < height; y++) {
+ for (x = 0; x < width; x++) {
+ cb = cg = cr = ca = sum = 0;
+ read = x - blurRadius;
+ if (read < 0) {
+ bk0 = -read;
+ read = 0;
+ } else {
+ if (read >= width) {
+ break;
+ }
+ bk0 = 0;
+ }
+ for (i = bk0; i < blurKernelSize; i++) {
+ if (read >= width) {
+ break;
+ }
+ var c = argb[read + yi];
+ bm = blurMult[i];
+ ca += bm[(c & -16777216) >>> 24];
+ cr += bm[(c & 16711680) >> 16];
+ cg += bm[(c & 65280) >> 8];
+ cb += bm[c & 255];
+ sum += blurKernel[i];
+ read++;
+ }
+ ri = yi + x;
+ a2[ri] = ca / sum;
+ r2[ri] = cr / sum;
+ g2[ri] = cg / sum;
+ b2[ri] = cb / sum;
+ }
+ yi += width;
+ }
+ yi = 0;
+ ym = -blurRadius;
+ ymi = ym * width;
+ for (y = 0; y < height; y++) {
+ for (x = 0; x < width; x++) {
+ cb = cg = cr = ca = sum = 0;
+ if (ym < 0) {
+ bk0 = ri = -ym;
+ read = x;
+ } else {
+ if (ym >= height) {
+ break;
+ }
+ bk0 = 0;
+ ri = ym;
+ read = x + ymi;
+ }
+ for (i = bk0; i < blurKernelSize; i++) {
+ if (ri >= height) {
+ break;
+ }
+ bm = blurMult[i];
+ ca += bm[a2[read]];
+ cr += bm[r2[read]];
+ cg += bm[g2[read]];
+ cb += bm[b2[read]];
+ sum += blurKernel[i];
+ ri++;
+ read += width;
+ }
+ argb[x + yi] =
+ ((ca / sum) << 24) | ((cr / sum) << 16) | ((cg / sum) << 8) | (cb / sum);
+ }
+ yi += width;
+ ymi += width;
+ ym++;
+ }
+ Filters._setPixels(pixels, argb);
+ }
+
+ Filters.blur = function(canvas, radius) {
+ blurARGB(canvas, radius);
+ };
+ var _default = Filters;
+ exports.default = _default;
+ },
+ {}
+ ],
+ 49: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var _omggif = _interopRequireDefault(_dereq_('omggif'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /** // This is not global, but ESLint is not aware that
+ * @module Image
+ * @submodule Image
+ * @for p5
+ * @requires core
+ */ /**
+ * This module defines the p5 methods for the p5.Image class
+ * for drawing images to the main display canvas.
+ */
+ // this module is implicitly enclosed with Browserify: this overrides the
+ // redefined-global error and permits using the name "frames" for the array
+ // of saved animation frames.
+ /* global frames:true */ var frames = []; // eslint-disable-line no-unused-vars
+ /**
+ * Creates a new p5.Image (the datatype for storing images). This provides a
+ * fresh buffer of pixels to play with. Set the size of the buffer with the
+ * width and height parameters.
+ *
+ * .pixels gives access to an array containing the values for all the pixels
+ * in the display window.
+ * These values are numbers. This array is the size (including an appropriate
+ * factor for the pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. See .pixels for
+ * more info. It may also be simpler to use set() or get().
+ *
+ * Before accessing the pixels of an image, the data must loaded with the
+ * loadPixels() function. After the array data has been modified, the
+ * updatePixels() function must be run to update the changes.
+ *
+ * @method createImage
+ * @param {Integer} width width in pixels
+ * @param {Integer} height height in pixels
+ * @return {p5.Image} the p5.Image object
+ * @example
+ *
+ *
+ * let img = createImage(66, 66);
+ * img.loadPixels();
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ *
+ *
+ * let img = createImage(66, 66);
+ * img.loadPixels();
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ * image(img, 34, 34);
+ *
+ *
+ *
+ *
+ *
+ * let pink = color(255, 102, 204);
+ * let img = createImage(66, 66);
+ * img.loadPixels();
+ * let d = pixelDensity();
+ * let halfImage = 4 * (img.width * d) * (img.height / 2 * d);
+ * for (let i = 0; i < halfImage; i += 4) {
+ * img.pixels[i] = red(pink);
+ * img.pixels[i + 1] = green(pink);
+ * img.pixels[i + 2] = blue(pink);
+ * img.pixels[i + 3] = alpha(pink);
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ * @alt
+ * 66x66 dark turquoise rect in center of canvas.
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ * no image displayed
+ *
+ */ _main.default.prototype.createImage = function(width, height) {
+ _main.default._validateParameters('createImage', arguments);
+ return new _main.default.Image(width, height);
+ };
+
+ /**
+ * Save the current canvas as an image. The browser will either save the
+ * file immediately, or prompt the user with a dialogue window.
+ *
+ * @method saveCanvas
+ * @param {p5.Element|HTMLCanvasElement} selectedCanvas a variable
+ * representing a specific html5 canvas (optional)
+ * @param {String} [filename]
+ * @param {String} [extension] 'jpg' or 'png'
+ *
+ * @example
+ *
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * }
+ *
+ *
+ * // note that this example has the same result as above
+ * // if no canvas is specified, defaults to main canvas
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas('myCanvas', 'jpg');
+ *
+ * // all of the following are valid
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * saveCanvas(c, 'myCanvas.jpg');
+ * saveCanvas(c, 'myCanvas');
+ * saveCanvas(c);
+ * saveCanvas('myCanvas', 'png');
+ * saveCanvas('myCanvas');
+ * saveCanvas();
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ * no image displayed
+ * no image displayed
+ */
+ /**
+ * @method saveCanvas
+ * @param {String} [filename]
+ * @param {String} [extension]
+ */
+ _main.default.prototype.saveCanvas = function() {
+ _main.default._validateParameters('saveCanvas', arguments);
+
+ // copy arguments to array
+ var args = [].slice.call(arguments);
+ var htmlCanvas, filename, extension;
+
+ if (arguments[0] instanceof HTMLCanvasElement) {
+ htmlCanvas = arguments[0];
+ args.shift();
+ } else if (arguments[0] instanceof _main.default.Element) {
+ htmlCanvas = arguments[0].elt;
+ args.shift();
+ } else {
+ htmlCanvas = this._curElement && this._curElement.elt;
+ }
+
+ if (args.length >= 1) {
+ filename = args[0];
+ }
+ if (args.length >= 2) {
+ extension = args[1];
+ }
+
+ extension =
+ extension ||
+ _main.default.prototype._checkFileExtension(filename, extension)[1] ||
+ 'png';
+
+ var mimeType;
+ switch (extension) {
+ default:
+ //case 'png':
+ mimeType = 'image/png';
+ break;
+ case 'jpeg':
+ case 'jpg':
+ mimeType = 'image/jpeg';
+ break;
+ }
+
+ htmlCanvas.toBlob(function(blob) {
+ _main.default.prototype.downloadFile(blob, filename, extension);
+ }, mimeType);
+ };
+
+ _main.default.prototype.saveGif = function(pImg, filename) {
+ var props = pImg.gifProperties;
+
+ //convert loopLimit back into Netscape Block formatting
+ var loopLimit = props.loopLimit;
+ if (loopLimit === 1) {
+ loopLimit = null;
+ } else if (loopLimit === null) {
+ loopLimit = 0;
+ }
+ var gifFormatDelay = props.delay / 10;
+ var opts = {
+ loop: loopLimit,
+ delay: gifFormatDelay
+ };
+
+ var buffer = new Uint8Array(
+ pImg.width * pImg.height * props.numFrames * gifFormatDelay
+ );
+
+ var gifWriter = new _omggif.default.GifWriter(
+ buffer,
+ pImg.width,
+ pImg.height,
+ opts
+ );
+ var palette = [];
+ //loop over frames and build pixel -> palette index for each
+ for (var i = 0; i < props.numFrames; i++) {
+ var pixelPaletteIndex = new Uint8Array(pImg.width * pImg.height);
+ var data = props.frames[i].data;
+ var dataLength = data.length;
+ for (var j = 0, k = 0; j < dataLength; j += 4, k++) {
+ var r = data[j + 0];
+ var g = data[j + 1];
+ var b = data[j + 2];
+ var color = (r << 16) | (g << 8) | (b << 0);
+ var index = palette.indexOf(color);
+ if (index === -1) {
+ pixelPaletteIndex[k] = palette.length;
+ palette.push(color);
+ } else {
+ pixelPaletteIndex[k] = index;
+ }
+ }
+ // force palette to be power of 2
+ var powof2 = 1;
+ while (powof2 < palette.length) {
+ powof2 <<= 1;
+ }
+ palette.length = powof2;
+ opts.palette = new Uint32Array(palette);
+ gifWriter.addFrame(0, 0, pImg.width, pImg.height, pixelPaletteIndex, opts);
+ }
+ gifWriter.end();
+ var extension = 'gif';
+ var blob = new Blob([buffer], { type: 'image/gif' });
+ _main.default.prototype.downloadFile(blob, filename, extension);
+ };
+
+ /**
+ * Capture a sequence of frames that can be used to create a movie.
+ * Accepts a callback. For example, you may wish to send the frames
+ * to a server where they can be stored or converted into a movie.
+ * If no callback is provided, the browser will pop up save dialogues in an
+ * attempt to download all of the images that have just been created. With the
+ * callback provided the image data isn't saved by default but instead passed
+ * as an argument to the callback function as an array of objects, with the
+ * size of array equal to the total number of frames.
+ *
+ * Note that saveFrames() will only save the first 15 frames of an animation.
+ * To export longer animations, you might look into a library like
+ * ccapture.js.
+ *
+ * @method saveFrames
+ * @param {String} filename
+ * @param {String} extension 'jpg' or 'png'
+ * @param {Number} duration Duration in seconds to save the frames for.
+ * @param {Number} framerate Framerate to save the frames in.
+ * @param {function(Array)} [callback] A callback function that will be executed
+ to handle the image data. This function
+ should accept an array as argument. The
+ array will contain the specified number of
+ frames of objects. Each object has three
+ properties: imageData - an
+ image/octet-stream, filename and extension.
+ * @example
+ *
+ * function draw() {
+ * background(mouseX);
+ * }
+ *
+ * function mousePressed() {
+ * saveFrames('out', 'png', 1, 25, data => {
+ * print(data);
+ * });
+ * }
+
+ *
+ * @alt
+ * canvas background goes from light to dark with mouse x.
+ *
+ */
+ _main.default.prototype.saveFrames = function(
+ fName,
+ ext,
+ _duration,
+ _fps,
+ callback
+ ) {
+ _main.default._validateParameters('saveFrames', arguments);
+ var duration = _duration || 3;
+ duration = _main.default.prototype.constrain(duration, 0, 15);
+ duration = duration * 1000;
+ var fps = _fps || 15;
+ fps = _main.default.prototype.constrain(fps, 0, 22);
+ var count = 0;
+
+ var makeFrame = _main.default.prototype._makeFrame;
+ var cnv = this._curElement.elt;
+ var frameFactory = setInterval(function() {
+ makeFrame(fName + count, ext, cnv);
+ count++;
+ }, 1000 / fps);
+
+ setTimeout(function() {
+ clearInterval(frameFactory);
+ if (callback) {
+ callback(frames);
+ } else {
+ var _arr = frames;
+ for (var _i = 0; _i < _arr.length; _i++) {
+ var f = _arr[_i];
+ _main.default.prototype.downloadFile(f.imageData, f.filename, f.ext);
+ }
+ }
+ frames = []; // clear frames
+ }, duration + 0.01);
+ };
+
+ _main.default.prototype._makeFrame = function(filename, extension, _cnv) {
+ var cnv;
+ if (this) {
+ cnv = this._curElement.elt;
+ } else {
+ cnv = _cnv;
+ }
+ var mimeType;
+ if (!extension) {
+ extension = 'png';
+ mimeType = 'image/png';
+ } else {
+ switch (extension.toLowerCase()) {
+ case 'png':
+ mimeType = 'image/png';
+ break;
+ case 'jpeg':
+ mimeType = 'image/jpeg';
+ break;
+ case 'jpg':
+ mimeType = 'image/jpeg';
+ break;
+ default:
+ mimeType = 'image/png';
+ break;
+ }
+ }
+ var downloadMime = 'image/octet-stream';
+ var imageData = cnv.toDataURL(mimeType);
+ imageData = imageData.replace(mimeType, downloadMime);
+
+ var thisFrame = {};
+ thisFrame.imageData = imageData;
+ thisFrame.filename = filename;
+ thisFrame.ext = extension;
+ frames.push(thisFrame);
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27, omggif: 11 }
+ ],
+ 50: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var _filters = _interopRequireDefault(_dereq_('./filters'));
+ var _helpers = _interopRequireDefault(_dereq_('../core/helpers'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ var _omggif = _interopRequireDefault(_dereq_('omggif'));
+
+ _dereq_('../core/error_helpers');
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Image
+ * @submodule Loading & Displaying
+ * @for p5
+ * @requires core
+ */ /**
+ * Loads an image from a path and creates a p5.Image from it.
+ *
+ * The image may not be immediately available for rendering
+ * If you want to ensure that the image is ready before doing
+ * anything with it, place the loadImage() call in preload().
+ * You may also supply a callback function to handle the image when it's ready.
+ *
+ * The path to the image should be relative to the HTML file
+ * that links in your sketch. Loading an image from a URL or other
+ * remote location may be blocked due to your browser's built-in
+ * security.
+ *
+ * @method loadImage
+ * @param {String} path Path of the image to be loaded
+ * @param {function(p5.Image)} [successCallback] Function to be called once
+ * the image is loaded. Will be passed the
+ * p5.Image.
+ * @param {function(Event)} [failureCallback] called with event error if
+ * the image fails to load.
+ * @return {p5.Image} the p5.Image object
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * // here we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', img => {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and grided ceililng above
+ * image of the underside of a white umbrella and grided ceililng above
+ *
+ */ _main.default.prototype.loadImage = function(
+ path,
+ successCallback,
+ failureCallback
+ ) {
+ _main.default._validateParameters('loadImage', arguments);
+ var pImg = new _main.default.Image(1, 1, this);
+ var self = this;
+
+ var req = new Request(path, {
+ method: 'GET',
+ mode: 'cors'
+ });
+
+ fetch(path, req).then(function(response) {
+ // GIF section
+ if (response.headers.get('content-type').includes('image/gif')) {
+ response.arrayBuffer().then(
+ function(arrayBuffer) {
+ if (arrayBuffer) {
+ var byteArray = new Uint8Array(arrayBuffer);
+ _createGif(
+ byteArray,
+ pImg,
+ successCallback,
+ failureCallback,
+ function(pImg) {
+ self._decrementPreload();
+ }.bind(self)
+ );
+ }
+ },
+ function(e) {
+ if (typeof failureCallback === 'function') {
+ failureCallback(e);
+ } else {
+ console.error(e);
+ }
+ }
+ );
+ } else {
+ // Non-GIF Section
+ var img = new Image();
+
+ img.onload = function() {
+ pImg.width = pImg.canvas.width = img.width;
+ pImg.height = pImg.canvas.height = img.height;
+
+ // Draw the image into the backing canvas of the p5.Image
+ pImg.drawingContext.drawImage(img, 0, 0);
+ pImg.modified = true;
+ if (typeof successCallback === 'function') {
+ successCallback(pImg);
+ }
+ self._decrementPreload();
+ };
+
+ img.onerror = function(e) {
+ _main.default._friendlyFileLoadError(0, img.src);
+ if (typeof failureCallback === 'function') {
+ failureCallback(e);
+ } else {
+ console.error(e);
+ }
+ };
+
+ // Set crossOrigin in case image is served with CORS headers.
+ // This will let us draw to the canvas without tainting it.
+ // See https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image
+ // When using data-uris the file will be loaded locally
+ // so we don't need to worry about crossOrigin with base64 file types.
+ if (path.indexOf('data:image/') !== 0) {
+ img.crossOrigin = 'Anonymous';
+ }
+ // start loading the image
+ img.src = path;
+ }
+ pImg.modified = true;
+ });
+ return pImg;
+ };
+
+ /**
+ * Helper function for loading GIF-based images
+ *
+ */
+ function _createGif(
+ arrayBuffer,
+ pImg,
+ successCallback,
+ failureCallback,
+ finishCallback
+ ) {
+ var gifReader = new _omggif.default.GifReader(arrayBuffer);
+ pImg.width = pImg.canvas.width = gifReader.width;
+ pImg.height = pImg.canvas.height = gifReader.height;
+ var frames = [];
+ var numFrames = gifReader.numFrames();
+ var framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4);
+ // I didn't realize this at first but some GIFs encode with frame
+ // Reworking delay to be frame level will make it less powerful
+ // to modify for users. For now this works with 99% of GIFs that
+ // I can find and for those that it doesn't there is just a retiming
+ // of the frames, which would be minor for all but the strangest GIFs
+ var averageDelay = 0;
+ if (numFrames > 1) {
+ var loadGIFFrameIntoImage = function loadGIFFrameIntoImage(
+ frameNum,
+ gifReader
+ ) {
+ try {
+ gifReader.decodeAndBlitFrameRGBA(frameNum, framePixels);
+ } catch (e) {
+ _main.default._friendlyFileLoadError(8, pImg.src);
+ if (typeof failureCallback === 'function') {
+ failureCallback(e);
+ } else {
+ console.error(e);
+ }
+ }
+ };
+ for (var j = 0; j < numFrames; j++) {
+ var frameInfo = gifReader.frameInfo(j);
+ averageDelay += frameInfo.delay;
+ // Some GIFs are encoded so that they expect the previous frame
+ // to be under the current frame. This can occur at a sub-frame level
+ // There are possible disposal codes but I didn't encounter any
+ if (gifReader.frameInfo(j).disposal === 1 && j > 0) {
+ pImg.drawingContext.putImageData(frames[j - 1], 0, 0);
+ } else {
+ pImg.drawingContext.clearRect(0, 0, pImg.width, pImg.height);
+ framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4);
+ }
+ loadGIFFrameIntoImage(j, gifReader);
+ var imageData = new ImageData(framePixels, pImg.width, pImg.height);
+ pImg.drawingContext.putImageData(imageData, 0, 0);
+ frames.push(
+ pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height)
+ );
+ }
+
+ //Uses Netscape block encoding
+ //to repeat forever, this will be 0
+ //to repeat just once, this will be null
+ //to repeat N times (1 0 && sVal < iVal) {
+ return sVal;
+ } else {
+ return iVal;
+ }
+ }
+
+ /**
+ * Draw an image to the p5.js canvas.
+ *
+ * This function can be used with different numbers of parameters. The
+ * simplest use requires only three parameters: img, x, and y—where (x, y) is
+ * the position of the image. Two more parameters can optionally be added to
+ * specify the width and height of the image.
+ *
+ * This function can also be used with all eight Number parameters. To
+ * differentiate between all these parameters, p5.js uses the language of
+ * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source
+ * image" (which corresponds to "sx", "sy", etc.) below. Specifying the
+ * "source image" dimensions can be useful when you want to display a
+ * subsection of the source image instead of the whole thing. Here's a diagram
+ * to explain further:
+ *
+ *
+ * @method image
+ * @param {p5.Image|p5.Element} img the image to display
+ * @param {Number} x the x-coordinate of the top-left corner of the image
+ * @param {Number} y the y-coordinate of the top-left corner of the image
+ * @param {Number} [width] the width to draw the image
+ * @param {Number} [height] the height to draw the image
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * background(50);
+ * // Top-left corner of the img is at (10, 10)
+ * // Width and height are 50 x 50
+ * image(img, 10, 10, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * // Here, we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', img => {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/gradient.png');
+ * }
+ * function setup() {
+ * // 1. Background image
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height, 100 x 100
+ * image(img, 0, 0);
+ * // 2. Top right image
+ * // Top-left corner of destination rectangle is at (50, 0)
+ * // Destination rectangle width and height are 40 x 20
+ * // The next parameters are relative to the source image:
+ * // - Starting at position (50, 50) on the source image, capture a 50 x 50
+ * // subsection
+ * // - Draw this subsection to fill the dimensions of the destination rectangle
+ * image(img, 50, 0, 40, 20, 50, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and gridded ceiling above
+ * image of the underside of a white umbrella and gridded ceiling above
+ *
+ */
+ /**
+ * @method image
+ * @param {p5.Image|p5.Element} img
+ * @param {Number} dx the x-coordinate of the destination
+ * rectangle in which to draw the source image
+ * @param {Number} dy the y-coordinate of the destination
+ * rectangle in which to draw the source image
+ * @param {Number} dWidth the width of the destination rectangle
+ * @param {Number} dHeight the height of the destination rectangle
+ * @param {Number} sx the x-coordinate of the subsection of the source
+ * image to draw into the destination rectangle
+ * @param {Number} sy the y-coordinate of the subsection of the source
+ * image to draw into the destination rectangle
+ * @param {Number} [sWidth] the width of the subsection of the
+ * source image to draw into the destination
+ * rectangle
+ * @param {Number} [sHeight] the height of the subsection of the
+ * source image to draw into the destination rectangle
+ */
+ _main.default.prototype.image = function(
+ img,
+ dx,
+ dy,
+ dWidth,
+ dHeight,
+ sx,
+ sy,
+ sWidth,
+ sHeight
+ ) {
+ // set defaults per spec: https://goo.gl/3ykfOq
+
+ _main.default._validateParameters('image', arguments);
+
+ var defW = img.width;
+ var defH = img.height;
+
+ if (img.elt && img.elt.videoWidth && !img.canvas) {
+ // video no canvas
+ defW = img.elt.videoWidth;
+ defH = img.elt.videoHeight;
+ }
+
+ var _dx = dx;
+ var _dy = dy;
+ var _dw = dWidth || defW;
+ var _dh = dHeight || defH;
+ var _sx = sx || 0;
+ var _sy = sy || 0;
+ var _sw = sWidth || defW;
+ var _sh = sHeight || defH;
+
+ _sw = _sAssign(_sw, defW);
+ _sh = _sAssign(_sh, defH);
+
+ // This part needs cleanup and unit tests
+ // see issues https://github.com/processing/p5.js/issues/1741
+ // and https://github.com/processing/p5.js/issues/1673
+ var pd = 1;
+
+ if (img.elt && !img.canvas && img.elt.style.width) {
+ //if img is video and img.elt.size() has been used and
+ //no width passed to image()
+ if (img.elt.videoWidth && !dWidth) {
+ pd = img.elt.videoWidth;
+ } else {
+ //all other cases
+ pd = img.elt.width;
+ }
+ pd /= parseInt(img.elt.style.width, 10);
+ }
+
+ _sx *= pd;
+ _sy *= pd;
+ _sh *= pd;
+ _sw *= pd;
+
+ var vals = _helpers.default.modeAdjust(
+ _dx,
+ _dy,
+ _dw,
+ _dh,
+ this._renderer._imageMode
+ );
+
+ // tint the image if there is a tint
+ this._renderer.image(img, _sx, _sy, _sw, _sh, vals.x, vals.y, vals.w, vals.h);
+ };
+
+ /**
+ * Sets the fill value for displaying images. Images can be tinted to
+ * specified colors or made transparent by including an alpha value.
+ *
+ * To apply transparency to an image without affecting its color, use
+ * white as the tint color and specify an alpha value. For instance,
+ * tint(255, 128) will make an image 50% transparent (assuming the default
+ * alpha range of 0-255, which can be changed with colorMode()).
+ *
+ * The value for the gray parameter must be less than or equal to the current
+ * maximum value as specified by colorMode(). The default maximum value is
+ * 255.
+ *
+ *
+ * @method tint
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @param {Number} [alpha]
+ *
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * tint(0, 153, 204); // Tint blue
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * tint(0, 153, 204, 126); // Tint blue and set transparency
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * tint(255, 126); // Apply transparency without changing color
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 side by side images of umbrella and ceiling, one image with blue tint
+ * Images of umbrella and ceiling, one half of image with blue tint
+ * 2 side by side images of umbrella and ceiling, one image translucent
+ *
+ */
+
+ /**
+ * @method tint
+ * @param {String} value a color string
+ */
+
+ /**
+ * @method tint
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ */
+
+ /**
+ * @method tint
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ */
+
+ /**
+ * @method tint
+ * @param {p5.Color} color the tint color
+ */
+ _main.default.prototype.tint = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('tint', args);
+ var c = this.color.apply(this, args);
+ this._renderer._tint = c.levels;
+ };
+
+ /**
+ * Removes the current fill value for displaying images and reverts to
+ * displaying images with their original hues.
+ *
+ * @method noTint
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * tint(0, 153, 204); // Tint blue
+ * image(img, 0, 0);
+ * noTint(); // Disable tint
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 side by side images of bricks, left image with blue tint
+ *
+ */
+ _main.default.prototype.noTint = function() {
+ this._renderer._tint = null;
+ };
+
+ /**
+ * Apply the current tint color to the input image, return the resulting
+ * canvas.
+ *
+ * @private
+ * @param {p5.Image} The image to be tinted
+ * @return {canvas} The resulting tinted canvas
+ *
+ */
+ _main.default.prototype._getTintedImageCanvas = function(img) {
+ if (!img.canvas) {
+ return img;
+ }
+ var pixels = _filters.default._toPixels(img.canvas);
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = img.canvas.width;
+ tmpCanvas.height = img.canvas.height;
+ var tmpCtx = tmpCanvas.getContext('2d');
+ var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height);
+ var newPixels = id.data;
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+ var a = pixels[i + 3];
+
+ newPixels[i] = r * this._renderer._tint[0] / 255;
+ newPixels[i + 1] = g * this._renderer._tint[1] / 255;
+ newPixels[i + 2] = b * this._renderer._tint[2] / 255;
+ newPixels[i + 3] = a * this._renderer._tint[3] / 255;
+ }
+
+ tmpCtx.putImageData(id, 0, 0);
+ return tmpCanvas;
+ };
+
+ /**
+ * Set image mode. Modifies the location from which images are drawn by
+ * changing the way in which parameters given to image() are interpreted.
+ * The default mode is imageMode(CORNER), which interprets the second and
+ * third parameters of image() as the upper-left corner of the image. If
+ * two additional parameters are specified, they are used to set the image's
+ * width and height.
+ *
+ * imageMode(CORNERS) interprets the second and third parameters of image()
+ * as the location of one corner, and the fourth and fifth parameters as the
+ * opposite corner.
+ *
+ * imageMode(CENTER) interprets the second and third parameters of image()
+ * as the image's center point. If two additional parameters are specified,
+ * they are used to set the image's width and height.
+ *
+ * @method imageMode
+ * @param {Constant} mode either CORNER, CORNERS, or CENTER
+ * @example
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * imageMode(CORNER);
+ * image(img, 10, 10, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * imageMode(CORNERS);
+ * image(img, 10, 10, 90, 40);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * imageMode(CENTER);
+ * image(img, 50, 50, 80, 80);
+ * }
+ *
+ *
+ *
+ * @alt
+ * small square image of bricks
+ * horizontal rectangle image of bricks
+ * large square image of bricks
+ *
+ */
+ _main.default.prototype.imageMode = function(m) {
+ _main.default._validateParameters('imageMode', arguments);
+ if (
+ m === constants.CORNER ||
+ m === constants.CORNERS ||
+ m === constants.CENTER
+ ) {
+ this._renderer._imageMode = m;
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 21,
+ '../core/error_helpers': 23,
+ '../core/helpers': 24,
+ '../core/main': 27,
+ './filters': 48,
+ omggif: 11
+ }
+ ],
+ 51: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var _filters = _interopRequireDefault(_dereq_('./filters'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Image
+ * @submodule Image
+ * @requires core
+ * @requires constants
+ * @requires filters
+ */ /**
+ * This module defines the p5.Image class and P5 methods for
+ * drawing images to the main display canvas.
+ */ /*
+ * Class methods
+ */ /**
+ * Creates a new p5.Image. A p5.Image is a canvas backed representation of an
+ * image.
+ *
+ * p5 can display .gif, .jpg and .png images. Images may be displayed
+ * in 2D and 3D space. Before an image is used, it must be loaded with the
+ * loadImage() function. The p5.Image class contains fields for the width and
+ * height of the image, as well as an array called pixels[] that contains the
+ * values for every pixel in the image.
+ *
+ * The methods described below allow easy access to the image's pixels and
+ * alpha channel and simplify the process of compositing.
+ *
+ * Before using the pixels[] array, be sure to use the loadPixels() method on
+ * the image to make sure that the pixel data is properly loaded.
+ * @example
+ *
+ * function setup() {
+ * let img = createImage(100, 100); // same as new p5.Image(100, 100);
+ * img.loadPixels();
+ * createCanvas(100, 100);
+ * background(0);
+ *
+ * // helper for writing color to array
+ * function writeColor(image, x, y, red, green, blue, alpha) {
+ * let index = (x + y * width) * 4;
+ * image.pixels[index] = red;
+ * image.pixels[index + 1] = green;
+ * image.pixels[index + 2] = blue;
+ * image.pixels[index + 3] = alpha;
+ * }
+ *
+ * let x, y;
+ * // fill with random colors
+ * for (y = 0; y < img.height; y++) {
+ * for (x = 0; x < img.width; x++) {
+ * let red = random(255);
+ * let green = random(255);
+ * let blue = random(255);
+ * let alpha = 255;
+ * writeColor(img, x, y, red, green, blue, alpha);
+ * }
+ * }
+ *
+ * // draw a red line
+ * y = 0;
+ * for (x = 0; x < img.width; x++) {
+ * writeColor(img, x, y, 255, 0, 0, 255);
+ * }
+ *
+ * // draw a green line
+ * y = img.height - 1;
+ * for (x = 0; x < img.width; x++) {
+ * writeColor(img, x, y, 0, 255, 0, 255);
+ * }
+ *
+ * img.updatePixels();
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ * @class p5.Image
+ * @param {Number} width
+ * @param {Number} height
+ */ _main.default.Image = function(width, height) {
+ /**
+ * Image width.
+ * @property {Number} width
+ * @readOnly
+ * @example
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (let i = 0; i < img.width; i++) {
+ * let c = img.get(i, img.height / 2);
+ * stroke(c);
+ * line(i, height / 2, i, height);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains in top and horizontal lines in corresponding colors in bottom.
+ *
+ */ this.width = width;
+ /**
+ * Image height.
+ * @property {Number} height
+ * @readOnly
+ * @example
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (let i = 0; i < img.height; i++) {
+ * let c = img.get(img.width / 2, i);
+ * stroke(c);
+ * line(0, i, width / 2, i);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains on right and vertical lines in corresponding colors on left.
+ *
+ */ this.height = height;
+ this.canvas = document.createElement('canvas');
+ this.canvas.width = this.width;
+ this.canvas.height = this.height;
+ this.drawingContext = this.canvas.getContext('2d');
+ this._pixelsState = this;
+ this._pixelDensity = 1;
+ //Object for working with GIFs, defaults to null
+ this.gifProperties = null;
+ //For WebGL Texturing only: used to determine whether to reupload texture to GPU
+ this._modified = false;
+ /**
+ * Array containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high denisty displays may have more pixels (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100x100 pixels, there will be 40,000. With
+ * pixelDensity = 2, there will be 160,000. The first four values
+ * (indices 0-3) in the array will be the R, G, B, A values of the pixel at
+ * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A
+ * values of the pixel at (1, 0). More generally, to set values for a pixel
+ * at (x, y):
+ * ```javascript
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
+ * // loop over
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
+ * }
+ * }
+ * ```
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * let img = createImage(66, 66);
+ * img.loadPixels();
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ *
+ * let pink = color(255, 102, 204);
+ * let img = createImage(66, 66);
+ * img.loadPixels();
+ * for (let i = 0; i < 4 * (width * height / 2); i += 4) {
+ * img.pixels[i] = red(pink);
+ * img.pixels[i + 1] = green(pink);
+ * img.pixels[i + 2] = blue(pink);
+ * img.pixels[i + 3] = alpha(pink);
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ * @alt
+ * 66x66 turquoise rect in center of canvas
+ * 66x66 pink rect in center of canvas
+ *
+ */
+ this.pixels = [];
+ };
+
+ /**
+ * Helper function for animating GIF-based images with time
+ *
+ */
+ _main.default.Image.prototype._animateGif = function(pInst) {
+ var props = this.gifProperties;
+ if (props.playing) {
+ props.timeDisplayed += pInst.deltaTime;
+ }
+
+ if (props.timeDisplayed >= props.delay) {
+ //GIF is bound to 'realtime' so can skip frames
+ var skips = Math.floor(props.timeDisplayed / props.delay);
+ props.timeDisplayed = 0;
+ props.displayIndex += skips;
+ props.loopCount = Math.floor(props.displayIndex / props.numFrames);
+ if (props.loopLimit !== null && props.loopCount >= props.loopLimit) {
+ props.playing = false;
+ } else {
+ var ind = props.displayIndex % props.numFrames;
+ this.drawingContext.putImageData(props.frames[ind], 0, 0);
+ props.displayIndex = ind;
+ this.setModified(true);
+ }
+ }
+ };
+
+ /**
+ * Helper fxn for sharing pixel methods
+ *
+ */
+ _main.default.Image.prototype._setProperty = function(prop, value) {
+ this[prop] = value;
+ this.setModified(true);
+ };
+
+ /**
+ * Loads the pixels data for this image into the [pixels] attribute.
+ *
+ * @method loadPixels
+ * @example
+ *
+ * let myImage;
+ * let halfImage;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * myImage.loadPixels();
+ * halfImage = 4 * myImage.width * myImage.height / 2;
+ * for (let i = 0; i < halfImage; i++) {
+ * myImage.pixels[i + halfImage] = myImage.pixels[i];
+ * }
+ * myImage.updatePixels();
+ * }
+ *
+ * function draw() {
+ * image(myImage, 0, 0, width, height);
+ * }
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ *
+ */
+ _main.default.Image.prototype.loadPixels = function() {
+ _main.default.Renderer2D.prototype.loadPixels.call(this);
+ this.setModified(true);
+ };
+
+ /**
+ * Updates the backing canvas for this image with the contents of
+ * the [pixels] array.
+ *
+ * If this image is an animated GIF then the pixels will be updated
+ * in the frame that is currently displayed.
+ *
+ * @method updatePixels
+ * @param {Integer} x x-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} y y-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} w height of the target update area for the
+ * underlying canvas
+ * @param {Integer} h height of the target update area for the
+ * underlying canvas
+ * @example
+ *
+ * let myImage;
+ * let halfImage;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * myImage.loadPixels();
+ * halfImage = 4 * myImage.width * myImage.height / 2;
+ * for (let i = 0; i < halfImage; i++) {
+ * myImage.pixels[i + halfImage] = myImage.pixels[i];
+ * }
+ * myImage.updatePixels();
+ * }
+ *
+ * function draw() {
+ * image(myImage, 0, 0, width, height);
+ * }
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ *
+ */
+ /**
+ * @method updatePixels
+ */
+ _main.default.Image.prototype.updatePixels = function(x, y, w, h) {
+ _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h);
+ this.setModified(true);
+ };
+
+ /**
+ * Get a region of pixels from an image.
+ *
+ * If no params are passed, the whole image is returned.
+ * If x and y are the only params passed a single pixel is extracted.
+ * If all params are passed a rectangle region is extracted and a p5.Image
+ * is returned.
+ *
+ * @method get
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
+ * @example
+ *
+ * let myImage;
+ * let c;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * background(myImage);
+ * noStroke();
+ * c = myImage.get(60, 90);
+ * fill(c);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * //get() returns color here
+ *
+ *
+ * @alt
+ * image of rocky mountains with 50x50 green rect in front
+ *
+ */
+ /**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+ /**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of pixel at x,y in array format [R, G, B, A]
+ */
+ _main.default.Image.prototype.get = function(x, y, w, h) {
+ _main.default._validateParameters('p5.Image.get', arguments);
+ return _main.default.Renderer2D.prototype.get.apply(this, arguments);
+ };
+
+ _main.default.Image.prototype._getPixel =
+ _main.default.Renderer2D.prototype._getPixel;
+
+ /**
+ * Set the color of a single pixel or write an image into
+ * this p5.Image.
+ *
+ * Note that for a large number of pixels this will
+ * be slower than directly manipulating the pixels array
+ * and then calling updatePixels().
+ *
+ * @method set
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number|Number[]|Object} a grayscale value | pixel array |
+ * a p5.Color | image to copy
+ * @example
+ *
+ *
+ * let img = createImage(66, 66);
+ * img.loadPixels();
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ * image(img, 34, 34);
+ *
+ *
+ *
+ * @alt
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ *
+ */
+ _main.default.Image.prototype.set = function(x, y, imgOrCol) {
+ _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+ };
+
+ /**
+ * Resize the image to a new width and height. To make the image scale
+ * proportionally, use 0 as the value for the wide or high parameter.
+ * For instance, to make the width of an image 150 pixels, and change
+ * the height using the same proportion, use resize(150, 0).
+ *
+ * @method resize
+ * @param {Number} width the resized image width
+ * @param {Number} height the resized image height
+ * @example
+ *
+ * let img;
+ *
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+
+ * function draw() {
+ * image(img, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * img.resize(50, 100);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. zoomed in
+ *
+ */
+ _main.default.Image.prototype.resize = function(width, height) {
+ // Copy contents to a temporary canvas, resize the original
+ // and then copy back.
+ //
+ // There is a faster approach that involves just one copy and swapping the
+ // this.canvas reference. We could switch to that approach if (as i think
+ // is the case) there an expectation that the user would not hold a
+ // reference to the backing canvas of a p5.Image. But since we do not
+ // enforce that at the moment, I am leaving in the slower, but safer
+ // implementation.
+
+ // auto-resize
+ if (width === 0 && height === 0) {
+ width = this.canvas.width;
+ height = this.canvas.height;
+ } else if (width === 0) {
+ width = this.canvas.width * height / this.canvas.height;
+ } else if (height === 0) {
+ height = this.canvas.height * width / this.canvas.width;
+ }
+
+ width = Math.floor(width);
+ height = Math.floor(height);
+
+ var tempCanvas = document.createElement('canvas');
+ tempCanvas.width = width;
+ tempCanvas.height = height;
+
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ //adapted from github.com/LinusU/resize-image-data
+ var nearestNeighbor = function nearestNeighbor(src, dst) {
+ var pos = 0;
+ for (var y = 0; y < dst.height; y++) {
+ for (var x = 0; x < dst.width; x++) {
+ var srcX = Math.floor(x * src.width / dst.width);
+ var srcY = Math.floor(y * src.height / dst.height);
+ var srcPos = (srcY * src.width + srcX) * 4;
+ dst.data[pos++] = src.data[srcPos++]; // R
+ dst.data[pos++] = src.data[srcPos++]; // G
+ dst.data[pos++] = src.data[srcPos++]; // B
+ dst.data[pos++] = src.data[srcPos++]; // A
+ }
+ }
+ };
+ for (var i = 0; i < props.numFrames; i++) {
+ var resizedImageData = this.drawingContext.createImageData(width, height);
+
+ nearestNeighbor(props.frames[i], resizedImageData);
+ props.frames[i] = resizedImageData;
+ }
+ }
+
+ // prettier-ignore
+ tempCanvas.getContext('2d').drawImage(
+ this.canvas,
+ 0, 0, this.canvas.width, this.canvas.height,
+ 0, 0, tempCanvas.width, tempCanvas.height);
+
+ // Resize the original canvas, which will clear its contents
+ this.canvas.width = this.width = width;
+ this.canvas.height = this.height = height;
+
+ //Copy the image back
+
+ // prettier-ignore
+ this.drawingContext.drawImage(
+ tempCanvas,
+ 0, 0, width, height,
+ 0, 0, width, height);
+
+ if (this.pixels.length > 0) {
+ this.loadPixels();
+ }
+
+ this.setModified(true);
+ };
+
+ /**
+ * Copies a region of pixels from one image to another. If no
+ * srcImage is specified this is used as the source. If the source
+ * and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target region.
+ *
+ * @method copy
+ * @param {p5.Image|p5.Element} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ * @example
+ *
+ * let photo;
+ * let bricks;
+ * let x;
+ * let y;
+ *
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks.jpg');
+ * }
+ *
+ * function setup() {
+ * x = bricks.width / 2;
+ * y = bricks.height / 2;
+ * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);
+ * image(photo, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains and smaller image on top of bricks at top left
+ *
+ */
+ /**
+ * @method copy
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ */
+ _main.default.Image.prototype.copy = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default.prototype.copy.apply(this, args);
+ };
+
+ /**
+ * Masks part of an image from displaying by loading another
+ * image and using it's alpha channel as an alpha channel for
+ * this image.
+ *
+ * @method mask
+ * @param {p5.Image} srcImage source image
+ * @example
+ *
+ * let photo, maskImage;
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * maskImage = loadImage('assets/mask2.png');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * photo.mask(maskImage);
+ * image(photo, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains with white at right
+ *
+ *
+ * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
+ *
+ */
+ // TODO: - Accept an array of alpha values.
+ // - Use other channels of an image. p5 uses the
+ // blue channel (which feels kind of arbitrary). Note: at the
+ // moment this method does not match native processings original
+ // functionality exactly.
+ _main.default.Image.prototype.mask = function(p5Image) {
+ if (p5Image === undefined) {
+ p5Image = this;
+ }
+ var currBlend = this.drawingContext.globalCompositeOperation;
+
+ var scaleFactor = 1;
+ if (p5Image instanceof _main.default.Renderer) {
+ scaleFactor = p5Image._pInst._pixelDensity;
+ }
+
+ var copyArgs = [
+ p5Image,
+ 0,
+ 0,
+ scaleFactor * p5Image.width,
+ scaleFactor * p5Image.height,
+ 0,
+ 0,
+ this.width,
+ this.height
+ ];
+
+ this.drawingContext.globalCompositeOperation = 'destination-in';
+ _main.default.Image.prototype.copy.apply(this, copyArgs);
+ this.drawingContext.globalCompositeOperation = currBlend;
+ this.setModified(true);
+ };
+
+ /**
+ * Applies an image filter to a p5.Image
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, BLUR, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ * @example
+ *
+ * let photo1;
+ * let photo2;
+ *
+ * function preload() {
+ * photo1 = loadImage('assets/rockies.jpg');
+ * photo2 = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * photo2.filter(GRAY);
+ * image(photo1, 0, 0);
+ * image(photo2, width / 2, 0);
+ * }
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains left one in color, right in black and white
+ *
+ */
+ _main.default.Image.prototype.filter = function(operation, value) {
+ _filters.default.apply(this.canvas, _filters.default[operation], value);
+ this.setModified(true);
+ };
+
+ /**
+ * Copies a region of pixels from one image to another, using a specified
+ * blend mode to do the operation.
+ *
+ * @method blend
+ * @param {p5.Image} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ * @param {Constant} blendMode the blend mode. either
+ * BLEND, DARKEST, LIGHTEST, DIFFERENCE,
+ * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
+ *
+ * Available blend modes are: normal | multiply | screen | overlay |
+ * darken | lighten | color-dodge | color-burn | hard-light |
+ * soft-light | difference | exclusion | hue | saturation |
+ * color | luminosity
+ *
+ *
+ * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
+ * @example
+ *
+ * let mountains;
+ * let bricks;
+ *
+ * function preload() {
+ * mountains = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);
+ * image(mountains, 0, 0);
+ * image(bricks, 0, 0);
+ * }
+ *
+ *
+ * let mountains;
+ * let bricks;
+ *
+ * function preload() {
+ * mountains = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);
+ * image(mountains, 0, 0);
+ * image(bricks, 0, 0);
+ * }
+ *
+ *
+ * let mountains;
+ * let bricks;
+ *
+ * function preload() {
+ * mountains = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);
+ * image(mountains, 0, 0);
+ * image(bricks, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ */
+ /**
+ * @method blend
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ * @param {Constant} blendMode
+ */
+ _main.default.Image.prototype.blend = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default.prototype.blend.apply(this, args);
+ this.setModified(true);
+ };
+
+ /**
+ * helper method for web GL mode to indicate that an image has been
+ * changed or unchanged since last upload. gl texture upload will
+ * set this value to false after uploading the texture.
+ * @method setModified
+ * @param {boolean} val sets whether or not the image has been
+ * modified.
+ * @private
+ */
+ _main.default.Image.prototype.setModified = function(val) {
+ this._modified = val; //enforce boolean?
+ };
+
+ /**
+ * helper method for web GL mode to figure out if the image
+ * has been modified and might need to be re-uploaded to texture
+ * memory between frames.
+ * @method isModified
+ * @private
+ * @return {boolean} a boolean indicating whether or not the
+ * image has been updated or modified since last texture upload.
+ */
+ _main.default.Image.prototype.isModified = function() {
+ return this._modified;
+ };
+
+ /**
+ * Saves the image to a file and force the browser to download it.
+ * Accepts two strings for filename and file extension
+ * Supports png (default), jpg, and gif
+ *
+ * Note that the file will only be downloaded as an animated GIF
+ * if the p5.Image was loaded from a GIF file.
+ * @method save
+ * @param {String} filename give your file a name
+ * @param {String} extension 'png' or 'jpg'
+ * @example
+ *
+ * let photo;
+ *
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function draw() {
+ * image(photo, 0, 0);
+ * }
+ *
+ * function keyTyped() {
+ * if (key === 's') {
+ * photo.save('photo', 'png');
+ * }
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains.
+ *
+ */
+ _main.default.Image.prototype.save = function(filename, extension) {
+ if (this.gifProperties) {
+ _main.default.prototype.saveGif(this, filename);
+ } else {
+ _main.default.prototype.saveCanvas(this.canvas, filename, extension);
+ }
+ };
+
+ // GIF Section
+ /**
+ * Starts an animated GIF over at the beginning state.
+ *
+ * @method reset
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-wink-loop-once.gif');
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * // The GIF file that we loaded only loops once
+ * // so it freezes on the last frame after playing through
+ * image(gif, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * // Click to reset the GIF and begin playback from start
+ * gif.reset();
+ * }
+ *
+ * @alt
+ * Animated image of a cartoon face that winks once and then freezes
+ * When you click it animates again, winks once and freezes
+ *
+ */
+ _main.default.Image.prototype.reset = function() {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ props.playing = true;
+ props.timeSinceStart = 0;
+ props.timeDisplayed = 0;
+ props.loopCount = 0;
+ props.displayIndex = 0;
+ this.drawingContext.putImageData(props.frames[0], 0, 0);
+ }
+ };
+
+ /**
+ * Gets the index for the frame that is currently visible in an animated GIF.
+ *
+ * @method getCurrentFrame
+ * @return {Number} The index for the currently displaying frame in animated GIF
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * function draw() {
+ * let frame = gif.getCurrentFrame();
+ * image(gif, 0, 0);
+ * text(frame, 10, 90);
+ * }
+ *
+ * @alt
+ * Animated image of a cartoon eye looking around and then
+ * looking outwards, in the lower-left hand corner a number counts
+ * up quickly to 124 and then starts back over at 0
+ *
+ */
+ _main.default.Image.prototype.getCurrentFrame = function() {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ return props.displayIndex % props.numFrames;
+ }
+ };
+
+ /**
+ * Sets the index of the frame that is currently visible in an animated GIF
+ *
+ * @method setFrame
+ * @param {Number} index the index for the frame that should be displayed
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * // Move your mouse up and down over canvas to see the GIF
+ * // frames animate
+ * function draw() {
+ * gif.pause();
+ * image(gif, 0, 0);
+ * // Get the highest frame number which is the number of frames - 1
+ * let maxFrame = gif.numFrames() - 1;
+ * // Set the current frame that is mapped to be relative to mouse position
+ * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));
+ * gif.setFrame(frameNumber);
+ * }
+ *
+ * @alt
+ * A still image of a cartoon eye that looks around when you move your mouse
+ * up and down over the canvas
+ *
+ */
+ _main.default.Image.prototype.setFrame = function(index) {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ if (index < props.numFrames && index >= 0) {
+ props.timeDisplayed = 0;
+ props.displayIndex = index;
+ this.drawingContext.putImageData(props.frames[index], 0, 0);
+ } else {
+ console.log(
+ 'Cannot set GIF to a frame number that is higher than total number of frames or below zero.'
+ );
+ }
+ }
+ };
+
+ /**
+ * Returns the number of frames in an animated GIF
+ *
+ * @method numFrames
+ * @return {Number}
+ * @example The number of frames in the animated GIF
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * // Move your mouse up and down over canvas to see the GIF
+ * // frames animate
+ * function draw() {
+ * gif.pause();
+ * image(gif, 0, 0);
+ * // Get the highest frame number which is the number of frames - 1
+ * let maxFrame = gif.numFrames() - 1;
+ * // Set the current frame that is mapped to be relative to mouse position
+ * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));
+ * gif.setFrame(frameNumber);
+ * }
+ *
+ * @alt
+ * A still image of a cartoon eye that looks around when you move your mouse
+ * up and down over the canvas
+ *
+ */
+ _main.default.Image.prototype.numFrames = function() {
+ if (this.gifProperties) {
+ return this.gifProperties.numFrames;
+ }
+ };
+
+ /**
+ * Plays an animated GIF that was paused with
+ * pause()
+ *
+ * @method play
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * image(gif, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * gif.pause();
+ * }
+ *
+ * function mouseReleased() {
+ * gif.play();
+ * }
+ *
+ * @alt
+ * An animated GIF of a drawing of small child with
+ * hair blowing in the wind, when you click the image
+ * freezes when you release it animates again
+ *
+ */
+ _main.default.Image.prototype.play = function() {
+ if (this.gifProperties) {
+ this.gifProperties.playing = true;
+ }
+ };
+
+ /**
+ * Pauses an animated GIF.
+ *
+ * @method pause
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * image(gif, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * gif.pause();
+ * }
+ *
+ * function mouseReleased() {
+ * gif.play();
+ * }
+ *
+ * @alt
+ * An animated GIF of a drawing of small child with
+ * hair blowing in the wind, when you click the image
+ * freezes when you release it animates again
+ *
+ */
+ _main.default.Image.prototype.pause = function() {
+ if (this.gifProperties) {
+ this.gifProperties.playing = false;
+ }
+ };
+
+ /**
+ * Changes the delay between frames in an animated GIF
+ *
+ * @method delay
+ * @param {Number} d the amount in milliseconds to delay between switching frames
+ * @example
+ *
+ * let gifFast, gifSlow;
+ *
+ * function preload() {
+ * gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * function setup() {
+ * gifFast.resize(width / 2, height / 2);
+ * gifSlow.resize(width / 2, height / 2);
+ *
+ * //Change the delay here
+ * gifFast.delay(10);
+ * gifSlow.delay(100);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * image(gifFast, 0, 0);
+ * image(gifSlow, width / 2, 0);
+ * }
+ *
+ * @alt
+ * Two animated gifs of cartoon eyes looking around
+ * The gif on the left animates quickly, on the right
+ * the animation is much slower
+ *
+ */
+ _main.default.Image.prototype.delay = function(d) {
+ if (this.gifProperties) {
+ this.gifProperties.delay = d;
+ }
+ };
+ var _default = _main.default.Image;
+ exports.default = _default;
+ },
+ { '../core/main': 27, './filters': 48 }
+ ],
+ 52: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var _filters = _interopRequireDefault(_dereq_('./filters'));
+ _dereq_('../color/p5.Color');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Image
+ * @submodule Pixels
+ * @for p5
+ * @requires core
+ */ /**
+ * Uint8ClampedArray
+ * containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high density displays will have more pixels[] (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100x100 pixels, there will be 40,000. On a
+ * retina display, there will be 160,000.
+ *
+ * The first four values (indices 0-3) in the array will be the R, G, B, A
+ * values of the pixel at (0, 0). The second four values (indices 4-7) will
+ * contain the R, G, B, A values of the pixel at (1, 0). More generally, to
+ * set values for a pixel at (x, y):
+ * ```javascript
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
+ * // loop over
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
+ * }
+ * }
+ * ```
+ * While the above method is complex, it is flexible enough to work with
+ * any pixelDensity. Note that set() will automatically take care of
+ * setting all the appropriate values in pixels[] for a given (x, y) at
+ * any pixelDensity, but the performance may not be as fast when lots of
+ * modifications are made to the pixel array.
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ *
+ * Note that this is not a standard javascript array. This means that
+ * standard javascript functions such as slice() or
+ * arrayCopy() do not
+ * work.
+ *
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * let pink = color(255, 102, 204);
+ * loadPixels();
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height / 2 * d);
+ * for (let i = 0; i < halfImage; i += 4) {
+ * pixels[i] = red(pink);
+ * pixels[i + 1] = green(pink);
+ * pixels[i + 2] = blue(pink);
+ * pixels[i + 3] = alpha(pink);
+ * }
+ * updatePixels();
+ *
+ *
+ *
+ * @alt
+ * top half of canvas pink, bottom grey
+ *
+ */ _main.default.prototype.pixels = []; /**
+ * Copies a region of pixels from one image to another, using a specified
+ * blend mode to do the operation.
+ *
+ * @method blend
+ * @param {p5.Image} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ * @param {Constant} blendMode the blend mode. either
+ * BLEND, DARKEST, LIGHTEST, DIFFERENCE,
+ * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
+ *
+ * @example
+ *
+ * let img0;
+ * let img1;
+ *
+ * function preload() {
+ * img0 = loadImage('assets/rockies.jpg');
+ * img1 = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img0);
+ * image(img1, 0, 0);
+ * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);
+ * }
+ *
+ *
+ * let img0;
+ * let img1;
+ *
+ * function preload() {
+ * img0 = loadImage('assets/rockies.jpg');
+ * img1 = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img0);
+ * image(img1, 0, 0);
+ * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);
+ * }
+ *
+ *
+ * let img0;
+ * let img1;
+ *
+ * function preload() {
+ * img0 = loadImage('assets/rockies.jpg');
+ * img1 = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img0);
+ * image(img1, 0, 0);
+ * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ *
+ */
+ /**
+ * @method blend
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ * @param {Constant} blendMode
+ */
+ _main.default.prototype.blend = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('blend', args);
+ if (this._renderer) {
+ var _this$_renderer;
+ (_this$_renderer = this._renderer).blend.apply(_this$_renderer, args);
+ } else {
+ _main.default.Renderer2D.prototype.blend.apply(this, args);
+ }
+ };
+
+ /**
+ * Copies a region of the canvas to another region of the canvas
+ * and copies a region of pixels from an image used as the srcImg parameter
+ * into the canvas srcImage is specified this is used as the source. If
+ * the source and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target region.
+ *
+ * @method copy
+ * @param {p5.Image|p5.Element} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ *
+ * @example
+ *
+ * let img;
+ *
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img);
+ * copy(img, 7, 22, 10, 10, 35, 25, 50, 50);
+ * stroke(255);
+ * noFill();
+ * // Rectangle shows area being copied
+ * rect(7, 22, 10, 10);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ */
+ /**
+ * @method copy
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ */
+ _main.default.prototype.copy = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('copy', args);
+
+ var srcImage, sx, sy, sw, sh, dx, dy, dw, dh;
+ if (args.length === 9) {
+ srcImage = args[0];
+ sx = args[1];
+ sy = args[2];
+ sw = args[3];
+ sh = args[4];
+ dx = args[5];
+ dy = args[6];
+ dw = args[7];
+ dh = args[8];
+ } else if (args.length === 8) {
+ srcImage = this;
+ sx = args[0];
+ sy = args[1];
+ sw = args[2];
+ sh = args[3];
+ dx = args[4];
+ dy = args[5];
+ dw = args[6];
+ dh = args[7];
+ } else {
+ throw new Error('Signature not supported');
+ }
+
+ _main.default.prototype._copyHelper(
+ this,
+ srcImage,
+ sx,
+ sy,
+ sw,
+ sh,
+ dx,
+ dy,
+ dw,
+ dh
+ );
+ };
+
+ _main.default.prototype._copyHelper = function(
+ dstImage,
+ srcImage,
+ sx,
+ sy,
+ sw,
+ sh,
+ dx,
+ dy,
+ dw,
+ dh
+ ) {
+ srcImage.loadPixels();
+ var s = srcImage.canvas.width / srcImage.width;
+ // adjust coord system for 3D when renderer
+ // ie top-left = -width/2, -height/2
+ var sxMod = 0;
+ var syMod = 0;
+ if (srcImage._renderer && srcImage._renderer.isP3D) {
+ sxMod = srcImage.width / 2;
+ syMod = srcImage.height / 2;
+ }
+ if (dstImage._renderer && dstImage._renderer.isP3D) {
+ _main.default.RendererGL.prototype.image.call(
+ dstImage._renderer,
+ srcImage,
+ sx + sxMod,
+ sy + syMod,
+ sw,
+ sh,
+ dx,
+ dy,
+ dw,
+ dh
+ );
+ } else {
+ dstImage.drawingContext.drawImage(
+ srcImage.canvas,
+ s * (sx + sxMod),
+ s * (sy + syMod),
+ s * sw,
+ s * sh,
+ dx,
+ dy,
+ dw,
+ dh
+ );
+ }
+ };
+
+ /**
+ * Applies a filter to the canvas.
+ *
+ *
+ * The presets options are:
+ *
+ *
+ * THRESHOLD
+ * Converts the image to black and white pixels depending if they are above or
+ * below the threshold defined by the level parameter. The parameter must be
+ * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
+ *
+ *
+ * GRAY
+ * Converts any colors in the image to grayscale equivalents. No parameter
+ * is used.
+ *
+ *
+ * OPAQUE
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ *
+ * INVERT
+ * Sets each pixel to its inverse value. No parameter is used.
+ *
+ *
+ * POSTERIZE
+ * Limits each channel of the image to the number of colors specified as the
+ * parameter. The parameter can be set to values between 2 and 255, but
+ * results are most noticeable in the lower ranges.
+ *
+ *
+ * BLUR
+ * Executes a Gaussian blur with the level parameter specifying the extent
+ * of the blurring. If no parameter is used, the blur is equivalent to
+ * Gaussian blur of radius 1. Larger values increase the blur.
+ *
+ *
+ * ERODE
+ * Reduces the light areas. No parameter is used.
+ *
+ *
+ * DILATE
+ * Increases the light areas. No parameter is used.
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, BLUR, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ *
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(THRESHOLD);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(GRAY);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(OPAQUE);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(INVERT);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(POSTERIZE, 3);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(DILATE);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(BLUR, 3);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(ERODE);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black and white image of a brick wall.
+ * greyscale image of a brickwall
+ * image of a brickwall
+ * jade colored image of a brickwall
+ * red and pink image of a brickwall
+ * image of a brickwall
+ * blurry image of a brickwall
+ * image of a brickwall
+ * image of a brickwall with less detail
+ *
+ */
+ _main.default.prototype.filter = function(operation, value) {
+ _main.default._validateParameters('filter', arguments);
+ if (this.canvas !== undefined) {
+ _filters.default.apply(this.canvas, _filters.default[operation], value);
+ } else {
+ _filters.default.apply(this.elt, _filters.default[operation], value);
+ }
+ };
+
+ /**
+ * Get a region of pixels, or a single pixel, from the canvas.
+ *
+ * Returns an array of [R,G,B,A] values for any pixel or grabs a section of
+ * an image. If no parameters are specified, the entire image is returned.
+ * Use the x and y parameters to get the value of one pixel. Get a section of
+ * the display window by specifying additional w and h parameters. When
+ * getting an image, the x and y parameters define the coordinates for the
+ * upper-left corner of the image, regardless of the current imageMode().
+ *
+ * Getting the color of a single pixel with get(x, y) is easy, but not as fast
+ * as grabbing the data directly from pixels[]. The equivalent statement to
+ * get(x, y) using pixels[] with pixel density d is
+ * ```javascript
+ * let x, y, d; // set these to the coordinates
+ * let off = (y * width + x) * d * 4;
+ * let components = [
+ * pixels[off],
+ * pixels[off + 1],
+ * pixels[off + 2],
+ * pixels[off + 3]
+ * ];
+ * print(components);
+ * ```
+ *
+ *
+ * See the reference for pixels[] for more information.
+ *
+ * If you want to extract an array of colors or a subimage from an p5.Image object,
+ * take a look at p5.Image.get()
+ *
+ * @method get
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * let c = get();
+ * image(c, width / 2, 0);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * let c = get(50, 90);
+ * fill(c);
+ * noStroke();
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 images of the rocky mountains, side-by-side
+ * Image of the rocky mountains with 50x50 green rect in center of canvas
+ *
+ */
+ /**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+ /**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of pixel at x,y in array format [R, G, B, A]
+ */
+ _main.default.prototype.get = function(x, y, w, h) {
+ var _this$_renderer2;
+ _main.default._validateParameters('get', arguments);
+ return (_this$_renderer2 = this._renderer).get.apply(
+ _this$_renderer2,
+ arguments
+ );
+ };
+
+ /**
+ * Loads the pixel data for the display window into the pixels[] array. This
+ * function must always be called before reading from or writing to pixels[].
+ * Note that only changes made with set() or direct manipulation of pixels[]
+ * will occur.
+ *
+ * @method loadPixels
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
+ * loadPixels();
+ * for (let i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ *
+ */
+ _main.default.prototype.loadPixels = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('loadPixels', args);
+ this._renderer.loadPixels();
+ };
+
+ /**
+ * Changes the color of any pixel, or writes an image directly to the
+ * display window.
+ * The x and y parameters specify the pixel to change and the c parameter
+ * specifies the color value. This can be a p5.Color object, or [R, G, B, A]
+ * pixel array. It can also be a single grayscale value.
+ * When setting an image, the x and y parameters define the coordinates for
+ * the upper-left corner of the image, regardless of the current imageMode().
+ *
+ *
+ * After using set(), you must call updatePixels() for your changes to appear.
+ * This should be called once all pixels have been set, and must be called before
+ * calling .get() or drawing the image.
+ *
+ * Setting the color of a single pixel with set(x, y) is easy, but not as
+ * fast as putting the data directly into pixels[]. Setting the pixels[]
+ * values directly may be complicated when working with a retina display,
+ * but will perform better when lots of pixels need to be set directly on
+ * every loop.
+ * See the reference for pixels[] for more information.
+ *
+ * @method set
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array |
+ * a p5.Color object | a p5.Image to copy
+ * @example
+ *
+ *
+ * let black = color(0);
+ * set(30, 20, black);
+ * set(85, 20, black);
+ * set(85, 75, black);
+ * set(30, 75, black);
+ * updatePixels();
+ *
+ *
+ *
+ *
+ *
+ * for (let i = 30; i < width - 15; i++) {
+ * for (let j = 20; j < height - 25; j++) {
+ * let c = color(204 - j, 153 - i, 0);
+ * set(i, j, c);
+ * }
+ * }
+ * updatePixels();
+ *
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * set(0, 0, img);
+ * updatePixels();
+ * line(0, 0, width, height);
+ * line(0, height, width, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 4 black points in the shape of a square middle-right of canvas.
+ * square with orangey-brown gradient lightening at bottom right.
+ * image of the rocky mountains. with lines like an 'x' through the center.
+ */
+ _main.default.prototype.set = function(x, y, imgOrCol) {
+ this._renderer.set(x, y, imgOrCol);
+ };
+ /**
+ * Updates the display window with the data in the pixels[] array.
+ * Use in conjunction with loadPixels(). If you're only reading pixels from
+ * the array, there's no need to call updatePixels() — updating is only
+ * necessary to apply changes. updatePixels() should be called anytime the
+ * pixels array is manipulated or set() is called, and only changes made with
+ * set() or direct changes to pixels[] will occur.
+ *
+ * @method updatePixels
+ * @param {Number} [x] x-coordinate of the upper-left corner of region
+ * to update
+ * @param {Number} [y] y-coordinate of the upper-left corner of region
+ * to update
+ * @param {Number} [w] width of region to update
+ * @param {Number} [h] height of region to update
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
+ * loadPixels();
+ * for (let i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ */
+ _main.default.prototype.updatePixels = function(x, y, w, h) {
+ _main.default._validateParameters('updatePixels', arguments);
+ // graceful fail - if loadPixels() or set() has not been called, pixel
+ // array will be empty, ignore call to updatePixels()
+ if (this.pixels.length === 0) {
+ return;
+ }
+ this._renderer.updatePixels(x, y, w, h);
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../color/p5.Color': 19, '../core/main': 27, './filters': 48 }
+ ],
+ 53: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ _dereq_('whatwg-fetch');
+ _dereq_('es6-promise/auto');
+ var _fetchJsonp = _interopRequireDefault(_dereq_('fetch-jsonp'));
+ var _fileSaver = _interopRequireDefault(_dereq_('file-saver'));
+ _dereq_('../core/error_helpers');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ function _typeof(obj) {
+ if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
+ _typeof = function _typeof(obj) {
+ return typeof obj;
+ };
+ } else {
+ _typeof = function _typeof(obj) {
+ return obj &&
+ typeof Symbol === 'function' &&
+ obj.constructor === Symbol &&
+ obj !== Symbol.prototype
+ ? 'symbol'
+ : typeof obj;
+ };
+ }
+ return _typeof(obj);
+ }
+
+ /**
+ * Loads a JSON file from a file or a URL, and returns an Object.
+ * Note that even if the JSON file contains an Array, an Object will be
+ * returned with index numbers as keys.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. JSONP is supported via a polyfill and you
+ * can pass in as the second argument an object with definitions of the json
+ * callback following the syntax specified here.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadJSON
+ * @param {String} path name of the file or url to load
+ * @param {Object} [jsonpOptions] options object for jsonp related settings
+ * @param {String} [datatype] "json" or "jsonp"
+ * @param {function} [callback] function to be executed after
+ * loadJSON() completes, data is passed
+ * in as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Object|Array} JSON data
+ * @example
+ *
+ * Calling loadJSON() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * // Examples use USGS Earthquake API:
+ * // https://earthquake.usgs.gov/fdsnws/event/1/#methods
+ * let earthquakes;
+ * function preload() {
+ * // Get the most recent earthquake in the database
+ * let url =
+ 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * earthquakes = loadJSON(url);
+ * }
+ *
+ * function setup() {
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * // Get the magnitude and name of the earthquake out of the loaded JSON
+ * let earthquakeMag = earthquakes.features[0].properties.mag;
+ * let earthquakeName = earthquakes.features[0].properties.place;
+ * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
+ * textAlign(CENTER);
+ * text(earthquakeName, 0, height - 30, width, 30);
+ * }
+ *
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ * function setup() {
+ * noLoop();
+ * let url =
+ 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * loadJSON(url, drawEarthquake);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * }
+ *
+ * function drawEarthquake(earthquakes) {
+ * // Get the magnitude and name of the earthquake out of the loaded JSON
+ * let earthquakeMag = earthquakes.features[0].properties.mag;
+ * let earthquakeName = earthquakes.features[0].properties.place;
+ * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
+ * textAlign(CENTER);
+ * text(earthquakeName, 0, height - 30, width, 30);
+ * }
+ *
+ *
+ * @alt
+ * 50x50 ellipse that changes from black to white depending on the current humidity
+ * 50x50 ellipse that changes from black to white depending on the current humidity
+ *
+ */
+ /**
+ * @method loadJSON
+ * @param {String} path
+ * @param {String} datatype
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+ /**
+ * @method loadJSON
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+ _main.default.prototype.loadJSON = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('loadJSON', args);
+ var path = args[0];
+ var callback;
+ var errorCallback;
+ var options;
+
+ var ret = {}; // object needed for preload
+ var t = 'json';
+
+ // check for explicit data type argument
+ for (var i = 1; i < args.length; i++) {
+ var arg = args[i];
+ if (typeof arg === 'string') {
+ if (arg === 'jsonp' || arg === 'json') {
+ t = arg;
+ }
+ } else if (typeof arg === 'function') {
+ if (!callback) {
+ callback = arg;
+ } else {
+ errorCallback = arg;
+ }
+ } else if (
+ _typeof(arg) === 'object' &&
+ (arg.hasOwnProperty('jsonpCallback') ||
+ arg.hasOwnProperty('jsonpCallbackFunction'))
+ ) {
+ t = 'jsonp';
+ options = arg;
+ }
+ }
+
+ var self = this;
+ this.httpDo(
+ path,
+ 'GET',
+ options,
+ t,
+ function(resp) {
+ for (var k in resp) {
+ ret[k] = resp[k];
+ }
+ if (typeof callback !== 'undefined') {
+ callback(resp);
+ }
+
+ self._decrementPreload();
+ },
+ function(err) {
+ // Error handling
+ _main.default._friendlyFileLoadError(5, path);
+
+ if (errorCallback) {
+ errorCallback(err);
+ } else {
+ throw err;
+ }
+ }
+ );
+
+ return ret;
+ };
+
+ /**
+ * Reads the contents of a file and creates a String array of its individual
+ * lines. If the name of the file is used as the parameter, as in the above
+ * example, the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadStrings
+ * @param {String} filename name of the file or url to load
+ * @param {function} [callback] function to be executed after loadStrings()
+ * completes, Array is passed in as first
+ * argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {String[]} Array of Strings
+ * @example
+ *
+ * Calling loadStrings() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * let result;
+ * function preload() {
+ * result = loadStrings('assets/test.txt');
+ * }
+
+ * function setup() {
+ * background(200);
+ * text(random(result), 10, 10, 80, 80);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ * function setup() {
+ * loadStrings('assets/test.txt', pickString);
+ * }
+ *
+ * function pickString(result) {
+ * background(200);
+ * text(random(result), 10, 10, 80, 80);
+ * }
+ *
+ *
+ * @alt
+ * randomly generated text from a file, for example "i smell like butter"
+ * randomly generated text from a file, for example "i have three feet"
+ *
+ */
+ _main.default.prototype.loadStrings = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('loadStrings', args);
+
+ var ret = [];
+ var callback, errorCallback;
+
+ for (var i = 1; i < args.length; i++) {
+ var arg = args[i];
+ if (typeof arg === 'function') {
+ if (typeof callback === 'undefined') {
+ callback = arg;
+ } else if (typeof errorCallback === 'undefined') {
+ errorCallback = arg;
+ }
+ }
+ }
+
+ var self = this;
+ _main.default.prototype.httpDo.call(
+ this,
+ args[0],
+ 'GET',
+ 'text',
+ function(data) {
+ // split lines handling mac/windows/linux endings
+ var lines = data
+ .replace(/\r\n/g, '\r')
+ .replace(/\n/g, '\r')
+ .split(/\r/);
+ Array.prototype.push.apply(ret, lines);
+
+ if (typeof callback !== 'undefined') {
+ callback(ret);
+ }
+
+ self._decrementPreload();
+ },
+ function(err) {
+ // Error handling
+ _main.default._friendlyFileLoadError(3, arguments[0]);
+
+ if (errorCallback) {
+ errorCallback(err);
+ } else {
+ throw err;
+ }
+ }
+ );
+
+ return ret;
+ };
+
+ /**
+ * Reads the contents of a file or URL and creates a p5.Table object with
+ * its values. If a file is specified, it must be located in the sketch's
+ * "data" folder. The filename parameter can also be a URL to a file found
+ * online. By default, the file is assumed to be comma-separated (in CSV
+ * format). Table only looks for a header row if the 'header' option is
+ * included.
+ *
+ * Possible options include:
+ *
+ * - csv - parse the table as comma-separated values
+ * - tsv - parse the table as tab-separated values
+ * - header - this table has a header (title) row
+ *
+ *
+ *
+ * When passing in multiple options, pass them in as separate parameters,
+ * seperated by commas. For example:
+ *
+ *
+ * loadTable('my_csv_file.csv', 'csv', 'header');
+ *
+ *
+ *
+ * All files loaded and saved use UTF-8 encoding.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. Calling loadTable() inside preload()
+ * guarantees to complete the operation before setup() and draw() are called.
+ *
Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadTable
+ * @param {String} filename name of the file or URL to load
+ * @param {String} options "header" "csv" "tsv"
+ * @param {function} [callback] function to be executed after
+ * loadTable() completes. On success, the
+ * Table object is passed in as the
+ * first argument.
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Object} Table object containing data
+ *
+ * @example
+ *
+ *
+ * // Given the following CSV file called "mammals.csv"
+ * // located in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * //the file can be remote
+ * //table = loadTable("http://p5js.org/reference/assets/mammals.csv",
+ * // "csv", "header");
+ * }
+ *
+ * function setup() {
+ * //count the columns
+ * print(table.getRowCount() + ' total rows in table');
+ * print(table.getColumnCount() + ' total columns in table');
+ *
+ * print(table.getColumn('name'));
+ * //["Goat", "Leopard", "Zebra"]
+ *
+ * //cycle through the table
+ * for (let r = 0; r < table.getRowCount(); r++)
+ * for (let c = 0; c < table.getColumnCount(); c++) {
+ * print(table.getString(r, c));
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * randomly generated text from a file, for example "i smell like butter"
+ * randomly generated text from a file, for example "i have three feet"
+ *
+ */
+ /**
+ * @method loadTable
+ * @param {String} filename
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Object}
+ */
+ _main.default.prototype.loadTable = function(path) {
+ var callback;
+ var errorCallback;
+ var options = [];
+ var header = false;
+ var ext = path.substring(path.lastIndexOf('.') + 1, path.length);
+ var sep = ',';
+ var separatorSet = false;
+
+ if (ext === 'tsv') {
+ //Only need to check extension is tsv because csv is default
+ sep = '\t';
+ }
+
+ for (var i = 1; i < arguments.length; i++) {
+ if (typeof arguments[i] === 'function') {
+ if (typeof callback === 'undefined') {
+ callback = arguments[i];
+ } else if (typeof errorCallback === 'undefined') {
+ errorCallback = arguments[i];
+ }
+ } else if (typeof arguments[i] === 'string') {
+ options.push(arguments[i]);
+ if (arguments[i] === 'header') {
+ header = true;
+ }
+ if (arguments[i] === 'csv') {
+ if (separatorSet) {
+ throw new Error('Cannot set multiple separator types.');
+ } else {
+ sep = ',';
+ separatorSet = true;
+ }
+ } else if (arguments[i] === 'tsv') {
+ if (separatorSet) {
+ throw new Error('Cannot set multiple separator types.');
+ } else {
+ sep = '\t';
+ separatorSet = true;
+ }
+ }
+ }
+ }
+
+ var t = new _main.default.Table();
+
+ var self = this;
+ this.httpDo(
+ path,
+ 'GET',
+ 'table',
+ function(resp) {
+ var state = {};
+
+ // define constants
+ var PRE_TOKEN = 0,
+ MID_TOKEN = 1,
+ POST_TOKEN = 2,
+ POST_RECORD = 4;
+
+ var QUOTE = '"',
+ CR = '\r',
+ LF = '\n';
+
+ var records = [];
+ var offset = 0;
+ var currentRecord = null;
+ var currentChar;
+
+ var tokenBegin = function tokenBegin() {
+ state.currentState = PRE_TOKEN;
+ state.token = '';
+ };
+
+ var tokenEnd = function tokenEnd() {
+ currentRecord.push(state.token);
+ tokenBegin();
+ };
+
+ var recordBegin = function recordBegin() {
+ state.escaped = false;
+ currentRecord = [];
+ tokenBegin();
+ };
+
+ var recordEnd = function recordEnd() {
+ state.currentState = POST_RECORD;
+ records.push(currentRecord);
+ currentRecord = null;
+ };
+
+ for (;;) {
+ currentChar = resp[offset++];
+
+ // EOF
+ if (currentChar == null) {
+ if (state.escaped) {
+ throw new Error('Unclosed quote in file.');
+ }
+ if (currentRecord) {
+ tokenEnd();
+ recordEnd();
+ break;
+ }
+ }
+ if (currentRecord === null) {
+ recordBegin();
+ }
+
+ // Handle opening quote
+ if (state.currentState === PRE_TOKEN) {
+ if (currentChar === QUOTE) {
+ state.escaped = true;
+ state.currentState = MID_TOKEN;
+ continue;
+ }
+ state.currentState = MID_TOKEN;
+ }
+
+ // mid-token and escaped, look for sequences and end quote
+ if (state.currentState === MID_TOKEN && state.escaped) {
+ if (currentChar === QUOTE) {
+ if (resp[offset] === QUOTE) {
+ state.token += QUOTE;
+ offset++;
+ } else {
+ state.escaped = false;
+ state.currentState = POST_TOKEN;
+ }
+ } else if (currentChar === CR) {
+ continue;
+ } else {
+ state.token += currentChar;
+ }
+ continue;
+ }
+
+ // fall-through: mid-token or post-token, not escaped
+ if (currentChar === CR) {
+ if (resp[offset] === LF) {
+ offset++;
+ }
+ tokenEnd();
+ recordEnd();
+ } else if (currentChar === LF) {
+ tokenEnd();
+ recordEnd();
+ } else if (currentChar === sep) {
+ tokenEnd();
+ } else if (state.currentState === MID_TOKEN) {
+ state.token += currentChar;
+ }
+ }
+
+ // set up column names
+ if (header) {
+ t.columns = records.shift();
+ } else {
+ for (var _i = 0; _i < records[0].length; _i++) {
+ t.columns[_i] = 'null';
+ }
+ }
+ var row;
+ for (var _i2 = 0; _i2 < records.length; _i2++) {
+ //Handles row of 'undefined' at end of some CSVs
+ if (records[_i2].length === 1) {
+ if (records[_i2][0] === 'undefined' || records[_i2][0] === '') {
+ continue;
+ }
+ }
+ row = new _main.default.TableRow();
+ row.arr = records[_i2];
+ row.obj = makeObject(records[_i2], t.columns);
+ t.addRow(row);
+ }
+ if (typeof callback === 'function') {
+ callback(t);
+ }
+
+ self._decrementPreload();
+ },
+ function(err) {
+ // Error handling
+ _main.default._friendlyFileLoadError(2, path);
+
+ if (errorCallback) {
+ errorCallback(err);
+ } else {
+ console.error(err);
+ }
+ }
+ );
+
+ return t;
+ };
+
+ // helper function to turn a row into a JSON object
+ function makeObject(row, headers) {
+ var ret = {};
+ headers = headers || [];
+ if (typeof headers === 'undefined') {
+ for (var j = 0; j < row.length; j++) {
+ headers[j.toString()] = j;
+ }
+ }
+ for (var i = 0; i < headers.length; i++) {
+ var key = headers[i];
+ var val = row[i];
+ ret[key] = val;
+ }
+ return ret;
+ }
+
+ /**
+ * Reads the contents of a file and creates an XML object with its values.
+ * If the name of the file is used as the parameter, as in the above example,
+ * the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. Calling loadXML() inside preload()
+ * guarantees to complete the operation before setup() and draw() are called.
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadXML
+ * @param {String} filename name of the file or URL to load
+ * @param {function} [callback] function to be executed after loadXML()
+ * completes, XML object is passed in as
+ * first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Object} XML object containing data
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < children.length; i++) {
+ * let id = children[i].getNum('id');
+ * let coloring = children[i].getString('species');
+ * let name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.prototype.loadXML = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ var ret = new _main.default.XML();
+ var callback, errorCallback;
+
+ for (var i = 1; i < args.length; i++) {
+ var arg = args[i];
+ if (typeof arg === 'function') {
+ if (typeof callback === 'undefined') {
+ callback = arg;
+ } else if (typeof errorCallback === 'undefined') {
+ errorCallback = arg;
+ }
+ }
+ }
+
+ var self = this;
+ this.httpDo(
+ args[0],
+ 'GET',
+ 'xml',
+ function(xml) {
+ for (var key in xml) {
+ ret[key] = xml[key];
+ }
+ if (typeof callback !== 'undefined') {
+ callback(ret);
+ }
+
+ self._decrementPreload();
+ },
+ function(err) {
+ // Error handling
+ _main.default._friendlyFileLoadError(1, arguments[0]);
+
+ if (errorCallback) {
+ errorCallback(err);
+ } else {
+ throw err;
+ }
+ }
+ );
+
+ return ret;
+ };
+
+ /**
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadBytes
+ * @param {string} file name of the file or URL to load
+ * @param {function} [callback] function to be executed after loadBytes()
+ * completes
+ * @param {function} [errorCallback] function to be executed if there
+ * is an error
+ * @returns {Object} an object whose 'bytes' property will be the loaded buffer
+ *
+ * @example
+ *
+ * let data;
+ *
+ * function preload() {
+ * data = loadBytes('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * for (let i = 0; i < 5; i++) {
+ * console.log(data.bytes[i].toString(16));
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.prototype.loadBytes = function(file, callback, errorCallback) {
+ var ret = {};
+
+ var self = this;
+ this.httpDo(
+ file,
+ 'GET',
+ 'arrayBuffer',
+ function(arrayBuffer) {
+ ret.bytes = new Uint8Array(arrayBuffer);
+
+ if (typeof callback === 'function') {
+ callback(ret);
+ }
+
+ self._decrementPreload();
+ },
+ function(err) {
+ // Error handling
+ _main.default._friendlyFileLoadError(6, file);
+
+ if (errorCallback) {
+ errorCallback(err);
+ } else {
+ throw err;
+ }
+ }
+ );
+
+ return ret;
+ };
+
+ /**
+ * Method for executing an HTTP GET request. If data type is not specified,
+ * p5 will try to guess based on the URL, defaulting to text. This is equivalent to
+ * calling httpDo(path, 'GET'). The 'binary' datatype will return
+ * a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer
+ * which can be used to initialize typed arrays (such as Uint8Array).
+ *
+ * @method httpGet
+ * @param {String} path name of the file or url to load
+ * @param {String} [datatype] "json", "jsonp", "binary", "arrayBuffer",
+ * "xml", or "text"
+ * @param {Object|Boolean} [data] param data passed sent with request
+ * @param {function} [callback] function to be executed after
+ * httpGet() completes, data is passed in
+ * as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Promise} A promise that resolves with the data when the operation
+ * completes successfully or rejects with the error after
+ * one occurs.
+ * @example
+ *
+ * // Examples use USGS Earthquake API:
+ * // https://earthquake.usgs.gov/fdsnws/event/1/#methods
+ * let earthquakes;
+ * function preload() {
+ * // Get the most recent earthquake in the database
+ * let url =
+ 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +
+ * 'format=geojson&limit=1&orderby=time';
+ * httpGet(url, 'jsonp', false, function(response) {
+ * // when the HTTP request completes, populate the variable that holds the
+ * // earthquake data used in the visualization.
+ * earthquakes = response;
+ * });
+ * }
+ *
+ * function draw() {
+ * if (!earthquakes) {
+ * // Wait until the earthquake data has loaded before drawing.
+ * return;
+ * }
+ * background(200);
+ * // Get the magnitude and name of the earthquake out of the loaded JSON
+ * let earthquakeMag = earthquakes.features[0].properties.mag;
+ * let earthquakeName = earthquakes.features[0].properties.place;
+ * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
+ * textAlign(CENTER);
+ * text(earthquakeName, 0, height - 30, width, 30);
+ * noLoop();
+ * }
+ *
+ */
+ /**
+ * @method httpGet
+ * @param {String} path
+ * @param {Object|Boolean} data
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Promise}
+ */
+ /**
+ * @method httpGet
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ * @return {Promise}
+ */
+ _main.default.prototype.httpGet = function() {
+ _main.default._validateParameters('httpGet', arguments);
+
+ var args = Array.prototype.slice.call(arguments);
+ args.splice(1, 0, 'GET');
+ return _main.default.prototype.httpDo.apply(this, args);
+ };
+
+ /**
+ * Method for executing an HTTP POST request. If data type is not specified,
+ * p5 will try to guess based on the URL, defaulting to text. This is equivalent to
+ * calling httpDo(path, 'POST').
+ *
+ * @method httpPost
+ * @param {String} path name of the file or url to load
+ * @param {String} [datatype] "json", "jsonp", "xml", or "text".
+ * If omitted, httpPost() will guess.
+ * @param {Object|Boolean} [data] param data passed sent with request
+ * @param {function} [callback] function to be executed after
+ * httpPost() completes, data is passed in
+ * as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Promise} A promise that resolves with the data when the operation
+ * completes successfully or rejects with the error after
+ * one occurs.
+ *
+ * @example
+ *
+ *
+ * // Examples use jsonplaceholder.typicode.com for a Mock Data API
+ *
+ * let url = 'https://jsonplaceholder.typicode.com/posts';
+ * let postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };
+ *
+ * function setup() {
+ * createCanvas(800, 800);
+ * }
+ *
+ * function mousePressed() {
+ * // Pick new random color values
+ * let r = random(255);
+ * let g = random(255);
+ * let b = random(255);
+ *
+ * httpPost(url, 'json', postData, function(result) {
+ * strokeWeight(2);
+ * stroke(r, g, b);
+ * fill(r, g, b, 127);
+ * ellipse(mouseX, mouseY, 200, 200);
+ * text(result.body, mouseX, mouseY);
+ * });
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let url = 'https://invalidURL'; // A bad URL that will cause errors
+ * let postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };
+ *
+ * function setup() {
+ * createCanvas(800, 800);
+ * }
+ *
+ * function mousePressed() {
+ * // Pick new random color values
+ * let r = random(255);
+ * let g = random(255);
+ * let b = random(255);
+ *
+ * httpPost(
+ * url,
+ * 'json',
+ * postData,
+ * function(result) {
+ * // ... won't be called
+ * },
+ * function(error) {
+ * strokeWeight(2);
+ * stroke(r, g, b);
+ * fill(r, g, b, 127);
+ * text(error.toString(), mouseX, mouseY);
+ * }
+ * );
+ * }
+ *
+ *
+ */
+ /**
+ * @method httpPost
+ * @param {String} path
+ * @param {Object|Boolean} data
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Promise}
+ */
+ /**
+ * @method httpPost
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ * @return {Promise}
+ */
+ _main.default.prototype.httpPost = function() {
+ _main.default._validateParameters('httpPost', arguments);
+
+ var args = Array.prototype.slice.call(arguments);
+ args.splice(1, 0, 'POST');
+ return _main.default.prototype.httpDo.apply(this, args);
+ };
+
+ /**
+ * Method for executing an HTTP request. If data type is not specified,
+ * p5 will try to guess based on the URL, defaulting to text.
+ * For more advanced use, you may also pass in the path as the first argument
+ * and a object as the second argument, the signature follows the one specified
+ * in the Fetch API specification.
+ * This method is suitable for fetching files up to size of 64MB when "GET" is used.
+ *
+ * @method httpDo
+ * @param {String} path name of the file or url to load
+ * @param {String} [method] either "GET", "POST", or "PUT",
+ * defaults to "GET"
+ * @param {String} [datatype] "json", "jsonp", "xml", or "text"
+ * @param {Object} [data] param data passed sent with request
+ * @param {function} [callback] function to be executed after
+ * httpGet() completes, data is passed in
+ * as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Promise} A promise that resolves with the data when the operation
+ * completes successfully or rejects with the error after
+ * one occurs.
+ *
+ * @example
+ *
+ *
+ * // Examples use USGS Earthquake API:
+ * // https://earthquake.usgs.gov/fdsnws/event/1/#methods
+ *
+ * // displays an animation of all USGS earthquakes
+ * let earthquakes;
+ * let eqFeatureIndex = 0;
+ *
+ * function preload() {
+ * let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';
+ * httpDo(
+ * url,
+ * {
+ * method: 'GET',
+ * // Other Request options, like special headers for apis
+ * headers: { authorization: 'Bearer secretKey' }
+ * },
+ * function(res) {
+ * earthquakes = res;
+ * }
+ * );
+ * }
+ *
+ * function draw() {
+ * // wait until the data is loaded
+ * if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {
+ * return;
+ * }
+ * clear();
+ *
+ * let feature = earthquakes.features[eqFeatureIndex];
+ * let mag = feature.properties.mag;
+ * let rad = mag / 11 * ((width + height) / 2);
+ * fill(255, 0, 0, 100);
+ * ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);
+ *
+ * if (eqFeatureIndex >= earthquakes.features.length) {
+ * eqFeatureIndex = 0;
+ * } else {
+ * eqFeatureIndex += 1;
+ * }
+ * }
+ *
+ *
+ */
+ /**
+ * @method httpDo
+ * @param {String} path
+ * @param {Object} options Request object options as documented in the
+ * "fetch" API
+ * reference
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Promise}
+ */
+ _main.default.prototype.httpDo = function() {
+ var type;
+ var callback;
+ var errorCallback;
+ var request;
+ var promise;
+ var jsonpOptions = {};
+ var cbCount = 0;
+ var contentType = 'text/plain';
+ // Trim the callbacks off the end to get an idea of how many arguments are passed
+ for (var i = arguments.length - 1; i > 0; i--) {
+ if (
+ typeof (i < 0 || arguments.length <= i ? undefined : arguments[i]) ===
+ 'function'
+ ) {
+ cbCount++;
+ } else {
+ break;
+ }
+ }
+ // The number of arguments minus callbacks
+ var argsCount = arguments.length - cbCount;
+ var path = arguments.length <= 0 ? undefined : arguments[0];
+ if (
+ argsCount === 2 &&
+ typeof path === 'string' &&
+ _typeof(arguments.length <= 1 ? undefined : arguments[1]) === 'object'
+ ) {
+ // Intended for more advanced use, pass in Request parameters directly
+ request = new Request(path, arguments.length <= 1 ? undefined : arguments[1]);
+ callback = arguments.length <= 2 ? undefined : arguments[2];
+ errorCallback = arguments.length <= 3 ? undefined : arguments[3];
+ } else {
+ // Provided with arguments
+ var method = 'GET';
+ var data;
+
+ for (var j = 1; j < arguments.length; j++) {
+ var a = j < 0 || arguments.length <= j ? undefined : arguments[j];
+ if (typeof a === 'string') {
+ if (a === 'GET' || a === 'POST' || a === 'PUT' || a === 'DELETE') {
+ method = a;
+ } else if (
+ a === 'json' ||
+ a === 'jsonp' ||
+ a === 'binary' ||
+ a === 'arrayBuffer' ||
+ a === 'xml' ||
+ a === 'text' ||
+ a === 'table'
+ ) {
+ type = a;
+ } else {
+ data = a;
+ }
+ } else if (typeof a === 'number') {
+ data = a.toString();
+ } else if (_typeof(a) === 'object') {
+ if (
+ a.hasOwnProperty('jsonpCallback') ||
+ a.hasOwnProperty('jsonpCallbackFunction')
+ ) {
+ for (var attr in a) {
+ jsonpOptions[attr] = a[attr];
+ }
+ } else if (a instanceof _main.default.XML) {
+ data = a.serialize();
+ contentType = 'application/xml';
+ } else {
+ data = JSON.stringify(a);
+ contentType = 'application/json';
+ }
+ } else if (typeof a === 'function') {
+ if (!callback) {
+ callback = a;
+ } else {
+ errorCallback = a;
+ }
+ }
+ }
+
+ request = new Request(path, {
+ method: method,
+ mode: 'cors',
+ body: data,
+ headers: new Headers({
+ 'Content-Type': contentType
+ })
+ });
+ }
+ // do some sort of smart type checking
+ if (!type) {
+ if (path.includes('json')) {
+ type = 'json';
+ } else if (path.includes('xml')) {
+ type = 'xml';
+ } else {
+ type = 'text';
+ }
+ }
+
+ if (type === 'jsonp') {
+ promise = (0, _fetchJsonp.default)(path, jsonpOptions);
+ } else {
+ promise = fetch(request);
+ }
+ promise = promise.then(function(res) {
+ if (!res.ok) {
+ var err = new Error(res.body);
+ err.status = res.status;
+ err.ok = false;
+ throw err;
+ } else {
+ var fileSize = 0;
+ if (type !== 'jsonp') {
+ fileSize = res.headers.get('content-length');
+ }
+ if (fileSize && fileSize > 64000000) {
+ _main.default._friendlyFileLoadError(7, path);
+ }
+ switch (type) {
+ case 'json':
+ case 'jsonp':
+ return res.json();
+ case 'binary':
+ return res.blob();
+ case 'arrayBuffer':
+ return res.arrayBuffer();
+ case 'xml':
+ return res.text().then(function(text) {
+ var parser = new DOMParser();
+ var xml = parser.parseFromString(text, 'text/xml');
+ return new _main.default.XML(xml.documentElement);
+ });
+ default:
+ return res.text();
+ }
+ }
+ });
+ promise.then(callback || function() {});
+ promise.catch(errorCallback || console.error);
+ return promise;
+ };
+
+ /**
+ * @module IO
+ * @submodule Output
+ * @for p5
+ */
+
+ window.URL = window.URL || window.webkitURL;
+
+ // private array of p5.PrintWriter objects
+ _main.default.prototype._pWriters = [];
+
+ /**
+ * @method createWriter
+ * @param {String} name name of the file to be created
+ * @param {String} [extension]
+ * @return {p5.PrintWriter}
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * const writer = createWriter('squares.txt');
+ * for (let i = 0; i < 10; i++) {
+ * writer.print(i * i);
+ * }
+ * writer.close();
+ * writer.clear();
+ * }
+ * }
+ *
+ *
+ */
+ _main.default.prototype.createWriter = function(name, extension) {
+ var newPW;
+ // check that it doesn't already exist
+ for (var i in _main.default.prototype._pWriters) {
+ if (_main.default.prototype._pWriters[i].name === name) {
+ // if a p5.PrintWriter w/ this name already exists...
+ // return p5.prototype._pWriters[i]; // return it w/ contents intact.
+ // or, could return a new, empty one with a unique name:
+ newPW = new _main.default.PrintWriter(name + this.millis(), extension);
+ _main.default.prototype._pWriters.push(newPW);
+ return newPW;
+ }
+ }
+ newPW = new _main.default.PrintWriter(name, extension);
+ _main.default.prototype._pWriters.push(newPW);
+ return newPW;
+ };
+
+ /**
+ * @class p5.PrintWriter
+ * @param {String} filename
+ * @param {String} [extension]
+ */
+ _main.default.PrintWriter = function(filename, extension) {
+ var self = this;
+ this.name = filename;
+ this.content = '';
+ //Changed to write because it was being overloaded by function below.
+ /**
+ * Writes data to the PrintWriter stream
+ * @method write
+ * @param {Array} data all data to be written by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // write 'Hello world!'' to the file
+ * writer.write(['Hello world!']);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile2.txt'
+ * let writer = createWriter('newFile2.txt');
+ * // write 'apples,bananas,123' to the file
+ * writer.write(['apples', 'bananas', 123]);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile3.txt'
+ * let writer = createWriter('newFile3.txt');
+ * // write 'My name is: Teddy' to the file
+ * writer.write('My name is:');
+ * writer.write(' Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ */
+ this.write = function(data) {
+ this.content += data;
+ };
+ /**
+ * Writes data to the PrintWriter stream, and adds a new line at the end
+ * @method print
+ * @param {Array} data all data to be printed by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // creates a file containing
+ * // My name is:
+ * // Teddy
+ * writer.print('My name is:');
+ * writer.print('Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * let writer;
+ *
+ * function setup() {
+ * createCanvas(400, 400);
+ * // create a PrintWriter
+ * writer = createWriter('newFile.txt');
+ * }
+ *
+ * function draw() {
+ * // print all mouseX and mouseY coordinates to the stream
+ * writer.print([mouseX, mouseY]);
+ * }
+ *
+ * function mouseClicked() {
+ * // close the PrintWriter and save the file
+ * writer.close();
+ * }
+ *
+ *
+ */
+ this.print = function(data) {
+ this.content += ''.concat(data, '\n');
+ };
+ /**
+ * Clears the data already written to the PrintWriter object
+ * @method clear
+ * @example
+ *
+ * // create writer object
+ * let writer = createWriter('newFile.txt');
+ * writer.write(['clear me']);
+ * // clear writer object here
+ * writer.clear();
+ * // close writer
+ * writer.close();
+ *
+ *
+ */
+ this.clear = function() {
+ this.content = '';
+ };
+ /**
+ * Closes the PrintWriter
+ * @method close
+ * @example
+ *
+ *
+ * // create a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // create a file called 'newFile2.txt'
+ * let writer = createWriter('newFile2.txt');
+ * // write some data to the file
+ * writer.write([100, 101, 102]);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ */
+ this.close = function() {
+ // convert String to Array for the writeFile Blob
+ var arr = [];
+ arr.push(this.content);
+ _main.default.prototype.writeFile(arr, filename, extension);
+ // remove from _pWriters array and delete self
+ for (var i in _main.default.prototype._pWriters) {
+ if (_main.default.prototype._pWriters[i].name === this.name) {
+ // remove from _pWriters array
+ _main.default.prototype._pWriters.splice(i, 1);
+ }
+ }
+ self.clear();
+ self = {};
+ };
+ };
+
+ /**
+ * @module IO
+ * @submodule Output
+ * @for p5
+ */
+
+ // object, filename, options --> saveJSON, saveStrings,
+ // filename, [extension] [canvas] --> saveImage
+
+ /**
+ * Save an image, text, json, csv, wav, or html. Prompts download to
+ * the client's computer. Note that it is not recommended to call save()
+ * within draw if it's looping, as the save() function will open a new save
+ * dialog every frame.
+ * The default behavior is to save the canvas as an image. You can
+ * optionally specify a filename.
+ * For example:
+ *
+ * save();
+ * save('myCanvas.jpg'); // save a specific canvas with a filename
+ *
+ *
+ * Alternately, the first parameter can be a pointer to a canvas
+ * p5.Element, an Array of Strings,
+ * an Array of JSON, a JSON object, a p5.Table, a p5.Image, or a
+ * p5.SoundFile (requires p5.sound). The second parameter is a filename
+ * (including extension). The third parameter is for options specific
+ * to this type of object. This method will save a file that fits the
+ * given parameters. For example:
+ *
+ *
+ * // Saves canvas as an image
+ * save('myCanvas.jpg');
+ *
+ * // Saves pImage as a png image
+ * let img = createImage(10, 10);
+ * save(img, 'my.png');
+ *
+ * // Saves canvas as an image
+ * let cnv = createCanvas(100, 100);
+ * save(cnv, 'myCanvas.jpg');
+ *
+ * // Saves p5.Renderer object as an image
+ * let gb = createGraphics(100, 100);
+ * save(gb, 'myGraphics.jpg');
+ *
+ * let myTable = new p5.Table();
+ *
+ * // Saves table as html file
+ * save(myTable, 'myTable.html');
+ *
+ * // Comma Separated Values
+ * save(myTable, 'myTable.csv');
+ *
+ * // Tab Separated Values
+ * save(myTable, 'myTable.tsv');
+ *
+ * let myJSON = { a: 1, b: true };
+ *
+ * // Saves pretty JSON
+ * save(myJSON, 'my.json');
+ *
+ * // Optimizes JSON filesize
+ * save(myJSON, 'my.json', true);
+ *
+ * // Saves array of strings to a text file with line breaks after each item
+ * let arrayOfStrings = ['a', 'b'];
+ * save(arrayOfStrings, 'my.txt');
+ *
+ *
+ * @method save
+ * @param {Object|String} [objectOrFilename] If filename is provided, will
+ * save canvas as an image with
+ * either png or jpg extension
+ * depending on the filename.
+ * If object is provided, will
+ * save depending on the object
+ * and filename (see examples
+ * above).
+ * @param {String} [filename] If an object is provided as the first
+ * parameter, then the second parameter
+ * indicates the filename,
+ * and should include an appropriate
+ * file extension (see examples above).
+ * @param {Boolean|String} [options] Additional options depend on
+ * filetype. For example, when saving JSON,
+ * true indicates that the
+ * output will be optimized for filesize,
+ * rather than readability.
+ */
+ _main.default.prototype.save = function(object, _filename, _options) {
+ // parse the arguments and figure out which things we are saving
+ var args = arguments;
+ // =================================================
+ // OPTION 1: saveCanvas...
+
+ // if no arguments are provided, save canvas
+ var cnv = this._curElement ? this._curElement.elt : this.elt;
+ if (args.length === 0) {
+ _main.default.prototype.saveCanvas(cnv);
+ return;
+ } else if (
+ args[0] instanceof _main.default.Renderer ||
+ args[0] instanceof _main.default.Graphics
+ ) {
+ // otherwise, parse the arguments
+
+ // if first param is a p5Graphics, then saveCanvas
+ _main.default.prototype.saveCanvas(args[0].elt, args[1], args[2]);
+ return;
+ } else if (args.length === 1 && typeof args[0] === 'string') {
+ // if 1st param is String and only one arg, assume it is canvas filename
+ _main.default.prototype.saveCanvas(cnv, args[0]);
+ } else {
+ // =================================================
+ // OPTION 2: extension clarifies saveStrings vs. saveJSON
+ var extension = _checkFileExtension(args[1], args[2])[1];
+ switch (extension) {
+ case 'json':
+ _main.default.prototype.saveJSON(args[0], args[1], args[2]);
+ return;
+ case 'txt':
+ _main.default.prototype.saveStrings(args[0], args[1], args[2]);
+ return;
+ // =================================================
+ // OPTION 3: decide based on object...
+ default:
+ if (args[0] instanceof Array) {
+ _main.default.prototype.saveStrings(args[0], args[1], args[2]);
+ } else if (args[0] instanceof _main.default.Table) {
+ _main.default.prototype.saveTable(args[0], args[1], args[2]);
+ } else if (args[0] instanceof _main.default.Image) {
+ _main.default.prototype.saveCanvas(args[0].canvas, args[1]);
+ } else if (args[0] instanceof _main.default.SoundFile) {
+ _main.default.prototype.saveSound(args[0], args[1], args[2], args[3]);
+ }
+ }
+ }
+ };
+
+ /**
+ * Writes the contents of an Array or a JSON object to a .json file.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveJSON
+ * @param {Array|Object} json
+ * @param {String} filename
+ * @param {Boolean} [optimize] If true, removes line breaks
+ * and spaces from the output
+ * file to optimize filesize
+ * (but not readability).
+ * @example
+ *
+ * let json = {}; // new JSON Object
+ *
+ * json.id = 0;
+ * json.species = 'Panthera leo';
+ * json.name = 'Lion';
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * saveJSON(json, 'lion.json');
+ * }
+ * }
+ *
+ * // saves the following to a file called "lion.json":
+ * // {
+ * // "id": 0,
+ * // "species": "Panthera leo",
+ * // "name": "Lion"
+ * // }
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.prototype.saveJSON = function(json, filename, opt) {
+ _main.default._validateParameters('saveJSON', arguments);
+ var stringify;
+ if (opt) {
+ stringify = JSON.stringify(json);
+ } else {
+ stringify = JSON.stringify(json, undefined, 2);
+ }
+ this.saveStrings(stringify.split('\n'), filename, 'json');
+ };
+
+ _main.default.prototype.saveJSONObject = _main.default.prototype.saveJSON;
+ _main.default.prototype.saveJSONArray = _main.default.prototype.saveJSON;
+
+ /**
+ * Writes an array of Strings to a text file, one line per String.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveStrings
+ * @param {String[]} list string array to be written
+ * @param {String} filename filename for output
+ * @param {String} [extension] the filename's extension
+ * @example
+ *
+ * let words = 'apple bear cat dog';
+ *
+ * // .split() outputs an Array
+ * let list = split(words, ' ');
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * saveStrings(list, 'nouns.txt');
+ * }
+ * }
+ *
+ * // Saves the following to a file called 'nouns.txt':
+ * //
+ * // apple
+ * // bear
+ * // cat
+ * // dog
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.prototype.saveStrings = function(list, filename, extension) {
+ _main.default._validateParameters('saveStrings', arguments);
+ var ext = extension || 'txt';
+ var pWriter = this.createWriter(filename, ext);
+ for (var i = 0; i < list.length; i++) {
+ if (i < list.length - 1) {
+ pWriter.print(list[i]);
+ } else {
+ pWriter.print(list[i]);
+ }
+ }
+ pWriter.close();
+ pWriter.clear();
+ };
+
+ // =======
+ // HELPERS
+ // =======
+
+ function escapeHelper(content) {
+ return content
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+ }
+
+ /**
+ * Writes the contents of a Table object to a file. Defaults to a
+ * text file with comma-separated-values ('csv') but can also
+ * use tab separation ('tsv'), or generate an HTML table ('html').
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveTable
+ * @param {p5.Table} Table the Table object to save to a file
+ * @param {String} filename the filename to which the Table should be saved
+ * @param {String} [options] can be one of "tsv", "csv", or "html"
+ * @example
+ *
+ * let table;
+ *
+ * function setup() {
+ * table = new p5.Table();
+ *
+ * table.addColumn('id');
+ * table.addColumn('species');
+ * table.addColumn('name');
+ *
+ * let newRow = table.addRow();
+ * newRow.setNum('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Panthera leo');
+ * newRow.setString('name', 'Lion');
+ *
+ * // To save, un-comment next line then click 'run'
+ * // saveTable(table, 'new.csv');
+ * }
+ *
+ * // Saves the following to a file called 'new.csv':
+ * // id,species,name
+ * // 0,Panthera leo,Lion
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.prototype.saveTable = function(table, filename, options) {
+ _main.default._validateParameters('saveTable', arguments);
+ var ext;
+ if (options === undefined) {
+ ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
+ } else {
+ ext = options;
+ }
+ var pWriter = this.createWriter(filename, ext);
+
+ var header = table.columns;
+
+ var sep = ','; // default to CSV
+ if (ext === 'tsv') {
+ sep = '\t';
+ }
+ if (ext !== 'html') {
+ // make header if it has values
+ if (header[0] !== '0') {
+ for (var h = 0; h < header.length; h++) {
+ if (h < header.length - 1) {
+ pWriter.write(header[h] + sep);
+ } else {
+ pWriter.write(header[h]);
+ }
+ }
+ pWriter.write('\n');
+ }
+
+ // make rows
+ for (var i = 0; i < table.rows.length; i++) {
+ var j = void 0;
+ for (j = 0; j < table.rows[i].arr.length; j++) {
+ if (j < table.rows[i].arr.length - 1) {
+ pWriter.write(table.rows[i].arr[j] + sep);
+ } else if (i < table.rows.length - 1) {
+ pWriter.write(table.rows[i].arr[j]);
+ } else {
+ pWriter.write(table.rows[i].arr[j]);
+ }
+ }
+ pWriter.write('\n');
+ }
+ } else {
+ // otherwise, make HTML
+ pWriter.print('');
+ pWriter.print('');
+ var str = ' ';
+ pWriter.print(str);
+ pWriter.print('');
+
+ pWriter.print('');
+ pWriter.print(' ');
+
+ // make header if it has values
+ if (header[0] !== '0') {
+ pWriter.print(' ');
+ for (var k = 0; k < header.length; k++) {
+ var e = escapeHelper(header[k]);
+ pWriter.print(' '.concat(e));
+ pWriter.print(' ');
+ }
+ pWriter.print(' ');
+ }
+
+ // make rows
+ for (var row = 0; row < table.rows.length; row++) {
+ pWriter.print(' ');
+ for (var col = 0; col < table.columns.length; col++) {
+ var entry = table.rows[row].getString(col);
+ var htmlEntry = escapeHelper(entry);
+ pWriter.print(' '.concat(htmlEntry));
+ pWriter.print(' ');
+ }
+ pWriter.print(' ');
+ }
+ pWriter.print('
');
+ pWriter.print('');
+ pWriter.print('');
+ }
+ // close and clear the pWriter
+ pWriter.close();
+ pWriter.clear();
+ }; // end saveTable()
+
+ /**
+ * Generate a blob of file data as a url to prepare for download.
+ * Accepts an array of data, a filename, and an extension (optional).
+ * This is a private function because it does not do any formatting,
+ * but it is used by saveStrings, saveJSON, saveTable etc.
+ *
+ * @param {Array} dataToDownload
+ * @param {String} filename
+ * @param {String} [extension]
+ * @private
+ */
+ _main.default.prototype.writeFile = function(
+ dataToDownload,
+ filename,
+ extension
+ ) {
+ var type = 'application/octet-stream';
+ if (_main.default.prototype._isSafari()) {
+ type = 'text/plain';
+ }
+ var blob = new Blob(dataToDownload, {
+ type: type
+ });
+
+ _main.default.prototype.downloadFile(blob, filename, extension);
+ };
+
+ /**
+ * Forces download. Accepts a url to filedata/blob, a filename,
+ * and an extension (optional).
+ * This is a private function because it does not do any formatting,
+ * but it is used by saveStrings, saveJSON, saveTable etc.
+ *
+ * @method downloadFile
+ * @private
+ * @param {String|Blob} data either an href generated by createObjectURL,
+ * or a Blob object containing the data
+ * @param {String} [filename]
+ * @param {String} [extension]
+ */
+ _main.default.prototype.downloadFile = function(data, fName, extension) {
+ var fx = _checkFileExtension(fName, extension);
+ var filename = fx[0];
+
+ if (data instanceof Blob) {
+ _fileSaver.default.saveAs(data, filename);
+ return;
+ }
+
+ var a = document.createElement('a');
+ a.href = data;
+ a.download = filename;
+
+ // Firefox requires the link to be added to the DOM before click()
+ a.onclick = function(e) {
+ destroyClickedElement(e);
+ e.stopPropagation();
+ };
+
+ a.style.display = 'none';
+ document.body.appendChild(a);
+
+ // Safari will open this file in the same page as a confusing Blob.
+ if (_main.default.prototype._isSafari()) {
+ var aText = 'Hello, Safari user! To download this file...\n';
+ aText += '1. Go to File --> Save As.\n';
+ aText += '2. Choose "Page Source" as the Format.\n';
+ aText += '3. Name it with this extension: ."'.concat(fx[1], '"');
+ alert(aText);
+ }
+ a.click();
+ };
+
+ /**
+ * Returns a file extension, or another string
+ * if the provided parameter has no extension.
+ *
+ * @param {String} filename
+ * @param {String} [extension]
+ * @return {String[]} [fileName, fileExtension]
+ *
+ * @private
+ */
+ function _checkFileExtension(filename, extension) {
+ if (!extension || extension === true || extension === 'true') {
+ extension = '';
+ }
+ if (!filename) {
+ filename = 'untitled';
+ }
+ var ext = '';
+ // make sure the file will have a name, see if filename needs extension
+ if (filename && filename.includes('.')) {
+ ext = filename.split('.').pop();
+ }
+ // append extension if it doesn't exist
+ if (extension) {
+ if (ext !== extension) {
+ ext = extension;
+ filename = ''.concat(filename, '.').concat(ext);
+ }
+ }
+ return [filename, ext];
+ }
+ _main.default.prototype._checkFileExtension = _checkFileExtension;
+
+ /**
+ * Returns true if the browser is Safari, false if not.
+ * Safari makes trouble for downloading files.
+ *
+ * @return {Boolean} [description]
+ * @private
+ */
+ _main.default.prototype._isSafari = function() {
+ var x = Object.prototype.toString.call(window.HTMLElement);
+ return x.indexOf('Constructor') > 0;
+ };
+
+ /**
+ * Helper function, a callback for download that deletes
+ * an invisible anchor element from the DOM once the file
+ * has been automatically downloaded.
+ *
+ * @private
+ */
+ function destroyClickedElement(event) {
+ document.body.removeChild(event.target);
+ }
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/error_helpers': 23,
+ '../core/main': 27,
+ 'es6-promise/auto': 5,
+ 'fetch-jsonp': 7,
+ 'file-saver': 8,
+ 'whatwg-fetch': 15
+ }
+ ],
+ 54: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /**
+ * Table objects store data with multiple rows and columns, much
+ * like in a traditional spreadsheet. Tables can be generated from
+ * scratch, dynamically, or using data from an existing file.
+ *
+ * @class p5.Table
+ * @constructor
+ * @param {p5.TableRow[]} [rows] An array of p5.TableRow objects
+ */ /**
+ * @module IO
+ * @submodule Table
+ * @requires core
+ */ /**
+ * Table Options
+ * Generic class for handling tabular data, typically from a
+ * CSV, TSV, or other sort of spreadsheet file.
+ * CSV files are
+ *
+ * comma separated values, often with the data in quotes. TSV
+ * files use tabs as separators, and usually don't bother with the
+ * quotes.
+ * File names should end with .csv if they're comma separated.
+ * A rough "spec" for CSV can be found
+ * here.
+ * To load files, use the loadTable method.
+ * To save tables to your computer, use the save method
+ * or the saveTable method.
+ *
+ * Possible options include:
+ *
+ * - csv - parse the table as comma-separated values
+ *
- tsv - parse the table as tab-separated values
+ *
- header - this table has a header (title) row
+ *
+ */
+ _main.default.Table = function(rows) {
+ /**
+ * An array containing the names of the columns in the table, if the "header" the table is
+ * loaded with the "header" parameter.
+ * @property columns {String[]}
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //print the column names
+ * for (let c = 0; c < table.getColumnCount(); c++) {
+ * print('column ' + c + ' is named ' + table.columns[c]);
+ * }
+ * }
+ *
+ *
+ */
+ this.columns = [];
+
+ /**
+ * An array containing the p5.TableRow objects that make up the
+ * rows of the table. The same result as calling getRows()
+ * @property rows {p5.TableRow[]}
+ */
+ this.rows = [];
+ };
+
+ /**
+ * Use addRow() to add a new row of data to a p5.Table object. By default,
+ * an empty row is created. Typically, you would store a reference to
+ * the new row in a TableRow object (see newRow in the example above),
+ * and then set individual values using set().
+ *
+ * If a p5.TableRow object is included as a parameter, then that row is
+ * duplicated and added to the table.
+ *
+ * @method addRow
+ * @param {p5.TableRow} [row] row to be added to the table
+ * @return {p5.TableRow} the row that was added
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //add a row
+ * let newRow = table.addRow();
+ * newRow.setString('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Canis Lupus');
+ * newRow.setString('name', 'Wolf');
+ *
+ * //print the results
+ * for (let r = 0; r < table.getRowCount(); r++)
+ * for (let c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.addRow = function(row) {
+ // make sure it is a valid TableRow
+ var r = row || new _main.default.TableRow();
+
+ if (typeof r.arr === 'undefined' || typeof r.obj === 'undefined') {
+ //r = new p5.prototype.TableRow(r);
+ throw new Error('invalid TableRow: '.concat(r));
+ }
+ r.table = this;
+ this.rows.push(r);
+ return r;
+ };
+
+ /**
+ * Removes a row from the table object.
+ *
+ * @method removeRow
+ * @param {Integer} id ID number of the row to remove
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //remove the first row
+ * table.removeRow(0);
+ *
+ * //print the results
+ * for (let r = 0; r < table.getRowCount(); r++)
+ * for (let c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.removeRow = function(id) {
+ this.rows[id].table = null; // remove reference to table
+ var chunk = this.rows.splice(id + 1, this.rows.length);
+ this.rows.pop();
+ this.rows = this.rows.concat(chunk);
+ };
+
+ /**
+ * Returns a reference to the specified p5.TableRow. The reference
+ * can then be used to get and set values of the selected row.
+ *
+ * @method getRow
+ * @param {Integer} rowID ID number of the row to get
+ * @return {p5.TableRow} p5.TableRow object
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let row = table.getRow(1);
+ * //print it column by column
+ * //note: a row is an object, not an array
+ * for (let c = 0; c < table.getColumnCount(); c++) {
+ * print(row.getString(c));
+ * }
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.getRow = function(r) {
+ return this.rows[r];
+ };
+
+ /**
+ * Gets all rows from the table. Returns an array of p5.TableRows.
+ *
+ * @method getRows
+ * @return {p5.TableRow[]} Array of p5.TableRows
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let rows = table.getRows();
+ *
+ * //warning: rows is an array of objects
+ * for (let r = 0; r < rows.length; r++) {
+ * rows[r].set('name', 'Unicorn');
+ * }
+ *
+ * //print the results
+ * for (let r = 0; r < table.getRowCount(); r++)
+ * for (let c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.getRows = function() {
+ return this.rows;
+ };
+
+ /**
+ * Finds the first row in the Table that contains the value
+ * provided, and returns a reference to that row. Even if
+ * multiple rows are possible matches, only the first matching
+ * row is returned. The column to search may be specified by
+ * either its ID or title.
+ *
+ * @method findRow
+ * @param {String} value The value to match
+ * @param {Integer|String} column ID number or title of the
+ * column to search
+ * @return {p5.TableRow}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //find the animal named zebra
+ * let row = table.findRow('Zebra', 'name');
+ * //find the corresponding species
+ * print(row.getString('species'));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.findRow = function(value, column) {
+ // try the Object
+ if (typeof column === 'string') {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column] === value) {
+ return this.rows[i];
+ }
+ }
+ } else {
+ // try the Array
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column] === value) {
+ return this.rows[j];
+ }
+ }
+ }
+ // otherwise...
+ return null;
+ };
+
+ /**
+ * Finds the rows in the Table that contain the value
+ * provided, and returns references to those rows. Returns an
+ * Array, so for must be used to iterate through all the rows,
+ * as shown in the example above. The column to search may be
+ * specified by either its ID or title.
+ *
+ * @method findRows
+ * @param {String} value The value to match
+ * @param {Integer|String} column ID number or title of the
+ * column to search
+ * @return {p5.TableRow[]} An Array of TableRow objects
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //add another goat
+ * let newRow = table.addRow();
+ * newRow.setString('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Scape Goat');
+ * newRow.setString('name', 'Goat');
+ *
+ * //find the rows containing animals named Goat
+ * let rows = table.findRows('Goat', 'name');
+ * print(rows.length + ' Goats found');
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.findRows = function(value, column) {
+ var ret = [];
+ if (typeof column === 'string') {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column] === value) {
+ ret.push(this.rows[i]);
+ }
+ }
+ } else {
+ // try the Array
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column] === value) {
+ ret.push(this.rows[j]);
+ }
+ }
+ }
+ return ret;
+ };
+
+ /**
+ * Finds the first row in the Table that matches the regular
+ * expression provided, and returns a reference to that row.
+ * Even if multiple rows are possible matches, only the first
+ * matching row is returned. The column to search may be
+ * specified by either its ID or title.
+ *
+ * @method matchRow
+ * @param {String|RegExp} regexp The regular expression to match
+ * @param {String|Integer} column The column ID (number) or
+ * title (string)
+ * @return {p5.TableRow} TableRow object
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //Search using specified regex on a given column, return TableRow object
+ * let mammal = table.matchRow(new RegExp('ant'), 1);
+ * print(mammal.getString(1));
+ * //Output "Panthera pardus"
+ * }
+ *
+ *
+ *
+ */
+ _main.default.Table.prototype.matchRow = function(regexp, column) {
+ if (typeof column === 'number') {
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column].match(regexp)) {
+ return this.rows[j];
+ }
+ }
+ } else {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column].match(regexp)) {
+ return this.rows[i];
+ }
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Finds the rows in the Table that match the regular expression provided,
+ * and returns references to those rows. Returns an array, so for must be
+ * used to iterate through all the rows, as shown in the example. The
+ * column to search may be specified by either its ID or title.
+ *
+ * @method matchRows
+ * @param {String} regexp The regular expression to match
+ * @param {String|Integer} [column] The column ID (number) or
+ * title (string)
+ * @return {p5.TableRow[]} An Array of TableRow objects
+ * @example
+ *
+ *
+ * let table;
+ *
+ * function setup() {
+ * table = new p5.Table();
+ *
+ * table.addColumn('name');
+ * table.addColumn('type');
+ *
+ * let newRow = table.addRow();
+ * newRow.setString('name', 'Lion');
+ * newRow.setString('type', 'Mammal');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', 'Snake');
+ * newRow.setString('type', 'Reptile');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', 'Mosquito');
+ * newRow.setString('type', 'Insect');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', 'Lizard');
+ * newRow.setString('type', 'Reptile');
+ *
+ * let rows = table.matchRows('R.*', 'type');
+ * for (let i = 0; i < rows.length; i++) {
+ * print(rows[i].getString('name') + ': ' + rows[i].getString('type'));
+ * }
+ * }
+ * // Sketch prints:
+ * // Snake: Reptile
+ * // Lizard: Reptile
+ *
+ *
+ */
+ _main.default.Table.prototype.matchRows = function(regexp, column) {
+ var ret = [];
+ if (typeof column === 'number') {
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column].match(regexp)) {
+ ret.push(this.rows[j]);
+ }
+ }
+ } else {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column].match(regexp)) {
+ ret.push(this.rows[i]);
+ }
+ }
+ }
+ return ret;
+ };
+
+ /**
+ * Retrieves all values in the specified column, and returns them
+ * as an array. The column may be specified by either its ID or title.
+ *
+ * @method getColumn
+ * @param {String|Number} column String or Number of the column to return
+ * @return {Array} Array of column values
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //getColumn returns an array that can be printed directly
+ * print(table.getColumn('species'));
+ * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"]
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.getColumn = function(value) {
+ var ret = [];
+ if (typeof value === 'string') {
+ for (var i = 0; i < this.rows.length; i++) {
+ ret.push(this.rows[i].obj[value]);
+ }
+ } else {
+ for (var j = 0; j < this.rows.length; j++) {
+ ret.push(this.rows[j].arr[value]);
+ }
+ }
+ return ret;
+ };
+
+ /**
+ * Removes all rows from a Table. While all rows are removed,
+ * columns and column titles are maintained.
+ *
+ * @method clearRows
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.clearRows();
+ * print(table.getRowCount() + ' total rows in table');
+ * print(table.getColumnCount() + ' total columns in table');
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.clearRows = function() {
+ delete this.rows;
+ this.rows = [];
+ };
+
+ /**
+ * Use addColumn() to add a new column to a Table object.
+ * Typically, you will want to specify a title, so the column
+ * may be easily referenced later by name. (If no title is
+ * specified, the new column's title will be null.)
+ *
+ * @method addColumn
+ * @param {String} [title] title of the given column
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.addColumn('carnivore');
+ * table.set(0, 'carnivore', 'no');
+ * table.set(1, 'carnivore', 'yes');
+ * table.set(2, 'carnivore', 'no');
+ *
+ * //print the results
+ * for (let r = 0; r < table.getRowCount(); r++)
+ * for (let c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.addColumn = function(title) {
+ var t = title || null;
+ this.columns.push(t);
+ };
+
+ /**
+ * Returns the total number of columns in a Table.
+ *
+ * @method getColumnCount
+ * @return {Integer} Number of columns in this table
+ * @example
+ *
+ *
+ * // given the cvs file "blobs.csv" in /assets directory
+ * // ID, Name, Flavor, Shape, Color
+ * // Blob1, Blobby, Sweet, Blob, Pink
+ * // Blob2, Saddy, Savory, Blob, Blue
+ *
+ * let table;
+ *
+ * function preload() {
+ * table = loadTable('assets/blobs.csv');
+ * }
+ *
+ * function setup() {
+ * createCanvas(200, 100);
+ * textAlign(CENTER);
+ * background(255);
+ * }
+ *
+ * function draw() {
+ * let numOfColumn = table.getColumnCount();
+ * text('There are ' + numOfColumn + ' columns in the table.', 100, 50);
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getColumnCount = function() {
+ return this.columns.length;
+ };
+
+ /**
+ * Returns the total number of rows in a Table.
+ *
+ * @method getRowCount
+ * @return {Integer} Number of rows in this table
+ * @example
+ *
+ *
+ * // given the cvs file "blobs.csv" in /assets directory
+ * //
+ * // ID, Name, Flavor, Shape, Color
+ * // Blob1, Blobby, Sweet, Blob, Pink
+ * // Blob2, Saddy, Savory, Blob, Blue
+ *
+ * let table;
+ *
+ * function preload() {
+ * table = loadTable('assets/blobs.csv');
+ * }
+ *
+ * function setup() {
+ * createCanvas(200, 100);
+ * textAlign(CENTER);
+ * background(255);
+ * }
+ *
+ * function draw() {
+ * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getRowCount = function() {
+ return this.rows.length;
+ };
+
+ /**
+ * Removes any of the specified characters (or "tokens").
+ *
+ * If no column is specified, then the values in all columns and
+ * rows are processed. A specific column may be referenced by
+ * either its ID or title.
+ *
+ * @method removeTokens
+ * @param {String} chars String listing characters to be removed
+ * @param {String|Integer} [column] Column ID (number)
+ * or name (string)
+ *
+ * @example
+ *
+ * function setup() {
+ * let table = new p5.Table();
+ *
+ * table.addColumn('name');
+ * table.addColumn('type');
+ *
+ * let newRow = table.addRow();
+ * newRow.setString('name', ' $Lion ,');
+ * newRow.setString('type', ',,,Mammal');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', '$Snake ');
+ * newRow.setString('type', ',,,Reptile');
+ *
+ * table.removeTokens(',$ ');
+ * print(table.getArray());
+ * }
+ *
+ * // prints:
+ * // 0 "Lion" "Mamal"
+ * // 1 "Snake" "Reptile"
+ *
+ */
+ _main.default.Table.prototype.removeTokens = function(chars, column) {
+ var escape = function escape(s) {
+ return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
+ };
+ var charArray = [];
+ for (var i = 0; i < chars.length; i++) {
+ charArray.push(escape(chars.charAt(i)));
+ }
+ var regex = new RegExp(charArray.join('|'), 'g');
+
+ if (typeof column === 'undefined') {
+ for (var c = 0; c < this.columns.length; c++) {
+ for (var d = 0; d < this.rows.length; d++) {
+ var s = this.rows[d].arr[c];
+ s = s.replace(regex, '');
+ this.rows[d].arr[c] = s;
+ this.rows[d].obj[this.columns[c]] = s;
+ }
+ }
+ } else if (typeof column === 'string') {
+ for (var j = 0; j < this.rows.length; j++) {
+ var val = this.rows[j].obj[column];
+ val = val.replace(regex, '');
+ this.rows[j].obj[column] = val;
+ var pos = this.columns.indexOf(column);
+ this.rows[j].arr[pos] = val;
+ }
+ } else {
+ for (var k = 0; k < this.rows.length; k++) {
+ var str = this.rows[k].arr[column];
+ str = str.replace(regex, '');
+ this.rows[k].arr[column] = str;
+ this.rows[k].obj[this.columns[column]] = str;
+ }
+ }
+ };
+
+ /**
+ * Trims leading and trailing whitespace, such as spaces and tabs,
+ * from String table values. If no column is specified, then the
+ * values in all columns and rows are trimmed. A specific column
+ * may be referenced by either its ID or title.
+ *
+ * @method trim
+ * @param {String|Integer} [column] Column ID (number)
+ * or name (string)
+ * @example
+ *
+ * function setup() {
+ * let table = new p5.Table();
+ *
+ * table.addColumn('name');
+ * table.addColumn('type');
+ *
+ * let newRow = table.addRow();
+ * newRow.setString('name', ' Lion ,');
+ * newRow.setString('type', ' Mammal ');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', ' Snake ');
+ * newRow.setString('type', ' Reptile ');
+ *
+ * table.trim();
+ * print(table.getArray());
+ * }
+ *
+ * // prints:
+ * // 0 "Lion" "Mamal"
+ * // 1 "Snake" "Reptile"
+ *
+ */
+ _main.default.Table.prototype.trim = function(column) {
+ var regex = new RegExp(' ', 'g');
+
+ if (typeof column === 'undefined') {
+ for (var c = 0; c < this.columns.length; c++) {
+ for (var d = 0; d < this.rows.length; d++) {
+ var s = this.rows[d].arr[c];
+ s = s.replace(regex, '');
+ this.rows[d].arr[c] = s;
+ this.rows[d].obj[this.columns[c]] = s;
+ }
+ }
+ } else if (typeof column === 'string') {
+ for (var j = 0; j < this.rows.length; j++) {
+ var val = this.rows[j].obj[column];
+ val = val.replace(regex, '');
+ this.rows[j].obj[column] = val;
+ var pos = this.columns.indexOf(column);
+ this.rows[j].arr[pos] = val;
+ }
+ } else {
+ for (var k = 0; k < this.rows.length; k++) {
+ var str = this.rows[k].arr[column];
+ str = str.replace(regex, '');
+ this.rows[k].arr[column] = str;
+ this.rows[k].obj[this.columns[column]] = str;
+ }
+ }
+ };
+
+ /**
+ * Use removeColumn() to remove an existing column from a Table
+ * object. The column to be removed may be identified by either
+ * its title (a String) or its index value (an int).
+ * removeColumn(0) would remove the first column, removeColumn(1)
+ * would remove the second column, and so on.
+ *
+ * @method removeColumn
+ * @param {String|Integer} column columnName (string) or ID (number)
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.removeColumn('id');
+ * print(table.getColumnCount());
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.removeColumn = function(c) {
+ var cString;
+ var cNumber;
+ if (typeof c === 'string') {
+ // find the position of c in the columns
+ cString = c;
+ cNumber = this.columns.indexOf(c);
+ } else {
+ cNumber = c;
+ cString = this.columns[c];
+ }
+
+ var chunk = this.columns.splice(cNumber + 1, this.columns.length);
+ this.columns.pop();
+ this.columns = this.columns.concat(chunk);
+
+ for (var i = 0; i < this.rows.length; i++) {
+ var tempR = this.rows[i].arr;
+ var chip = tempR.splice(cNumber + 1, tempR.length);
+ tempR.pop();
+ this.rows[i].arr = tempR.concat(chip);
+ delete this.rows[i].obj[cString];
+ }
+ };
+
+ /**
+ * Stores a value in the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified
+ * by either its ID or title.
+ *
+ * @method set
+ * @param {Integer} row row ID
+ * @param {String|Integer} column column ID (Number)
+ * or title (String)
+ * @param {String|Number} value value to assign
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.set(0, 'species', 'Canis Lupus');
+ * table.set(0, 'name', 'Wolf');
+ *
+ * //print the results
+ * for (let r = 0; r < table.getRowCount(); r++)
+ * for (let c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.set = function(row, column, value) {
+ this.rows[row].set(column, value);
+ };
+
+ /**
+ * Stores a Float value in the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified
+ * by either its ID or title.
+ *
+ * @method setNum
+ * @param {Integer} row row ID
+ * @param {String|Integer} column column ID (Number)
+ * or title (String)
+ * @param {Number} value value to assign
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.setNum(1, 'id', 1);
+ *
+ * print(table.getColumn(0));
+ * //["0", 1, "2"]
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.setNum = function(row, column, value) {
+ this.rows[row].setNum(column, value);
+ };
+
+ /**
+ * Stores a String value in the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified
+ * by either its ID or title.
+ *
+ * @method setString
+ * @param {Integer} row row ID
+ * @param {String|Integer} column column ID (Number)
+ * or title (String)
+ * @param {String} value value to assign
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //add a row
+ * let newRow = table.addRow();
+ * newRow.setString('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Canis Lupus');
+ * newRow.setString('name', 'Wolf');
+ *
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.setString = function(row, column, value) {
+ this.rows[row].setString(column, value);
+ };
+
+ /**
+ * Retrieves a value from the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified by
+ * either its ID or title.
+ *
+ * @method get
+ * @param {Integer} row row ID
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String|Number}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * print(table.get(0, 1));
+ * //Capra hircus
+ * print(table.get(0, 'species'));
+ * //Capra hircus
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.get = function(row, column) {
+ return this.rows[row].get(column);
+ };
+
+ /**
+ * Retrieves a Float value from the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified by
+ * either its ID or title.
+ *
+ * @method getNum
+ * @param {Integer} row row ID
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {Number}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * print(table.getNum(1, 0) + 100);
+ * //id 1 + 100 = 101
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.getNum = function(row, column) {
+ return this.rows[row].getNum(column);
+ };
+
+ /**
+ * Retrieves a String value from the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified by
+ * either its ID or title.
+ *
+ * @method getString
+ * @param {Integer} row row ID
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * // table is comma separated value "CSV"
+ * // and has specifiying header for column labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * print(table.getString(0, 0)); // 0
+ * print(table.getString(0, 1)); // Capra hircus
+ * print(table.getString(0, 2)); // Goat
+ * print(table.getString(1, 0)); // 1
+ * print(table.getString(1, 1)); // Panthera pardus
+ * print(table.getString(1, 2)); // Leopard
+ * print(table.getString(2, 0)); // 2
+ * print(table.getString(2, 1)); // Equus zebra
+ * print(table.getString(2, 2)); // Zebra
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+
+ _main.default.Table.prototype.getString = function(row, column) {
+ return this.rows[row].getString(column);
+ };
+
+ /**
+ * Retrieves all table data and returns as an object. If a column name is
+ * passed in, each row object will be stored with that attribute as its
+ * title.
+ *
+ * @method getObject
+ * @param {String} [headerColumn] Name of the column which should be used to
+ * title each row object (optional)
+ * @return {Object}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let tableObject = table.getObject();
+ *
+ * print(tableObject);
+ * //outputs an object
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.getObject = function(headerColumn) {
+ var tableObject = {};
+ var obj, cPos, index;
+
+ for (var i = 0; i < this.rows.length; i++) {
+ obj = this.rows[i].obj;
+
+ if (typeof headerColumn === 'string') {
+ cPos = this.columns.indexOf(headerColumn); // index of columnID
+ if (cPos >= 0) {
+ index = obj[headerColumn];
+ tableObject[index] = obj;
+ } else {
+ throw new Error(
+ 'This table has no column named "'.concat(headerColumn, '"')
+ );
+ }
+ } else {
+ tableObject[i] = this.rows[i].obj;
+ }
+ }
+ return tableObject;
+ };
+
+ /**
+ * Retrieves all table data and returns it as a multidimensional array.
+ *
+ * @method getArray
+ * @return {Array}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leoperd
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * // table is comma separated value "CSV"
+ * // and has specifiying header for column labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let tableArray = table.getArray();
+ * for (let i = 0; i < tableArray.length; i++) {
+ * print(tableArray[i]);
+ * }
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+ _main.default.Table.prototype.getArray = function() {
+ var tableArray = [];
+ for (var i = 0; i < this.rows.length; i++) {
+ tableArray.push(this.rows[i].arr);
+ }
+ return tableArray;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 55: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module IO
+ * @submodule Table
+ * @requires core
+ */ /**
+ * A TableRow object represents a single row of data values,
+ * stored in columns, from a table.
+ *
+ * A Table Row contains both an ordered array, and an unordered
+ * JSON object.
+ *
+ * @class p5.TableRow
+ * @constructor
+ * @param {String} [str] optional: populate the row with a
+ * string of values, separated by the
+ * separator
+ * @param {String} [separator] comma separated values (csv) by default
+ */ _main.default.TableRow = function(str, separator) {
+ var arr = [];
+ var obj = {};
+ if (str) {
+ separator = separator || ',';
+ arr = str.split(separator);
+ }
+ for (var i = 0; i < arr.length; i++) {
+ var key = i;
+ var val = arr[i];
+ obj[key] = val;
+ }
+ this.arr = arr;
+ this.obj = obj;
+ this.table = null;
+ };
+
+ /**
+ * Stores a value in the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method set
+ * @param {String|Integer} column Column ID (Number)
+ * or Title (String)
+ * @param {String|Number} value The value to be stored
+ *
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let rows = table.getRows();
+ * for (let r = 0; r < rows.length; r++) {
+ * rows[r].set('name', 'Unicorn');
+ * }
+ *
+ * //print the results
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.set = function(column, value) {
+ // if typeof column is string, use .obj
+ if (typeof column === 'string') {
+ var cPos = this.table.columns.indexOf(column); // index of columnID
+ if (cPos >= 0) {
+ this.obj[column] = value;
+ this.arr[cPos] = value;
+ } else {
+ throw new Error('This table has no column named "'.concat(column, '"'));
+ }
+ } else {
+ // if typeof column is number, use .arr
+ if (column < this.table.columns.length) {
+ this.arr[column] = value;
+ var cTitle = this.table.columns[column];
+ this.obj[cTitle] = value;
+ } else {
+ throw new Error(
+ 'Column #'.concat(column, ' is out of the range of this table')
+ );
+ }
+ }
+ };
+
+ /**
+ * Stores a Float value in the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method setNum
+ * @param {String|Integer} column Column ID (Number)
+ * or Title (String)
+ * @param {Number|String} value The value to be stored
+ * as a Float
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let rows = table.getRows();
+ * for (let r = 0; r < rows.length; r++) {
+ * rows[r].setNum('id', r + 10);
+ * }
+ *
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.setNum = function(column, value) {
+ var floatVal = parseFloat(value);
+ this.set(column, floatVal);
+ };
+
+ /**
+ * Stores a String value in the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method setString
+ * @param {String|Integer} column Column ID (Number)
+ * or Title (String)
+ * @param {String|Number|Boolean|Object} value The value to be stored
+ * as a String
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let rows = table.getRows();
+ * for (let r = 0; r < rows.length; r++) {
+ * let name = rows[r].getString('name');
+ * rows[r].setString('name', 'A ' + name + ' named George');
+ * }
+ *
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.setString = function(column, value) {
+ var stringVal = value.toString();
+ this.set(column, stringVal);
+ };
+
+ /**
+ * Retrieves a value from the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method get
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String|Number}
+ *
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let names = [];
+ * let rows = table.getRows();
+ * for (let r = 0; r < rows.length; r++) {
+ * names.push(rows[r].get('name'));
+ * }
+ *
+ * print(names);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.get = function(column) {
+ if (typeof column === 'string') {
+ return this.obj[column];
+ } else {
+ return this.arr[column];
+ }
+ };
+
+ /**
+ * Retrieves a Float value from the TableRow's specified
+ * column. The column may be specified by either its ID or
+ * title.
+ *
+ * @method getNum
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {Number} Float Floating point number
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let rows = table.getRows();
+ * let minId = Infinity;
+ * let maxId = -Infinity;
+ * for (let r = 0; r < rows.length; r++) {
+ * let id = rows[r].getNum('id');
+ * minId = min(minId, id);
+ * maxId = min(maxId, id);
+ * }
+ * print('minimum id = ' + minId + ', maximum id = ' + maxId);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.getNum = function(column) {
+ var ret;
+ if (typeof column === 'string') {
+ ret = parseFloat(this.obj[column]);
+ } else {
+ ret = parseFloat(this.arr[column]);
+ }
+
+ if (ret.toString() === 'NaN') {
+ throw 'Error: '.concat(this.obj[column], ' is NaN (Not a Number)');
+ }
+ return ret;
+ };
+
+ /**
+ * Retrieves an String value from the TableRow's specified
+ * column. The column may be specified by either its ID or
+ * title.
+ *
+ * @method getString
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String} String
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * let table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * let rows = table.getRows();
+ * let longest = '';
+ * for (let r = 0; r < rows.length; r++) {
+ * let species = rows[r].getString('species');
+ * if (longest.length < species.length) {
+ * longest = species;
+ * }
+ * }
+ *
+ * print('longest: ' + longest);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.getString = function(column) {
+ if (typeof column === 'string') {
+ return this.obj[column].toString();
+ } else {
+ return this.arr[column].toString();
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 56: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module IO
+ * @submodule Input
+ * @requires core
+ */ /**
+ * XML is a representation of an XML object, able to parse XML code. Use
+ * loadXML() to load external XML files and create XML objects.
+ *
+ * @class p5.XML
+ * @constructor
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < children.length; i++) {
+ * let id = children[i].getNum('id');
+ * let coloring = children[i].getString('species');
+ * let name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */ _main.default.XML = function(DOM) {
+ if (!DOM) {
+ var xmlDoc = document.implementation.createDocument(null, 'doc');
+ this.DOM = xmlDoc.createElement('root');
+ } else {
+ this.DOM = DOM;
+ }
+ };
+
+ /**
+ * Gets a copy of the element's parent. Returns the parent as another
+ * p5.XML object.
+ *
+ * @method getParent
+ * @return {p5.XML} element parent
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ * let parent = children[1].getParent();
+ * print(parent.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+ _main.default.XML.prototype.getParent = function() {
+ return new _main.default.XML(this.DOM.parentElement);
+ };
+
+ /**
+ * Gets the element's full name, which is returned as a String.
+ *
+ * @method getName
+ * @return {String} the name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+ _main.default.XML.prototype.getName = function() {
+ return this.DOM.tagName;
+ };
+
+ /**
+ * Sets the element's name, which is specified as a String.
+ *
+ * @method setName
+ * @param {String} the new name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * xml.setName('fish');
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ * // fish
+ *
+ */
+ _main.default.XML.prototype.setName = function(name) {
+ var content = this.DOM.innerHTML;
+ var attributes = this.DOM.attributes;
+ var xmlDoc = document.implementation.createDocument(null, 'default');
+ var newDOM = xmlDoc.createElement(name);
+ newDOM.innerHTML = content;
+ for (var i = 0; i < attributes.length; i++) {
+ newDOM.setAttribute(attributes[i].nodeName, attributes.nodeValue);
+ }
+ this.DOM = newDOM;
+ };
+
+ /**
+ * Checks whether or not the element has any children, and returns the result
+ * as a boolean.
+ *
+ * @method hasChildren
+ * @return {boolean}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.hasChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ *
+ */
+ _main.default.XML.prototype.hasChildren = function() {
+ return this.DOM.children.length > 0;
+ };
+
+ /**
+ * Get the names of all of the element's children, and returns the names as an
+ * array of Strings. This is the same as looping through and calling getName()
+ * on each child element individually.
+ *
+ * @method listChildren
+ * @return {String[]} names of the children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.listChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // ["animal", "animal", "animal"]
+ *
+ */
+ _main.default.XML.prototype.listChildren = function() {
+ var arr = [];
+ for (var i = 0; i < this.DOM.childNodes.length; i++) {
+ arr.push(this.DOM.childNodes[i].nodeName);
+ }
+ return arr;
+ };
+
+ /**
+ * Returns all of the element's children as an array of p5.XML objects. When
+ * the name parameter is specified, then it will return all children that match
+ * that name.
+ *
+ * @method getChildren
+ * @param {String} [name] element name
+ * @return {p5.XML[]} children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let animals = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < animals.length; i++) {
+ * print(animals[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.getChildren = function(param) {
+ if (param) {
+ return elementsToP5XML(this.DOM.getElementsByTagName(param));
+ } else {
+ return elementsToP5XML(this.DOM.children);
+ }
+ };
+
+ function elementsToP5XML(elements) {
+ var arr = [];
+ for (var i = 0; i < elements.length; i++) {
+ arr.push(new _main.default.XML(elements[i]));
+ }
+ return arr;
+ }
+
+ /**
+ * Returns the first of the element's children that matches the name parameter
+ * or the child of the given index.It returns undefined if no matching
+ * child is found.
+ *
+ * @method getChild
+ * @param {String|Integer} name element name or index
+ * @return {p5.XML}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let secondChild = xml.getChild(1);
+ * print(secondChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Leopard"
+ *
+ */
+ _main.default.XML.prototype.getChild = function(param) {
+ if (typeof param === 'string') {
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (
+ var _iterator = this.DOM.children[Symbol.iterator](), _step;
+ !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
+ _iteratorNormalCompletion = true
+ ) {
+ var child = _step.value;
+ if (child.tagName === param) return new _main.default.XML(child);
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ } else {
+ return new _main.default.XML(this.DOM.children[param]);
+ }
+ };
+
+ /**
+ * Appends a new child to the element. The child can be specified with
+ * either a String, which will be used as the new tag's name, or as a
+ * reference to an existing p5.XML object.
+ * A reference to the newly created child is returned as an p5.XML object.
+ *
+ * @method addChild
+ * @param {p5.XML} node a p5.XML Object which will be the child to be added
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let child = new p5.XML();
+ * child.setName('animal');
+ * child.setAttribute('id', '3');
+ * child.setAttribute('species', 'Ornithorhynchus anatinus');
+ * child.setContent('Platypus');
+ * xml.addChild(child);
+ *
+ * let animals = xml.getChildren('animal');
+ * print(animals[animals.length - 1].getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.addChild = function(node) {
+ if (node instanceof _main.default.XML) {
+ this.DOM.appendChild(node.DOM);
+ } else {
+ // PEND
+ }
+ };
+
+ /**
+ * Removes the element specified by name or index.
+ *
+ * @method removeChild
+ * @param {String|Integer} name element name or index
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild('animal');
+ * let children = xml.getChildren();
+ * for (let i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Leopard"
+ * // "Zebra"
+ *
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild(1);
+ * let children = xml.getChildren();
+ * for (let i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.removeChild = function(param) {
+ var ind = -1;
+ if (typeof param === 'string') {
+ for (var i = 0; i < this.DOM.children.length; i++) {
+ if (this.DOM.children[i].tagName === param) {
+ ind = i;
+ break;
+ }
+ }
+ } else {
+ ind = param;
+ }
+ if (ind !== -1) {
+ this.DOM.removeChild(this.DOM.children[ind]);
+ }
+ };
+
+ /**
+ * Counts the specified element's number of attributes, returned as an Number.
+ *
+ * @method getAttributeCount
+ * @return {Integer}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getAttributeCount());
+ * }
+ *
+ * // Sketch prints:
+ * // 2
+ *
+ */
+ _main.default.XML.prototype.getAttributeCount = function() {
+ return this.DOM.attributes.length;
+ };
+
+ /**
+ * Gets all of the specified element's attributes, and returns them as an
+ * array of Strings.
+ *
+ * @method listAttributes
+ * @return {String[]} an array of strings containing the names of attributes
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.listAttributes());
+ * }
+ *
+ * // Sketch prints:
+ * // ["id", "species"]
+ *
+ */
+ _main.default.XML.prototype.listAttributes = function() {
+ var arr = [];
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (
+ var _iterator2 = this.DOM.attributes[Symbol.iterator](), _step2;
+ !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
+ _iteratorNormalCompletion2 = true
+ ) {
+ var attribute = _step2.value;
+ arr.push(attribute.nodeName);
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+
+ return arr;
+ };
+
+ /**
+ * Checks whether or not an element has the specified attribute.
+ *
+ * @method hasAttribute
+ * @param {String} the attribute to be checked
+ * @return {boolean} true if attribute found else false
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.hasAttribute('species'));
+ * print(firstChild.hasAttribute('color'));
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ * // false
+ *
+ */
+ _main.default.XML.prototype.hasAttribute = function(name) {
+ var obj = {};
+ var _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+ try {
+ for (
+ var _iterator3 = this.DOM.attributes[Symbol.iterator](), _step3;
+ !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done);
+ _iteratorNormalCompletion3 = true
+ ) {
+ var attribute = _step3.value;
+ obj[attribute.nodeName] = attribute.nodeValue;
+ }
+ } catch (err) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
+ _iterator3.return();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+
+ return obj[name] ? true : false;
+ };
+
+ /**
+ * Returns an attribute value of the element as an Number. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, the value 0 is returned.
+ *
+ * @method getNum
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {Number}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getNum('id'));
+ * }
+ *
+ * // Sketch prints:
+ * // 0
+ *
+ */
+ _main.default.XML.prototype.getNum = function(name, defaultValue) {
+ var obj = {};
+ var _iteratorNormalCompletion4 = true;
+ var _didIteratorError4 = false;
+ var _iteratorError4 = undefined;
+ try {
+ for (
+ var _iterator4 = this.DOM.attributes[Symbol.iterator](), _step4;
+ !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done);
+ _iteratorNormalCompletion4 = true
+ ) {
+ var attribute = _step4.value;
+ obj[attribute.nodeName] = attribute.nodeValue;
+ }
+ } catch (err) {
+ _didIteratorError4 = true;
+ _iteratorError4 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
+ _iterator4.return();
+ }
+ } finally {
+ if (_didIteratorError4) {
+ throw _iteratorError4;
+ }
+ }
+ }
+
+ return Number(obj[name]) || defaultValue || 0;
+ };
+
+ /**
+ * Returns an attribute value of the element as an String. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, null is returned.
+ *
+ * @method getString
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ *
+ */
+ _main.default.XML.prototype.getString = function(name, defaultValue) {
+ var obj = {};
+ var _iteratorNormalCompletion5 = true;
+ var _didIteratorError5 = false;
+ var _iteratorError5 = undefined;
+ try {
+ for (
+ var _iterator5 = this.DOM.attributes[Symbol.iterator](), _step5;
+ !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done);
+ _iteratorNormalCompletion5 = true
+ ) {
+ var attribute = _step5.value;
+ obj[attribute.nodeName] = attribute.nodeValue;
+ }
+ } catch (err) {
+ _didIteratorError5 = true;
+ _iteratorError5 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
+ _iterator5.return();
+ }
+ } finally {
+ if (_didIteratorError5) {
+ throw _iteratorError5;
+ }
+ }
+ }
+
+ return obj[name] ? String(obj[name]) : defaultValue || null;
+ };
+
+ /**
+ * Sets the content of an element's attribute. The first parameter specifies
+ * the attribute name, while the second specifies the new content.
+ *
+ * @method setAttribute
+ * @param {String} name the full name of the attribute
+ * @param {Number|String|Boolean} value the value of the attribute
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * firstChild.setAttribute('species', 'Jamides zebra');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ * // "Jamides zebra"
+ *
+ */
+ _main.default.XML.prototype.setAttribute = function(name, value) {
+ this.DOM.setAttribute(name, value);
+ };
+
+ /**
+ * Returns the content of an element. If there is no such content,
+ * defaultValue is returned if specified, otherwise null is returned.
+ *
+ * @method getContent
+ * @param {String} [defaultValue] value returned if no content is found
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ */
+ _main.default.XML.prototype.getContent = function(defaultValue) {
+ var str;
+ str = this.DOM.textContent;
+ str = str.replace(/\s\s+/g, ',');
+ return str || defaultValue || null;
+ };
+
+ /**
+ * Sets the element's content.
+ *
+ * @method setContent
+ * @param {String} text the new content
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * firstChild.setContent('Mountain Goat');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Mountain Goat"
+ *
+ */
+ _main.default.XML.prototype.setContent = function(content) {
+ if (!this.DOM.children.length) {
+ this.DOM.textContent = content;
+ }
+ };
+
+ /**
+ * Serializes the element into a string. This function is useful for preparing
+ * the content to be sent over a http request or saved to file.
+ *
+ * @method serialize
+ * @return {String} Serialized string of the element
+ * @example
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.serialize());
+ * }
+ *
+ * // Sketch prints:
+ * //
+ * // Goat
+ * // Leopard
+ * // Zebra
+ * //
+ *
+ */
+ _main.default.XML.prototype.serialize = function() {
+ var xmlSerializer = new XMLSerializer();
+ return xmlSerializer.serializeToString(this.DOM);
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 57: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Math
+ * @submodule Calculation
+ * @for p5
+ * @requires core
+ */ /**
+ * Calculates the absolute value (magnitude) of a number. Maps to Math.abs().
+ * The absolute value of a number is always positive.
+ *
+ * @method abs
+ * @param {Number} n number to compute
+ * @return {Number} absolute value of given number
+ * @example
+ *
+ * function setup() {
+ * let x = -3;
+ * let y = abs(x);
+ *
+ * print(x); // -3
+ * print(y); // 3
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */ _main.default.prototype.abs = Math.abs; /**
+ * Calculates the closest int value that is greater than or equal to the
+ * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03)
+ * returns the value 10.
+ *
+ * @method ceil
+ * @param {Number} n number to round up
+ * @return {Integer} rounded up number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * // map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * //Get the ceiling of the mapped number.
+ * let bx = ceil(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals
+ *
+ */
+ _main.default.prototype.ceil = Math.ceil;
+
+ /**
+ * Constrains a value between a minimum and maximum value.
+ *
+ * @method constrain
+ * @param {Number} n number to constrain
+ * @param {Number} low minimum limit
+ * @param {Number} high maximum limit
+ * @return {Number} constrained number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ *
+ * let leftWall = 25;
+ * let rightWall = 75;
+ *
+ * // xm is just the mouseX, while
+ * // xc is the mouseX, but constrained
+ * // between the leftWall and rightWall!
+ * let xm = mouseX;
+ * let xc = constrain(mouseX, leftWall, rightWall);
+ *
+ * // Draw the walls.
+ * stroke(150);
+ * line(leftWall, 0, leftWall, height);
+ * line(rightWall, 0, rightWall, height);
+ *
+ * // Draw xm and xc as circles.
+ * noStroke();
+ * fill(150);
+ * ellipse(xm, 33, 9, 9); // Not Constrained
+ * fill(0);
+ * ellipse(xc, 66, 9, 9); // Constrained
+ * }
+ *
+ *
+ * @alt
+ * 2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines
+ *
+ */
+ _main.default.prototype.constrain = function(n, low, high) {
+ _main.default._validateParameters('constrain', arguments);
+ return Math.max(Math.min(n, high), low);
+ };
+
+ /**
+ * Calculates the distance between two points, in either two or three dimensions.
+ *
+ * @method dist
+ * @param {Number} x1 x-coordinate of the first point
+ * @param {Number} y1 y-coordinate of the first point
+ * @param {Number} x2 x-coordinate of the second point
+ * @param {Number} y2 y-coordinate of the second point
+ * @return {Number} distance between the two points
+ *
+ * @example
+ *
+ * // Move your mouse inside the canvas to see the
+ * // change in distance between two points!
+ * function draw() {
+ * background(200);
+ * fill(0);
+ *
+ * let x1 = 10;
+ * let y1 = 90;
+ * let x2 = mouseX;
+ * let y2 = mouseY;
+ *
+ * line(x1, y1, x2, y2);
+ * ellipse(x1, y1, 7, 7);
+ * ellipse(x2, y2, 7, 7);
+ *
+ * // d is the length of the line
+ * // the distance from point 1 to point 2.
+ * let d = int(dist(x1, y1, x2, y2));
+ *
+ * // Let's write d along the line we are drawing!
+ * push();
+ * translate((x1 + x2) / 2, (y1 + y2) / 2);
+ * rotate(atan2(y2 - y1, x2 - x1));
+ * text(nfc(d, 1), 0, -5);
+ * pop();
+ * // Fancy!
+ * }
+ *
+ *
+ * @alt
+ * 2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed.
+ */
+ /**
+ * @method dist
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate of the first point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate of the second point
+ * @return {Number} distance between the two points
+ */
+ _main.default.prototype.dist = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('dist', args);
+ if (args.length === 4) {
+ //2D
+ return hypot(args[2] - args[0], args[3] - args[1]);
+ } else if (args.length === 6) {
+ //3D
+ return hypot(args[3] - args[0], args[4] - args[1], args[5] - args[2]);
+ }
+ };
+
+ /**
+ * Returns Euler's number e (2.71828...) raised to the power of the n
+ * parameter. Maps to Math.exp().
+ *
+ * @method exp
+ * @param {Number} n exponent to raise
+ * @return {Number} e^n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Compute the exp() function with a value between 0 and 2
+ * let xValue = map(mouseX, 0, width, 0, 2);
+ * let yValue = exp(xValue);
+ *
+ * let y = map(yValue, 0, 8, height, 0);
+ *
+ * let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ *
+ * // Draw the exp(x) curve,
+ * // over the domain of x from 0 to 2
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (let x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, 2);
+ * yValue = exp(xValue);
+ * y = map(yValue, 0, 8, height, 0);
+ * vertex(x, y);
+ * }
+ *
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height - 1, width, height - 1);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves along a curve with mouse x. e^n displayed.
+ *
+ */
+ _main.default.prototype.exp = Math.exp;
+
+ /**
+ * Calculates the closest int value that is less than or equal to the
+ * value of the parameter. Maps to Math.floor().
+ *
+ * @method floor
+ * @param {Number} n number to round down
+ * @return {Integer} rounded down number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * //Get the floor of the mapped number.
+ * let bx = floor(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals
+ *
+ */
+ _main.default.prototype.floor = Math.floor;
+
+ /**
+ * Calculates a number between two numbers at a specific increment. The amt
+ * parameter is the amount to interpolate between the two values where 0.0
+ * equal to the first point, 0.1 is very near the first point, 0.5 is
+ * half-way in between, and 1.0 is equal to the second point. If the
+ * value of amt is more than 1.0 or less than 0.0, the number will be
+ * calculated accordingly in the ratio of the two given numbers. The lerp
+ * function is convenient for creating motion along a straight
+ * path and for drawing dotted lines.
+ *
+ * @method lerp
+ * @param {Number} start first value
+ * @param {Number} stop second value
+ * @param {Number} amt number
+ * @return {Number} lerped value
+ * @example
+ *
+ * function setup() {
+ * background(200);
+ * let a = 20;
+ * let b = 80;
+ * let c = lerp(a, b, 0.2);
+ * let d = lerp(a, b, 0.5);
+ * let e = lerp(a, b, 0.8);
+ *
+ * let y = 50;
+ *
+ * strokeWeight(5);
+ * stroke(0); // Draw the original points in black
+ * point(a, y);
+ * point(b, y);
+ *
+ * stroke(100); // Draw the lerp points in gray
+ * point(c, y);
+ * point(d, y);
+ * point(e, y);
+ * }
+ *
+ *
+ * @alt
+ * 5 points horizontally staggered mid-canvas. mid 3 are grey, outer black
+ *
+ */
+ _main.default.prototype.lerp = function(start, stop, amt) {
+ _main.default._validateParameters('lerp', arguments);
+ return amt * (stop - start) + start;
+ };
+
+ /**
+ * Calculates the natural logarithm (the base-e logarithm) of a number. This
+ * function expects the n parameter to be a value greater than 0.0. Maps to
+ * Math.log().
+ *
+ * @method log
+ * @param {Number} n number greater than 0
+ * @return {Number} natural logarithm of n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * let maxX = 2.8;
+ * let maxY = 1.5;
+ *
+ * // Compute the natural log of a value between 0 and maxX
+ * let xValue = map(mouseX, 0, width, 0, maxX);
+ * let yValue, y;
+ * if (xValue > 0) {
+ // Cannot take the log of a negative number.
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ *
+ * // Display the calculation occurring.
+ * let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ * }
+ *
+ * // Draw the log(x) curve,
+ * // over the domain of x from 0 to maxX
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (let x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, maxX);
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ * vertex(x, y);
+ * }
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height / 2, width, height / 2);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves along a curve with mouse x. natural logarithm of n displayed.
+ *
+ */
+ _main.default.prototype.log = Math.log;
+
+ /**
+ * Calculates the magnitude (or length) of a vector. A vector is a direction
+ * in space commonly used in computer graphics and linear algebra. Because it
+ * has no "start" position, the magnitude of a vector can be thought of as
+ * the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is
+ * a shortcut for writing dist(0, 0, x, y).
+ *
+ * @method mag
+ * @param {Number} a first value
+ * @param {Number} b second value
+ * @return {Number} magnitude of vector from (0,0) to (a,b)
+ * @example
+ *
+ * function setup() {
+ * let x1 = 20;
+ * let x2 = 80;
+ * let y1 = 30;
+ * let y2 = 70;
+ *
+ * line(0, 0, x1, y1);
+ * print(mag(x1, y1)); // Prints "36.05551275463989"
+ * line(0, 0, x2, y1);
+ * print(mag(x2, y1)); // Prints "85.44003745317531"
+ * line(0, 0, x1, y2);
+ * print(mag(x1, y2)); // Prints "72.80109889280519"
+ * line(0, 0, x2, y2);
+ * print(mag(x2, y2)); // Prints "106.3014581273465"
+ * }
+ *
+ *
+ * @alt
+ * 4 lines of different length radiate from top left of canvas.
+ *
+ */
+ _main.default.prototype.mag = function(x, y) {
+ _main.default._validateParameters('mag', arguments);
+ return hypot(x, y);
+ };
+
+ /**
+ * Re-maps a number from one range to another.
+ *
+ * In the first example above, the number 25 is converted from a value in the
+ * range of 0 to 100 into a value that ranges from the left edge of the
+ * window (0) to the right edge (width).
+ *
+ * @method map
+ * @param {Number} value the incoming value to be converted
+ * @param {Number} start1 lower bound of the value's current range
+ * @param {Number} stop1 upper bound of the value's current range
+ * @param {Number} start2 lower bound of the value's target range
+ * @param {Number} stop2 upper bound of the value's target range
+ * @param {Boolean} [withinBounds] constrain the value to the newly mapped range
+ * @return {Number} remapped number
+ * @example
+ *
+ * let value = 25;
+ * let m = map(value, 0, 100, 0, width);
+ * ellipse(m, 50, 10, 10);
+
+ *
+ *
+ * function setup() {
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * let x1 = map(mouseX, 0, width, 25, 75);
+ * ellipse(x1, 25, 25, 25);
+ * //This ellipse is constrained to the 0-100 range
+ * //after setting withinBounds to true
+ * let x2 = map(mouseX, 0, width, 0, 100, true);
+ * ellipse(x2, 75, 25, 25);
+ * }
+
+ *
+ * @alt
+ * 10 by 10 white ellipse with in mid left canvas
+ * 2 25 by 25 white ellipses move with mouse x. Bottom has more range from X
+ *
+ */
+ _main.default.prototype.map = function(
+ n,
+ start1,
+ stop1,
+ start2,
+ stop2,
+ withinBounds
+ ) {
+ _main.default._validateParameters('map', arguments);
+ var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2;
+ if (!withinBounds) {
+ return newval;
+ }
+ if (start2 < stop2) {
+ return this.constrain(newval, start2, stop2);
+ } else {
+ return this.constrain(newval, stop2, start2);
+ }
+ };
+
+ /**
+ * Determines the largest value in a sequence of numbers, and then returns
+ * that value. max() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method max
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} maximum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how max() works!
+ * let numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * let spacing = 15;
+ * let elemsY = 25;
+ * for (let i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * let maxX = 33;
+ * let maxY = 80;
+ * // Draw the Maximum value in the array.
+ * textSize(32);
+ * text(max(numArray), maxX, maxY);
+ * }
+ *
+ *
+ * @alt
+ * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9
+ *
+ */
+ /**
+ * @method max
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+ _main.default.prototype.max = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('max', args);
+ if (args[0] instanceof Array) {
+ return Math.max.apply(null, args[0]);
+ } else {
+ return Math.max.apply(null, args);
+ }
+ };
+
+ /**
+ * Determines the smallest value in a sequence of numbers, and then returns
+ * that value. min() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method min
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} minimum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how min() works!
+ * let numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * let spacing = 15;
+ * let elemsY = 25;
+ * for (let i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * let maxX = 33;
+ * let maxY = 80;
+ * // Draw the Minimum value in the array.
+ * textSize(32);
+ * text(min(numArray), maxX, maxY);
+ * }
+ *
+ *
+ * @alt
+ * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1
+ *
+ */
+ /**
+ * @method min
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+ _main.default.prototype.min = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('min', args);
+ if (args[0] instanceof Array) {
+ return Math.min.apply(null, args[0]);
+ } else {
+ return Math.min.apply(null, args);
+ }
+ };
+
+ /**
+ * Normalizes a number from another range into a value between 0 and 1.
+ * Identical to map(value, low, high, 0, 1).
+ * Numbers outside of the range are not clamped to 0 and 1, because
+ * out-of-range values are often intentional and useful. (See the example above.)
+ *
+ * @method norm
+ * @param {Number} value incoming value to be normalized
+ * @param {Number} start lower bound of the value's current range
+ * @param {Number} stop upper bound of the value's current range
+ * @return {Number} normalized number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * let currentNum = mouseX;
+ * let lowerBound = 0;
+ * let upperBound = width; //100;
+ * let normalized = norm(currentNum, lowerBound, upperBound);
+ * let lineY = 70;
+ * stroke(3);
+ * line(0, lineY, width, lineY);
+ * //Draw an ellipse mapped to the non-normalized value.
+ * noStroke();
+ * fill(50);
+ * let s = 7; // ellipse size
+ * ellipse(currentNum, lineY, s, s);
+ *
+ * // Draw the guide
+ * let guideY = lineY + 15;
+ * text('0', 0, guideY);
+ * textAlign(RIGHT);
+ * text('100', width, guideY);
+ *
+ * // Draw the normalized value
+ * textAlign(LEFT);
+ * fill(0);
+ * textSize(32);
+ * let normalY = 40;
+ * let normalX = 20;
+ * text(normalized, normalX, normalY);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves with mouse. 0 shown left & 100 right and updating values center
+ *
+ */
+ _main.default.prototype.norm = function(n, start, stop) {
+ _main.default._validateParameters('norm', arguments);
+ return this.map(n, start, stop, 0, 1);
+ };
+
+ /**
+ * Facilitates exponential expressions. The pow() function is an efficient
+ * way of multiplying numbers by themselves (or their reciprocals) in large
+ * quantities. For example, pow(3, 5) is equivalent to the expression
+ * 3 × 3 × 3 × 3 × 3 and pow(3, -5) is equivalent to 1 /
+ * 3 × 3 × 3 × 3 × 3. Maps to
+ * Math.pow().
+ *
+ * @method pow
+ * @param {Number} n base of the exponential expression
+ * @param {Number} e power by which to raise the base
+ * @return {Number} n^e
+ * @example
+ *
+ * function setup() {
+ * //Exponentially increase the size of an ellipse.
+ * let eSize = 3; // Original Size
+ * let eLoc = 10; // Original Location
+ *
+ * ellipse(eLoc, eLoc, eSize, eSize);
+ *
+ * ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));
+ *
+ * ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));
+ *
+ * ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
+ * }
+ *
+ *
+ * @alt
+ * small to large ellipses radiating from top left of canvas
+ *
+ */
+ _main.default.prototype.pow = Math.pow;
+
+ /**
+ * Calculates the integer closest to the n parameter. For example,
+ * round(133.8) returns the value 134. Maps to Math.round().
+ *
+ * @method round
+ * @param {Number} n number to round
+ * @return {Integer} rounded number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * // Round the mapped number.
+ * let bx = round(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * horizontal center line squared values displayed on top and regular on bottom.
+ *
+ */
+ _main.default.prototype.round = Math.round;
+
+ /**
+ * Squares a number (multiplies a number by itself). The result is always a
+ * positive number, as multiplying two negative numbers always yields a
+ * positive result. For example, -1 * -1 = 1.
+ *
+ * @method sq
+ * @param {Number} n number to square
+ * @return {Number} squared number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * let eSize = 7;
+ * let x1 = map(mouseX, 0, width, 0, 10);
+ * let y1 = 80;
+ * let x2 = sq(x1);
+ * let y2 = 20;
+ *
+ * // Draw the non-squared.
+ * line(0, y1, width, y1);
+ * ellipse(x1, y1, eSize, eSize);
+ *
+ * // Draw the squared.
+ * line(0, y2, width, y2);
+ * ellipse(x2, y2, eSize, eSize);
+ *
+ * // Draw dividing line.
+ * stroke(100);
+ * line(0, height / 2, width, height / 2);
+ *
+ * // Draw text.
+ * let spacing = 15;
+ * noStroke();
+ * fill(0);
+ * text('x = ' + x1, 0, y1 + spacing);
+ * text('sq(x) = ' + x2, 0, y2 + spacing);
+ * }
+ *
+ *
+ * @alt
+ * horizontal center line squared values displayed on top and regular on bottom.
+ *
+ */
+ _main.default.prototype.sq = function(n) {
+ return n * n;
+ };
+
+ /**
+ * Calculates the square root of a number. The square root of a number is
+ * always positive, even though there may be a valid negative root. The
+ * square root s of number a is such that s*s = a. It is the opposite of
+ * squaring. Maps to Math.sqrt().
+ *
+ * @method sqrt
+ * @param {Number} n non-negative number to square root
+ * @return {Number} square root of number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * let eSize = 7;
+ * let x1 = mouseX;
+ * let y1 = 80;
+ * let x2 = sqrt(x1);
+ * let y2 = 20;
+ *
+ * // Draw the non-squared.
+ * line(0, y1, width, y1);
+ * ellipse(x1, y1, eSize, eSize);
+ *
+ * // Draw the squared.
+ * line(0, y2, width, y2);
+ * ellipse(x2, y2, eSize, eSize);
+ *
+ * // Draw dividing line.
+ * stroke(100);
+ * line(0, height / 2, width, height / 2);
+ *
+ * // Draw text.
+ * noStroke();
+ * fill(0);
+ * let spacing = 15;
+ * text('x = ' + x1, 0, y1 + spacing);
+ * text('sqrt(x) = ' + x2, 0, y2 + spacing);
+ * }
+ *
+ *
+ * @alt
+ * horizontal center line squareroot values displayed on top and regular on bottom.
+ *
+ */
+ _main.default.prototype.sqrt = Math.sqrt;
+
+ // Calculate the length of the hypotenuse of a right triangle
+ // This won't under- or overflow in intermediate steps
+ // https://en.wikipedia.org/wiki/Hypot
+ function hypot(x, y, z) {
+ // Use the native implementation if it's available
+ if (typeof Math.hypot === 'function') {
+ return Math.hypot.apply(null, arguments);
+ }
+
+ // Otherwise use the V8 implementation
+ // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217
+ var length = arguments.length;
+ var args = [];
+ var max = 0;
+ for (var i = 0; i < length; i++) {
+ var n = arguments[i];
+ n = +n;
+ if (n === Infinity || n === -Infinity) {
+ return Infinity;
+ }
+ n = Math.abs(n);
+ if (n > max) {
+ max = n;
+ }
+ args[i] = n;
+ }
+
+ if (max === 0) {
+ max = 1;
+ }
+ var sum = 0;
+ var compensation = 0;
+ for (var j = 0; j < length; j++) {
+ var m = args[j] / max;
+ var summand = m * m - compensation;
+ var preliminary = sum + summand;
+ compensation = preliminary - sum - summand;
+ sum = preliminary;
+ }
+ return Math.sqrt(sum) * max;
+ }
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 58: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Math
+ * @submodule Vector
+ * @for p5
+ * @requires core
+ */ /**
+ * Creates a new p5.Vector (the datatype for storing vectors). This provides a
+ * two or three dimensional vector, specifically a Euclidean (also known as
+ * geometric) vector. A vector is an entity that has both magnitude and
+ * direction.
+ *
+ * @method createVector
+ * @param {Number} [x] x component of the vector
+ * @param {Number} [y] y component of the vector
+ * @param {Number} [z] z component of the vector
+ * @return {p5.Vector}
+ * @example
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * fill(255, 102, 204);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));
+ * scale(0.75);
+ * sphere();
+ * }
+ *
+ *
+ * @alt
+ * a purple sphere lit by a point light oscillating horizontally
+ */ _main.default.prototype.createVector = function(x, y, z) {
+ if (this instanceof _main.default) {
+ return new _main.default.Vector(this, arguments);
+ } else {
+ return new _main.default.Vector(x, y, z);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 59: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } //////////////////////////////////////////////////////////////
+ // http://mrl.nyu.edu/~perlin/noise/
+ // Adapting from PApplet.java
+ // which was adapted from toxi
+ // which was adapted from the german demo group farbrausch
+ // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip
+ // someday we might consider using "improved noise"
+ // http://mrl.nyu.edu/~perlin/paper445.pdf
+ // See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/
+ // blob/master/introduction/Noise1D/noise.js
+ /**
+ * @module Math
+ * @submodule Noise
+ * @for p5
+ * @requires core
+ */ var PERLIN_YWRAPB = 4;
+ var PERLIN_YWRAP = 1 << PERLIN_YWRAPB;
+ var PERLIN_ZWRAPB = 8;
+ var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB;
+ var PERLIN_SIZE = 4095;
+ var perlin_octaves = 4; // default to medium smooth
+ var perlin_amp_falloff = 0.5; // 50% reduction/octave
+ var scaled_cosine = function scaled_cosine(i) {
+ return 0.5 * (1.0 - Math.cos(i * Math.PI));
+ };
+ var perlin; // will be initialized lazily by noise() or noiseSeed()
+ /**
+ * Returns the Perlin noise value at specified coordinates. Perlin noise is
+ * a random sequence generator producing a more natural ordered, harmonic
+ * succession of numbers compared to the standard random() function.
+ * It was invented by Ken Perlin in the 1980s and been used since in
+ * graphical applications to produce procedural textures, natural motion,
+ * shapes, terrains etc.
The main difference to the
+ * random() function is that Perlin noise is defined in an infinite
+ * n-dimensional space where each pair of coordinates corresponds to a
+ * fixed semi-random value (fixed only for the lifespan of the program; see
+ * the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,
+ * depending on the number of coordinates given. The resulting value will
+ * always be between 0.0 and 1.0. The noise value can be animated by moving
+ * through the noise space as demonstrated in the example above. The 2nd
+ * and 3rd dimension can also be interpreted as time.
The actual
+ * noise is structured similar to an audio signal, in respect to the
+ * function's use of frequencies. Similar to the concept of harmonics in
+ * physics, perlin noise is computed over several octaves which are added
+ * together for the final result.
Another way to adjust the
+ * character of the resulting sequence is the scale of the input
+ * coordinates. As the function works within an infinite space the value of
+ * the coordinates doesn't matter as such, only the distance between
+ * successive coordinates does (eg. when using noise() within a
+ * loop). As a general rule the smaller the difference between coordinates,
+ * the smoother the resulting noise sequence will be. Steps of 0.005-0.03
+ * work best for most applications, but this will differ depending on use.
+ *
+ *
+ * @method noise
+ * @param {Number} x x-coordinate in noise space
+ * @param {Number} [y] y-coordinate in noise space
+ * @param {Number} [z] z-coordinate in noise space
+ * @return {Number} Perlin noise value (between 0 and 1) at specified
+ * coordinates
+ * @example
+ *
+ *
+ * let xoff = 0.0;
+ *
+ * function draw() {
+ * background(204);
+ * xoff = xoff + 0.01;
+ * let n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * }
+ *
+ *
+ *
+ * let noiseScale=0.02;
+ *
+ * function draw() {
+ * background(0);
+ * for (let x=0; x < width; x++) {
+ * let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
+ * stroke(noiseVal*255);
+ * line(x, mouseY+noiseVal*80, x, height);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical line moves left to right with updating noise values.
+ * horizontal wave pattern effected by mouse x-position & updating noise values.
+ *
+ */ _main.default.prototype.noise = function(x) {
+ var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
+ if (perlin == null) {
+ perlin = new Array(PERLIN_SIZE + 1);
+ for (var i = 0; i < PERLIN_SIZE + 1; i++) {
+ perlin[i] = Math.random();
+ }
+ }
+
+ if (x < 0) {
+ x = -x;
+ }
+ if (y < 0) {
+ y = -y;
+ }
+ if (z < 0) {
+ z = -z;
+ }
+
+ var xi = Math.floor(x),
+ yi = Math.floor(y),
+ zi = Math.floor(z);
+ var xf = x - xi;
+ var yf = y - yi;
+ var zf = z - zi;
+ var rxf, ryf;
+
+ var r = 0;
+ var ampl = 0.5;
+
+ var n1, n2, n3;
+
+ for (var o = 0; o < perlin_octaves; o++) {
+ var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);
+
+ rxf = scaled_cosine(xf);
+ ryf = scaled_cosine(yf);
+
+ n1 = perlin[of & PERLIN_SIZE];
+ n1 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n1);
+ n2 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE];
+ n2 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);
+ n1 += ryf * (n2 - n1);
+
+ of += PERLIN_ZWRAP;
+ n2 = perlin[of & PERLIN_SIZE];
+ n2 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n2);
+ n3 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE];
+ n3 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);
+ n2 += ryf * (n3 - n2);
+
+ n1 += scaled_cosine(zf) * (n2 - n1);
+
+ r += n1 * ampl;
+ ampl *= perlin_amp_falloff;
+ xi <<= 1;
+ xf *= 2;
+ yi <<= 1;
+ yf *= 2;
+ zi <<= 1;
+ zf *= 2;
+
+ if (xf >= 1.0) {
+ xi++;
+ xf--;
+ }
+ if (yf >= 1.0) {
+ yi++;
+ yf--;
+ }
+ if (zf >= 1.0) {
+ zi++;
+ zf--;
+ }
+ }
+ return r;
+ };
+
+ /**
+ *
+ * Adjusts the character and level of detail produced by the Perlin noise
+ * function. Similar to harmonics in physics, noise is computed over
+ * several octaves. Lower octaves contribute more to the output signal and
+ * as such define the overall intensity of the noise, whereas higher octaves
+ * create finer grained details in the noise sequence.
+ *
+ * By default, noise is computed over 4 octaves with each octave contributing
+ * exactly half than its predecessor, starting at 50% strength for the 1st
+ * octave. This falloff amount can be changed by adding an additional function
+ * parameter. Eg. a falloff factor of 0.75 means each octave will now have
+ * 75% impact (25% less) of the previous lower octave. Any value between
+ * 0.0 and 1.0 is valid, however note that values greater than 0.5 might
+ * result in greater than 1.0 values returned by noise().
+ *
+ * By changing these parameters, the signal created by the noise()
+ * function can be adapted to fit very specific needs and characteristics.
+ *
+ * @method noiseDetail
+ * @param {Number} lod number of octaves to be used by the noise
+ * @param {Number} falloff falloff factor for each octave
+ * @example
+ *
+ *
+ * let noiseVal;
+ * let noiseScale = 0.02;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * for (let y = 0; y < height; y++) {
+ * for (let x = 0; x < width / 2; x++) {
+ * noiseDetail(2, 0.2);
+ * noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
+ * stroke(noiseVal * 255);
+ * point(x, y);
+ * noiseDetail(8, 0.65);
+ * noiseVal = noise(
+ * (mouseX + x + width / 2) * noiseScale,
+ * (mouseY + y) * noiseScale
+ * );
+ * stroke(noiseVal * 255);
+ * point(x + width / 2, y);
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 vertical grey smokey patterns affected my mouse x-position and noise.
+ *
+ */
+ _main.default.prototype.noiseDetail = function(lod, falloff) {
+ if (lod > 0) {
+ perlin_octaves = lod;
+ }
+ if (falloff > 0) {
+ perlin_amp_falloff = falloff;
+ }
+ };
+
+ /**
+ * Sets the seed value for noise(). By default, noise()
+ * produces different results each time the program is run. Set the
+ * value parameter to a constant to return the same pseudo-random
+ * numbers each time the software is run.
+ *
+ * @method noiseSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ * let xoff = 0.0;
+ *
+ * function setup() {
+ * noiseSeed(99);
+ * stroke(0, 10);
+ * }
+ *
+ * function draw() {
+ * xoff = xoff + .01;
+ * let n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical grey lines drawing in pattern affected by noise.
+ *
+ */
+ _main.default.prototype.noiseSeed = function(seed) {
+ // Linear Congruential Generator
+ // Variant of a Lehman Generator
+ var lcg = (function() {
+ // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
+ // m is basically chosen to be large (as it is the max period)
+ // and for its relationships to a and c
+ var m = 4294967296;
+ // a - 1 should be divisible by m's prime factors
+ var a = 1664525;
+ // c and m should be co-prime
+ var c = 1013904223;
+ var seed, z;
+ return {
+ setSeed: function setSeed(val) {
+ // pick a random seed if val is undefined or null
+ // the >>> 0 casts the seed to an unsigned 32-bit integer
+ z = seed = (val == null ? Math.random() * m : val) >>> 0;
+ },
+ getSeed: function getSeed() {
+ return seed;
+ },
+ rand: function rand() {
+ // define the recurrence relationship
+ z = (a * z + c) % m;
+ // return a float in [0, 1)
+ // if z = m then z / m = 0 therefore (z % m) / m < 1 always
+ return z / m;
+ }
+ };
+ })();
+
+ lcg.setSeed(seed);
+ perlin = new Array(PERLIN_SIZE + 1);
+ for (var i = 0; i < PERLIN_SIZE + 1; i++) {
+ perlin[i] = lcg.rand();
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 60: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Math
+ * @submodule Vector
+ * @requires constants
+ */ /**
+ * A class to describe a two or three dimensional vector, specifically
+ * a Euclidean (also known as geometric) vector. A vector is an entity
+ * that has both magnitude and direction. The datatype, however, stores
+ * the components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude
+ * and direction can be accessed via the methods mag() and heading().
+ *
+ * In many of the p5.js examples, you will see p5.Vector used to describe a
+ * position, velocity, or acceleration. For example, if you consider a rectangle
+ * moving across the screen, at any given instant it has a position (a vector
+ * that points from the origin to its location), a velocity (the rate at which
+ * the object's position changes per time unit, expressed as a vector), and
+ * acceleration (the rate at which the object's velocity changes per time
+ * unit, expressed as a vector).
+ *
+ * Since vectors represent groupings of values, we cannot simply use
+ * traditional addition/multiplication/etc. Instead, we'll need to do some
+ * "vector" math, which is made easy by the methods inside the p5.Vector class.
+ *
+ * @class p5.Vector
+ * @param {Number} [x] x component of the vector
+ * @param {Number} [y] y component of the vector
+ * @param {Number} [z] z component of the vector
+ * @example
+ *
+ *
+ * let v1 = createVector(40, 50);
+ * let v2 = createVector(40, 50);
+ *
+ * ellipse(v1.x, v1.y, 50, 50);
+ * ellipse(v2.x, v2.y, 50, 50);
+ * v1.add(v2);
+ * ellipse(v1.x, v1.y, 50, 50);
+ *
+ *
+ *
+ * @alt
+ * 2 white ellipses. One center-left the other bottom right and off canvas
+ *
+ */ _main.default.Vector = function Vector() {
+ var x, y, z;
+ // This is how it comes in with createVector()
+ if (arguments[0] instanceof _main.default) {
+ // save reference to p5 if passed in
+ this.p5 = arguments[0];
+ x = arguments[1][0] || 0;
+ y = arguments[1][1] || 0;
+ z = arguments[1][2] || 0;
+ // This is what we'll get with new p5.Vector()
+ } else {
+ x = arguments[0] || 0;
+ y = arguments[1] || 0;
+ z = arguments[2] || 0;
+ }
+ /**
+ * The x component of the vector
+ * @property x {Number}
+ */
+ this.x = x;
+ /**
+ * The y component of the vector
+ * @property y {Number}
+ */
+ this.y = y;
+ /**
+ * The z component of the vector
+ * @property z {Number}
+ */
+ this.z = z;
+ };
+
+ /**
+ * Returns a string representation of a vector v by calling String(v)
+ * or v.toString(). This method is useful for logging vectors in the
+ * console.
+ * @method toString
+ * @return {String}
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(20, 30);
+ * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text(v1.toString(), 10, 25, 90, 75);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.toString = function p5VectorToString() {
+ return 'p5.Vector Object : ['
+ .concat(this.x, ', ')
+ .concat(this.y, ', ')
+ .concat(this.z, ']');
+ };
+
+ /**
+ * Sets the x, y, and z component of the vector using two or three separate
+ * variables, the data from a p5.Vector, or the values from a float array.
+ * @method set
+ * @param {Number} [x] the x component of the vector
+ * @param {Number} [y] the y component of the vector
+ * @param {Number} [z] the z component of the vector
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(1, 2, 3);
+ * v.set(4, 5, 6); // Sets vector to [4, 5, 6]
+ *
+ * let v1 = createVector(0, 0, 0);
+ * let arr = [1, 2, 3];
+ * v1.set(arr); // Sets vector to [1, 2, 3]
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let v0, v1;
+ * function setup() {
+ * createCanvas(100, 100);
+ *
+ * v0 = createVector(0, 0);
+ * v1 = createVector(50, 50);
+ * }
+ *
+ * function draw() {
+ * background(240);
+ *
+ * drawArrow(v0, v1, 'black');
+ * v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));
+ *
+ * noStroke();
+ * text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ /**
+ * @method set
+ * @param {p5.Vector|Number[]} value the vector to set
+ * @chainable
+ */
+ _main.default.Vector.prototype.set = function set(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ this.x = x.x || 0;
+ this.y = x.y || 0;
+ this.z = x.z || 0;
+ return this;
+ }
+ if (x instanceof Array) {
+ this.x = x[0] || 0;
+ this.y = x[1] || 0;
+ this.z = x[2] || 0;
+ return this;
+ }
+ this.x = x || 0;
+ this.y = y || 0;
+ this.z = z || 0;
+ return this;
+ };
+
+ /**
+ * Gets a copy of the vector, returns a p5.Vector object.
+ *
+ * @method copy
+ * @return {p5.Vector} the copy of the p5.Vector object
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = v1.copy();
+ * print(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);
+ * // Prints "true"
+ *
+ *
+ */
+ _main.default.Vector.prototype.copy = function copy() {
+ if (this.p5) {
+ return new _main.default.Vector(this.p5, [this.x, this.y, this.z]);
+ } else {
+ return new _main.default.Vector(this.x, this.y, this.z);
+ }
+ };
+
+ /**
+ * Adds x, y, and z components to a vector, adds one vector to another, or
+ * adds two independent vectors together. The version of the method that adds
+ * two vectors together is a static method and returns a p5.Vector, the others
+ * acts directly on the vector. See the examples for more context.
+ *
+ * @method add
+ * @param {Number} x the x component of the vector to be added
+ * @param {Number} [y] the y component of the vector to be added
+ * @param {Number} [z] the z component of the vector to be added
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * v.add(4, 5, 6);
+ * // v's components are set to [5, 7, 9]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(2, 3, 4);
+ *
+ * let v3 = p5.Vector.add(v1, v2);
+ * // v3 has components [3, 5, 7]
+ * print(v3);
+ *
+ *
+ *
+ *
+ *
+ * // red vector + blue vector = purple vector
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(-30, 20);
+ * drawArrow(v1, v2, 'blue');
+ *
+ * let v3 = p5.Vector.add(v1, v2);
+ * drawArrow(v0, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ /**
+ * @method add
+ * @param {p5.Vector|Number[]} value the vector to add
+ * @chainable
+ */
+ _main.default.Vector.prototype.add = function add(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ this.x += x.x || 0;
+ this.y += x.y || 0;
+ this.z += x.z || 0;
+ return this;
+ }
+ if (x instanceof Array) {
+ this.x += x[0] || 0;
+ this.y += x[1] || 0;
+ this.z += x[2] || 0;
+ return this;
+ }
+ this.x += x || 0;
+ this.y += y || 0;
+ this.z += z || 0;
+ return this;
+ };
+
+ /**
+ * Subtracts x, y, and z components from a vector, subtracts one vector from
+ * another, or subtracts two independent vectors. The version of the method
+ * that subtracts two vectors is a static method and returns a p5.Vector, the
+ * other acts directly on the vector. See the examples for more context.
+ *
+ * @method sub
+ * @param {Number} x the x component of the vector to subtract
+ * @param {Number} [y] the y component of the vector to subtract
+ * @param {Number} [z] the z component of the vector to subtract
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(4, 5, 6);
+ * v.sub(1, 1, 1);
+ * // v's components are set to [3, 4, 5]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * let v1 = createVector(2, 3, 4);
+ * let v2 = createVector(1, 2, 3);
+ *
+ * let v3 = p5.Vector.sub(v1, v2);
+ * // v3 has components [1, 1, 1]
+ * print(v3);
+ *
+ *
+ *
+ *
+ *
+ * // red vector - blue vector = purple vector
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(70, 50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * let v3 = p5.Vector.sub(v1, v2);
+ * drawArrow(v2, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ /**
+ * @method sub
+ * @param {p5.Vector|Number[]} value the vector to subtract
+ * @chainable
+ */
+ _main.default.Vector.prototype.sub = function sub(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ this.x -= x.x || 0;
+ this.y -= x.y || 0;
+ this.z -= x.z || 0;
+ return this;
+ }
+ if (x instanceof Array) {
+ this.x -= x[0] || 0;
+ this.y -= x[1] || 0;
+ this.z -= x[2] || 0;
+ return this;
+ }
+ this.x -= x || 0;
+ this.y -= y || 0;
+ this.z -= z || 0;
+ return this;
+ };
+
+ /**
+ * Multiply the vector by a scalar. The static version of this method
+ * creates a new p5.Vector while the non static version acts on the vector
+ * directly. See the examples for more context.
+ *
+ * @method mult
+ * @param {Number} n the number to multiply with the vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * v.mult(2);
+ * // v's components are set to [2, 4, 6]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = p5.Vector.mult(v1, 2);
+ * // v2 has components [2, 4, 6]
+ * print(v2);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(25, -25);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let num = map(mouseX, 0, width, -2, 2, true);
+ * let v2 = p5.Vector.mult(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('multiplied by ' + num.toFixed(2), 5, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.mult = function mult(n) {
+ if (!(typeof n === 'number' && isFinite(n))) {
+ console.warn(
+ 'p5.Vector.prototype.mult:',
+ 'n is undefined or not a finite number'
+ );
+
+ return this;
+ }
+ this.x *= n;
+ this.y *= n;
+ this.z *= n;
+ return this;
+ };
+
+ /**
+ * Divide the vector by a scalar. The static version of this method creates a
+ * new p5.Vector while the non static version acts on the vector directly.
+ * See the examples for more context.
+ *
+ * @method div
+ * @param {number} n the number to divide the vector by
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(6, 4, 2);
+ * v.div(2); //v's components are set to [3, 2, 1]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * let v1 = createVector(6, 4, 2);
+ * let v2 = p5.Vector.div(v1, 2);
+ * // v2 has components [3, 2, 1]
+ * print(v2);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 100);
+ * let v1 = createVector(50, -50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let num = map(mouseX, 0, width, 10, 0.5, true);
+ * let v2 = p5.Vector.div(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('divided by ' + num.toFixed(2), 10, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.div = function div(n) {
+ if (!(typeof n === 'number' && isFinite(n))) {
+ console.warn(
+ 'p5.Vector.prototype.div:',
+ 'n is undefined or not a finite number'
+ );
+
+ return this;
+ }
+ if (n === 0) {
+ console.warn('p5.Vector.prototype.div:', 'divide by 0');
+ return this;
+ }
+ this.x /= n;
+ this.y /= n;
+ this.z /= n;
+ return this;
+ };
+
+ /**
+ * Calculates the magnitude (length) of the vector and returns the result as
+ * a float (this is simply the equation sqrt(x*x + y*y + z*z).)
+ *
+ * @method mag
+ * @return {Number} magnitude of the vector
+ * @example
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ *
+ *
+ * let v = createVector(20.0, 30.0, 40.0);
+ * let m = v.mag();
+ * print(m); // Prints "53.85164807134504"
+ *
+ *
+ */
+ _main.default.Vector.prototype.mag = function mag() {
+ return Math.sqrt(this.magSq());
+ };
+
+ /**
+ * Calculates the squared magnitude of the vector and returns the result
+ * as a float (this is simply the equation (x*x + y*y + z*z).)
+ * Faster if the real length is not required in the
+ * case of comparing vectors, etc.
+ *
+ * @method magSq
+ * @return {number} squared magnitude of the vector
+ * @example
+ *
+ *
+ * // Static method
+ * let v1 = createVector(6, 4, 2);
+ * print(v1.magSq()); // Prints "56"
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.magSq = function magSq() {
+ var x = this.x;
+ var y = this.y;
+ var z = this.z;
+ return x * x + y * y + z * z;
+ };
+
+ /**
+ * Calculates the dot product of two vectors. The version of the method
+ * that computes the dot product of two independent vectors is a static
+ * method. See the examples for more context.
+ *
+ *
+ * @method dot
+ * @param {Number} x x component of the vector
+ * @param {Number} [y] y component of the vector
+ * @param {Number} [z] z component of the vector
+ * @return {Number} the dot product
+ *
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(2, 3, 4);
+ *
+ * print(v1.dot(v2)); // Prints "20"
+ *
+ *
+ *
+ *
+ *
+ * //Static method
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(3, 2, 1);
+ * print(p5.Vector.dot(v1, v2)); // Prints "10"
+ *
+ *
+ */
+ /**
+ * @method dot
+ * @param {p5.Vector} value value component of the vector or a p5.Vector
+ * @return {Number}
+ */
+ _main.default.Vector.prototype.dot = function dot(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ return this.dot(x.x, x.y, x.z);
+ }
+ return this.x * (x || 0) + this.y * (y || 0) + this.z * (z || 0);
+ };
+
+ /**
+ * Calculates and returns a vector composed of the cross product between
+ * two vectors. Both the static and non static methods return a new p5.Vector.
+ * See the examples for more context.
+ *
+ * @method cross
+ * @param {p5.Vector} v p5.Vector to be crossed
+ * @return {p5.Vector} p5.Vector composed of cross product
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(1, 2, 3);
+ *
+ * v1.cross(v2); // v's components are [0, 0, 0]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let crossProduct = p5.Vector.cross(v1, v2);
+ * // crossProduct has components [0, 0, 1]
+ * print(crossProduct);
+ *
+ *
+ */
+ _main.default.Vector.prototype.cross = function cross(v) {
+ var x = this.y * v.z - this.z * v.y;
+ var y = this.z * v.x - this.x * v.z;
+ var z = this.x * v.y - this.y * v.x;
+ if (this.p5) {
+ return new _main.default.Vector(this.p5, [x, y, z]);
+ } else {
+ return new _main.default.Vector(x, y, z);
+ }
+ };
+
+ /**
+ * Calculates the Euclidean distance between two points (considering a
+ * point as a vector object).
+ *
+ * @method dist
+ * @param {p5.Vector} v the x, y, and z coordinates of a p5.Vector
+ * @return {Number} the distance
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let distance = v1.dist(v2); // distance is 1.4142...
+ * print(distance);
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let distance = p5.Vector.dist(v1, v2);
+ * // distance is 1.4142...
+ * print(distance);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ *
+ * let v1 = createVector(70, 50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.dist = function dist(v) {
+ return v
+ .copy()
+ .sub(this)
+ .mag();
+ };
+
+ /**
+ * Normalize the vector to length 1 (make it a unit vector).
+ *
+ * @method normalize
+ * @return {p5.Vector} normalized p5.Vector
+ * @example
+ *
+ *
+ * let v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.normalize();
+ * // v's components are set to
+ * // [0.4454354, 0.8908708, 0.089087084]
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(mouseX - 50, mouseY - 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ * v1.normalize();
+ * drawArrow(v0, v1.mult(35), 'blue');
+ *
+ * noFill();
+ * ellipse(50, 50, 35 * 2);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.normalize = function normalize() {
+ var len = this.mag();
+ // here we multiply by the reciprocal instead of calling 'div()'
+ // since div duplicates this zero check.
+ if (len !== 0) this.mult(1 / len);
+ return this;
+ };
+
+ /**
+ * Limit the magnitude of this vector to the value used for the max
+ * parameter.
+ *
+ * @method limit
+ * @param {Number} max the maximum magnitude for the vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.limit(5);
+ * // v's components are set to
+ * // [2.2271771, 4.4543543, 0.4454354]
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(mouseX - 50, mouseY - 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ * drawArrow(v0, v1.limit(35), 'blue');
+ *
+ * noFill();
+ * ellipse(50, 50, 35 * 2);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.limit = function limit(max) {
+ var mSq = this.magSq();
+ if (mSq > max * max) {
+ this.div(Math.sqrt(mSq)) //normalize it
+ .mult(max);
+ }
+ return this;
+ };
+
+ /**
+ * Set the magnitude of this vector to the value used for the len
+ * parameter.
+ *
+ * @method setMag
+ * @param {number} len the new length for this vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.setMag(10);
+ * // v's components are set to [6.0, 8.0, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(50, 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ *
+ * let length = map(mouseX, 0, width, 0, 141, true);
+ * v1.setMag(length);
+ * drawArrow(v0, v1, 'blue');
+ *
+ * noStroke();
+ * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.setMag = function setMag(n) {
+ return this.normalize().mult(n);
+ };
+
+ /**
+ * Calculate the angle of rotation for this vector (only 2D vectors)
+ *
+ * @method heading
+ * @return {Number} the angle of rotation
+ * @example
+ *
+ *
+ * function setup() {
+ * let v1 = createVector(30, 50);
+ * print(v1.heading()); // 1.0303768265243125
+ *
+ * v1 = createVector(40, 50);
+ * print(v1.heading()); // 0.8960553845713439
+ *
+ * v1 = createVector(30, 70);
+ * print(v1.heading()); // 1.1659045405098132
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(mouseX - 50, mouseY - 50);
+ *
+ * drawArrow(v0, v1, 'black');
+ *
+ * let myHeading = v1.heading();
+ * noStroke();
+ * text(
+ * 'vector heading: ' +
+ * myHeading.toFixed(2) +
+ * ' radians or ' +
+ * degrees(myHeading).toFixed(2) +
+ * ' degrees',
+ * 10,
+ * 50,
+ * 90,
+ * 50
+ * );
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.heading = function heading() {
+ var h = Math.atan2(this.y, this.x);
+ if (this.p5) return this.p5._fromRadians(h);
+ return h;
+ };
+
+ /**
+ * Rotate the vector by an angle (only 2D vectors), magnitude remains the
+ * same
+ *
+ * @method rotate
+ * @param {number} angle the angle of rotation
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10.0, 20.0);
+ * // v has components [10.0, 20.0, 0.0]
+ * v.rotate(HALF_PI);
+ * // v's components are set to [-20.0, 9.999999, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * let angle = 0;
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(50, 0);
+ *
+ * drawArrow(v0, v1.rotate(angle), 'black');
+ * angle += 0.01;
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.rotate = function rotate(a) {
+ var newHeading = this.heading() + a;
+ if (this.p5) newHeading = this.p5._toRadians(newHeading);
+ var mag = this.mag();
+ this.x = Math.cos(newHeading) * mag;
+ this.y = Math.sin(newHeading) * mag;
+ return this;
+ };
+
+ /**
+ * Calculates and returns the angle (in radians) between two vectors.
+ * @method angleBetween
+ * @param {p5.Vector} value the x, y, and z components of a p5.Vector
+ * @return {Number} the angle between (in radians)
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let angle = v1.angleBetween(v2);
+ * // angle is PI/2
+ * print(angle);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ * let v0 = createVector(50, 50);
+ *
+ * let v1 = createVector(50, 0);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(mouseX - 50, mouseY - 50);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * let angleBetween = v1.angleBetween(v2);
+ * noStroke();
+ * text(
+ * 'angle between: ' +
+ * angleBetween.toFixed(2) +
+ * ' radians or ' +
+ * degrees(angleBetween).toFixed(2) +
+ * ' degrees',
+ * 10,
+ * 50,
+ * 90,
+ * 50
+ * );
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+
+ _main.default.Vector.prototype.angleBetween = function angleBetween(v) {
+ var dotmagmag = this.dot(v) / (this.mag() * v.mag());
+ // Mathematically speaking: the dotmagmag variable will be between -1 and 1
+ // inclusive. Practically though it could be slightly outside this range due
+ // to floating-point rounding issues. This can make Math.acos return NaN.
+ //
+ // Solution: we'll clamp the value to the -1,1 range
+ var angle;
+ angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag)));
+ angle = angle * Math.sign(this.cross(v).z || 1);
+ if (this.p5) {
+ angle = this.p5._fromRadians(angle);
+ }
+ return angle;
+ };
+ /**
+ * Linear interpolate the vector to another vector
+ *
+ * @method lerp
+ * @param {Number} x the x component
+ * @param {Number} y the y component
+ * @param {Number} z the z component
+ * @param {Number} amt the amount of interpolation; some value between 0.0
+ * (old vector) and 1.0 (new vector). 0.9 is very near
+ * the new vector. 0.5 is halfway in between.
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * let v = createVector(1, 1, 0);
+ *
+ * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]
+ *
+ *
+ *
+ *
+ *
+ * let v1 = createVector(0, 0, 0);
+ * let v2 = createVector(100, 100, 0);
+ *
+ * let v3 = p5.Vector.lerp(v1, v2, 0.5);
+ * // v3 has components [50,50,0]
+ * print(v3);
+ *
+ *
+ *
+ *
+ *
+ * let step = 0.01;
+ * let amount = 0;
+ *
+ * function draw() {
+ * background(240);
+ * let v0 = createVector(0, 0);
+ *
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(90, 90);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * if (amount > 1 || amount < 0) {
+ * step *= -1;
+ * }
+ * amount += step;
+ * let v3 = p5.Vector.lerp(v1, v2, amount);
+ *
+ * drawArrow(v0, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ /**
+ * @method lerp
+ * @param {p5.Vector} v the p5.Vector to lerp to
+ * @param {Number} amt
+ * @chainable
+ */
+ _main.default.Vector.prototype.lerp = function lerp(x, y, z, amt) {
+ if (x instanceof _main.default.Vector) {
+ return this.lerp(x.x, x.y, x.z, y);
+ }
+ this.x += (x - this.x) * amt || 0;
+ this.y += (y - this.y) * amt || 0;
+ this.z += (z - this.z) * amt || 0;
+ return this;
+ };
+
+ /**
+ * Return a representation of this vector as a float array. This is only
+ * for temporary use. If used in any other fashion, the contents should be
+ * copied by using the p5.Vector.copy() method to copy into your own
+ * array.
+ *
+ * @method array
+ * @return {Number[]} an Array with the 3 values
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(20, 30);
+ * print(v.array()); // Prints : Array [20, 30, 0]
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(10.0, 20.0, 30.0);
+ * let f = v.array();
+ * print(f[0]); // Prints "10.0"
+ * print(f[1]); // Prints "20.0"
+ * print(f[2]); // Prints "30.0"
+ *
+ *
+ */
+ _main.default.Vector.prototype.array = function array() {
+ return [this.x || 0, this.y || 0, this.z || 0];
+ };
+
+ /**
+ * Equality check against a p5.Vector
+ *
+ * @method equals
+ * @param {Number} [x] the x component of the vector
+ * @param {Number} [y] the y component of the vector
+ * @param {Number} [z] the z component of the vector
+ * @return {Boolean} whether the vectors are equals
+ * @example
+ *
+ *
+ * let v1 = createVector(5, 10, 20);
+ * let v2 = createVector(5, 10, 20);
+ * let v3 = createVector(13, 10, 19);
+ *
+ * print(v1.equals(v2.x, v2.y, v2.z)); // true
+ * print(v1.equals(v3.x, v3.y, v3.z)); // false
+ *
+ *
+ *
+ *
+ *
+ * let v1 = createVector(10.0, 20.0, 30.0);
+ * let v2 = createVector(10.0, 20.0, 30.0);
+ * let v3 = createVector(0.0, 0.0, 0.0);
+ * print(v1.equals(v2)); // true
+ * print(v1.equals(v3)); // false
+ *
+ *
+ */
+ /**
+ * @method equals
+ * @param {p5.Vector|Array} value the vector to compare
+ * @return {Boolean}
+ */
+ _main.default.Vector.prototype.equals = function equals(x, y, z) {
+ var a, b, c;
+ if (x instanceof _main.default.Vector) {
+ a = x.x || 0;
+ b = x.y || 0;
+ c = x.z || 0;
+ } else if (x instanceof Array) {
+ a = x[0] || 0;
+ b = x[1] || 0;
+ c = x[2] || 0;
+ } else {
+ a = x || 0;
+ b = y || 0;
+ c = z || 0;
+ }
+ return this.x === a && this.y === b && this.z === c;
+ };
+
+ // Static Methods
+
+ /**
+ * Make a new 2D vector from an angle
+ *
+ * @method fromAngle
+ * @static
+ * @param {Number} angle the desired angle, in radians (unaffected by angleMode)
+ * @param {Number} [length] the length of the new vector (defaults to 1)
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Create a variable, proportional to the mouseX,
+ * // varying from 0-360, to represent an angle in degrees.
+ * let myDegrees = map(mouseX, 0, width, 0, 360);
+ *
+ * // Display that variable in an onscreen text.
+ * // (Note the nfc() function to truncate additional decimal places,
+ * // and the "\xB0" character for the degree symbol.)
+ * let readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0';
+ * noStroke();
+ * fill(0);
+ * text(readout, 5, 15);
+ *
+ * // Create a p5.Vector using the fromAngle function,
+ * // and extract its x and y components.
+ * let v = p5.Vector.fromAngle(radians(myDegrees), 30);
+ * let vx = v.x;
+ * let vy = v.y;
+ *
+ * push();
+ * translate(width / 2, height / 2);
+ * noFill();
+ * stroke(150);
+ * line(0, 0, 30, 0);
+ * stroke(0);
+ * line(0, 0, vx, vy);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.fromAngle = function fromAngle(angle, length) {
+ if (typeof length === 'undefined') {
+ length = 1;
+ }
+ return new _main.default.Vector(
+ length * Math.cos(angle),
+ length * Math.sin(angle),
+ 0
+ );
+ };
+
+ /**
+ * Make a new 3D vector from a pair of ISO spherical angles
+ *
+ * @method fromAngles
+ * @static
+ * @param {Number} theta the polar angle, in radians (zero is up)
+ * @param {Number} phi the azimuthal angle, in radians
+ * (zero is out of the screen)
+ * @param {Number} [length] the length of the new vector (defaults to 1)
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * fill(255);
+ * noStroke();
+ * }
+ * function draw() {
+ * background(255);
+ *
+ * let t = millis() / 1000;
+ *
+ * // add three point lights
+ * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));
+ * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));
+ * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));
+ *
+ * sphere(35);
+ * }
+ *
+ *
+ */
+ _main.default.Vector.fromAngles = function(theta, phi, length) {
+ if (typeof length === 'undefined') {
+ length = 1;
+ }
+ var cosPhi = Math.cos(phi);
+ var sinPhi = Math.sin(phi);
+ var cosTheta = Math.cos(theta);
+ var sinTheta = Math.sin(theta);
+
+ return new _main.default.Vector(
+ length * sinTheta * sinPhi,
+ -length * cosTheta,
+ length * sinTheta * cosPhi
+ );
+ };
+
+ /**
+ * Make a new 2D unit vector from a random angle
+ *
+ * @method random2D
+ * @static
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * let v = p5.Vector.random2D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.0] or
+ * // [-0.4695841, -0.14366731, 0.0] or
+ * // [0.6091097, -0.22805278, 0.0]
+ * print(v);
+ *
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(1);
+ * }
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = p5.Vector.random2D();
+ * drawArrow(v0, v1.mult(50), 'black');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * let arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.random2D = function random2D() {
+ return this.fromAngle(Math.random() * constants.TWO_PI);
+ };
+
+ /**
+ * Make a new random 3D unit vector.
+ *
+ * @method random3D
+ * @static
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * let v = p5.Vector.random3D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.599168] or
+ * // [-0.4695841, -0.14366731, -0.8711202] or
+ * // [0.6091097, -0.22805278, -0.7595902]
+ * print(v);
+ *
+ *
+ */
+ _main.default.Vector.random3D = function random3D() {
+ var angle = Math.random() * constants.TWO_PI;
+ var vz = Math.random() * 2 - 1;
+ var vzBase = Math.sqrt(1 - vz * vz);
+ var vx = vzBase * Math.cos(angle);
+ var vy = vzBase * Math.sin(angle);
+ return new _main.default.Vector(vx, vy, vz);
+ };
+
+ // Adds two vectors together and returns a new one.
+ /**
+ * @method add
+ * @static
+ * @param {p5.Vector} v1 a p5.Vector to add
+ * @param {p5.Vector} v2 a p5.Vector to add
+ * @param {p5.Vector} target the vector to receive the result
+ */
+ /**
+ * @method add
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @return {p5.Vector} the resulting p5.Vector
+ *
+ */
+
+ _main.default.Vector.add = function add(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ } else {
+ target.set(v1);
+ }
+ target.add(v2);
+ return target;
+ };
+
+ /*
+ * Subtracts one p5.Vector from another and returns a new one. The second
+ * vector (v2) is subtracted from the first (v1), resulting in v1-v2.
+ */
+ /**
+ * @method sub
+ * @static
+ * @param {p5.Vector} v1 a p5.Vector to subtract from
+ * @param {p5.Vector} v2 a p5.Vector to subtract
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+ /**
+ * @method sub
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @return {p5.Vector} the resulting p5.Vector
+ */
+
+ _main.default.Vector.sub = function sub(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ } else {
+ target.set(v1);
+ }
+ target.sub(v2);
+ return target;
+ };
+
+ /**
+ * Multiplies a vector by a scalar and returns a new vector.
+ */
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v the vector to multiply
+ * @param {Number} n
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v
+ * @param {Number} n
+ * @return {p5.Vector} the resulting new p5.Vector
+ */
+ _main.default.Vector.mult = function mult(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ } else {
+ target.set(v);
+ }
+ target.mult(n);
+ return target;
+ };
+
+ /**
+ * Divides a vector by a scalar and returns a new vector.
+ */
+ /**
+ * @method div
+ * @static
+ * @param {p5.Vector} v the vector to divide
+ * @param {Number} n
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+ /**
+ * @method div
+ * @static
+ * @param {p5.Vector} v
+ * @param {Number} n
+ * @return {p5.Vector} the resulting new p5.Vector
+ */
+ _main.default.Vector.div = function div(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ } else {
+ target.set(v);
+ }
+ target.div(n);
+ return target;
+ };
+
+ /**
+ * Calculates the dot product of two vectors.
+ */
+ /**
+ * @method dot
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the dot product
+ */
+ _main.default.Vector.dot = function dot(v1, v2) {
+ return v1.dot(v2);
+ };
+
+ /**
+ * Calculates the cross product of two vectors.
+ */
+ /**
+ * @method cross
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the cross product
+ */
+ _main.default.Vector.cross = function cross(v1, v2) {
+ return v1.cross(v2);
+ };
+
+ /**
+ * Calculates the Euclidean distance between two points (considering a
+ * point as a vector object).
+ */
+ /**
+ * @method dist
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the distance
+ */
+ _main.default.Vector.dist = function dist(v1, v2) {
+ return v1.dist(v2);
+ };
+
+ /**
+ * Linear interpolate a vector to another vector and return the result as a
+ * new vector.
+ */
+ /**
+ * @method lerp
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @param {Number} amt
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+ /**
+ * @method lerp
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @param {Number} amt
+ * @return {Number} the lerped value
+ */
+ _main.default.Vector.lerp = function lerp(v1, v2, amt, target) {
+ if (!target) {
+ target = v1.copy();
+ } else {
+ target.set(v1);
+ }
+ target.lerp(v2, amt);
+ return target;
+ };
+
+ /**
+ * @method mag
+ * @param {p5.Vector} vecT the vector to return the magnitude of
+ * @return {Number} the magnitude of vecT
+ * @static
+ */
+ _main.default.Vector.mag = function mag(vecT) {
+ var x = vecT.x,
+ y = vecT.y,
+ z = vecT.z;
+ var magSq = x * x + y * y + z * z;
+ return Math.sqrt(magSq);
+ };
+ var _default = _main.default.Vector;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 61: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /** // variables used for random number generators
+ * @module Math
+ * @submodule Random
+ * @for p5
+ * @requires core
+ */
+ var randomStateProp = '_lcg_random_state'; // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
+ // m is basically chosen to be large (as it is the max period)
+ // and for its relationships to a and c
+ var m = 4294967296; // a - 1 should be divisible by m's prime factors
+ var a = 1664525; // c and m should be co-prime
+ var c = 1013904223;
+ var y2 = 0;
+
+ // Linear Congruential Generator that stores its state at instance[stateProperty]
+ _main.default.prototype._lcg = function(stateProperty) {
+ // define the recurrence relationship
+ this[stateProperty] = (a * this[stateProperty] + c) % m;
+ // return a float in [0, 1)
+ // we've just used % m, so / m is always < 1
+ return this[stateProperty] / m;
+ };
+
+ _main.default.prototype._lcgSetSeed = function(stateProperty, val) {
+ // pick a random seed if val is undefined or null
+ // the >>> 0 casts the seed to an unsigned 32-bit integer
+ this[stateProperty] = (val == null ? Math.random() * m : val) >>> 0;
+ };
+
+ /**
+ * Sets the seed value for random().
+ *
+ * By default, random() produces different results each time the program
+ * is run. Set the seed parameter to a constant to return the same
+ * pseudo-random numbers each time the software is run.
+ *
+ * @method randomSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ *
+ * randomSeed(99);
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(0, 255);
+ * stroke(r);
+ * line(i, 0, i, 100);
+ * }
+ *
+ *
+ *
+ * @alt
+ * many vertical lines drawn in white, black or grey.
+ *
+ */
+ _main.default.prototype.randomSeed = function(seed) {
+ this._lcgSetSeed(randomStateProp, seed);
+ this._gaussian_previous = false;
+ };
+
+ /**
+ * Return a random floating-point number.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ *
+ * If no argument is given, returns a random number from 0
+ * up to (but not including) 1.
+ *
+ * If one argument is given and it is a number, returns a random number from 0
+ * up to (but not including) the number.
+ *
+ * If one argument is given and it is an array, returns a random element from
+ * that array.
+ *
+ * If two arguments are given, returns a random number from the
+ * first argument up to (but not including) the second argument.
+ *
+ * @method random
+ * @param {Number} [min] the lower bound (inclusive)
+ * @param {Number} [max] the upper bound (exclusive)
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(50);
+ * stroke(r * 5);
+ * line(50, i, 50 + r, i);
+ * }
+ *
+ *
+ *
+ *
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(-50, 50);
+ * line(50, i, 50 + r, i);
+ * }
+ *
+ *
+ *
+ *
+ * // Get a random element from an array using the random(Array) syntax
+ * let words = ['apple', 'bear', 'cat', 'dog'];
+ * let word = random(words); // select random word
+ * text(word, 10, 50); // draw the word
+ *
+ *
+ *
+ * @alt
+ * 100 horizontal lines from center canvas to right. size+fill change each time
+ * 100 horizontal lines from center of canvas. height & side change each render
+ * word displayed at random. Either apple, bear, cat, or dog
+ *
+ */
+ /**
+ * @method random
+ * @param {Array} choices the array to choose from
+ * @return {*} the random element from the array
+ * @example
+ */
+ _main.default.prototype.random = function(min, max) {
+ _main.default._validateParameters('random', arguments);
+ var rand;
+
+ if (this[randomStateProp] != null) {
+ rand = this._lcg(randomStateProp);
+ } else {
+ rand = Math.random();
+ }
+ if (typeof min === 'undefined') {
+ return rand;
+ } else if (typeof max === 'undefined') {
+ if (min instanceof Array) {
+ return min[Math.floor(rand * min.length)];
+ } else {
+ return rand * min;
+ }
+ } else {
+ if (min > max) {
+ var tmp = min;
+ min = max;
+ max = tmp;
+ }
+
+ return rand * (max - min) + min;
+ }
+ };
+
+ /**
+ *
+ * Returns a random number fitting a Gaussian, or
+ * normal, distribution. There is theoretically no minimum or maximum
+ * value that randomGaussian() might return. Rather, there is
+ * just a very low probability that values far from the mean will be
+ * returned; and a higher probability that numbers near the mean will
+ * be returned.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ * If no args, returns a mean of 0 and standard deviation of 1.
+ * If one arg, that arg is the mean (standard deviation is 1).
+ * If two args, first is mean, second is standard deviation.
+ *
+ * @method randomGaussian
+ * @param {Number} mean the mean
+ * @param {Number} sd the standard deviation
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (let y = 0; y < 100; y++) {
+ * let x = randomGaussian(50, 15);
+ * line(50, y, x, y);
+ * }
+ *
+ *
+ *
+ *
+ * let distribution = new Array(360);
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * for (let i = 0; i < distribution.length; i++) {
+ * distribution[i] = floor(randomGaussian(0, 15));
+ * }
+ * }
+ *
+ * function draw() {
+ * background(204);
+ *
+ * translate(width / 2, width / 2);
+ *
+ * for (let i = 0; i < distribution.length; i++) {
+ * rotate(TWO_PI / distribution.length);
+ * stroke(0);
+ * let dist = abs(distribution[i]);
+ * line(0, 0, dist, 0);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * 100 horizontal lines from center of canvas. height & side change each render
+ * black lines radiate from center of canvas. size determined each render
+ */
+ _main.default.prototype.randomGaussian = function(mean, sd) {
+ var y1, x1, x2, w;
+ if (this._gaussian_previous) {
+ y1 = y2;
+ this._gaussian_previous = false;
+ } else {
+ do {
+ x1 = this.random(2) - 1;
+ x2 = this.random(2) - 1;
+ w = x1 * x1 + x2 * x2;
+ } while (w >= 1);
+ w = Math.sqrt(-2 * Math.log(w) / w);
+ y1 = x1 * w;
+ y2 = x2 * w;
+ this._gaussian_previous = true;
+ }
+
+ var m = mean || 0;
+ var s = sd || 1;
+ return y1 * s + m;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 62: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Math
+ * @submodule Trigonometry
+ * @for p5
+ * @requires core
+ * @requires constants
+ */ /*
+ * all DEGREES/RADIANS conversion should be done in the p5 instance
+ * if possible, using the p5._toRadians(), p5._fromRadians() methods.
+ */ _main.default.prototype._angleMode =
+ constants.RADIANS;
+ /**
+ * The inverse of cos(), returns the arc cosine of a value. This function
+ * expects the values in the range of -1 to 1 and values are returned in
+ * the range 0 to PI (3.1415927).
+ *
+ * @method acos
+ * @param {Number} value the value whose arc cosine is to be returned
+ * @return {Number} the arc cosine of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI;
+ * let c = cos(a);
+ * let ac = acos(c);
+ * // Prints: "3.1415927 : -1.0 : 3.1415927"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 4.0;
+ * let c = cos(a);
+ * let ac = acos(c);
+ * // Prints: "3.926991 : -0.70710665 : 2.3561943"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ */ _main.default.prototype.acos = function(ratio) {
+ return this._fromRadians(Math.acos(ratio));
+ };
+
+ /**
+ * The inverse of sin(), returns the arc sine of a value. This function
+ * expects the values in the range of -1 to 1 and values are returned
+ * in the range -PI/2 to PI/2.
+ *
+ * @method asin
+ * @param {Number} value the value whose arc sine is to be returned
+ * @return {Number} the arc sine of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI + PI / 3;
+ * let s = sin(a);
+ * let as = asin(s);
+ * // Prints: "1.0471976 : 0.86602545 : 1.0471976"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 3.0;
+ * let s = sin(a);
+ * let as = asin(s);
+ * // Prints: "4.1887903 : -0.86602545 : -1.0471976"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ *
+ */
+ _main.default.prototype.asin = function(ratio) {
+ return this._fromRadians(Math.asin(ratio));
+ };
+
+ /**
+ * The inverse of tan(), returns the arc tangent of a value. This function
+ * expects the values in the range of -Infinity to Infinity (exclusive) and
+ * values are returned in the range -PI/2 to PI/2.
+ *
+ * @method atan
+ * @param {Number} value the value whose arc tangent is to be returned
+ * @return {Number} the arc tangent of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI + PI / 3;
+ * let t = tan(a);
+ * let at = atan(t);
+ * // Prints: "1.0471976 : 1.7320509 : 1.0471976"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 3.0;
+ * let t = tan(a);
+ * let at = atan(t);
+ * // Prints: "4.1887903 : 1.7320513 : 1.0471977"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ *
+ */
+ _main.default.prototype.atan = function(ratio) {
+ return this._fromRadians(Math.atan(ratio));
+ };
+
+ /**
+ * Calculates the angle (in radians) from a specified point to the coordinate
+ * origin as measured from the positive x-axis. Values are returned as a
+ * float in the range from PI to -PI. The atan2() function is most often used
+ * for orienting geometry to the position of the cursor.
+ *
+ * Note: The y-coordinate of the point is the first parameter, and the
+ * x-coordinate is the second parameter, due the the structure of calculating
+ * the tangent.
+ *
+ * @method atan2
+ * @param {Number} y y-coordinate of the point
+ * @param {Number} x x-coordinate of the point
+ * @return {Number} the arc tangent of the given point
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(204);
+ * translate(width / 2, height / 2);
+ * let a = atan2(mouseY - height / 2, mouseX - width / 2);
+ * rotate(a);
+ * rect(-30, -5, 60, 10);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60 by 10 rect at center of canvas rotates with mouse movements
+ *
+ */
+ _main.default.prototype.atan2 = function(y, x) {
+ return this._fromRadians(Math.atan2(y, x));
+ };
+
+ /**
+ * Calculates the cosine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method cos
+ * @param {Number} angle the angle
+ * @return {Number} the cosine of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 25.0;
+ * for (let i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines form wave patterns, extend-down on left and right side
+ *
+ */
+ _main.default.prototype.cos = function(angle) {
+ return Math.cos(this._toRadians(angle));
+ };
+
+ /**
+ * Calculates the sine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method sin
+ * @param {Number} angle the angle
+ * @return {Number} the sine of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 25.0;
+ * for (let i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines extend down and up from center to form wave pattern
+ *
+ */
+ _main.default.prototype.sin = function(angle) {
+ return Math.sin(this._toRadians(angle));
+ };
+
+ /**
+ * Calculates the tangent of an angle. This function takes into account
+ * the current angleMode. Values are returned in the range of all real numbers.
+ *
+ * @method tan
+ * @param {Number} angle the angle
+ * @return {Number} the tangent of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 50.0;
+ * for (let i = 0; i < 100; i = i + 2) {
+ * line(i, 50, i, 50 + tan(a) * 2.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines end down and up from center to form spike pattern
+ *
+ */
+ _main.default.prototype.tan = function(angle) {
+ return Math.tan(this._toRadians(angle));
+ };
+
+ /**
+ * Converts a radian measurement to its corresponding value in degrees.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. This function does not take into account the
+ * current angleMode.
+ *
+ * @method degrees
+ * @param {Number} radians the radians value to convert to degrees
+ * @return {Number} the converted angle
+ *
+ *
+ * @example
+ *
+ *
+ * let rad = PI / 4;
+ * let deg = degrees(rad);
+ * print(rad + ' radians is ' + deg + ' degrees');
+ * // Prints: 0.7853981633974483 radians is 45 degrees
+ *
+ *
+ *
+ */
+ _main.default.prototype.degrees = function(angle) {
+ return angle * constants.RAD_TO_DEG;
+ };
+
+ /**
+ * Converts a degree measurement to its corresponding value in radians.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. This function does not take into account the
+ * current angleMode.
+ *
+ * @method radians
+ * @param {Number} degrees the degree value to convert to radians
+ * @return {Number} the converted angle
+ *
+ * @example
+ *
+ *
+ * let deg = 45.0;
+ * let rad = radians(deg);
+ * print(deg + ' degrees is ' + rad + ' radians');
+ * // Prints: 45 degrees is 0.7853981633974483 radians
+ *
+ *
+ */
+ _main.default.prototype.radians = function(angle) {
+ return angle * constants.DEG_TO_RAD;
+ };
+
+ /**
+ * Sets the current mode of p5 to given mode. Default mode is RADIANS.
+ *
+ * @method angleMode
+ * @param {Constant} mode either RADIANS or DEGREES
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(204);
+ * angleMode(DEGREES); // Change the mode to DEGREES
+ * let a = atan2(mouseY - height / 2, mouseX - width / 2);
+ * translate(width / 2, height / 2);
+ * push();
+ * rotate(a);
+ * rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
+ * pop();
+ * angleMode(RADIANS); // Change the mode to RADIANS
+ * rotate(a); // variable a stays the same
+ * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
+ * }
+ *
+ *
+ *
+ * @alt
+ * 40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster.
+ *
+ *
+ */
+ _main.default.prototype.angleMode = function(mode) {
+ if (mode === constants.DEGREES || mode === constants.RADIANS) {
+ this._angleMode = mode;
+ }
+ };
+
+ /**
+ * converts angles from the current angleMode to RADIANS
+ *
+ * @method _toRadians
+ * @private
+ * @param {Number} angle
+ * @returns {Number}
+ */
+ _main.default.prototype._toRadians = function(angle) {
+ if (this._angleMode === constants.DEGREES) {
+ return angle * constants.DEG_TO_RAD;
+ }
+ return angle;
+ };
+
+ /**
+ * converts angles from the current angleMode to DEGREES
+ *
+ * @method _toDegrees
+ * @private
+ * @param {Number} angle
+ * @returns {Number}
+ */
+ _main.default.prototype._toDegrees = function(angle) {
+ if (this._angleMode === constants.RADIANS) {
+ return angle * constants.RAD_TO_DEG;
+ }
+ return angle;
+ };
+
+ /**
+ * converts angles from RADIANS into the current angleMode
+ *
+ * @method _fromRadians
+ * @private
+ * @param {Number} angle
+ * @returns {Number}
+ */
+ _main.default.prototype._fromRadians = function(angle) {
+ if (this._angleMode === constants.DEGREES) {
+ return angle * constants.RAD_TO_DEG;
+ }
+ return angle;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 63: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Typography
+ * @submodule Attributes
+ * @for p5
+ * @requires core
+ * @requires constants
+ */ /**
+ * Sets the current alignment for drawing text. Accepts two
+ * arguments: horizAlign (LEFT, CENTER, or RIGHT) and
+ * vertAlign (TOP, BOTTOM, CENTER, or BASELINE).
+ *
+ * The horizAlign parameter is in reference to the x value
+ * of the text() function, while the vertAlign parameter is
+ * in reference to the y value.
+ *
+ * So if you write textAlign(LEFT), you are aligning the left
+ * edge of your text to the x value you give in text(). If you
+ * write textAlign(RIGHT, TOP), you are aligning the right edge
+ * of your text to the x value and the top of edge of the text
+ * to the y value.
+ *
+ * @method textAlign
+ * @param {Constant} horizAlign horizontal alignment, either LEFT,
+ * CENTER, or RIGHT
+ * @param {Constant} [vertAlign] vertical alignment, either TOP,
+ * BOTTOM, CENTER, or BASELINE
+ * @chainable
+ * @example
+ *
+ *
+ * textSize(16);
+ * textAlign(RIGHT);
+ * text('ABCD', 50, 30);
+ * textAlign(CENTER);
+ * text('EFGH', 50, 50);
+ * textAlign(LEFT);
+ * text('IJKL', 50, 70);
+ *
+ *
+ *
+ *
+ *
+ * textSize(16);
+ * strokeWeight(0.5);
+ *
+ * line(0, 12, width, 12);
+ * textAlign(CENTER, TOP);
+ * text('TOP', 0, 12, width);
+ *
+ * line(0, 37, width, 37);
+ * textAlign(CENTER, CENTER);
+ * text('CENTER', 0, 37, width);
+ *
+ * line(0, 62, width, 62);
+ * textAlign(CENTER, BASELINE);
+ * text('BASELINE', 0, 62, width);
+ *
+ * line(0, 87, width, 87);
+ * textAlign(CENTER, BOTTOM);
+ * text('BOTTOM', 0, 87, width);
+ *
+ *
+ *
+ * @alt
+ *Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left.
+ * The names of the four vertical alignments rendered each showing that alignment's placement relative to a horizontal line.
+ *
+ */ /**
+ * @method textAlign
+ * @return {Object}
+ */ _main.default.prototype.textAlign = function(horizAlign, vertAlign) {
+ var _this$_renderer;
+ _main.default._validateParameters('textAlign', arguments);
+ return (_this$_renderer = this._renderer).textAlign.apply(
+ _this$_renderer,
+ arguments
+ );
+ };
+
+ /**
+ * Sets/gets the spacing, in pixels, between lines of text. This
+ * setting will be used in all subsequent calls to the text() function.
+ *
+ * @method textLeading
+ * @param {Number} leading the size in pixels for spacing between lines
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * // Text to display. The "\n" is a "new line" character
+ * let lines = 'L1\nL2\nL3';
+ * textSize(12);
+ *
+ * textLeading(10); // Set leading to 10
+ * text(lines, 10, 25);
+ *
+ * textLeading(20); // Set leading to 20
+ * text(lines, 40, 25);
+ *
+ * textLeading(30); // Set leading to 30
+ * text(lines, 70, 25);
+ *
+ *
+ *
+ * @alt
+ *set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set
+ */
+ /**
+ * @method textLeading
+ * @return {Number}
+ */
+ _main.default.prototype.textLeading = function(theLeading) {
+ var _this$_renderer2;
+ _main.default._validateParameters('textLeading', arguments);
+ return (_this$_renderer2 = this._renderer).textLeading.apply(
+ _this$_renderer2,
+ arguments
+ );
+ };
+
+ /**
+ * Sets/gets the current font size. This size will be used in all subsequent
+ * calls to the text() function. Font size is measured in pixels.
+ *
+ * @method textSize
+ * @param {Number} theSize the size of the letters in units of pixels
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * textSize(12);
+ * text('Font Size 12', 10, 30);
+ * textSize(14);
+ * text('Font Size 14', 10, 60);
+ * textSize(16);
+ * text('Font Size 16', 10, 90);
+ *
+ *
+ *
+ * @alt
+ *Font Size 12 displayed small, Font Size 14 medium & Font Size 16 large
+ */
+ /**
+ * @method textSize
+ * @return {Number}
+ */
+ _main.default.prototype.textSize = function(theSize) {
+ var _this$_renderer3;
+ _main.default._validateParameters('textSize', arguments);
+ return (_this$_renderer3 = this._renderer).textSize.apply(
+ _this$_renderer3,
+ arguments
+ );
+ };
+
+ /**
+ * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC.
+ * Note: this may be is overridden by CSS styling. For non-system fonts
+ * (opentype, truetype, etc.) please load styled fonts instead.
+ *
+ * @method textStyle
+ * @param {Constant} theStyle styling for text, either NORMAL,
+ * ITALIC, BOLD or BOLDITALIC
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(0);
+ * textSize(12);
+ * textStyle(NORMAL);
+ * text('Font Style Normal', 10, 15);
+ * textStyle(ITALIC);
+ * text('Font Style Italic', 10, 40);
+ * textStyle(BOLD);
+ * text('Font Style Bold', 10, 65);
+ * textStyle(BOLDITALIC);
+ * text('Font Style Bold Italic', 10, 90);
+ *
+ *
+ *
+ * @alt
+ *words Font Style Normal displayed normally, Italic in italic, bold in bold and bold italic in bold italics.
+ */
+ /**
+ * @method textStyle
+ * @return {String}
+ */
+ _main.default.prototype.textStyle = function(theStyle) {
+ var _this$_renderer4;
+ _main.default._validateParameters('textStyle', arguments);
+ return (_this$_renderer4 = this._renderer).textStyle.apply(
+ _this$_renderer4,
+ arguments
+ );
+ };
+
+ /**
+ * Calculates and returns the width of any character or text string.
+ *
+ * @method textWidth
+ * @param {String} theText the String of characters to measure
+ * @return {Number}
+ * @example
+ *
+ *
+ * textSize(28);
+ *
+ * let aChar = 'P';
+ * let cWidth = textWidth(aChar);
+ * text(aChar, 0, 40);
+ * line(cWidth, 0, cWidth, 50);
+ *
+ * let aString = 'p5.js';
+ * let sWidth = textWidth(aString);
+ * text(aString, 0, 85);
+ * line(sWidth, 50, sWidth, 100);
+ *
+ *
+ *
+ * @alt
+ *Letter P and p5.js are displayed with vertical lines at end. P is wide
+ *
+ */
+ _main.default.prototype.textWidth = function() {
+ var _this$_renderer5;
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ args[0] += '';
+ _main.default._validateParameters('textWidth', args);
+ if (args[0].length === 0) {
+ return 0;
+ }
+ return (_this$_renderer5 = this._renderer).textWidth.apply(
+ _this$_renderer5,
+ args
+ );
+ };
+
+ /**
+ * Returns the ascent of the current font at its current size. The ascent
+ * represents the distance, in pixels, of the tallest character above
+ * the baseline.
+ * @method textAscent
+ * @return {Number}
+ * @example
+ *
+ *
+ * let base = height * 0.75;
+ * let scalar = 0.8; // Different for each font
+ *
+ * textSize(32); // Set initial text size
+ * let asc = textAscent() * scalar; // Calc ascent
+ * line(0, base - asc, width, base - asc);
+ * text('dp', 0, base); // Draw text on baseline
+ *
+ * textSize(64); // Increase text size
+ * asc = textAscent() * scalar; // Recalc ascent
+ * line(40, base - asc, width, base - asc);
+ * text('dp', 40, base); // Draw text on baseline
+ *
+ *
+ */
+ _main.default.prototype.textAscent = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('textAscent', args);
+ return this._renderer.textAscent();
+ };
+
+ /**
+ * Returns the descent of the current font at its current size. The descent
+ * represents the distance, in pixels, of the character with the longest
+ * descender below the baseline.
+ * @method textDescent
+ * @return {Number}
+ * @example
+ *
+ *
+ * let base = height * 0.75;
+ * let scalar = 0.8; // Different for each font
+ *
+ * textSize(32); // Set initial text size
+ * let desc = textDescent() * scalar; // Calc ascent
+ * line(0, base + desc, width, base + desc);
+ * text('dp', 0, base); // Draw text on baseline
+ *
+ * textSize(64); // Increase text size
+ * desc = textDescent() * scalar; // Recalc ascent
+ * line(40, base + desc, width, base + desc);
+ * text('dp', 40, base); // Draw text on baseline
+ *
+ *
+ */
+ _main.default.prototype.textDescent = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('textDescent', args);
+ return this._renderer.textDescent();
+ };
+
+ /**
+ * Helper function to measure ascent and descent.
+ */
+ _main.default.prototype._updateTextMetrics = function() {
+ return this._renderer._updateTextMetrics();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 64: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ var opentype = _interopRequireWildcard(_dereq_('opentype.js'));
+
+ _dereq_('../core/error_helpers');
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Typography
+ * @submodule Loading & Displaying
+ * @for p5
+ * @requires core
+ */ /**
+ * Loads an opentype font file (.otf, .ttf) from a file or a URL,
+ * and returns a PFont Object. This method is asynchronous,
+ * meaning it may not finish before the next line in your sketch
+ * is executed.
+ *
+ * The path to the font should be relative to the HTML file
+ * that links in your sketch. Loading fonts from a URL or other
+ * remote location may be blocked due to your browser's built-in
+ * security.
+ *
+ * @method loadFont
+ * @param {String} path name of the file or url to load
+ * @param {Function} [callback] function to be executed after
+ * loadFont() completes
+ * @param {Function} [onError] function to be executed if
+ * an error occurs
+ * @return {p5.Font} p5.Font object
+ * @example
+ *
+ * Calling loadFont() inside preload() guarantees that the load
+ * operation will have completed before setup() and draw() are called.
+ *
+ *
+ * let myFont;
+ * function preload() {
+ * myFont = loadFont('assets/inconsolata.otf');
+ * }
+ *
+ * function setup() {
+ * fill('#ED225D');
+ * textFont(myFont);
+ * textSize(36);
+ * text('p5*js', 10, 50);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ * function setup() {
+ * loadFont('assets/inconsolata.otf', drawText);
+ * }
+ *
+ * function drawText(font) {
+ * fill('#ED225D');
+ * textFont(font, 36);
+ * text('p5*js', 10, 50);
+ * }
+ *
+ *
+ * You can also use the font filename string (without the file extension) to style other HTML
+ * elements.
+ *
+ *
+ * function preload() {
+ * loadFont('assets/inconsolata.otf');
+ * }
+ *
+ * function setup() {
+ * let myDiv = createDiv('hello there');
+ * myDiv.style('font-family', 'Inconsolata');
+ * }
+ *
+ *
+ * @alt
+ * p5*js in p5's theme dark pink
+ * p5*js in p5's theme dark pink
+ *
+ */ _main.default.prototype.loadFont = function(path, onSuccess, onError) {
+ _main.default._validateParameters('loadFont', arguments);
+ var p5Font = new _main.default.Font(this);
+
+ var self = this;
+ opentype.load(path, function(err, font) {
+ if (err) {
+ _main.default._friendlyFileLoadError(4, path);
+ if (typeof onError !== 'undefined') {
+ return onError(err);
+ }
+ console.error(err, path);
+ return;
+ }
+
+ p5Font.font = font;
+
+ if (typeof onSuccess !== 'undefined') {
+ onSuccess(p5Font);
+ }
+
+ self._decrementPreload();
+
+ // check that we have an acceptable font type
+ var validFontTypes = ['ttf', 'otf', 'woff', 'woff2'];
+
+ var fileNoPath = path
+ .split('\\')
+ .pop()
+ .split('/')
+ .pop();
+
+ var lastDotIdx = fileNoPath.lastIndexOf('.');
+ var fontFamily;
+ var newStyle;
+ var fileExt = lastDotIdx < 1 ? null : fileNoPath.substr(lastDotIdx + 1);
+
+ // if so, add it to the DOM (name-only) for use with DOM module
+ if (validFontTypes.includes(fileExt)) {
+ fontFamily = fileNoPath.substr(0, lastDotIdx);
+ newStyle = document.createElement('style');
+ newStyle.appendChild(
+ document.createTextNode(
+ '\n@font-face {\nfont-family: '
+ .concat(fontFamily, ';\nsrc: url(')
+ .concat(path, ');\n}\n')
+ )
+ );
+
+ document.head.appendChild(newStyle);
+ }
+ });
+
+ return p5Font;
+ };
+
+ /**
+ * Draws text to the screen. Displays the information specified in the first
+ * parameter on the screen in the position specified by the additional
+ * parameters. A default font will be used unless a font is set with the
+ * textFont() function and a default size will be used unless a font is set
+ * with textSize(). Change the color of the text with the fill() function.
+ * Change the outline of the text with the stroke() and strokeWeight()
+ * functions.
+ *
+ * The text displays in relation to the textAlign() function, which gives the
+ * option to draw to the left, right, and center of the coordinates.
+ *
+ * The x2 and y2 parameters define a rectangular area to display within and
+ * may only be used with string data. When these parameters are specified,
+ * they are interpreted based on the current rectMode() setting. Text that
+ * does not fit completely within the rectangle specified will not be drawn
+ * to the screen. If x2 and y2 are not specified, the baseline alignment is the
+ * default, which means that the text will be drawn upwards from x and y.
+ *
+ * WEBGL: Only opentype/truetype fonts are supported. You must load a font using the
+ * loadFont() method (see the example above).
+ * stroke() currently has no effect in webgl mode.
+ *
+ * @method text
+ * @param {String|Object|Array|Number|Boolean} str the alphanumeric
+ * symbols to be displayed
+ * @param {Number} x x-coordinate of text
+ * @param {Number} y y-coordinate of text
+ * @param {Number} [x2] by default, the width of the text box,
+ * see rectMode() for more info
+ * @param {Number} [y2] by default, the height of the text box,
+ * see rectMode() for more info
+ * @chainable
+ * @example
+ *
+ *
+ * textSize(32);
+ * text('word', 10, 30);
+ * fill(0, 102, 153);
+ * text('word', 10, 60);
+ * fill(0, 102, 153, 51);
+ * text('word', 10, 90);
+ *
+ *
+ *
+ *
+ * let s = 'The quick brown fox jumped over the lazy dog.';
+ * fill(50);
+ * text(s, 10, 10, 70, 80); // Text wraps within text box
+ *
+ *
+ *
+ *
+ *
+ * let inconsolata;
+ * function preload() {
+ * inconsolata = loadFont('assets/inconsolata.otf');
+ * }
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * textFont(inconsolata);
+ * textSize(width / 3);
+ * textAlign(CENTER, CENTER);
+ * }
+ * function draw() {
+ * background(0);
+ * let time = millis();
+ * rotateX(time / 1000);
+ * rotateZ(time / 1234);
+ * text('p5.js', 0, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ *'word' displayed 3 times going from black, blue to translucent blue
+ * The quick brown fox jumped over the lazy dog.
+ * the text 'p5.js' spinning in 3d
+ *
+ */
+ _main.default.prototype.text = function(str, x, y, maxWidth, maxHeight) {
+ var _this$_renderer;
+ _main.default._validateParameters('text', arguments);
+ return !(this._renderer._doFill || this._renderer._doStroke)
+ ? this
+ : (_this$_renderer = this._renderer).text.apply(_this$_renderer, arguments);
+ };
+
+ /**
+ * Sets the current font that will be drawn with the text() function.
+ *
+ * WEBGL: Only fonts loaded via loadFont() are supported.
+ *
+ * @method textFont
+ * @return {Object} the current font
+ *
+ * @example
+ *
+ *
+ * fill(0);
+ * textSize(12);
+ * textFont('Georgia');
+ * text('Georgia', 12, 30);
+ * textFont('Helvetica');
+ * text('Helvetica', 12, 60);
+ *
+ *
+ *
+ *
+ * let fontRegular, fontItalic, fontBold;
+ * function preload() {
+ * fontRegular = loadFont('assets/Regular.otf');
+ * fontItalic = loadFont('assets/Italic.ttf');
+ * fontBold = loadFont('assets/Bold.ttf');
+ * }
+ * function setup() {
+ * background(210);
+ * fill(0)
+ .strokeWeight(0)
+ .textSize(10);
+ * textFont(fontRegular);
+ * text('Font Style Normal', 10, 30);
+ * textFont(fontItalic);
+ * text('Font Style Italic', 10, 50);
+ * textFont(fontBold);
+ * text('Font Style Bold', 10, 70);
+ * }
+ *
+ *
+ *
+ * @alt
+ *words Font Style Normal displayed normally, Italic in italic and bold in bold
+ */
+ /**
+ * @method textFont
+ * @param {Object|String} font a font loaded via loadFont(), or a String
+ * representing a web safe font (a font
+ * that is generally available across all systems)
+ * @param {Number} [size] the font size to use
+ * @chainable
+ */
+ _main.default.prototype.textFont = function(theFont, theSize) {
+ _main.default._validateParameters('textFont', arguments);
+ if (arguments.length) {
+ if (!theFont) {
+ throw new Error('null font passed to textFont');
+ }
+
+ this._renderer._setProperty('_textFont', theFont);
+
+ if (theSize) {
+ this._renderer._setProperty('_textSize', theSize);
+ this._renderer._setProperty(
+ '_textLeading',
+ theSize * constants._DEFAULT_LEADMULT
+ );
+ }
+
+ return this._renderer._applyTextProperties();
+ }
+
+ return this._renderer._textFont;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 21,
+ '../core/error_helpers': 23,
+ '../core/main': 27,
+ 'opentype.js': 12
+ }
+ ],
+ 65: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ function _typeof(obj) {
+ if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
+ _typeof = function _typeof(obj) {
+ return typeof obj;
+ };
+ } else {
+ _typeof = function _typeof(obj) {
+ return obj &&
+ typeof Symbol === 'function' &&
+ obj.constructor === Symbol &&
+ obj !== Symbol.prototype
+ ? 'symbol'
+ : typeof obj;
+ };
+ }
+ return _typeof(obj);
+ }
+
+ /**
+ * Base class for font handling
+ * @class p5.Font
+ * @param {p5} [pInst] pointer to p5 instance
+ */
+ _main.default.Font = function(p) {
+ this.parent = p;
+
+ this.cache = {};
+
+ /**
+ * Underlying opentype font implementation
+ * @property font
+ */
+ this.font = undefined;
+ };
+
+ /**
+ * Returns a tight bounding box for the given text string using this
+ * font (currently only supports single lines)
+ *
+ * @method textBounds
+ * @param {String} line a line of text
+ * @param {Number} x x-position
+ * @param {Number} y y-position
+ * @param {Number} [fontSize] font size to use (optional) Default is 12.
+ * @param {Object} [options] opentype options (optional)
+ * opentype fonts contains alignment and baseline options.
+ * Default is 'LEFT' and 'alphabetic'
+ *
+ *
+ * @return {Object} a rectangle object with properties: x, y, w, h
+ *
+ * @example
+ *
+ *
+ * let font;
+ * let textString = 'Lorem ipsum dolor sit amet.';
+ * function preload() {
+ * font = loadFont('./assets/Regular.otf');
+ * }
+ * function setup() {
+ * background(210);
+ *
+ * let bbox = font.textBounds(textString, 10, 30, 12);
+ * fill(255);
+ * stroke(0);
+ * rect(bbox.x, bbox.y, bbox.w, bbox.h);
+ * fill(0);
+ * noStroke();
+ *
+ * textFont(font);
+ * textSize(12);
+ * text(textString, 10, 30);
+ * }
+ *
+ *
+ *
+ * @alt
+ *words Lorem ipsum dol go off canvas and contained by white bounding box
+ *
+ */
+ _main.default.Font.prototype.textBounds = function(str) {
+ var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
+ var fontSize = arguments.length > 3 ? arguments[3] : undefined;
+ var opts = arguments.length > 4 ? arguments[4] : undefined;
+ // Check cache for existing bounds. Take into consideration the text alignment
+ // settings. Default alignment should match opentype's origin: left-aligned &
+ // alphabetic baseline.
+ var p = (opts && opts.renderer && opts.renderer._pInst) || this.parent;
+
+ var ctx = p._renderer.drawingContext;
+ var alignment = ctx.textAlign || constants.LEFT;
+ var baseline = ctx.textBaseline || constants.BASELINE;
+ var cacheResults = false;
+ var result;
+ var key;
+
+ fontSize = fontSize || p._renderer._textSize;
+
+ // NOTE: cache disabled for now pending further discussion of #3436
+ if (cacheResults) {
+ key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline);
+ result = this.cache[key];
+ }
+
+ if (!result) {
+ var minX;
+ var minY;
+ var maxX;
+ var maxY;
+ var pos;
+ var xCoords = [];
+ var yCoords = [];
+ var scale = this._scale(fontSize);
+
+ this.font.forEachGlyph(str, x, y, fontSize, opts, function(
+ glyph,
+ gX,
+ gY,
+ gFontSize
+ ) {
+ var gm = glyph.getMetrics();
+ xCoords.push(gX + gm.xMin * scale);
+ xCoords.push(gX + gm.xMax * scale);
+ yCoords.push(gY + -gm.yMin * scale);
+ yCoords.push(gY + -gm.yMax * scale);
+ });
+
+ minX = Math.min.apply(null, xCoords);
+ minY = Math.min.apply(null, yCoords);
+ maxX = Math.max.apply(null, xCoords);
+ maxY = Math.max.apply(null, yCoords);
+
+ result = {
+ x: minX,
+ y: minY,
+ h: maxY - minY,
+ w: maxX - minX,
+ advance: minX - x
+ };
+
+ // Bounds are now calculated, so shift the x & y to match alignment settings
+ pos = this._handleAlignment(
+ p._renderer,
+ str,
+ result.x,
+ result.y,
+ result.w + result.advance
+ );
+
+ result.x = pos.x;
+ result.y = pos.y;
+
+ if (cacheResults) {
+ this.cache[key] = result;
+ }
+ }
+
+ return result;
+ };
+
+ /**
+ * Computes an array of points following the path for specified text
+ *
+ * @method textToPoints
+ * @param {String} txt a line of text
+ * @param {Number} x x-position
+ * @param {Number} y y-position
+ * @param {Number} fontSize font size to use (optional)
+ * @param {Object} [options] an (optional) object that can contain:
+ *
+ *
sampleFactor - the ratio of path-length to number of samples
+ * (default=.1); higher values yield more points and are therefore
+ * more precise
+ *
+ *
simplifyThreshold - if set to a non-zero value, collinear points will be
+ * be removed from the polygon; the value represents the threshold angle to use
+ * when determining whether two edges are collinear
+ *
+ * @return {Array} an array of points, each with x, y, alpha (the path angle)
+ * @example
+ *
+ *
+ * let font;
+ * function preload() {
+ * font = loadFont('assets/inconsolata.otf');
+ * }
+ *
+ * let points;
+ * let bounds;
+ * function setup() {
+ * createCanvas(100, 100);
+ * stroke(0);
+ * fill(255, 104, 204);
+ *
+ * points = font.textToPoints('p5', 0, 0, 10, {
+ * sampleFactor: 5,
+ * simplifyThreshold: 0
+ * });
+ * bounds = font.textBounds(' p5 ', 0, 0, 10);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * beginShape();
+ * translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);
+ * for (let i = 0; i < points.length; i++) {
+ * let p = points[i];
+ * vertex(
+ * p.x * width / bounds.w +
+ * sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,
+ * p.y * height / bounds.h
+ * );
+ * }
+ * endShape(CLOSE);
+ * }
+ *
+ *
+ *
+ */
+ _main.default.Font.prototype.textToPoints = function(
+ txt,
+ x,
+ y,
+ fontSize,
+ options
+ ) {
+ var xoff = 0;
+ var result = [];
+ var glyphs = this._getGlyphs(txt);
+
+ function isSpace(i) {
+ return (
+ (glyphs[i].name && glyphs[i].name === 'space') ||
+ (txt.length === glyphs.length && txt[i] === ' ') ||
+ (glyphs[i].index && glyphs[i].index === 3)
+ );
+ }
+
+ fontSize = fontSize || this.parent._renderer._textSize;
+
+ for (var i = 0; i < glyphs.length; i++) {
+ if (!isSpace(i)) {
+ // fix to #1817, #2069
+
+ var gpath = glyphs[i].getPath(x, y, fontSize),
+ paths = splitPaths(gpath.commands);
+
+ for (var j = 0; j < paths.length; j++) {
+ var pts = pathToPoints(paths[j], options);
+
+ for (var k = 0; k < pts.length; k++) {
+ pts[k].x += xoff;
+ result.push(pts[k]);
+ }
+ }
+ }
+
+ xoff += glyphs[i].advanceWidth * this._scale(fontSize);
+ }
+
+ return result;
+ };
+
+ // ----------------------------- End API ------------------------------
+
+ /**
+ * Returns the set of opentype glyphs for the supplied string.
+ *
+ * Note that there is not a strict one-to-one mapping between characters
+ * and glyphs, so the list of returned glyphs can be larger or smaller
+ * than the length of the given string.
+ *
+ * @private
+ * @param {String} str the string to be converted
+ * @return {Array} the opentype glyphs
+ */
+ _main.default.Font.prototype._getGlyphs = function(str) {
+ return this.font.stringToGlyphs(str);
+ };
+
+ /**
+ * Returns an opentype path for the supplied string and position.
+ *
+ * @private
+ * @param {String} line a line of text
+ * @param {Number} x x-position
+ * @param {Number} y y-position
+ * @param {Object} options opentype options (optional)
+ * @return {Object} the opentype path
+ */
+ _main.default.Font.prototype._getPath = function(line, x, y, options) {
+ var p = (options && options.renderer && options.renderer._pInst) || this.parent,
+ renderer = p._renderer,
+ pos = this._handleAlignment(renderer, line, x, y);
+
+ return this.font.getPath(line, pos.x, pos.y, renderer._textSize, options);
+ };
+
+ /*
+ * Creates an SVG-formatted path-data string
+ * (See http://www.w3.org/TR/SVG/paths.html#PathData)
+ * from the given opentype path or string/position
+ *
+ * @param {Object} path an opentype path, OR the following:
+ *
+ * @param {String} line a line of text
+ * @param {Number} x x-position
+ * @param {Number} y y-position
+ * @param {Object} options opentype options (optional), set options.decimals
+ * to set the decimal precision of the path-data
+ *
+ * @return {Object} this p5.Font object
+ */
+ _main.default.Font.prototype._getPathData = function(line, x, y, options) {
+ var decimals = 3;
+
+ // create path from string/position
+ if (typeof line === 'string' && arguments.length > 2) {
+ line = this._getPath(line, x, y, options);
+ } else if (_typeof(x) === 'object') {
+ // handle options specified in 2nd arg
+ options = x;
+ }
+
+ // handle svg arguments
+ if (options && typeof options.decimals === 'number') {
+ decimals = options.decimals;
+ }
+
+ return line.toPathData(decimals);
+ };
+
+ /*
+ * Creates an SVG element, as a string,
+ * from the given opentype path or string/position
+ *
+ * @param {Object} path an opentype path, OR the following:
+ *
+ * @param {String} line a line of text
+ * @param {Number} x x-position
+ * @param {Number} y y-position
+ * @param {Object} options opentype options (optional), set options.decimals
+ * to set the decimal precision of the path-data in the element,
+ * options.fill to set the fill color for the element,
+ * options.stroke to set the stroke color for the element,
+ * options.strokeWidth to set the strokeWidth for the element.
+ *
+ * @return {Object} this p5.Font object
+ */
+ _main.default.Font.prototype._getSVG = function(line, x, y, options) {
+ var decimals = 3;
+
+ // create path from string/position
+ if (typeof line === 'string' && arguments.length > 2) {
+ line = this._getPath(line, x, y, options);
+ } else if (_typeof(x) === 'object') {
+ // handle options specified in 2nd arg
+ options = x;
+ }
+
+ // handle svg arguments
+ if (options) {
+ if (typeof options.decimals === 'number') {
+ decimals = options.decimals;
+ }
+ if (typeof options.strokeWidth === 'number') {
+ line.strokeWidth = options.strokeWidth;
+ }
+ if (typeof options.fill !== 'undefined') {
+ line.fill = options.fill;
+ }
+ if (typeof options.stroke !== 'undefined') {
+ line.stroke = options.stroke;
+ }
+ }
+
+ return line.toSVG(decimals);
+ };
+
+ /*
+ * Renders an opentype path or string/position
+ * to the current graphics context
+ *
+ * @param {Object} path an opentype path, OR the following:
+ *
+ * @param {String} line a line of text
+ * @param {Number} x x-position
+ * @param {Number} y y-position
+ * @param {Object} options opentype options (optional)
+ *
+ * @return {p5.Font} this p5.Font object
+ */
+ _main.default.Font.prototype._renderPath = function(line, x, y, options) {
+ var pdata;
+ var pg = (options && options.renderer) || this.parent._renderer;
+ var ctx = pg.drawingContext;
+
+ if (_typeof(line) === 'object' && line.commands) {
+ pdata = line.commands;
+ } else {
+ //pos = handleAlignment(p, ctx, line, x, y);
+ pdata = this._getPath(line, x, y, options).commands;
+ }
+
+ ctx.beginPath();
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (
+ var _iterator = pdata[Symbol.iterator](), _step;
+ !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
+ _iteratorNormalCompletion = true
+ ) {
+ var cmd = _step.value;
+ if (cmd.type === 'M') {
+ ctx.moveTo(cmd.x, cmd.y);
+ } else if (cmd.type === 'L') {
+ ctx.lineTo(cmd.x, cmd.y);
+ } else if (cmd.type === 'C') {
+ ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
+ } else if (cmd.type === 'Q') {
+ ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
+ } else if (cmd.type === 'Z') {
+ ctx.closePath();
+ }
+ }
+
+ // only draw stroke if manually set by user
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ if (pg._doStroke && pg._strokeSet) {
+ ctx.stroke();
+ }
+
+ if (pg._doFill) {
+ // if fill hasn't been set by user, use default-text-fill
+ if (!pg._fillSet) {
+ pg._setFill(constants._DEFAULT_TEXT_FILL);
+ }
+ ctx.fill();
+ }
+
+ return this;
+ };
+
+ _main.default.Font.prototype._textWidth = function(str, fontSize) {
+ return this.font.getAdvanceWidth(str, fontSize);
+ };
+
+ _main.default.Font.prototype._textAscent = function(fontSize) {
+ return this.font.ascender * this._scale(fontSize);
+ };
+
+ _main.default.Font.prototype._textDescent = function(fontSize) {
+ return -this.font.descender * this._scale(fontSize);
+ };
+
+ _main.default.Font.prototype._scale = function(fontSize) {
+ return 1 / this.font.unitsPerEm * (fontSize || this.parent._renderer._textSize);
+ };
+
+ _main.default.Font.prototype._handleAlignment = function(
+ renderer,
+ line,
+ x,
+ y,
+ textWidth
+ ) {
+ var fontSize = renderer._textSize;
+
+ if (typeof textWidth === 'undefined') {
+ textWidth = this._textWidth(line, fontSize);
+ }
+
+ switch (renderer._textAlign) {
+ case constants.CENTER:
+ x -= textWidth / 2;
+ break;
+ case constants.RIGHT:
+ x -= textWidth;
+ break;
+ }
+
+ switch (renderer._textBaseline) {
+ case constants.TOP:
+ y += this._textAscent(fontSize);
+ break;
+ case constants.CENTER:
+ y += this._textAscent(fontSize) / 2;
+ break;
+ case constants.BOTTOM:
+ y -= this._textDescent(fontSize);
+ break;
+ }
+
+ return { x: x, y: y };
+ };
+
+ // path-utils
+
+ function pathToPoints(cmds, options) {
+ var opts = parseOpts(options, {
+ sampleFactor: 0.1,
+ simplifyThreshold: 0
+ });
+
+ var // total-length
+ len = pointAtLength(cmds, 0, 1),
+ t = len / (len * opts.sampleFactor),
+ pts = [];
+
+ for (var i = 0; i < len; i += t) {
+ pts.push(pointAtLength(cmds, i));
+ }
+
+ if (opts.simplifyThreshold) {
+ simplify(pts, opts.simplifyThreshold);
+ }
+
+ return pts;
+ }
+
+ function simplify(pts) {
+ var angle =
+ arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ var num = 0;
+ for (var i = pts.length - 1; pts.length > 3 && i >= 0; --i) {
+ if (collinear(at(pts, i - 1), at(pts, i), at(pts, i + 1), angle)) {
+ // Remove the middle point
+ pts.splice(i % pts.length, 1);
+ num++;
+ }
+ }
+ return num;
+ }
+
+ function splitPaths(cmds) {
+ var paths = [];
+ var current;
+ for (var i = 0; i < cmds.length; i++) {
+ if (cmds[i].type === 'M') {
+ if (current) {
+ paths.push(current);
+ }
+ current = [];
+ }
+ current.push(cmdToArr(cmds[i]));
+ }
+ paths.push(current);
+
+ return paths;
+ }
+
+ function cmdToArr(cmd) {
+ var arr = [cmd.type];
+ if (cmd.type === 'M' || cmd.type === 'L') {
+ // moveto or lineto
+ arr.push(cmd.x, cmd.y);
+ } else if (cmd.type === 'C') {
+ arr.push(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
+ } else if (cmd.type === 'Q') {
+ arr.push(cmd.x1, cmd.y1, cmd.x, cmd.y);
+ }
+ // else if (cmd.type === 'Z') { /* no-op */ }
+ return arr;
+ }
+
+ function parseOpts(options, defaults) {
+ if (_typeof(options) !== 'object') {
+ options = defaults;
+ } else {
+ for (var key in defaults) {
+ if (typeof options[key] === 'undefined') {
+ options[key] = defaults[key];
+ }
+ }
+ }
+ return options;
+ }
+
+ //////////////////////// Helpers ////////////////////////////
+
+ function at(v, i) {
+ var s = v.length;
+ return v[i < 0 ? i % s + s : i % s];
+ }
+
+ function collinear(a, b, c, thresholdAngle) {
+ if (!thresholdAngle) {
+ return areaTriangle(a, b, c) === 0;
+ }
+
+ if (typeof collinear.tmpPoint1 === 'undefined') {
+ collinear.tmpPoint1 = [];
+ collinear.tmpPoint2 = [];
+ }
+
+ var ab = collinear.tmpPoint1,
+ bc = collinear.tmpPoint2;
+ ab.x = b.x - a.x;
+ ab.y = b.y - a.y;
+ bc.x = c.x - b.x;
+ bc.y = c.y - b.y;
+
+ var dot = ab.x * bc.x + ab.y * bc.y,
+ magA = Math.sqrt(ab.x * ab.x + ab.y * ab.y),
+ magB = Math.sqrt(bc.x * bc.x + bc.y * bc.y),
+ angle = Math.acos(dot / (magA * magB));
+
+ return angle < thresholdAngle;
+ }
+
+ function areaTriangle(a, b, c) {
+ return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
+ }
+
+ // Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license)
+
+ function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
+ var t1 = 1 - t;
+ var t13 = Math.pow(t1, 3);
+ var t12 = Math.pow(t1, 2);
+ var t2 = t * t;
+ var t3 = t2 * t;
+ var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x;
+ var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y;
+ var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x);
+ var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y);
+ var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x);
+ var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y);
+ var ax = t1 * p1x + t * c1x;
+ var ay = t1 * p1y + t * c1y;
+ var cx = t1 * c2x + t * p2x;
+ var cy = t1 * c2y + t * p2y;
+ var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI;
+
+ if (mx > nx || my < ny) {
+ alpha += 180;
+ }
+
+ return {
+ x: x,
+ y: y,
+ m: { x: mx, y: my },
+ n: { x: nx, y: ny },
+ start: { x: ax, y: ay },
+ end: { x: cx, y: cy },
+ alpha: alpha
+ };
+ }
+
+ function getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
+ return length == null
+ ? bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y)
+ : findDotsAtSegment(
+ p1x,
+ p1y,
+ c1x,
+ c1y,
+ c2x,
+ c2y,
+ p2x,
+ p2y,
+ getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)
+ );
+ }
+
+ function pointAtLength(path, length, istotal) {
+ path = path2curve(path);
+ var x;
+ var y;
+ var p;
+ var l;
+ var sp = '';
+ var subpaths = {};
+ var point;
+ var len = 0;
+ for (var i = 0, ii = path.length; i < ii; i++) {
+ p = path[i];
+ if (p[0] === 'M') {
+ x = +p[1];
+ y = +p[2];
+ } else {
+ l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
+ if (len + l > length) {
+ if (!istotal) {
+ point = getPointAtSegmentLength(
+ x,
+ y,
+ p[1],
+ p[2],
+ p[3],
+ p[4],
+ p[5],
+ p[6],
+ length - len
+ );
+
+ return { x: point.x, y: point.y, alpha: point.alpha };
+ }
+ }
+ len += l;
+ x = +p[5];
+ y = +p[6];
+ }
+ sp += p.shift() + p;
+ }
+ subpaths.end = sp;
+
+ point = istotal
+ ? len
+ : findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
+
+ if (point.alpha) {
+ point = { x: point.x, y: point.y, alpha: point.alpha };
+ }
+
+ return point;
+ }
+
+ function pathToAbsolute(pathArray) {
+ var res = [],
+ x = 0,
+ y = 0,
+ mx = 0,
+ my = 0,
+ start = 0;
+ if (!pathArray) {
+ // console.warn("Unexpected state: undefined pathArray"); // shouldn't happen
+ return res;
+ }
+ if (pathArray[0][0] === 'M') {
+ x = +pathArray[0][1];
+ y = +pathArray[0][2];
+ mx = x;
+ my = y;
+ start++;
+ res[0] = ['M', x, y];
+ }
+
+ var dots;
+
+ var crz =
+ pathArray.length === 3 &&
+ pathArray[0][0] === 'M' &&
+ pathArray[1][0].toUpperCase() === 'R' &&
+ pathArray[2][0].toUpperCase() === 'Z';
+
+ for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
+ res.push((r = []));
+ pa = pathArray[i];
+ if (pa[0] !== String.prototype.toUpperCase.call(pa[0])) {
+ r[0] = String.prototype.toUpperCase.call(pa[0]);
+ switch (r[0]) {
+ case 'A':
+ r[1] = pa[1];
+ r[2] = pa[2];
+ r[3] = pa[3];
+ r[4] = pa[4];
+ r[5] = pa[5];
+ r[6] = +(pa[6] + x);
+ r[7] = +(pa[7] + y);
+ break;
+ case 'V':
+ r[1] = +pa[1] + y;
+ break;
+ case 'H':
+ r[1] = +pa[1] + x;
+ break;
+ case 'R':
+ dots = [x, y].concat(pa.slice(1));
+ for (var j = 2, jj = dots.length; j < jj; j++) {
+ dots[j] = +dots[j] + x;
+ dots[++j] = +dots[j] + y;
+ }
+ res.pop();
+ res = res.concat(catmullRom2bezier(dots, crz));
+ break;
+ case 'M':
+ mx = +pa[1] + x;
+ my = +pa[2] + y;
+ break;
+ default:
+ for (var _j = 1, _jj = pa.length; _j < _jj; _j++) {
+ r[_j] = +pa[_j] + (_j % 2 ? x : y);
+ }
+ }
+ } else if (pa[0] === 'R') {
+ dots = [x, y].concat(pa.slice(1));
+ res.pop();
+ res = res.concat(catmullRom2bezier(dots, crz));
+ r = ['R'].concat(pa.slice(-2));
+ } else {
+ for (var k = 0, kk = pa.length; k < kk; k++) {
+ r[k] = pa[k];
+ }
+ }
+ switch (r[0]) {
+ case 'Z':
+ x = mx;
+ y = my;
+ break;
+ case 'H':
+ x = r[1];
+ break;
+ case 'V':
+ y = r[1];
+ break;
+ case 'M':
+ mx = r[r.length - 2];
+ my = r[r.length - 1];
+ break;
+ default:
+ x = r[r.length - 2];
+ y = r[r.length - 1];
+ }
+ }
+ return res;
+ }
+
+ function path2curve(path, path2) {
+ var p = pathToAbsolute(path),
+ p2 = path2 && pathToAbsolute(path2);
+ var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null };
+ var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null };
+ var pcoms1 = []; // path commands of original path p
+ var pcoms2 = []; // path commands of original path p2
+ var ii;
+
+ var processPath = function processPath(path, d, pcom) {
+ var nx;
+ var ny;
+ var tq = { T: 1, Q: 1 };
+ if (!path) {
+ return ['C', d.x, d.y, d.x, d.y, d.x, d.y];
+ }
+ if (!(path[0] in tq)) {
+ d.qx = d.qy = null;
+ }
+ switch (path[0]) {
+ case 'M':
+ d.X = path[1];
+ d.Y = path[2];
+ break;
+ case 'A':
+ path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1))));
+ break;
+ case 'S':
+ if (pcom === 'C' || pcom === 'S') {
+ nx = d.x * 2 - d.bx;
+ ny = d.y * 2 - d.by;
+ } else {
+ nx = d.x;
+ ny = d.y;
+ }
+ path = ['C', nx, ny].concat(path.slice(1));
+ break;
+ case 'T':
+ if (pcom === 'Q' || pcom === 'T') {
+ d.qx = d.x * 2 - d.qx;
+ d.qy = d.y * 2 - d.qy;
+ } else {
+ d.qx = d.x;
+ d.qy = d.y;
+ }
+ path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
+ break;
+ case 'Q':
+ d.qx = path[1];
+ d.qy = path[2];
+ path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
+
+ break;
+ case 'L':
+ path = ['C'].concat(l2c(d.x, d.y, path[1], path[2]));
+ break;
+ case 'H':
+ path = ['C'].concat(l2c(d.x, d.y, path[1], d.y));
+ break;
+ case 'V':
+ path = ['C'].concat(l2c(d.x, d.y, d.x, path[1]));
+ break;
+ case 'Z':
+ path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y));
+ break;
+ }
+
+ return path;
+ },
+ fixArc = function fixArc(pp, i) {
+ if (pp[i].length > 7) {
+ pp[i].shift();
+ var pi = pp[i];
+ while (pi.length) {
+ pcoms1[i] = 'A';
+ if (p2) {
+ pcoms2[i] = 'A';
+ }
+ pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6)));
+ }
+ pp.splice(i, 1);
+ ii = Math.max(p.length, (p2 && p2.length) || 0);
+ }
+ },
+ fixM = function fixM(path1, path2, a1, a2, i) {
+ if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') {
+ path2.splice(i, 0, ['M', a2.x, a2.y]);
+ a1.bx = 0;
+ a1.by = 0;
+ a1.x = path1[i][1];
+ a1.y = path1[i][2];
+ ii = Math.max(p.length, (p2 && p2.length) || 0);
+ }
+ };
+
+ var pfirst = ''; // temporary holder for original path command
+ var pcom = ''; // holder for previous path command of original path
+
+ ii = Math.max(p.length, (p2 && p2.length) || 0);
+ for (var i = 0; i < ii; i++) {
+ if (p[i]) {
+ pfirst = p[i][0];
+ } // save current path command
+
+ if (pfirst !== 'C') {
+ pcoms1[i] = pfirst; // Save current path command
+ if (i) {
+ pcom = pcoms1[i - 1];
+ } // Get previous path command pcom
+ }
+ p[i] = processPath(p[i], attrs, pcom);
+
+ if (pcoms1[i] !== 'A' && pfirst === 'C') {
+ pcoms1[i] = 'C';
+ }
+
+ fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1
+
+ if (p2) {
+ // the same procedures is done to p2
+ if (p2[i]) {
+ pfirst = p2[i][0];
+ }
+ if (pfirst !== 'C') {
+ pcoms2[i] = pfirst;
+ if (i) {
+ pcom = pcoms2[i - 1];
+ }
+ }
+ p2[i] = processPath(p2[i], attrs2, pcom);
+
+ if (pcoms2[i] !== 'A' && pfirst === 'C') {
+ pcoms2[i] = 'C';
+ }
+
+ fixArc(p2, i);
+ }
+ fixM(p, p2, attrs, attrs2, i);
+ fixM(p2, p, attrs2, attrs, i);
+ var seg = p[i],
+ seg2 = p2 && p2[i],
+ seglen = seg.length,
+ seg2len = p2 && seg2.length;
+ attrs.x = seg[seglen - 2];
+ attrs.y = seg[seglen - 1];
+ attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x;
+ attrs.by = parseFloat(seg[seglen - 3]) || attrs.y;
+ attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x);
+ attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y);
+ attrs2.x = p2 && seg2[seg2len - 2];
+ attrs2.y = p2 && seg2[seg2len - 1];
+ }
+
+ return p2 ? [p, p2] : p;
+ }
+
+ function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) {
+ // for more information of where this Math came from visit:
+ // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
+ var PI = Math.PI;
+
+ var _120 = PI * 120 / 180;
+ var f1;
+ var f2;
+ var cx;
+ var cy;
+ var rad = PI / 180 * (+angle || 0);
+ var res = [];
+ var xy;
+
+ var rotate = function rotate(x, y, rad) {
+ var X = x * Math.cos(rad) - y * Math.sin(rad),
+ Y = x * Math.sin(rad) + y * Math.cos(rad);
+ return { x: X, y: Y };
+ };
+
+ if (!recursive) {
+ xy = rotate(x1, y1, -rad);
+ x1 = xy.x;
+ y1 = xy.y;
+ xy = rotate(x2, y2, -rad);
+ x2 = xy.x;
+ y2 = xy.y;
+ var x = (x1 - x2) / 2;
+ var y = (y1 - y2) / 2;
+ var h = x * x / (rx * rx) + y * y / (ry * ry);
+ if (h > 1) {
+ h = Math.sqrt(h);
+ rx = h * rx;
+ ry = h * ry;
+ }
+ var rx2 = rx * rx,
+ ry2 = ry * ry;
+ var k =
+ (lac === sweep_flag ? -1 : 1) *
+ Math.sqrt(
+ Math.abs(
+ (rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)
+ )
+ );
+
+ cx = k * rx * y / ry + (x1 + x2) / 2;
+ cy = k * -ry * x / rx + (y1 + y2) / 2;
+ f1 = Math.asin(((y1 - cy) / ry).toFixed(9));
+ f2 = Math.asin(((y2 - cy) / ry).toFixed(9));
+
+ f1 = x1 < cx ? PI - f1 : f1;
+ f2 = x2 < cx ? PI - f2 : f2;
+
+ if (f1 < 0) {
+ f1 = PI * 2 + f1;
+ }
+ if (f2 < 0) {
+ f2 = PI * 2 + f2;
+ }
+
+ if (sweep_flag && f1 > f2) {
+ f1 = f1 - PI * 2;
+ }
+ if (!sweep_flag && f2 > f1) {
+ f2 = f2 - PI * 2;
+ }
+ } else {
+ f1 = recursive[0];
+ f2 = recursive[1];
+ cx = recursive[2];
+ cy = recursive[3];
+ }
+ var df = f2 - f1;
+ if (Math.abs(df) > _120) {
+ var f2old = f2,
+ x2old = x2,
+ y2old = y2;
+ f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
+ x2 = cx + rx * Math.cos(f2);
+ y2 = cy + ry * Math.sin(f2);
+ res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [
+ f2,
+ f2old,
+ cx,
+ cy
+ ]);
+ }
+ df = f2 - f1;
+ var c1 = Math.cos(f1),
+ s1 = Math.sin(f1),
+ c2 = Math.cos(f2),
+ s2 = Math.sin(f2),
+ t = Math.tan(df / 4),
+ hx = 4 / 3 * rx * t,
+ hy = 4 / 3 * ry * t,
+ m1 = [x1, y1],
+ m2 = [x1 + hx * s1, y1 - hy * c1],
+ m3 = [x2 + hx * s2, y2 - hy * c2],
+ m4 = [x2, y2];
+ m2[0] = 2 * m1[0] - m2[0];
+ m2[1] = 2 * m1[1] - m2[1];
+ if (recursive) {
+ return [m2, m3, m4].concat(res);
+ } else {
+ res = [m2, m3, m4]
+ .concat(res)
+ .join()
+ .split(',');
+ var newres = [];
+ for (var i = 0, ii = res.length; i < ii; i++) {
+ newres[i] =
+ i % 2
+ ? rotate(res[i - 1], res[i], rad).y
+ : rotate(res[i], res[i + 1], rad).x;
+ }
+ return newres;
+ }
+ }
+
+ // http://schepers.cc/getting-to-the-point
+ function catmullRom2bezier(crp, z) {
+ var d = [];
+ for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
+ var p = [
+ {
+ x: +crp[i - 2],
+ y: +crp[i - 1]
+ },
+
+ {
+ x: +crp[i],
+ y: +crp[i + 1]
+ },
+
+ {
+ x: +crp[i + 2],
+ y: +crp[i + 3]
+ },
+
+ {
+ x: +crp[i + 4],
+ y: +crp[i + 5]
+ }
+ ];
+
+ if (z) {
+ if (!i) {
+ p[0] = {
+ x: +crp[iLen - 2],
+ y: +crp[iLen - 1]
+ };
+ } else if (iLen - 4 === i) {
+ p[3] = {
+ x: +crp[0],
+ y: +crp[1]
+ };
+ } else if (iLen - 2 === i) {
+ p[2] = {
+ x: +crp[0],
+ y: +crp[1]
+ };
+
+ p[3] = {
+ x: +crp[2],
+ y: +crp[3]
+ };
+ }
+ } else {
+ if (iLen - 4 === i) {
+ p[3] = p[2];
+ } else if (!i) {
+ p[0] = {
+ x: +crp[i],
+ y: +crp[i + 1]
+ };
+ }
+ }
+ d.push([
+ 'C',
+ (-p[0].x + 6 * p[1].x + p[2].x) / 6,
+ (-p[0].y + 6 * p[1].y + p[2].y) / 6,
+ (p[1].x + 6 * p[2].x - p[3].x) / 6,
+ (p[1].y + 6 * p[2].y - p[3].y) / 6,
+ p[2].x,
+ p[2].y
+ ]);
+ }
+
+ return d;
+ }
+
+ function l2c(x1, y1, x2, y2) {
+ return [x1, y1, x2, y2, x2, y2];
+ }
+
+ function q2c(x1, y1, ax, ay, x2, y2) {
+ var _13 = 1 / 3,
+ _23 = 2 / 3;
+ return [
+ _13 * x1 + _23 * ax,
+ _13 * y1 + _23 * ay,
+ _13 * x2 + _23 * ax,
+ _13 * y2 + _23 * ay,
+ x2,
+ y2
+ ];
+ }
+
+ function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
+ if (z == null) {
+ z = 1;
+ }
+ z = z > 1 ? 1 : z < 0 ? 0 : z;
+ var z2 = z / 2;
+ var n = 12;
+ var Tvalues = [
+ -0.1252,
+ 0.1252,
+ -0.3678,
+ 0.3678,
+ -0.5873,
+ 0.5873,
+ -0.7699,
+ 0.7699,
+ -0.9041,
+ 0.9041,
+ -0.9816,
+ 0.9816
+ ];
+
+ var sum = 0;
+ var Cvalues = [
+ 0.2491,
+ 0.2491,
+ 0.2335,
+ 0.2335,
+ 0.2032,
+ 0.2032,
+ 0.1601,
+ 0.1601,
+ 0.1069,
+ 0.1069,
+ 0.0472,
+ 0.0472
+ ];
+
+ for (var i = 0; i < n; i++) {
+ var ct = z2 * Tvalues[i] + z2,
+ xbase = base3(ct, x1, x2, x3, x4),
+ ybase = base3(ct, y1, y2, y3, y4),
+ comb = xbase * xbase + ybase * ybase;
+ sum += Cvalues[i] * Math.sqrt(comb);
+ }
+ return z2 * sum;
+ }
+
+ function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) {
+ if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
+ return;
+ }
+ var t = 1;
+ var step = t / 2;
+ var t2 = t - step;
+ var l;
+ var e = 0.01;
+ l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
+ while (Math.abs(l - ll) > e) {
+ step /= 2;
+ t2 += (l < ll ? 1 : -1) * step;
+ l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
+ }
+ return t2;
+ }
+
+ function base3(t, p1, p2, p3, p4) {
+ var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
+ t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
+ return t * t2 - 3 * p1 + 3 * p2;
+ }
+
+ function cacheKey() {
+ var hash = '';
+ for (var i = arguments.length - 1; i >= 0; --i) {
+ hash += '\uFF1F'.concat(
+ i < 0 || arguments.length <= i ? undefined : arguments[i]
+ );
+ }
+ return hash;
+ }
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 66: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Data
+ * @submodule Array Functions
+ * @for p5
+ * @requires core
+ */ /**
+ * Adds a value to the end of an array. Extends the length of
+ * the array by one. Maps to Array.push().
+ *
+ * @method append
+ * @deprecated Use array.push(value) instead.
+ * @param {Array} array Array to append
+ * @param {any} value to be added to the Array
+ * @return {Array} the array that was appended to
+ * @example
+ *
+ * function setup() {
+ * let myArray = ['Mango', 'Apple', 'Papaya'];
+ * print(myArray); // ['Mango', 'Apple', 'Papaya']
+ *
+ * append(myArray, 'Peach');
+ * print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']
+ * }
+ *
+ */ _main.default.prototype.append = function(array, value) {
+ array.push(value);
+ return array;
+ };
+
+ /**
+ * Copies an array (or part of an array) to another array. The src array is
+ * copied to the dst array, beginning at the position specified by
+ * srcPosition and into the position specified by dstPosition. The number of
+ * elements to copy is determined by length. Note that copying values
+ * overwrites existing values in the destination array. To append values
+ * instead of overwriting them, use concat().
+ *
+ * The simplified version with only two arguments, arrayCopy(src, dst),
+ * copies an entire array to another of the same size. It is equivalent to
+ * arrayCopy(src, 0, dst, 0, src.length).
+ *
+ * Using this function is far more efficient for copying array data than
+ * iterating through a for() loop and copying each element individually.
+ *
+ * @method arrayCopy
+ * @deprecated
+ * @param {Array} src the source Array
+ * @param {Integer} srcPosition starting position in the source Array
+ * @param {Array} dst the destination Array
+ * @param {Integer} dstPosition starting position in the destination Array
+ * @param {Integer} length number of Array elements to be copied
+ *
+ * @example
+ *
+ * let src = ['A', 'B', 'C'];
+ * let dst = [1, 2, 3];
+ * let srcPosition = 1;
+ * let dstPosition = 0;
+ * let length = 2;
+ *
+ * print(src); // ['A', 'B', 'C']
+ * print(dst); // [ 1 , 2 , 3 ]
+ *
+ * arrayCopy(src, srcPosition, dst, dstPosition, length);
+ * print(dst); // ['B', 'C', 3]
+ *
+ */
+ /**
+ * @method arrayCopy
+ * @deprecated Use arr1.copyWithin(arr2) instead.
+ * @param {Array} src
+ * @param {Array} dst
+ * @param {Integer} [length]
+ */
+ _main.default.prototype.arrayCopy = function(
+ src,
+ srcPosition,
+ dst,
+ dstPosition,
+ length
+ ) {
+ // the index to begin splicing from dst array
+ var start;
+ var end;
+
+ if (typeof length !== 'undefined') {
+ end = Math.min(length, src.length);
+ start = dstPosition;
+ src = src.slice(srcPosition, end + srcPosition);
+ } else {
+ if (typeof dst !== 'undefined') {
+ // src, dst, length
+ // rename so we don't get confused
+ end = dst;
+ end = Math.min(end, src.length);
+ } else {
+ // src, dst
+ end = src.length;
+ }
+
+ start = 0;
+ // rename so we don't get confused
+ dst = srcPosition;
+ src = src.slice(0, end);
+ }
+
+ // Since we are not returning the array and JavaScript is pass by reference
+ // we must modify the actual values of the array
+ // instead of reassigning arrays
+ Array.prototype.splice.apply(dst, [start, end].concat(src));
+ };
+
+ /**
+ * Concatenates two arrays, maps to Array.concat(). Does not modify the
+ * input arrays.
+ *
+ * @method concat
+ * @deprecated Use arr1.concat(arr2) instead.
+ * @param {Array} a first Array to concatenate
+ * @param {Array} b second Array to concatenate
+ * @return {Array} concatenated array
+ *
+ * @example
+ *
+ * function setup() {
+ * let arr1 = ['A', 'B', 'C'];
+ * let arr2 = [1, 2, 3];
+ *
+ * print(arr1); // ['A','B','C']
+ * print(arr2); // [1,2,3]
+ *
+ * let arr3 = concat(arr1, arr2);
+ *
+ * print(arr1); // ['A','B','C']
+ * print(arr2); // [1, 2, 3]
+ * print(arr3); // ['A','B','C', 1, 2, 3]
+ * }
+ *
+ */
+ _main.default.prototype.concat = function(list0, list1) {
+ return list0.concat(list1);
+ };
+
+ /**
+ * Reverses the order of an array, maps to Array.reverse()
+ *
+ * @method reverse
+ * @deprecated Use array.reverse() instead.
+ * @param {Array} list Array to reverse
+ * @return {Array} the reversed list
+ * @example
+ *
+ * function setup() {
+ * let myArray = ['A', 'B', 'C'];
+ * print(myArray); // ['A','B','C']
+ *
+ * reverse(myArray);
+ * print(myArray); // ['C','B','A']
+ * }
+ *
+ */
+ _main.default.prototype.reverse = function(list) {
+ return list.reverse();
+ };
+
+ /**
+ * Decreases an array by one element and returns the shortened array,
+ * maps to Array.pop().
+ *
+ * @method shorten
+ * @deprecated Use array.pop() instead.
+ * @param {Array} list Array to shorten
+ * @return {Array} shortened Array
+ * @example
+ *
+ * function setup() {
+ * let myArray = ['A', 'B', 'C'];
+ * print(myArray); // ['A', 'B', 'C']
+ * let newArray = shorten(myArray);
+ * print(myArray); // ['A','B','C']
+ * print(newArray); // ['A','B']
+ * }
+ *
+ */
+ _main.default.prototype.shorten = function(list) {
+ list.pop();
+ return list;
+ };
+
+ /**
+ * Randomizes the order of the elements of an array. Implements
+ *
+ * Fisher-Yates Shuffle Algorithm.
+ *
+ * @method shuffle
+ * @param {Array} array Array to shuffle
+ * @param {Boolean} [bool] modify passed array
+ * @return {Array} shuffled Array
+ * @example
+ *
+ * function setup() {
+ * let regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
+ * print(regularArr);
+ * shuffle(regularArr, true); // force modifications to passed array
+ * print(regularArr);
+ *
+ * // By default shuffle() returns a shuffled cloned array:
+ * let newArr = shuffle(regularArr);
+ * print(regularArr);
+ * print(newArr);
+ * }
+ *
+ */
+ _main.default.prototype.shuffle = function(arr, bool) {
+ var isView = ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(arr);
+ arr = bool || isView ? arr : arr.slice();
+
+ var rnd,
+ tmp,
+ idx = arr.length;
+ while (idx > 1) {
+ rnd = (Math.random() * idx) | 0;
+
+ tmp = arr[--idx];
+ arr[idx] = arr[rnd];
+ arr[rnd] = tmp;
+ }
+
+ return arr;
+ };
+
+ /**
+ * Sorts an array of numbers from smallest to largest, or puts an array of
+ * words in alphabetical order. The original array is not modified; a
+ * re-ordered array is returned. The count parameter states the number of
+ * elements to sort. For example, if there are 12 elements in an array and
+ * count is set to 5, only the first 5 elements in the array will be sorted.
+ *
+ * @method sort
+ * @deprecated Use array.sort() instead.
+ * @param {Array} list Array to sort
+ * @param {Integer} [count] number of elements to sort, starting from 0
+ * @return {Array} the sorted list
+ *
+ * @example
+ *
+ * function setup() {
+ * let words = ['banana', 'apple', 'pear', 'lime'];
+ * print(words); // ['banana', 'apple', 'pear', 'lime']
+ * let count = 4; // length of array
+ *
+ * words = sort(words, count);
+ * print(words); // ['apple', 'banana', 'lime', 'pear']
+ * }
+ *
+ *
+ * function setup() {
+ * let numbers = [2, 6, 1, 5, 14, 9, 8, 12];
+ * print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]
+ * let count = 5; // Less than the length of the array
+ *
+ * numbers = sort(numbers, count);
+ * print(numbers); // [1,2,5,6,14,9,8,12]
+ * }
+ *
+ */
+ _main.default.prototype.sort = function(list, count) {
+ var arr = count ? list.slice(0, Math.min(count, list.length)) : list;
+ var rest = count ? list.slice(Math.min(count, list.length)) : [];
+ if (typeof arr[0] === 'string') {
+ arr = arr.sort();
+ } else {
+ arr = arr.sort(function(a, b) {
+ return a - b;
+ });
+ }
+ return arr.concat(rest);
+ };
+
+ /**
+ * Inserts a value or an array of values into an existing array. The first
+ * parameter specifies the initial array to be modified, and the second
+ * parameter defines the data to be inserted. The third parameter is an index
+ * value which specifies the array position from which to insert data.
+ * (Remember that array index numbering starts at zero, so the first position
+ * is 0, the second position is 1, and so on.)
+ *
+ * @method splice
+ * @deprecated Use array.splice() instead.
+ * @param {Array} list Array to splice into
+ * @param {any} value value to be spliced in
+ * @param {Integer} position in the array from which to insert data
+ * @return {Array} the list
+ *
+ * @example
+ *
+ * function setup() {
+ * let myArray = [0, 1, 2, 3, 4];
+ * let insArray = ['A', 'B', 'C'];
+ * print(myArray); // [0, 1, 2, 3, 4]
+ * print(insArray); // ['A','B','C']
+ *
+ * splice(myArray, insArray, 3);
+ * print(myArray); // [0,1,2,'A','B','C',3,4]
+ * }
+ *
+ */
+ _main.default.prototype.splice = function(list, value, index) {
+ // note that splice returns spliced elements and not an array
+ Array.prototype.splice.apply(list, [index, 0].concat(value));
+
+ return list;
+ };
+
+ /**
+ * Extracts an array of elements from an existing array. The list parameter
+ * defines the array from which the elements will be copied, and the start
+ * and count parameters specify which elements to extract. If no count is
+ * given, elements will be extracted from the start to the end of the array.
+ * When specifying the start, remember that the first array element is 0.
+ * This function does not change the source array.
+ *
+ * @method subset
+ * @deprecated Use array.slice() instead.
+ * @param {Array} list Array to extract from
+ * @param {Integer} start position to begin
+ * @param {Integer} [count] number of values to extract
+ * @return {Array} Array of extracted elements
+ *
+ * @example
+ *
+ * function setup() {
+ * let myArray = [1, 2, 3, 4, 5];
+ * print(myArray); // [1, 2, 3, 4, 5]
+ *
+ * let sub1 = subset(myArray, 0, 3);
+ * let sub2 = subset(myArray, 2, 2);
+ * print(sub1); // [1,2,3]
+ * print(sub2); // [3,4]
+ * }
+ *
+ */
+ _main.default.prototype.subset = function(list, start, count) {
+ if (typeof count !== 'undefined') {
+ return list.slice(start, start + count);
+ } else {
+ return list.slice(start, list.length);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 67: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Data
+ * @submodule Conversion
+ * @for p5
+ * @requires core
+ */ /**
+ * Converts a string to its floating point representation. The contents of a
+ * string must resemble a number, or NaN (not a number) will be returned.
+ * For example, float("1234.56") evaluates to 1234.56, but float("giraffe")
+ * will return NaN.
+ *
+ * When an array of values is passed in, then an array of floats of the same
+ * length is returned.
+ *
+ * @method float
+ * @param {String} str float string to parse
+ * @return {Number} floating point representation of string
+ * @example
+ *
+ * let str = '20';
+ * let diameter = float(str);
+ * ellipse(width / 2, height / 2, diameter, diameter);
+ *
+ *
+ * print(float('10.31')); // 10.31
+ * print(float('Infinity')); // Infinity
+ * print(float('-Infinity')); // -Infinity
+ *
+ *
+ * @alt
+ * 20 by 20 white ellipse in the center of the canvas
+ *
+ */ _main.default.prototype.float = function(str) {
+ if (str instanceof Array) {
+ return str.map(parseFloat);
+ }
+ return parseFloat(str);
+ };
+
+ /**
+ * Converts a boolean, string, or float to its integer representation.
+ * When an array of values is passed in, then an int array of the same length
+ * is returned.
+ *
+ * @method int
+ * @param {String|Boolean|Number} n value to parse
+ * @param {Integer} [radix] the radix to convert to (default: 10)
+ * @return {Number} integer representation of value
+ *
+ * @example
+ *
+ * print(int('10')); // 10
+ * print(int(10.31)); // 10
+ * print(int(-10)); // -10
+ * print(int(true)); // 1
+ * print(int(false)); // 0
+ * print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]
+ * print(int(Infinity)); // Infinity
+ * print(int('-Infinity')); // -Infinity
+ *
+ */
+ /**
+ * @method int
+ * @param {Array} ns values to parse
+ * @return {Number[]} integer representation of values
+ */
+ _main.default.prototype.int = function(n) {
+ var radix =
+ arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
+ if (n === Infinity || n === 'Infinity') {
+ return Infinity;
+ } else if (n === -Infinity || n === '-Infinity') {
+ return -Infinity;
+ } else if (typeof n === 'string') {
+ return parseInt(n, radix);
+ } else if (typeof n === 'number') {
+ return n | 0;
+ } else if (typeof n === 'boolean') {
+ return n ? 1 : 0;
+ } else if (n instanceof Array) {
+ return n.map(function(n) {
+ return _main.default.prototype.int(n, radix);
+ });
+ }
+ };
+
+ /**
+ * Converts a boolean, string or number to its string representation.
+ * When an array of values is passed in, then an array of strings of the same
+ * length is returned.
+ *
+ * @method str
+ * @param {String|Boolean|Number|Array} n value to parse
+ * @return {String} string representation of value
+ * @example
+ *
+ * print(str('10')); // "10"
+ * print(str(10.31)); // "10.31"
+ * print(str(-10)); // "-10"
+ * print(str(true)); // "true"
+ * print(str(false)); // "false"
+ * print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ]
+ *
+ */
+ _main.default.prototype.str = function(n) {
+ if (n instanceof Array) {
+ return n.map(_main.default.prototype.str);
+ } else {
+ return String(n);
+ }
+ };
+
+ /**
+ * Converts a number or string to its boolean representation.
+ * For a number, any non-zero value (positive or negative) evaluates to true,
+ * while zero evaluates to false. For a string, the value "true" evaluates to
+ * true, while any other value evaluates to false. When an array of number or
+ * string values is passed in, then a array of booleans of the same length is
+ * returned.
+ *
+ * @method boolean
+ * @param {String|Boolean|Number|Array} n value to parse
+ * @return {Boolean} boolean representation of value
+ * @example
+ *
+ * print(boolean(0)); // false
+ * print(boolean(1)); // true
+ * print(boolean('true')); // true
+ * print(boolean('abcd')); // false
+ * print(boolean([0, 12, 'true'])); // [false, true, true]
+ *
+ */
+ _main.default.prototype.boolean = function(n) {
+ if (typeof n === 'number') {
+ return n !== 0;
+ } else if (typeof n === 'string') {
+ return n.toLowerCase() === 'true';
+ } else if (typeof n === 'boolean') {
+ return n;
+ } else if (n instanceof Array) {
+ return n.map(_main.default.prototype.boolean);
+ }
+ };
+
+ /**
+ * Converts a number, string representation of a number, or boolean to its byte
+ * representation. A byte can be only a whole number between -128 and 127, so
+ * when a value outside of this range is converted, it wraps around to the
+ * corresponding byte representation. When an array of number, string or boolean
+ * values is passed in, then an array of bytes the same length is returned.
+ *
+ * @method byte
+ * @param {String|Boolean|Number} n value to parse
+ * @return {Number} byte representation of value
+ *
+ * @example
+ *
+ * print(byte(127)); // 127
+ * print(byte(128)); // -128
+ * print(byte(23.4)); // 23
+ * print(byte('23.4')); // 23
+ * print(byte('hello')); // NaN
+ * print(byte(true)); // 1
+ * print(byte([0, 255, '100'])); // [0, -1, 100]
+ *
+ */
+ /**
+ * @method byte
+ * @param {Array} ns values to parse
+ * @return {Number[]} array of byte representation of values
+ */
+ _main.default.prototype.byte = function(n) {
+ var nn = _main.default.prototype.int(n, 10);
+ if (typeof nn === 'number') {
+ return (nn + 128) % 256 - 128;
+ } else if (nn instanceof Array) {
+ return nn.map(_main.default.prototype.byte);
+ }
+ };
+
+ /**
+ * Converts a number or string to its corresponding single-character
+ * string representation. If a string parameter is provided, it is first
+ * parsed as an integer and then translated into a single-character string.
+ * When an array of number or string values is passed in, then an array of
+ * single-character strings of the same length is returned.
+ *
+ * @method char
+ * @param {String|Number} n value to parse
+ * @return {String} string representation of value
+ *
+ * @example
+ *
+ * print(char(65)); // "A"
+ * print(char('65')); // "A"
+ * print(char([65, 66, 67])); // [ "A", "B", "C" ]
+ * print(join(char([65, 66, 67]), '')); // "ABC"
+ *
+ */
+ /**
+ * @method char
+ * @param {Array} ns values to parse
+ * @return {String[]} array of string representation of values
+ */
+ _main.default.prototype.char = function(n) {
+ if (typeof n === 'number' && !isNaN(n)) {
+ return String.fromCharCode(n);
+ } else if (n instanceof Array) {
+ return n.map(_main.default.prototype.char);
+ } else if (typeof n === 'string') {
+ return _main.default.prototype.char(parseInt(n, 10));
+ }
+ };
+
+ /**
+ * Converts a single-character string to its corresponding integer
+ * representation. When an array of single-character string values is passed
+ * in, then an array of integers of the same length is returned.
+ *
+ * @method unchar
+ * @param {String} n value to parse
+ * @return {Number} integer representation of value
+ *
+ * @example
+ *
+ * print(unchar('A')); // 65
+ * print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]
+ * print(unchar(split('ABC', ''))); // [ 65, 66, 67 ]
+ *
+ */
+ /**
+ * @method unchar
+ * @param {Array} ns values to parse
+ * @return {Number[]} integer representation of values
+ */
+ _main.default.prototype.unchar = function(n) {
+ if (typeof n === 'string' && n.length === 1) {
+ return n.charCodeAt(0);
+ } else if (n instanceof Array) {
+ return n.map(_main.default.prototype.unchar);
+ }
+ };
+
+ /**
+ * Converts a number to a string in its equivalent hexadecimal notation. If a
+ * second parameter is passed, it is used to set the number of characters to
+ * generate in the hexadecimal notation. When an array is passed in, an
+ * array of strings in hexadecimal notation of the same length is returned.
+ *
+ * @method hex
+ * @param {Number} n value to parse
+ * @param {Number} [digits]
+ * @return {String} hexadecimal string representation of value
+ *
+ * @example
+ *
+ * print(hex(255)); // "000000FF"
+ * print(hex(255, 6)); // "0000FF"
+ * print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]
+ * print(Infinity); // "FFFFFFFF"
+ * print(-Infinity); // "00000000"
+ *
+ */
+ /**
+ * @method hex
+ * @param {Number[]} ns array of values to parse
+ * @param {Number} [digits]
+ * @return {String[]} hexadecimal string representation of values
+ */
+ _main.default.prototype.hex = function(n, digits) {
+ digits = digits === undefined || digits === null ? (digits = 8) : digits;
+ if (n instanceof Array) {
+ return n.map(function(n) {
+ return _main.default.prototype.hex(n, digits);
+ });
+ } else if (n === Infinity || n === -Infinity) {
+ var c = n === Infinity ? 'F' : '0';
+ return c.repeat(digits);
+ } else if (typeof n === 'number') {
+ if (n < 0) {
+ n = 0xffffffff + n + 1;
+ }
+ var hex = Number(n)
+ .toString(16)
+ .toUpperCase();
+ while (hex.length < digits) {
+ hex = '0'.concat(hex);
+ }
+ if (hex.length >= digits) {
+ hex = hex.substring(hex.length - digits, hex.length);
+ }
+ return hex;
+ }
+ };
+
+ /**
+ * Converts a string representation of a hexadecimal number to its equivalent
+ * integer value. When an array of strings in hexadecimal notation is passed
+ * in, an array of integers of the same length is returned.
+ *
+ * @method unhex
+ * @param {String} n value to parse
+ * @return {Number} integer representation of hexadecimal value
+ *
+ * @example
+ *
+ * print(unhex('A')); // 10
+ * print(unhex('FF')); // 255
+ * print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]
+ *
+ */
+ /**
+ * @method unhex
+ * @param {Array} ns values to parse
+ * @return {Number[]} integer representations of hexadecimal value
+ */
+ _main.default.prototype.unhex = function(n) {
+ if (n instanceof Array) {
+ return n.map(_main.default.prototype.unhex);
+ } else {
+ return parseInt('0x'.concat(n), 16);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 68: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ _dereq_('../core/error_helpers');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /** //return p5; //LM is this a mistake?
+ * @module Data
+ * @submodule String Functions
+ * @for p5
+ * @requires core
+ */
+ /**
+ * Combines an array of Strings into one String, each separated by the
+ * character(s) used for the separator parameter. To join arrays of ints or
+ * floats, it's necessary to first convert them to Strings using nf() or
+ * nfs().
+ *
+ * @method join
+ * @param {Array} list array of Strings to be joined
+ * @param {String} separator String to be placed between each item
+ * @return {String} joined String
+ * @example
+ *
+ *
+ * let array = ['Hello', 'world!'];
+ * let separator = ' ';
+ * let message = join(array, separator);
+ * text(message, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * "hello world!" displayed middle left of canvas.
+ *
+ */ _main.default.prototype.join = function(list, separator) {
+ _main.default._validateParameters('join', arguments);
+ return list.join(separator);
+ };
+
+ /**
+ * This function is used to apply a regular expression to a piece of text,
+ * and return matching groups (elements found inside parentheses) as a
+ * String array. If there are no matches, a null value will be returned.
+ * If no groups are specified in the regular expression, but the sequence
+ * matches, an array of length 1 (with the matched text as the first element
+ * of the array) will be returned.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, an array is returned.
+ *
+ * If there are groups (specified by sets of parentheses) in the regular
+ * expression, then the contents of each will be returned in the array.
+ * Element [0] of a regular expression match returns the entire matching
+ * string, and the match groups start at element [1] (the first group is [1],
+ * the second [2], and so on).
+ *
+ * @method match
+ * @param {String} str the String to be searched
+ * @param {String} regexp the regexp to be used for matching
+ * @return {String[]} Array of Strings found
+ * @example
+ *
+ *
+ * let string = 'Hello p5js*!';
+ * let regexp = 'p5js\\*';
+ * let m = match(string, regexp);
+ * text(m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * "p5js*" displayed middle left of canvas.
+ *
+ */
+ _main.default.prototype.match = function(str, reg) {
+ _main.default._validateParameters('match', arguments);
+ return str.match(reg);
+ };
+
+ /**
+ * This function is used to apply a regular expression to a piece of text,
+ * and return a list of matching groups (elements found inside parentheses)
+ * as a two-dimensional String array. If there are no matches, a null value
+ * will be returned. If no groups are specified in the regular expression,
+ * but the sequence matches, a two dimensional array is still returned, but
+ * the second dimension is only of length one.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, a 2D array is returned.
+ *
+ * If there are groups (specified by sets of parentheses) in the regular
+ * expression, then the contents of each will be returned in the array.
+ * Assuming a loop with counter variable i, element [i][0] of a regular
+ * expression match returns the entire matching string, and the match groups
+ * start at element [i][1] (the first group is [i][1], the second [i][2],
+ * and so on).
+ *
+ * @method matchAll
+ * @param {String} str the String to be searched
+ * @param {String} regexp the regexp to be used for matching
+ * @return {String[]} 2d Array of Strings found
+ * @example
+ *
+ *
+ * let string = 'Hello p5js*! Hello world!';
+ * let regexp = 'Hello';
+ * matchAll(string, regexp);
+ *
+ *
+ */
+ _main.default.prototype.matchAll = function(str, reg) {
+ _main.default._validateParameters('matchAll', arguments);
+ var re = new RegExp(reg, 'g');
+ var match = re.exec(str);
+ var matches = [];
+ while (match !== null) {
+ matches.push(match);
+ // matched text: match[0]
+ // match start: match.index
+ // capturing group n: match[n]
+ match = re.exec(str);
+ }
+ return matches;
+ };
+
+ /**
+ * Utility function for formatting numbers into strings. There are two
+ * versions: one for formatting floats, and one for formatting ints.
+ * The values for the digits, left, and right parameters should always
+ * be positive integers.
+ * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter
+ * if greater than the current length of the number.
+ * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123
+ * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than
+ * the result will be 123.200.
+ *
+ * @method nf
+ * @param {Number|String} num the Number to format
+ * @param {Integer|String} [left] number of digits to the left of the
+ * decimal point
+ * @param {Integer|String} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * let myFont;
+ * function preload() {
+ * myFont = loadFont('assets/fonts/inconsolata.ttf');
+ * }
+ * function setup() {
+ * background(200);
+ * let num1 = 321;
+ * let num2 = -1321;
+ *
+ * noStroke();
+ * fill(0);
+ * textFont(myFont);
+ * textSize(22);
+ *
+ * text(nf(num1, 4, 2), 10, 30);
+ * text(nf(num2, 4, 2), 10, 80);
+ * // Draw dividing line
+ * stroke(120);
+ * line(0, 50, width, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * "0321.00" middle top, -1321.00" middle bottom canvas
+ */
+ /**
+ * @method nf
+ * @param {Array} nums the Numbers to format
+ * @param {Integer|String} [left]
+ * @param {Integer|String} [right]
+ * @return {String[]} formatted Strings
+ */
+ _main.default.prototype.nf = function(nums, left, right) {
+ _main.default._validateParameters('nf', arguments);
+ if (nums instanceof Array) {
+ return nums.map(function(x) {
+ return doNf(x, left, right);
+ });
+ } else {
+ var typeOfFirst = Object.prototype.toString.call(nums);
+ if (typeOfFirst === '[object Arguments]') {
+ if (nums.length === 3) {
+ return this.nf(nums[0], nums[1], nums[2]);
+ } else if (nums.length === 2) {
+ return this.nf(nums[0], nums[1]);
+ } else {
+ return this.nf(nums[0]);
+ }
+ } else {
+ return doNf(nums, left, right);
+ }
+ }
+ };
+
+ function doNf(num, left, right) {
+ var neg = num < 0;
+ var n = neg ? num.toString().substring(1) : num.toString();
+ var decimalInd = n.indexOf('.');
+ var intPart = decimalInd !== -1 ? n.substring(0, decimalInd) : n;
+ var decPart = decimalInd !== -1 ? n.substring(decimalInd + 1) : '';
+ var str = neg ? '-' : '';
+ if (typeof right !== 'undefined') {
+ var decimal = '';
+ if (decimalInd !== -1 || right - decPart.length > 0) {
+ decimal = '.';
+ }
+ if (decPart.length > right) {
+ decPart = decPart.substring(0, right);
+ }
+ for (var i = 0; i < left - intPart.length; i++) {
+ str += '0';
+ }
+ str += intPart;
+ str += decimal;
+ str += decPart;
+ for (var j = 0; j < right - decPart.length; j++) {
+ str += '0';
+ }
+ return str;
+ } else {
+ for (var k = 0; k < Math.max(left - intPart.length, 0); k++) {
+ str += '0';
+ }
+ str += n;
+ return str;
+ }
+ }
+
+ /**
+ * Utility function for formatting numbers into strings and placing
+ * appropriate commas to mark units of 1000. There are two versions: one
+ * for formatting ints, and one for formatting an array of ints. The value
+ * for the right parameter should always be a positive integer.
+ *
+ * @method nfc
+ * @param {Number|String} num the Number to format
+ * @param {Integer|String} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * background(200);
+ * let num = 11253106.115;
+ * let numArr = [1, 1, 2];
+ *
+ * noStroke();
+ * fill(0);
+ * textSize(12);
+ *
+ * // Draw formatted numbers
+ * text(nfc(num, 4), 10, 30);
+ * text(nfc(numArr, 2), 10, 80);
+ *
+ * // Draw dividing line
+ * stroke(120);
+ * line(0, 50, width, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * "11,253,106.115" top middle and "1.00,1.00,2.00" displayed bottom mid
+ */
+ /**
+ * @method nfc
+ * @param {Array} nums the Numbers to format
+ * @param {Integer|String} [right]
+ * @return {String[]} formatted Strings
+ */
+ _main.default.prototype.nfc = function(num, right) {
+ _main.default._validateParameters('nfc', arguments);
+ if (num instanceof Array) {
+ return num.map(function(x) {
+ return doNfc(x, right);
+ });
+ } else {
+ return doNfc(num, right);
+ }
+ };
+ function doNfc(num, right) {
+ num = num.toString();
+ var dec = num.indexOf('.');
+ var rem = dec !== -1 ? num.substring(dec) : '';
+ var n = dec !== -1 ? num.substring(0, dec) : num;
+ n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+ if (right === 0) {
+ rem = '';
+ } else if (typeof right !== 'undefined') {
+ if (right > rem.length) {
+ rem += dec === -1 ? '.' : '';
+ var len = right - rem.length + 1;
+ for (var i = 0; i < len; i++) {
+ rem += '0';
+ }
+ } else {
+ rem = rem.substring(0, right + 1);
+ }
+ }
+ return n + rem;
+ }
+
+ /**
+ * Utility function for formatting numbers into strings. Similar to nf() but
+ * puts a "+" in front of positive numbers and a "-" in front of negative
+ * numbers. There are two versions: one for formatting floats, and one for
+ * formatting ints. The values for left, and right parameters
+ * should always be positive integers.
+ *
+ * @method nfp
+ * @param {Number} num the Number to format
+ * @param {Integer} [left] number of digits to the left of the decimal
+ * point
+ * @param {Integer} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * background(200);
+ * let num1 = 11253106.115;
+ * let num2 = -11253106.115;
+ *
+ * noStroke();
+ * fill(0);
+ * textSize(12);
+ *
+ * // Draw formatted numbers
+ * text(nfp(num1, 4, 2), 10, 30);
+ * text(nfp(num2, 4, 2), 10, 80);
+ *
+ * // Draw dividing line
+ * stroke(120);
+ * line(0, 50, width, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * "+11253106.11" top middle and "-11253106.11" displayed bottom middle
+ */
+ /**
+ * @method nfp
+ * @param {Number[]} nums the Numbers to format
+ * @param {Integer} [left]
+ * @param {Integer} [right]
+ * @return {String[]} formatted Strings
+ */
+ _main.default.prototype.nfp = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('nfp', args);
+ var nfRes = _main.default.prototype.nf.apply(this, args);
+ if (nfRes instanceof Array) {
+ return nfRes.map(addNfp);
+ } else {
+ return addNfp(nfRes);
+ }
+ };
+
+ function addNfp(num) {
+ return parseFloat(num) > 0 ? '+'.concat(num.toString()) : num.toString();
+ }
+
+ /**
+ * Utility function for formatting numbers into strings. Similar to nf() but
+ * puts an additional "_" (space) in front of positive numbers just in case to align it with negative
+ * numbers which includes "-" (minus) sign.
+ * The main usecase of nfs() can be seen when one wants to align the digits (place values) of a non-negative
+ * number with some negative number (See the example to get a clear picture).
+ * There are two versions: one for formatting float, and one for formatting int.
+ * The values for the digits, left, and right parameters should always be positive integers.
+ * (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.
+ * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter
+ * if greater than the current length of the number.
+ * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123
+ * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than
+ * the result will be 123.200.
+ *
+ * @method nfs
+ * @param {Number} num the Number to format
+ * @param {Integer} [left] number of digits to the left of the decimal
+ * point
+ * @param {Integer} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * let myFont;
+ * function preload() {
+ * myFont = loadFont('assets/fonts/inconsolata.ttf');
+ * }
+ * function setup() {
+ * background(200);
+ * let num1 = 321;
+ * let num2 = -1321;
+ *
+ * noStroke();
+ * fill(0);
+ * textFont(myFont);
+ * textSize(22);
+ *
+ * // nfs() aligns num1 (positive number) with num2 (negative number) by
+ * // adding a blank space in front of the num1 (positive number)
+ * // [left = 4] in num1 add one 0 in front, to align the digits with num2
+ * // [right = 2] in num1 and num2 adds two 0's after both numbers
+ * // To see the differences check the example of nf() too.
+ * text(nfs(num1, 4, 2), 10, 30);
+ * text(nfs(num2, 4, 2), 10, 80);
+ * // Draw dividing line
+ * stroke(120);
+ * line(0, 50, width, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * "0321.00" top middle and "-1321.00" displayed bottom middle
+ */
+ /**
+ * @method nfs
+ * @param {Array} nums the Numbers to format
+ * @param {Integer} [left]
+ * @param {Integer} [right]
+ * @return {String[]} formatted Strings
+ */
+ _main.default.prototype.nfs = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('nfs', args);
+ var nfRes = _main.default.prototype.nf.apply(this, args);
+ if (nfRes instanceof Array) {
+ return nfRes.map(addNfs);
+ } else {
+ return addNfs(nfRes);
+ }
+ };
+
+ function addNfs(num) {
+ return parseFloat(num) >= 0 ? ' '.concat(num.toString()) : num.toString();
+ }
+
+ /**
+ * The split() function maps to String.split(), it breaks a String into
+ * pieces using a character or string as the delimiter. The delim parameter
+ * specifies the character or characters that mark the boundaries between
+ * each piece. A String[] array is returned that contains each of the pieces.
+ *
+ * The splitTokens() function works in a similar fashion, except that it
+ * splits using a range of characters instead of a specific character or
+ * sequence.
+ *
+ * @method split
+ * @param {String} value the String to be split
+ * @param {String} delim the String used to separate the data
+ * @return {String[]} Array of Strings
+ * @example
+ *
+ *
+ * let names = 'Pat,Xio,Alex';
+ * let splitString = split(names, ',');
+ * text(splitString[0], 5, 30);
+ * text(splitString[1], 5, 50);
+ * text(splitString[2], 5, 70);
+ *
+ *
+ *
+ * @alt
+ * "pat" top left, "Xio" mid left and "Alex" displayed bottom left
+ *
+ */
+ _main.default.prototype.split = function(str, delim) {
+ _main.default._validateParameters('split', arguments);
+ return str.split(delim);
+ };
+
+ /**
+ * The splitTokens() function splits a String at one or many character
+ * delimiters or "tokens." The delim parameter specifies the character or
+ * characters to be used as a boundary.
+ *
+ * If no delim characters are specified, any whitespace character is used to
+ * split. Whitespace characters include tab (\t), line feed (\n), carriage
+ * return (\r), form feed (\f), and space.
+ *
+ * @method splitTokens
+ * @param {String} value the String to be split
+ * @param {String} [delim] list of individual Strings that will be used as
+ * separators
+ * @return {String[]} Array of Strings
+ * @example
+ *
+ *
+ * function setup() {
+ * let myStr = 'Mango, Banana, Lime';
+ * let myStrArr = splitTokens(myStr, ',');
+ *
+ * print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
+ * }
+ *
+ *
+ */
+ _main.default.prototype.splitTokens = function(value, delims) {
+ _main.default._validateParameters('splitTokens', arguments);
+ var d;
+ if (typeof delims !== 'undefined') {
+ var str = delims;
+ var sqc = /\]/g.exec(str);
+ var sqo = /\[/g.exec(str);
+ if (sqo && sqc) {
+ str = str.slice(0, sqc.index) + str.slice(sqc.index + 1);
+ sqo = /\[/g.exec(str);
+ str = str.slice(0, sqo.index) + str.slice(sqo.index + 1);
+ d = new RegExp('[\\['.concat(str, '\\]]'), 'g');
+ } else if (sqc) {
+ str = str.slice(0, sqc.index) + str.slice(sqc.index + 1);
+ d = new RegExp('['.concat(str, '\\]]'), 'g');
+ } else if (sqo) {
+ str = str.slice(0, sqo.index) + str.slice(sqo.index + 1);
+ d = new RegExp('['.concat(str, '\\[]'), 'g');
+ } else {
+ d = new RegExp('['.concat(str, ']'), 'g');
+ }
+ } else {
+ d = /\s/g;
+ }
+ return value.split(d).filter(function(n) {
+ return n;
+ });
+ };
+
+ /**
+ * Removes whitespace characters from the beginning and end of a String. In
+ * addition to standard whitespace characters such as space, carriage return,
+ * and tab, this function also removes the Unicode "nbsp" character.
+ *
+ * @method trim
+ * @param {String} str a String to be trimmed
+ * @return {String} a trimmed String
+ *
+ * @example
+ *
+ *
+ * let string = trim(' No new lines\n ');
+ * text(string + ' here', 2, 50);
+ *
+ *
+ *
+ * @alt
+ * "No new lines here" displayed center canvas
+ */
+ /**
+ * @method trim
+ * @param {Array} strs an Array of Strings to be trimmed
+ * @return {String[]} an Array of trimmed Strings
+ */
+ _main.default.prototype.trim = function(str) {
+ _main.default._validateParameters('trim', arguments);
+ if (str instanceof Array) {
+ return str.map(this.trim);
+ } else {
+ return str.trim();
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/error_helpers': 23, '../core/main': 27 }
+ ],
+ 69: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module IO
+ * @submodule Time & Date
+ * @for p5
+ * @requires core
+ */ /**
+ * p5.js communicates with the clock on your computer. The day() function
+ * returns the current day as a value from 1 - 31.
+ *
+ * @method day
+ * @return {Integer} the current day
+ * @example
+ *
+ *
+ * let d = day();
+ * text('Current day: \n' + d, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current day is displayed
+ *
+ */ _main.default.prototype.day = function() {
+ return new Date().getDate();
+ }; /**
+ * p5.js communicates with the clock on your computer. The hour() function
+ * returns the current hour as a value from 0 - 23.
+ *
+ * @method hour
+ * @return {Integer} the current hour
+ * @example
+ *
+ *
+ * let h = hour();
+ * text('Current hour:\n' + h, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current hour is displayed
+ *
+ */
+ _main.default.prototype.hour = function() {
+ return new Date().getHours();
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The minute() function
+ * returns the current minute as a value from 0 - 59.
+ *
+ * @method minute
+ * @return {Integer} the current minute
+ * @example
+ *
+ *
+ * let m = minute();
+ * text('Current minute: \n' + m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current minute is displayed
+ *
+ */
+ _main.default.prototype.minute = function() {
+ return new Date().getMinutes();
+ };
+
+ /**
+ * Returns the number of milliseconds (thousandths of a second) since
+ * starting the program. This information is often used for timing events and
+ * animation sequences.
+ *
+ * @method millis
+ * @return {Number} the number of milliseconds since starting the program
+ * @example
+ *
+ *
+ * let millisecond = millis();
+ * text('Milliseconds \nrunning: \n' + millisecond, 5, 40);
+ *
+ *
+ *
+ * @alt
+ * number of milliseconds since program has started displayed
+ *
+ */
+ _main.default.prototype.millis = function() {
+ return window.performance.now();
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The month() function
+ * returns the current month as a value from 1 - 12.
+ *
+ * @method month
+ * @return {Integer} the current month
+ * @example
+ *
+ *
+ * let m = month();
+ * text('Current month: \n' + m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current month is displayed
+ *
+ */
+ _main.default.prototype.month = function() {
+ return (
+ //January is 0!
+ new Date().getMonth() + 1
+ );
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The second() function
+ * returns the current second as a value from 0 - 59.
+ *
+ * @method second
+ * @return {Integer} the current second
+ * @example
+ *
+ *
+ * let s = second();
+ * text('Current second: \n' + s, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current second is displayed
+ *
+ */
+ _main.default.prototype.second = function() {
+ return new Date().getSeconds();
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The year() function
+ * returns the current year as an integer (2014, 2015, 2016, etc).
+ *
+ * @method year
+ * @return {Integer} the current year
+ * @example
+ *
+ *
+ * let y = year();
+ * text('Current year: \n' + y, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current year is displayed
+ *
+ */
+ _main.default.prototype.year = function() {
+ return new Date().getFullYear();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 70: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ _dereq_('./p5.Geometry');
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Shape
+ * @submodule 3D Primitives
+ * @for p5
+ * @requires core
+ * @requires p5.Geometry
+ */ /**
+ * Draw a plane with given a width and height
+ * @method plane
+ * @param {Number} [width] width of the plane
+ * @param {Number} [height] height of the plane
+ * @param {Integer} [detailX] Optional number of triangle
+ * subdivisions in x-dimension
+ * @param {Integer} [detailY] Optional number of triangle
+ * subdivisions in y-dimension
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a plane
+ * // with width 50 and height 50
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * plane(50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Nothing displayed on canvas
+ * Rotating interior view of a box with sides that change color.
+ * 3d red and green gradient.
+ * Rotating interior view of a cylinder with sides that change color.
+ * Rotating view of a cylinder with sides that change color.
+ * 3d red and green gradient.
+ * rotating view of a multi-colored cylinder with concave sides.
+ */ _main.default.prototype.plane = function(width, height, detailX, detailY) {
+ this._assert3d('plane');
+ _main.default._validateParameters('plane', arguments);
+ if (typeof width === 'undefined') {
+ width = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = width;
+ }
+
+ if (typeof detailX === 'undefined') {
+ detailX = 1;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 1;
+ }
+
+ var gId = 'plane|'.concat(detailX, '|').concat(detailY);
+
+ if (!this._renderer.geometryInHash(gId)) {
+ var _plane = function _plane() {
+ var u, v, p;
+ for (var i = 0; i <= this.detailY; i++) {
+ v = i / this.detailY;
+ for (var j = 0; j <= this.detailX; j++) {
+ u = j / this.detailX;
+ p = new _main.default.Vector(u - 0.5, v - 0.5, 0);
+ this.vertices.push(p);
+ this.uvs.push(u, v);
+ }
+ }
+ };
+ var planeGeom = new _main.default.Geometry(detailX, detailY, _plane);
+ planeGeom.computeFaces().computeNormals();
+ if (detailX <= 1 && detailY <= 1) {
+ planeGeom._makeTriangleEdges()._edgesToVertices();
+ } else {
+ console.log(
+ 'Cannot draw stroke on plane objects with more' +
+ ' than 1 detailX or 1 detailY'
+ );
+ }
+ this._renderer.createBuffers(gId, planeGeom);
+ }
+
+ this._renderer.drawBuffersScaled(gId, width, height, 1);
+ return this;
+ };
+
+ /**
+ * Draw a box with given width, height and depth
+ * @method box
+ * @param {Number} [width] width of the box
+ * @param {Number} [Height] height of the box
+ * @param {Number} [depth] depth of the box
+ * @param {Integer} [detailX] Optional number of triangle
+ * subdivisions in x-dimension
+ * @param {Integer} [detailY] Optional number of triangle
+ * subdivisions in y-dimension
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a spinning box
+ * // with width, height and depth of 50
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(50);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.box = function(width, height, depth, detailX, detailY) {
+ this._assert3d('box');
+ _main.default._validateParameters('box', arguments);
+ if (typeof width === 'undefined') {
+ width = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = width;
+ }
+ if (typeof depth === 'undefined') {
+ depth = height;
+ }
+
+ var perPixelLighting =
+ this._renderer.attributes && this._renderer.attributes.perPixelLighting;
+ if (typeof detailX === 'undefined') {
+ detailX = perPixelLighting ? 1 : 4;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = perPixelLighting ? 1 : 4;
+ }
+
+ var gId = 'box|'.concat(detailX, '|').concat(detailY);
+ if (!this._renderer.geometryInHash(gId)) {
+ var _box = function _box() {
+ var cubeIndices = [
+ [0, 4, 2, 6], // -1, 0, 0],// -x
+ [1, 3, 5, 7], // +1, 0, 0],// +x
+ [0, 1, 4, 5], // 0, -1, 0],// -y
+ [2, 6, 3, 7], // 0, +1, 0],// +y
+ [0, 2, 1, 3], // 0, 0, -1],// -z
+ [4, 5, 6, 7] // 0, 0, +1] // +z
+ ];
+ //using strokeIndices instead of faces for strokes
+ //to avoid diagonal stroke lines across face of box
+ this.strokeIndices = [
+ [0, 1],
+ [1, 3],
+ [3, 2],
+ [6, 7],
+ [8, 9],
+ [9, 11],
+ [14, 15],
+ [16, 17],
+ [17, 19],
+ [18, 19],
+ [20, 21],
+ [22, 23]
+ ];
+
+ for (var i = 0; i < cubeIndices.length; i++) {
+ var cubeIndex = cubeIndices[i];
+ var v = i * 4;
+ for (var j = 0; j < 4; j++) {
+ var d = cubeIndex[j];
+ //inspired by lightgl:
+ //https://github.com/evanw/lightgl.js
+ //octants:https://en.wikipedia.org/wiki/Octant_(solid_geometry)
+ var octant = new _main.default.Vector(
+ ((d & 1) * 2 - 1) / 2,
+ ((d & 2) - 1) / 2,
+ ((d & 4) / 2 - 1) / 2
+ );
+
+ this.vertices.push(octant);
+ this.uvs.push(j & 1, (j & 2) / 2);
+ }
+ this.faces.push([v, v + 1, v + 2]);
+ this.faces.push([v + 2, v + 1, v + 3]);
+ }
+ };
+ var boxGeom = new _main.default.Geometry(detailX, detailY, _box);
+ boxGeom.computeNormals();
+ if (detailX <= 4 && detailY <= 4) {
+ boxGeom._makeTriangleEdges()._edgesToVertices();
+ } else {
+ console.log(
+ 'Cannot draw stroke on box objects with more' +
+ ' than 4 detailX or 4 detailY'
+ );
+ }
+ //initialize our geometry buffer with
+ //the key val pair:
+ //geometry Id, Geom object
+ this._renderer.createBuffers(gId, boxGeom);
+ }
+ this._renderer.drawBuffersScaled(gId, width, height, depth);
+
+ return this;
+ };
+
+ /**
+ * Draw a sphere with given radius.
+ *
+ * DetailX and detailY determines the number of subdivisions in the x-dimension
+ * and the y-dimension of a sphere. More subdivisions make the sphere seem
+ * smoother. The recommended maximum values are both 24. Using a value greater
+ * than 24 may cause a warning or slow down the browser.
+ * @method sphere
+ * @param {Number} [radius] radius of circle
+ * @param {Integer} [detailX] optional number of subdivisions in x-dimension
+ * @param {Integer} [detailY] optional number of subdivisions in y-dimension
+ *
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a sphere with radius 40
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * let detailX;
+ * // slide to see how detailX works
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 24, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * sphere(40, detailX.value(), 16);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * let detailY;
+ * // slide to see how detailY works
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(3, 16, 3);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * sphere(40, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.sphere = function(radius, detailX, detailY) {
+ this._assert3d('sphere');
+ _main.default._validateParameters('sphere', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 16;
+ }
+
+ this.ellipsoid(radius, radius, radius, detailX, detailY);
+
+ return this;
+ };
+
+ /**
+ * @private
+ * Helper function for creating both cones and cylinders
+ * Will only generate well-defined geometry when bottomRadius, height > 0
+ * and topRadius >= 0
+ * If topRadius == 0, topCap should be false
+ */
+ var _truncatedCone = function _truncatedCone(
+ bottomRadius,
+ topRadius,
+ height,
+ detailX,
+ detailY,
+ bottomCap,
+ topCap
+ ) {
+ bottomRadius = bottomRadius <= 0 ? 1 : bottomRadius;
+ topRadius = topRadius < 0 ? 0 : topRadius;
+ height = height <= 0 ? bottomRadius : height;
+ detailX = detailX < 3 ? 3 : detailX;
+ detailY = detailY < 1 ? 1 : detailY;
+ bottomCap = bottomCap === undefined ? true : bottomCap;
+ topCap = topCap === undefined ? topRadius !== 0 : topCap;
+ var start = bottomCap ? -2 : 0;
+ var end = detailY + (topCap ? 2 : 0);
+ //ensure constant slant for interior vertex normals
+ var slant = Math.atan2(bottomRadius - topRadius, height);
+ var sinSlant = Math.sin(slant);
+ var cosSlant = Math.cos(slant);
+ var yy, ii, jj;
+ for (yy = start; yy <= end; ++yy) {
+ var v = yy / detailY;
+ var y = height * v;
+ var ringRadius = void 0;
+ if (yy < 0) {
+ //for the bottomCap edge
+ y = 0;
+ v = 0;
+ ringRadius = bottomRadius;
+ } else if (yy > detailY) {
+ //for the topCap edge
+ y = height;
+ v = 1;
+ ringRadius = topRadius;
+ } else {
+ //for the middle
+ ringRadius = bottomRadius + (topRadius - bottomRadius) * v;
+ }
+ if (yy === -2 || yy === detailY + 2) {
+ //center of bottom or top caps
+ ringRadius = 0;
+ }
+
+ y -= height / 2; //shift coordiate origin to the center of object
+ for (ii = 0; ii < detailX; ++ii) {
+ var u = ii / detailX;
+ var ur = 2 * Math.PI * u;
+ var sur = Math.sin(ur);
+ var cur = Math.cos(ur);
+
+ //VERTICES
+ this.vertices.push(
+ new _main.default.Vector(sur * ringRadius, y, cur * ringRadius)
+ );
+
+ //VERTEX NORMALS
+ var vertexNormal = void 0;
+ if (yy < 0) {
+ vertexNormal = new _main.default.Vector(0, -1, 0);
+ } else if (yy > detailY && topRadius) {
+ vertexNormal = new _main.default.Vector(0, 1, 0);
+ } else {
+ vertexNormal = new _main.default.Vector(
+ sur * cosSlant,
+ sinSlant,
+ cur * cosSlant
+ );
+ }
+ this.vertexNormals.push(vertexNormal);
+ //UVs
+ this.uvs.push(u, v);
+ }
+ }
+
+ var startIndex = 0;
+ if (bottomCap) {
+ for (jj = 0; jj < detailX; ++jj) {
+ var nextjj = (jj + 1) % detailX;
+ this.faces.push([
+ startIndex + jj,
+ startIndex + detailX + nextjj,
+ startIndex + detailX + jj
+ ]);
+ }
+ startIndex += detailX * 2;
+ }
+ for (yy = 0; yy < detailY; ++yy) {
+ for (ii = 0; ii < detailX; ++ii) {
+ var nextii = (ii + 1) % detailX;
+ this.faces.push([
+ startIndex + ii,
+ startIndex + nextii,
+ startIndex + detailX + nextii
+ ]);
+
+ this.faces.push([
+ startIndex + ii,
+ startIndex + detailX + nextii,
+ startIndex + detailX + ii
+ ]);
+ }
+ startIndex += detailX;
+ }
+ if (topCap) {
+ startIndex += detailX;
+ for (ii = 0; ii < detailX; ++ii) {
+ this.faces.push([
+ startIndex + ii,
+ startIndex + (ii + 1) % detailX,
+ startIndex + detailX
+ ]);
+ }
+ }
+ };
+
+ /**
+ * Draw a cylinder with given radius and height
+ *
+ * DetailX and detailY determines the number of subdivisions in the x-dimension
+ * and the y-dimension of a cylinder. More subdivisions make the cylinder seem smoother.
+ * The recommended maximum value for detailX is 24. Using a value greater than 24
+ * may cause a warning or slow down the browser.
+ *
+ * @method cylinder
+ * @param {Number} [radius] radius of the surface
+ * @param {Number} [height] height of the cylinder
+ * @param {Integer} [detailX] number of subdivisions in x-dimension;
+ * default is 24
+ * @param {Integer} [detailY] number of subdivisions in y-dimension;
+ * default is 1
+ * @param {Boolean} [bottomCap] whether to draw the bottom of the cylinder
+ * @param {Boolean} [topCap] whether to draw the top of the cylinder
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a spinning cylinder
+ * // with radius 20 and height 50
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateX(frameCount * 0.01);
+ * rotateZ(frameCount * 0.01);
+ * cylinder(20, 50);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailX works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 24, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * cylinder(20, 75, detailX.value(), 1);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(1, 16, 1);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * cylinder(20, 75, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.cylinder = function(
+ radius,
+ height,
+ detailX,
+ detailY,
+ bottomCap,
+ topCap
+ ) {
+ this._assert3d('cylinder');
+ _main.default._validateParameters('cylinder', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = radius;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 1;
+ }
+ if (typeof topCap === 'undefined') {
+ topCap = true;
+ }
+ if (typeof bottomCap === 'undefined') {
+ bottomCap = true;
+ }
+
+ var gId = 'cylinder|'
+ .concat(detailX, '|')
+ .concat(detailY, '|')
+ .concat(bottomCap, '|')
+ .concat(topCap);
+ if (!this._renderer.geometryInHash(gId)) {
+ var cylinderGeom = new _main.default.Geometry(detailX, detailY);
+ _truncatedCone.call(
+ cylinderGeom,
+ 1,
+ 1,
+ 1,
+ detailX,
+ detailY,
+ bottomCap,
+ topCap
+ );
+
+ // normals are computed in call to _truncatedCone
+ if (detailX <= 24 && detailY <= 16) {
+ cylinderGeom._makeTriangleEdges()._edgesToVertices();
+ } else {
+ console.log(
+ 'Cannot draw stroke on cylinder objects with more' +
+ ' than 24 detailX or 16 detailY'
+ );
+ }
+ this._renderer.createBuffers(gId, cylinderGeom);
+ }
+
+ this._renderer.drawBuffersScaled(gId, radius, height, radius);
+
+ return this;
+ };
+
+ /**
+ * Draw a cone with given radius and height
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a cone. More subdivisions make the cone seem smoother. The
+ * recommended maximum value for detailX is 24. Using a value greater than 24
+ * may cause a warning or slow down the browser.
+ * @method cone
+ * @param {Number} [radius] radius of the bottom surface
+ * @param {Number} [height] height of the cone
+ * @param {Integer} [detailX] number of segments,
+ * the more segments the smoother geometry
+ * default is 24
+ * @param {Integer} [detailY] number of segments,
+ * the more segments the smoother geometry
+ * default is 1
+ * @param {Boolean} [cap] whether to draw the base of the cone
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a spinning cone
+ * // with radius 40 and height 70
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateZ(frameCount * 0.01);
+ * cone(40, 70);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailx works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 16, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * cone(30, 65, detailX.value(), 16);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(3, 16, 3);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * cone(30, 65, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.cone = function(radius, height, detailX, detailY, cap) {
+ this._assert3d('cone');
+ _main.default._validateParameters('cone', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = radius;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 1;
+ }
+ if (typeof cap === 'undefined') {
+ cap = true;
+ }
+
+ var gId = 'cone|'
+ .concat(detailX, '|')
+ .concat(detailY, '|')
+ .concat(cap);
+ if (!this._renderer.geometryInHash(gId)) {
+ var coneGeom = new _main.default.Geometry(detailX, detailY);
+ _truncatedCone.call(coneGeom, 1, 0, 1, detailX, detailY, cap, false);
+ if (detailX <= 24 && detailY <= 16) {
+ coneGeom._makeTriangleEdges()._edgesToVertices();
+ } else {
+ console.log(
+ 'Cannot draw stroke on cone objects with more' +
+ ' than 24 detailX or 16 detailY'
+ );
+ }
+ this._renderer.createBuffers(gId, coneGeom);
+ }
+
+ this._renderer.drawBuffersScaled(gId, radius, height, radius);
+
+ return this;
+ };
+
+ /**
+ * Draw an ellipsoid with given radius
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a cone. More subdivisions make the ellipsoid appear to be smoother.
+ * Avoid detail number above 150, it may crash the browser.
+ * @method ellipsoid
+ * @param {Number} [radiusx] x-radius of ellipsoid
+ * @param {Number} [radiusy] y-radius of ellipsoid
+ * @param {Number} [radiusz] z-radius of ellipsoid
+ * @param {Integer} [detailX] number of segments,
+ * the more segments the smoother geometry
+ * default is 24. Avoid detail number above
+ * 150, it may crash the browser.
+ * @param {Integer} [detailY] number of segments,
+ * the more segments the smoother geometry
+ * default is 16. Avoid detail number above
+ * 150, it may crash the browser.
+ * @chainable
+ * @example
+ *
+ *
+ * // draw an ellipsoid
+ * // with radius 30, 40 and 40.
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * ellipsoid(30, 40, 40);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailX works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(2, 24, 12);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * ellipsoid(30, 40, 40, detailX.value(), 8);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(2, 24, 6);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 9);
+ * rotateY(millis() / 1000);
+ * ellipsoid(30, 40, 40, 12, detailY.value());
+ * }
+ *
+ *
+ *
+ */
+ _main.default.prototype.ellipsoid = function(
+ radiusX,
+ radiusY,
+ radiusZ,
+ detailX,
+ detailY
+ ) {
+ this._assert3d('ellipsoid');
+ _main.default._validateParameters('ellipsoid', arguments);
+ if (typeof radiusX === 'undefined') {
+ radiusX = 50;
+ }
+ if (typeof radiusY === 'undefined') {
+ radiusY = radiusX;
+ }
+ if (typeof radiusZ === 'undefined') {
+ radiusZ = radiusX;
+ }
+
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 16;
+ }
+
+ var gId = 'ellipsoid|'.concat(detailX, '|').concat(detailY);
+
+ if (!this._renderer.geometryInHash(gId)) {
+ var _ellipsoid = function _ellipsoid() {
+ for (var i = 0; i <= this.detailY; i++) {
+ var v = i / this.detailY;
+ var phi = Math.PI * v - Math.PI / 2;
+ var cosPhi = Math.cos(phi);
+ var sinPhi = Math.sin(phi);
+
+ for (var j = 0; j <= this.detailX; j++) {
+ var u = j / this.detailX;
+ var theta = 2 * Math.PI * u;
+ var cosTheta = Math.cos(theta);
+ var sinTheta = Math.sin(theta);
+ var p = new _main.default.Vector(
+ cosPhi * sinTheta,
+ sinPhi,
+ cosPhi * cosTheta
+ );
+ this.vertices.push(p);
+ this.vertexNormals.push(p);
+ this.uvs.push(u, v);
+ }
+ }
+ };
+ var ellipsoidGeom = new _main.default.Geometry(detailX, detailY, _ellipsoid);
+ ellipsoidGeom.computeFaces();
+ if (detailX <= 24 && detailY <= 24) {
+ ellipsoidGeom._makeTriangleEdges()._edgesToVertices();
+ } else {
+ console.log(
+ 'Cannot draw stroke on ellipsoids with more' +
+ ' than 24 detailX or 24 detailY'
+ );
+ }
+ this._renderer.createBuffers(gId, ellipsoidGeom);
+ }
+
+ this._renderer.drawBuffersScaled(gId, radiusX, radiusY, radiusZ);
+
+ return this;
+ };
+
+ /**
+ * Draw a torus with given radius and tube radius
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a torus. More subdivisions make the torus appear to be smoother.
+ * The default and maximum values for detailX and detailY are 24 and 16, respectively.
+ * Setting them to relatively small values like 4 and 6 allows you to create new
+ * shapes other than a torus.
+ * @method torus
+ * @param {Number} [radius] radius of the whole ring
+ * @param {Number} [tubeRadius] radius of the tube
+ * @param {Integer} [detailX] number of segments in x-dimension,
+ * the more segments the smoother geometry
+ * default is 24
+ * @param {Integer} [detailY] number of segments in y-dimension,
+ * the more segments the smoother geometry
+ * default is 16
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a spinning torus
+ * // with ring radius 30 and tube radius 15
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * torus(30, 15);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailX works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 24, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * torus(30, 15, detailX.value(), 12);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(3, 16, 3);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * torus(30, 15, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.torus = function(radius, tubeRadius, detailX, detailY) {
+ this._assert3d('torus');
+ _main.default._validateParameters('torus', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ } else if (!radius) {
+ return; // nothing to draw
+ }
+
+ if (typeof tubeRadius === 'undefined') {
+ tubeRadius = 10;
+ } else if (!tubeRadius) {
+ return; // nothing to draw
+ }
+
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 16;
+ }
+
+ var tubeRatio = (tubeRadius / radius).toPrecision(4);
+ var gId = 'torus|'
+ .concat(tubeRatio, '|')
+ .concat(detailX, '|')
+ .concat(detailY);
+
+ if (!this._renderer.geometryInHash(gId)) {
+ var _torus = function _torus() {
+ for (var i = 0; i <= this.detailY; i++) {
+ var v = i / this.detailY;
+ var phi = 2 * Math.PI * v;
+ var cosPhi = Math.cos(phi);
+ var sinPhi = Math.sin(phi);
+ var r = 1 + tubeRatio * cosPhi;
+
+ for (var j = 0; j <= this.detailX; j++) {
+ var u = j / this.detailX;
+ var theta = 2 * Math.PI * u;
+ var cosTheta = Math.cos(theta);
+ var sinTheta = Math.sin(theta);
+
+ var p = new _main.default.Vector(
+ r * cosTheta,
+ r * sinTheta,
+ tubeRatio * sinPhi
+ );
+
+ var n = new _main.default.Vector(
+ cosPhi * cosTheta,
+ cosPhi * sinTheta,
+ sinPhi
+ );
+
+ this.vertices.push(p);
+ this.vertexNormals.push(n);
+ this.uvs.push(u, v);
+ }
+ }
+ };
+ var torusGeom = new _main.default.Geometry(detailX, detailY, _torus);
+ torusGeom.computeFaces();
+ if (detailX <= 24 && detailY <= 16) {
+ torusGeom._makeTriangleEdges()._edgesToVertices();
+ } else {
+ console.log(
+ 'Cannot draw strokes on torus object with more' +
+ ' than 24 detailX or 16 detailY'
+ );
+ }
+ this._renderer.createBuffers(gId, torusGeom);
+ }
+ this._renderer.drawBuffersScaled(gId, radius, radius, radius);
+
+ return this;
+ };
+
+ ///////////////////////
+ /// 2D primitives
+ /////////////////////////
+
+ /**
+ * Draws a point, a coordinate in space at the dimension of one pixel,
+ * given x, y and z coordinates. The color of the point is determined
+ * by the current stroke, while the point size is determined by current
+ * stroke weight.
+ * @private
+ * @param {Number} x x-coordinate of point
+ * @param {Number} y y-coordinate of point
+ * @param {Number} z z-coordinate of point
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(50);
+ * stroke(255);
+ * strokeWeight(4);
+ * point(25, 0);
+ * strokeWeight(3);
+ * point(-25, 0);
+ * strokeWeight(2);
+ * point(0, 25);
+ * strokeWeight(1);
+ * point(0, -25);
+ * }
+ *
+ *
+ */
+ _main.default.RendererGL.prototype.point = function(x, y, z) {
+ if (typeof z === 'undefined') {
+ z = 0;
+ }
+
+ var _vertex = [];
+ _vertex.push(new _main.default.Vector(x, y, z));
+ this._drawPoints(_vertex, this._pointVertexBuffer);
+
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.triangle = function(args) {
+ var x1 = args[0],
+ y1 = args[1];
+ var x2 = args[2],
+ y2 = args[3];
+ var x3 = args[4],
+ y3 = args[5];
+
+ var gId = 'tri';
+ if (!this.geometryInHash(gId)) {
+ var _triangle = function _triangle() {
+ var vertices = [];
+ vertices.push(new _main.default.Vector(0, 0, 0));
+ vertices.push(new _main.default.Vector(0, 1, 0));
+ vertices.push(new _main.default.Vector(1, 0, 0));
+ this.strokeIndices = [[0, 1], [1, 2], [2, 0]];
+ this.vertices = vertices;
+ this.faces = [[0, 1, 2]];
+ this.uvs = [0, 0, 0, 1, 1, 1];
+ };
+ var triGeom = new _main.default.Geometry(1, 1, _triangle);
+ triGeom._makeTriangleEdges()._edgesToVertices();
+ triGeom.computeNormals();
+ this.createBuffers(gId, triGeom);
+ }
+
+ // only one triangle is cached, one point is at the origin, and the
+ // two adjacent sides are tne unit vectors along the X & Y axes.
+ //
+ // this matrix multiplication transforms those two unit vectors
+ // onto the required vector prior to rendering, and moves the
+ // origin appropriately.
+ var uMVMatrix = this.uMVMatrix.copy();
+ try {
+ // prettier-ignore
+ var mult = new _main.default.Matrix([
+ x2 - x1, y2 - y1, 0, 0, // the resulting unit X-axis
+ x3 - x1, y3 - y1, 0, 0, // the resulting unit Y-axis
+ 0, 0, 1, 0, // the resulting unit Z-axis (unchanged)
+ x1, y1, 0, 1 // the resulting origin
+ ]).mult(this.uMVMatrix);
+
+ this.uMVMatrix = mult;
+
+ this.drawBuffers(gId);
+ } finally {
+ this.uMVMatrix = uMVMatrix;
+ }
+
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.ellipse = function(args) {
+ this.arc(
+ args[0],
+ args[1],
+ args[2],
+ args[3],
+ 0,
+ constants.TWO_PI,
+ constants.OPEN,
+ args[4]
+ );
+ };
+
+ _main.default.RendererGL.prototype.arc = function(args) {
+ var x = arguments[0];
+ var y = arguments[1];
+ var width = arguments[2];
+ var height = arguments[3];
+ var start = arguments[4];
+ var stop = arguments[5];
+ var mode = arguments[6];
+ var detail = arguments[7] || 25;
+
+ var shape;
+ var gId;
+
+ // check if it is an ellipse or an arc
+ if (Math.abs(stop - start) >= constants.TWO_PI) {
+ shape = 'ellipse';
+ gId = ''.concat(shape, '|').concat(detail, '|');
+ } else {
+ shape = 'arc';
+ gId = ''
+ .concat(shape, '|')
+ .concat(start, '|')
+ .concat(stop, '|')
+ .concat(mode, '|')
+ .concat(detail, '|');
+ }
+
+ if (!this.geometryInHash(gId)) {
+ var _arc = function _arc() {
+ this.strokeIndices = [];
+
+ // if the start and stop angles are not the same, push vertices to the array
+ if (start.toFixed(10) !== stop.toFixed(10)) {
+ // if the mode specified is PIE or null, push the mid point of the arc in vertices
+ if (mode === constants.PIE || typeof mode === 'undefined') {
+ this.vertices.push(new _main.default.Vector(0.5, 0.5, 0));
+ this.uvs.push([0.5, 0.5]);
+ }
+
+ // vertices for the perimeter of the circle
+ for (var i = 0; i <= detail; i++) {
+ var u = i / detail;
+ var theta = (stop - start) * u + start;
+
+ var _x = 0.5 + Math.cos(theta) / 2;
+ var _y = 0.5 + Math.sin(theta) / 2;
+
+ this.vertices.push(new _main.default.Vector(_x, _y, 0));
+ this.uvs.push([_x, _y]);
+
+ if (i < detail - 1) {
+ this.faces.push([0, i + 1, i + 2]);
+ this.strokeIndices.push([i + 1, i + 2]);
+ }
+ }
+
+ // check the mode specified in order to push vertices and faces, different for each mode
+ switch (mode) {
+ case constants.PIE:
+ this.faces.push([
+ 0,
+ this.vertices.length - 2,
+ this.vertices.length - 1
+ ]);
+
+ this.strokeIndices.push([0, 1]);
+ this.strokeIndices.push([
+ this.vertices.length - 2,
+ this.vertices.length - 1
+ ]);
+
+ this.strokeIndices.push([0, this.vertices.length - 1]);
+ break;
+
+ case constants.CHORD:
+ this.strokeIndices.push([0, 1]);
+ this.strokeIndices.push([0, this.vertices.length - 1]);
+ break;
+
+ case constants.OPEN:
+ this.strokeIndices.push([0, 1]);
+ break;
+
+ default:
+ this.faces.push([
+ 0,
+ this.vertices.length - 2,
+ this.vertices.length - 1
+ ]);
+
+ this.strokeIndices.push([
+ this.vertices.length - 2,
+ this.vertices.length - 1
+ ]);
+ }
+ }
+ };
+
+ var arcGeom = new _main.default.Geometry(detail, 1, _arc);
+ arcGeom.computeNormals();
+
+ if (detail <= 50) {
+ arcGeom._makeTriangleEdges()._edgesToVertices(arcGeom);
+ } else {
+ console.log('Cannot stroke '.concat(shape, ' with more than 50 detail'));
+ }
+
+ this.createBuffers(gId, arcGeom);
+ }
+
+ var uMVMatrix = this.uMVMatrix.copy();
+
+ try {
+ this.uMVMatrix.translate([x, y, 0]);
+ this.uMVMatrix.scale(width, height, 1);
+
+ this.drawBuffers(gId);
+ } finally {
+ this.uMVMatrix = uMVMatrix;
+ }
+
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.rect = function(args) {
+ var perPixelLighting = this._pInst._glAttributes.perPixelLighting;
+ var x = args[0];
+ var y = args[1];
+ var width = args[2];
+ var height = args[3];
+ var detailX = args[4] || (perPixelLighting ? 1 : 24);
+ var detailY = args[5] || (perPixelLighting ? 1 : 16);
+ var gId = 'rect|'.concat(detailX, '|').concat(detailY);
+ if (!this.geometryInHash(gId)) {
+ var _rect = function _rect() {
+ for (var i = 0; i <= this.detailY; i++) {
+ var v = i / this.detailY;
+ for (var j = 0; j <= this.detailX; j++) {
+ var u = j / this.detailX;
+ var p = new _main.default.Vector(u, v, 0);
+ this.vertices.push(p);
+ this.uvs.push(u, v);
+ }
+ }
+ // using stroke indices to avoid stroke over face(s) of rectangle
+ if (detailX > 0 && detailY > 0) {
+ this.strokeIndices = [
+ [0, detailX],
+ [detailX, (detailX + 1) * (detailY + 1) - 1],
+ [(detailX + 1) * (detailY + 1) - 1, (detailX + 1) * detailY],
+ [(detailX + 1) * detailY, 0]
+ ];
+ }
+ };
+ var rectGeom = new _main.default.Geometry(detailX, detailY, _rect);
+ rectGeom
+ .computeFaces()
+ .computeNormals()
+ ._makeTriangleEdges()
+ ._edgesToVertices();
+ this.createBuffers(gId, rectGeom);
+ }
+
+ // only a single rectangle (of a given detail) is cached: a square with
+ // opposite corners at (0,0) & (1,1).
+ //
+ // before rendering, this square is scaled & moved to the required location.
+ var uMVMatrix = this.uMVMatrix.copy();
+ try {
+ this.uMVMatrix.translate([x, y, 0]);
+ this.uMVMatrix.scale(width, height, 1);
+
+ this.drawBuffers(gId);
+ } finally {
+ this.uMVMatrix = uMVMatrix;
+ }
+ return this;
+ };
+
+ // prettier-ignore
+ _main.default.RendererGL.prototype.quad = function (x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) {
+ var gId = "quad|".concat(
+ x1, "|").concat(y1, "|").concat(z1, "|").concat(x2, "|").concat(y2, "|").concat(z2, "|").concat(x3, "|").concat(y3, "|").concat(z3, "|").concat(x4, "|").concat(y4, "|").concat(z4);
+ if (!this.geometryInHash(gId)) {
+ var _quad = function _quad() {
+ this.vertices.push(new _main.default.Vector(x1, y1, z1));
+ this.vertices.push(new _main.default.Vector(x2, y2, z2));
+ this.vertices.push(new _main.default.Vector(x3, y3, z3));
+ this.vertices.push(new _main.default.Vector(x4, y4, z4));
+ this.uvs.push(0, 0, 1, 0, 1, 1, 0, 1);
+ this.strokeIndices = [[0, 1], [1, 2], [2, 3], [3, 0]];
+ };
+ var quadGeom = new _main.default.Geometry(2, 2, _quad);
+ quadGeom.
+ computeNormals().
+ _makeTriangleEdges().
+ _edgesToVertices();
+ quadGeom.faces = [[0, 1, 2], [2, 3, 0]];
+ this.createBuffers(gId, quadGeom);
+ }
+ this.drawBuffers(gId);
+ return this;
+};
+
+ //this implementation of bezier curve
+ //is based on Bernstein polynomial
+ // pretier-ignore
+ _main.default.RendererGL.prototype.bezier = function(
+ x1,
+ y1,
+ z1, // x2
+ x2, // y2
+ y2, // x3
+ z2, // y3
+ x3, // x4
+ y3, // y4
+ z3,
+ x4,
+ y4,
+ z4
+ ) {
+ if (arguments.length === 8) {
+ y4 = y3;
+ x4 = x3;
+ y3 = z2;
+ x3 = y2;
+ y2 = x2;
+ x2 = z1;
+ z1 = z2 = z3 = z4 = 0;
+ }
+ var bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail
+ this.beginShape();
+ for (var i = 0; i <= bezierDetail; i++) {
+ var c1 = Math.pow(1 - i / bezierDetail, 3);
+ var c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2);
+ var c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail);
+ var c4 = Math.pow(i / bezierDetail, 3);
+ this.vertex(
+ x1 * c1 + x2 * c2 + x3 * c3 + x4 * c4,
+ y1 * c1 + y2 * c2 + y3 * c3 + y4 * c4,
+ z1 * c1 + z2 * c2 + z3 * c3 + z4 * c4
+ );
+ }
+ this.endShape();
+ return this;
+ };
+
+ // pretier-ignore
+ _main.default.RendererGL.prototype.curve = function(
+ x1,
+ y1,
+ z1, // x2
+ x2, // y2
+ y2, // x3
+ z2, // y3
+ x3, // x4
+ y3, // y4
+ z3,
+ x4,
+ y4,
+ z4
+ ) {
+ if (arguments.length === 8) {
+ x4 = x3;
+ y4 = y3;
+ x3 = y2;
+ y3 = x2;
+ x2 = z1;
+ y2 = x2;
+ z1 = z2 = z3 = z4 = 0;
+ }
+ var curveDetail = this._pInst._curveDetail;
+ this.beginShape();
+ for (var i = 0; i <= curveDetail; i++) {
+ var c1 = Math.pow(i / curveDetail, 3) * 0.5;
+ var c2 = Math.pow(i / curveDetail, 2) * 0.5;
+ var c3 = i / curveDetail * 0.5;
+ var c4 = 0.5;
+ var vx =
+ c1 * (-x1 + 3 * x2 - 3 * x3 + x4) +
+ c2 * (2 * x1 - 5 * x2 + 4 * x3 - x4) +
+ c3 * (-x1 + x3) +
+ c4 * (2 * x2);
+ var vy =
+ c1 * (-y1 + 3 * y2 - 3 * y3 + y4) +
+ c2 * (2 * y1 - 5 * y2 + 4 * y3 - y4) +
+ c3 * (-y1 + y3) +
+ c4 * (2 * y2);
+ var vz =
+ c1 * (-z1 + 3 * z2 - 3 * z3 + z4) +
+ c2 * (2 * z1 - 5 * z2 + 4 * z3 - z4) +
+ c3 * (-z1 + z3) +
+ c4 * (2 * z2);
+ this.vertex(vx, vy, vz);
+ }
+ this.endShape();
+ return this;
+ };
+
+ /**
+ * Draw a line given two points
+ * @private
+ * @param {Number} x0 x-coordinate of first vertex
+ * @param {Number} y0 y-coordinate of first vertex
+ * @param {Number} z0 z-coordinate of first vertex
+ * @param {Number} x1 x-coordinate of second vertex
+ * @param {Number} y1 y-coordinate of second vertex
+ * @param {Number} z1 z-coordinate of second vertex
+ * @chainable
+ * @example
+ *
+ *
+ * //draw a line
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * // Use fill instead of stroke to change the color of shape.
+ * fill(255, 0, 0);
+ * line(10, 10, 0, 60, 60, 20);
+ * }
+ *
+ *
+ */
+ _main.default.RendererGL.prototype.line = function() {
+ if (arguments.length === 6) {
+ this.beginShape();
+ this.vertex(
+ arguments.length <= 0 ? undefined : arguments[0],
+ arguments.length <= 1 ? undefined : arguments[1],
+ arguments.length <= 2 ? undefined : arguments[2]
+ );
+ this.vertex(
+ arguments.length <= 3 ? undefined : arguments[3],
+ arguments.length <= 4 ? undefined : arguments[4],
+ arguments.length <= 5 ? undefined : arguments[5]
+ );
+ this.endShape();
+ } else if (arguments.length === 4) {
+ this.beginShape();
+ this.vertex(
+ arguments.length <= 0 ? undefined : arguments[0],
+ arguments.length <= 1 ? undefined : arguments[1],
+ 0
+ );
+ this.vertex(
+ arguments.length <= 2 ? undefined : arguments[2],
+ arguments.length <= 3 ? undefined : arguments[3],
+ 0
+ );
+ this.endShape();
+ }
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.bezierVertex = function() {
+ if (this.immediateMode._bezierVertex.length === 0) {
+ throw Error('vertex() must be used once before calling bezierVertex()');
+ } else {
+ var w_x = [];
+ var w_y = [];
+ var w_z = [];
+ var t, _x, _y, _z, i;
+ var argLength = arguments.length;
+
+ t = 0;
+
+ if (
+ this._lookUpTableBezier.length === 0 ||
+ this._lutBezierDetail !== this._pInst._curveDetail
+ ) {
+ this._lookUpTableBezier = [];
+ this._lutBezierDetail = this._pInst._curveDetail;
+ var step = 1 / this._lutBezierDetail;
+ var start = 0;
+ var end = 1;
+ var j = 0;
+ while (start < 1) {
+ t = parseFloat(start.toFixed(6));
+ this._lookUpTableBezier[j] = this._bezierCoefficients(t);
+ if (end.toFixed(6) === step.toFixed(6)) {
+ t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6));
+ ++j;
+ this._lookUpTableBezier[j] = this._bezierCoefficients(t);
+ break;
+ }
+ start += step;
+ end -= step;
+ ++j;
+ }
+ }
+
+ var LUTLength = this._lookUpTableBezier.length;
+
+ if (argLength === 6) {
+ this.isBezier = true;
+
+ w_x = [
+ this.immediateMode._bezierVertex[0],
+ arguments.length <= 0 ? undefined : arguments[0],
+ arguments.length <= 2 ? undefined : arguments[2],
+ arguments.length <= 4 ? undefined : arguments[4]
+ ];
+ w_y = [
+ this.immediateMode._bezierVertex[1],
+ arguments.length <= 1 ? undefined : arguments[1],
+ arguments.length <= 3 ? undefined : arguments[3],
+ arguments.length <= 5 ? undefined : arguments[5]
+ ];
+
+ for (i = 0; i < LUTLength; i++) {
+ _x =
+ w_x[0] * this._lookUpTableBezier[i][0] +
+ w_x[1] * this._lookUpTableBezier[i][1] +
+ w_x[2] * this._lookUpTableBezier[i][2] +
+ w_x[3] * this._lookUpTableBezier[i][3];
+ _y =
+ w_y[0] * this._lookUpTableBezier[i][0] +
+ w_y[1] * this._lookUpTableBezier[i][1] +
+ w_y[2] * this._lookUpTableBezier[i][2] +
+ w_y[3] * this._lookUpTableBezier[i][3];
+ this.vertex(_x, _y);
+ }
+ this.immediateMode._bezierVertex[0] =
+ arguments.length <= 4 ? undefined : arguments[4];
+ this.immediateMode._bezierVertex[1] =
+ arguments.length <= 5 ? undefined : arguments[5];
+ } else if (argLength === 9) {
+ this.isBezier = true;
+
+ w_x = [
+ this.immediateMode._bezierVertex[0],
+ arguments.length <= 0 ? undefined : arguments[0],
+ arguments.length <= 3 ? undefined : arguments[3],
+ arguments.length <= 6 ? undefined : arguments[6]
+ ];
+ w_y = [
+ this.immediateMode._bezierVertex[1],
+ arguments.length <= 1 ? undefined : arguments[1],
+ arguments.length <= 4 ? undefined : arguments[4],
+ arguments.length <= 7 ? undefined : arguments[7]
+ ];
+ w_z = [
+ this.immediateMode._bezierVertex[2],
+ arguments.length <= 2 ? undefined : arguments[2],
+ arguments.length <= 5 ? undefined : arguments[5],
+ arguments.length <= 8 ? undefined : arguments[8]
+ ];
+ for (i = 0; i < LUTLength; i++) {
+ _x =
+ w_x[0] * this._lookUpTableBezier[i][0] +
+ w_x[1] * this._lookUpTableBezier[i][1] +
+ w_x[2] * this._lookUpTableBezier[i][2] +
+ w_x[3] * this._lookUpTableBezier[i][3];
+ _y =
+ w_y[0] * this._lookUpTableBezier[i][0] +
+ w_y[1] * this._lookUpTableBezier[i][1] +
+ w_y[2] * this._lookUpTableBezier[i][2] +
+ w_y[3] * this._lookUpTableBezier[i][3];
+ _z =
+ w_z[0] * this._lookUpTableBezier[i][0] +
+ w_z[1] * this._lookUpTableBezier[i][1] +
+ w_z[2] * this._lookUpTableBezier[i][2] +
+ w_z[3] * this._lookUpTableBezier[i][3];
+ this.vertex(_x, _y, _z);
+ }
+ this.immediateMode._bezierVertex[0] =
+ arguments.length <= 6 ? undefined : arguments[6];
+ this.immediateMode._bezierVertex[1] =
+ arguments.length <= 7 ? undefined : arguments[7];
+ this.immediateMode._bezierVertex[2] =
+ arguments.length <= 8 ? undefined : arguments[8];
+ }
+ }
+ };
+
+ _main.default.RendererGL.prototype.quadraticVertex = function() {
+ if (this.immediateMode._quadraticVertex.length === 0) {
+ throw Error('vertex() must be used once before calling quadraticVertex()');
+ } else {
+ var w_x = [];
+ var w_y = [];
+ var w_z = [];
+ var t, _x, _y, _z, i;
+ var argLength = arguments.length;
+
+ t = 0;
+
+ if (
+ this._lookUpTableQuadratic.length === 0 ||
+ this._lutQuadraticDetail !== this._pInst._curveDetail
+ ) {
+ this._lookUpTableQuadratic = [];
+ this._lutQuadraticDetail = this._pInst._curveDetail;
+ var step = 1 / this._lutQuadraticDetail;
+ var start = 0;
+ var end = 1;
+ var j = 0;
+ while (start < 1) {
+ t = parseFloat(start.toFixed(6));
+ this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t);
+ if (end.toFixed(6) === step.toFixed(6)) {
+ t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6));
+ ++j;
+ this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t);
+ break;
+ }
+ start += step;
+ end -= step;
+ ++j;
+ }
+ }
+
+ var LUTLength = this._lookUpTableQuadratic.length;
+
+ if (argLength === 4) {
+ this.isQuadratic = true;
+
+ w_x = [
+ this.immediateMode._quadraticVertex[0],
+ arguments.length <= 0 ? undefined : arguments[0],
+ arguments.length <= 2 ? undefined : arguments[2]
+ ];
+ w_y = [
+ this.immediateMode._quadraticVertex[1],
+ arguments.length <= 1 ? undefined : arguments[1],
+ arguments.length <= 3 ? undefined : arguments[3]
+ ];
+
+ for (i = 0; i < LUTLength; i++) {
+ _x =
+ w_x[0] * this._lookUpTableQuadratic[i][0] +
+ w_x[1] * this._lookUpTableQuadratic[i][1] +
+ w_x[2] * this._lookUpTableQuadratic[i][2];
+ _y =
+ w_y[0] * this._lookUpTableQuadratic[i][0] +
+ w_y[1] * this._lookUpTableQuadratic[i][1] +
+ w_y[2] * this._lookUpTableQuadratic[i][2];
+ this.vertex(_x, _y);
+ }
+
+ this.immediateMode._quadraticVertex[0] =
+ arguments.length <= 2 ? undefined : arguments[2];
+ this.immediateMode._quadraticVertex[1] =
+ arguments.length <= 3 ? undefined : arguments[3];
+ } else if (argLength === 6) {
+ this.isQuadratic = true;
+
+ w_x = [
+ this.immediateMode._quadraticVertex[0],
+ arguments.length <= 0 ? undefined : arguments[0],
+ arguments.length <= 3 ? undefined : arguments[3]
+ ];
+ w_y = [
+ this.immediateMode._quadraticVertex[1],
+ arguments.length <= 1 ? undefined : arguments[1],
+ arguments.length <= 4 ? undefined : arguments[4]
+ ];
+ w_z = [
+ this.immediateMode._quadraticVertex[2],
+ arguments.length <= 2 ? undefined : arguments[2],
+ arguments.length <= 5 ? undefined : arguments[5]
+ ];
+
+ for (i = 0; i < LUTLength; i++) {
+ _x =
+ w_x[0] * this._lookUpTableQuadratic[i][0] +
+ w_x[1] * this._lookUpTableQuadratic[i][1] +
+ w_x[2] * this._lookUpTableQuadratic[i][2];
+ _y =
+ w_y[0] * this._lookUpTableQuadratic[i][0] +
+ w_y[1] * this._lookUpTableQuadratic[i][1] +
+ w_y[2] * this._lookUpTableQuadratic[i][2];
+ _z =
+ w_z[0] * this._lookUpTableQuadratic[i][0] +
+ w_z[1] * this._lookUpTableQuadratic[i][1] +
+ w_z[2] * this._lookUpTableQuadratic[i][2];
+ this.vertex(_x, _y, _z);
+ }
+
+ this.immediateMode._quadraticVertex[0] =
+ arguments.length <= 3 ? undefined : arguments[3];
+ this.immediateMode._quadraticVertex[1] =
+ arguments.length <= 4 ? undefined : arguments[4];
+ this.immediateMode._quadraticVertex[2] =
+ arguments.length <= 5 ? undefined : arguments[5];
+ }
+ }
+ };
+
+ _main.default.RendererGL.prototype.curveVertex = function() {
+ var w_x = [];
+ var w_y = [];
+ var w_z = [];
+ var t, _x, _y, _z, i;
+ t = 0;
+ var argLength = arguments.length;
+
+ if (
+ this._lookUpTableBezier.length === 0 ||
+ this._lutBezierDetail !== this._pInst._curveDetail
+ ) {
+ this._lookUpTableBezier = [];
+ this._lutBezierDetail = this._pInst._curveDetail;
+ var step = 1 / this._lutBezierDetail;
+ var start = 0;
+ var end = 1;
+ var j = 0;
+ while (start < 1) {
+ t = parseFloat(start.toFixed(6));
+ this._lookUpTableBezier[j] = this._bezierCoefficients(t);
+ if (end.toFixed(6) === step.toFixed(6)) {
+ t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6));
+ ++j;
+ this._lookUpTableBezier[j] = this._bezierCoefficients(t);
+ break;
+ }
+ start += step;
+ end -= step;
+ ++j;
+ }
+ }
+
+ var LUTLength = this._lookUpTableBezier.length;
+
+ if (argLength === 2) {
+ this.immediateMode._curveVertex.push(
+ arguments.length <= 0 ? undefined : arguments[0]
+ );
+ this.immediateMode._curveVertex.push(
+ arguments.length <= 1 ? undefined : arguments[1]
+ );
+ if (this.immediateMode._curveVertex.length === 8) {
+ this.isCurve = true;
+ w_x = this._bezierToCatmull([
+ this.immediateMode._curveVertex[0],
+ this.immediateMode._curveVertex[2],
+ this.immediateMode._curveVertex[4],
+ this.immediateMode._curveVertex[6]
+ ]);
+
+ w_y = this._bezierToCatmull([
+ this.immediateMode._curveVertex[1],
+ this.immediateMode._curveVertex[3],
+ this.immediateMode._curveVertex[5],
+ this.immediateMode._curveVertex[7]
+ ]);
+
+ for (i = 0; i < LUTLength; i++) {
+ _x =
+ w_x[0] * this._lookUpTableBezier[i][0] +
+ w_x[1] * this._lookUpTableBezier[i][1] +
+ w_x[2] * this._lookUpTableBezier[i][2] +
+ w_x[3] * this._lookUpTableBezier[i][3];
+ _y =
+ w_y[0] * this._lookUpTableBezier[i][0] +
+ w_y[1] * this._lookUpTableBezier[i][1] +
+ w_y[2] * this._lookUpTableBezier[i][2] +
+ w_y[3] * this._lookUpTableBezier[i][3];
+ this.vertex(_x, _y);
+ }
+ for (i = 0; i < argLength; i++) {
+ this.immediateMode._curveVertex.shift();
+ }
+ }
+ } else if (argLength === 3) {
+ this.immediateMode._curveVertex.push(
+ arguments.length <= 0 ? undefined : arguments[0]
+ );
+ this.immediateMode._curveVertex.push(
+ arguments.length <= 1 ? undefined : arguments[1]
+ );
+ this.immediateMode._curveVertex.push(
+ arguments.length <= 2 ? undefined : arguments[2]
+ );
+ if (this.immediateMode._curveVertex.length === 12) {
+ this.isCurve = true;
+ w_x = this._bezierToCatmull([
+ this.immediateMode._curveVertex[0],
+ this.immediateMode._curveVertex[3],
+ this.immediateMode._curveVertex[6],
+ this.immediateMode._curveVertex[9]
+ ]);
+
+ w_y = this._bezierToCatmull([
+ this.immediateMode._curveVertex[1],
+ this.immediateMode._curveVertex[4],
+ this.immediateMode._curveVertex[7],
+ this.immediateMode._curveVertex[10]
+ ]);
+
+ w_z = this._bezierToCatmull([
+ this.immediateMode._curveVertex[2],
+ this.immediateMode._curveVertex[5],
+ this.immediateMode._curveVertex[8],
+ this.immediateMode._curveVertex[11]
+ ]);
+
+ for (i = 0; i < LUTLength; i++) {
+ _x =
+ w_x[0] * this._lookUpTableBezier[i][0] +
+ w_x[1] * this._lookUpTableBezier[i][1] +
+ w_x[2] * this._lookUpTableBezier[i][2] +
+ w_x[3] * this._lookUpTableBezier[i][3];
+ _y =
+ w_y[0] * this._lookUpTableBezier[i][0] +
+ w_y[1] * this._lookUpTableBezier[i][1] +
+ w_y[2] * this._lookUpTableBezier[i][2] +
+ w_y[3] * this._lookUpTableBezier[i][3];
+ _z =
+ w_z[0] * this._lookUpTableBezier[i][0] +
+ w_z[1] * this._lookUpTableBezier[i][1] +
+ w_z[2] * this._lookUpTableBezier[i][2] +
+ w_z[3] * this._lookUpTableBezier[i][3];
+ this.vertex(_x, _y, _z);
+ }
+ for (i = 0; i < argLength; i++) {
+ this.immediateMode._curveVertex.shift();
+ }
+ }
+ }
+ };
+
+ _main.default.RendererGL.prototype.image = function(
+ img,
+ sx,
+ sy,
+ sWidth,
+ sHeight,
+ dx,
+ dy,
+ dWidth,
+ dHeight
+ ) {
+ if (this._isErasing) {
+ this.blendMode(this._cachedBlendMode);
+ }
+
+ this._pInst.push();
+
+ this._pInst.texture(img);
+ this._pInst.textureMode(constants.NORMAL);
+
+ var u0 = 0;
+ if (sx <= img.width) {
+ u0 = sx / img.width;
+ }
+
+ var u1 = 1;
+ if (sx + sWidth <= img.width) {
+ u1 = (sx + sWidth) / img.width;
+ }
+
+ var v0 = 0;
+ if (sy <= img.height) {
+ v0 = sy / img.height;
+ }
+
+ var v1 = 1;
+ if (sy + sHeight <= img.height) {
+ v1 = (sy + sHeight) / img.height;
+ }
+
+ this.beginShape();
+ this.vertex(dx, dy, 0, u0, v0);
+ this.vertex(dx + dWidth, dy, 0, u1, v0);
+ this.vertex(dx + dWidth, dy + dHeight, 0, u1, v1);
+ this.vertex(dx, dy + dHeight, 0, u0, v1);
+ this.endShape(constants.CLOSE);
+
+ this._pInst.pop();
+
+ if (this._isErasing) {
+ this.blendMode(constants.REMOVE);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27, './p5.Geometry': 76 }
+ ],
+ 71: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /** // implementation based on three.js 'orbitControls':
+ * @module Lights, Camera
+ * @submodule Interaction
+ * @for p5
+ * @requires core
+ */ /**
+ * Allows movement around a 3D sketch using a mouse or trackpad. Left-clicking
+ * and dragging will rotate the camera position about the center of the sketch,
+ * right-clicking and dragging will pan the camera position without rotation,
+ * and using the mouse wheel (scrolling) will move the camera closer or further
+ * from the center of the sketch. This function can be called with parameters
+ * dictating sensitivity to mouse movement along the X and Y axes. Calling
+ * this function without parameters is equivalent to calling orbitControl(1,1).
+ * To reverse direction of movement in either axis, enter a negative number
+ * for sensitivity.
+ * @method orbitControl
+ * @for p5
+ * @param {Number} [sensitivityX] sensitivity to mouse movement along X axis
+ * @param {Number} [sensitivityY] sensitivity to mouse movement along Y axis
+ * @param {Number} [sensitivityZ] sensitivity to scroll movement along Z axis
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * }
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * rotateY(0.5);
+ * box(30, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Camera orbits around a box when mouse is hold-clicked & then moved.
+ */
+ // https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/OrbitControls.js
+ _main.default.prototype.orbitControl = function(
+ sensitivityX,
+ sensitivityY,
+ sensitivityZ
+ ) {
+ this._assert3d('orbitControl');
+ _main.default._validateParameters('orbitControl', arguments);
+
+ // If the mouse is not in bounds of the canvas, disable all behaviors:
+ var mouseInCanvas =
+ this.mouseX < this.width &&
+ this.mouseX > 0 &&
+ this.mouseY < this.height &&
+ this.mouseY > 0;
+ if (!mouseInCanvas) return;
+
+ var cam = this._renderer._curCamera;
+
+ if (typeof sensitivityX === 'undefined') {
+ sensitivityX = 1;
+ }
+ if (typeof sensitivityY === 'undefined') {
+ sensitivityY = sensitivityX;
+ }
+ if (typeof sensitivityZ === 'undefined') {
+ sensitivityZ = 0.5;
+ }
+
+ // default right-mouse and mouse-wheel behaviors (context menu and scrolling,
+ // respectively) are disabled here to allow use of those events for panning and
+ // zooming
+
+ // disable context menu for canvas element and add 'contextMenuDisabled'
+ // flag to p5 instance
+ if (this.contextMenuDisabled !== true) {
+ this.canvas.oncontextmenu = function() {
+ return false;
+ };
+ this._setProperty('contextMenuDisabled', true);
+ }
+
+ // disable default scrolling behavior on the canvas element and add
+ // 'wheelDefaultDisabled' flag to p5 instance
+ if (this.wheelDefaultDisabled !== true) {
+ this.canvas.onwheel = function() {
+ return false;
+ };
+ this._setProperty('wheelDefaultDisabled', true);
+ }
+
+ var scaleFactor = this.height < this.width ? this.height : this.width;
+
+ // ZOOM if there is a change in mouseWheelDelta
+ if (this._mouseWheelDeltaY !== this._pmouseWheelDeltaY) {
+ // zoom according to direction of mouseWheelDeltaY rather than value
+ if (this._mouseWheelDeltaY > 0) {
+ this._renderer._curCamera._orbit(0, 0, sensitivityZ * scaleFactor);
+ } else {
+ this._renderer._curCamera._orbit(0, 0, -sensitivityZ * scaleFactor);
+ }
+ }
+
+ if (this.mouseIsPressed) {
+ // ORBIT BEHAVIOR
+ if (this.mouseButton === this.LEFT) {
+ var deltaTheta = -sensitivityX * (this.mouseX - this.pmouseX) / scaleFactor;
+ var deltaPhi = sensitivityY * (this.mouseY - this.pmouseY) / scaleFactor;
+ this._renderer._curCamera._orbit(deltaTheta, deltaPhi, 0);
+ } else if (this.mouseButton === this.RIGHT) {
+ // PANNING BEHAVIOR along X/Z camera axes and restricted to X/Z plane
+ // in world space
+ var local = cam._getLocalAxes();
+
+ // normalize portions along X/Z axes
+ var xmag = Math.sqrt(local.x[0] * local.x[0] + local.x[2] * local.x[2]);
+ if (xmag !== 0) {
+ local.x[0] /= xmag;
+ local.x[2] /= xmag;
+ }
+
+ // normalize portions along X/Z axes
+ var ymag = Math.sqrt(local.y[0] * local.y[0] + local.y[2] * local.y[2]);
+ if (ymag !== 0) {
+ local.y[0] /= ymag;
+ local.y[2] /= ymag;
+ }
+
+ // move along those vectors by amount controlled by mouseX, pmouseY
+ var dx = -1 * sensitivityX * (this.mouseX - this.pmouseX);
+ var dz = -1 * sensitivityY * (this.mouseY - this.pmouseY);
+
+ // restrict movement to XZ plane in world space
+ cam.setPosition(
+ cam.eyeX + dx * local.x[0] + dz * local.z[0],
+ cam.eyeY,
+ cam.eyeZ + dx * local.x[2] + dz * local.z[2]
+ );
+ }
+ }
+ return this;
+ };
+
+ /**
+ * debugMode() helps visualize 3D space by adding a grid to indicate where the
+ * ‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z
+ * directions. This function can be called without parameters to create a
+ * default grid and axes icon, or it can be called according to the examples
+ * above to customize the size and position of the grid and/or axes icon. The
+ * grid is drawn using the most recently set stroke color and weight. To
+ * specify these parameters, add a call to stroke() and strokeWeight()
+ * just before the end of the draw() loop.
+ *
+ * By default, the grid will run through the origin (0,0,0) of the sketch
+ * along the XZ plane
+ * and the axes icon will be offset from the origin. Both the grid and axes
+ * icon will be sized according to the current canvas size. Note that because the
+ * grid runs parallel to the default camera view, it is often helpful to use
+ * debugMode along with orbitControl to allow full view of the grid.
+ * @method debugMode
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * // Press the spacebar to turn debugMode off!
+ * if (keyIsDown(32)) {
+ * noDebugMode();
+ * }
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z. the grid and icon disappear when the
+ * spacebar is pressed.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(GRID);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(AXES);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(GRID, 100, 10, 0, 0, 0);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0);
+ * }
+ *
+ * function draw() {
+ * noStroke();
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * // set the stroke color and weight for the grid!
+ * stroke(255, 0, 150);
+ * strokeWeight(0.8);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z.
+ */
+
+ /**
+ * @method debugMode
+ * @param {Constant} mode either GRID or AXES
+ */
+
+ /**
+ * @method debugMode
+ * @param {Constant} mode
+ * @param {Number} [gridSize] size of one side of the grid
+ * @param {Number} [gridDivisions] number of divisions in the grid
+ * @param {Number} [xOff] X axis offset from origin (0,0,0)
+ * @param {Number} [yOff] Y axis offset from origin (0,0,0)
+ * @param {Number} [zOff] Z axis offset from origin (0,0,0)
+ */
+
+ /**
+ * @method debugMode
+ * @param {Constant} mode
+ * @param {Number} [axesSize] size of axes icon
+ * @param {Number} [xOff]
+ * @param {Number} [yOff]
+ * @param {Number} [zOff]
+ */
+
+ /**
+ * @method debugMode
+ * @param {Number} [gridSize]
+ * @param {Number} [gridDivisions]
+ * @param {Number} [gridXOff]
+ * @param {Number} [gridYOff]
+ * @param {Number} [gridZOff]
+ * @param {Number} [axesSize]
+ * @param {Number} [axesXOff]
+ * @param {Number} [axesYOff]
+ * @param {Number} [axesZOff]
+ */
+
+ _main.default.prototype.debugMode = function() {
+ this._assert3d('debugMode');
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('debugMode', args);
+
+ // start by removing existing 'post' registered debug methods
+ for (var i = this._registeredMethods.post.length - 1; i >= 0; i--) {
+ // test for equality...
+ if (
+ this._registeredMethods.post[i].toString() === this._grid().toString() ||
+ this._registeredMethods.post[i].toString() === this._axesIcon().toString()
+ ) {
+ this._registeredMethods.post.splice(i, 1);
+ }
+ }
+
+ // then add new debugMode functions according to the argument list
+ if (args[0] === constants.GRID) {
+ this.registerMethod(
+ 'post',
+ this._grid.call(this, args[1], args[2], args[3], args[4], args[5])
+ );
+ } else if (args[0] === constants.AXES) {
+ this.registerMethod(
+ 'post',
+ this._axesIcon.call(this, args[1], args[2], args[3], args[4])
+ );
+ } else {
+ this.registerMethod(
+ 'post',
+ this._grid.call(this, args[0], args[1], args[2], args[3], args[4])
+ );
+
+ this.registerMethod(
+ 'post',
+ this._axesIcon.call(this, args[5], args[6], args[7], args[8])
+ );
+ }
+ };
+
+ /**
+ * Turns off debugMode() in a 3D sketch.
+ * @method noDebugMode
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * // Press the spacebar to turn debugMode off!
+ * if (keyIsDown(32)) {
+ * noDebugMode();
+ * }
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z. the grid and icon disappear when the
+ * spacebar is pressed.
+ */
+ _main.default.prototype.noDebugMode = function() {
+ this._assert3d('noDebugMode');
+
+ // start by removing existing 'post' registered debug methods
+ for (var i = this._registeredMethods.post.length - 1; i >= 0; i--) {
+ // test for equality...
+ if (
+ this._registeredMethods.post[i].toString() === this._grid().toString() ||
+ this._registeredMethods.post[i].toString() === this._axesIcon().toString()
+ ) {
+ this._registeredMethods.post.splice(i, 1);
+ }
+ }
+ };
+
+ /**
+ * For use with debugMode
+ * @private
+ * @method _grid
+ * @param {Number} [size] size of grid sides
+ * @param {Number} [div] number of grid divisions
+ * @param {Number} [xOff] offset of grid center from origin in X axis
+ * @param {Number} [yOff] offset of grid center from origin in Y axis
+ * @param {Number} [zOff] offset of grid center from origin in Z axis
+ */
+ _main.default.prototype._grid = function(size, numDivs, xOff, yOff, zOff) {
+ if (typeof size === 'undefined') {
+ size = this.width / 2;
+ }
+ if (typeof numDivs === 'undefined') {
+ // ensure at least 2 divisions
+ numDivs = Math.round(size / 30) < 4 ? 4 : Math.round(size / 30);
+ }
+ if (typeof xOff === 'undefined') {
+ xOff = 0;
+ }
+ if (typeof yOff === 'undefined') {
+ yOff = 0;
+ }
+ if (typeof zOff === 'undefined') {
+ zOff = 0;
+ }
+
+ var spacing = size / numDivs;
+ var halfSize = size / 2;
+
+ return function() {
+ this.push();
+ this.stroke(
+ this._renderer.curStrokeColor[0] * 255,
+ this._renderer.curStrokeColor[1] * 255,
+ this._renderer.curStrokeColor[2] * 255
+ );
+
+ this._renderer.uMVMatrix.set(
+ this._renderer._curCamera.cameraMatrix.mat4[0],
+ this._renderer._curCamera.cameraMatrix.mat4[1],
+ this._renderer._curCamera.cameraMatrix.mat4[2],
+ this._renderer._curCamera.cameraMatrix.mat4[3],
+ this._renderer._curCamera.cameraMatrix.mat4[4],
+ this._renderer._curCamera.cameraMatrix.mat4[5],
+ this._renderer._curCamera.cameraMatrix.mat4[6],
+ this._renderer._curCamera.cameraMatrix.mat4[7],
+ this._renderer._curCamera.cameraMatrix.mat4[8],
+ this._renderer._curCamera.cameraMatrix.mat4[9],
+ this._renderer._curCamera.cameraMatrix.mat4[10],
+ this._renderer._curCamera.cameraMatrix.mat4[11],
+ this._renderer._curCamera.cameraMatrix.mat4[12],
+ this._renderer._curCamera.cameraMatrix.mat4[13],
+ this._renderer._curCamera.cameraMatrix.mat4[14],
+ this._renderer._curCamera.cameraMatrix.mat4[15]
+ );
+
+ // Lines along X axis
+ for (var q = 0; q <= numDivs; q++) {
+ this.beginShape(this.LINES);
+ this.vertex(-halfSize + xOff, yOff, q * spacing - halfSize + zOff);
+ this.vertex(+halfSize + xOff, yOff, q * spacing - halfSize + zOff);
+ this.endShape();
+ }
+
+ // Lines along Z axis
+ for (var i = 0; i <= numDivs; i++) {
+ this.beginShape(this.LINES);
+ this.vertex(i * spacing - halfSize + xOff, yOff, -halfSize + zOff);
+ this.vertex(i * spacing - halfSize + xOff, yOff, +halfSize + zOff);
+ this.endShape();
+ }
+
+ this.pop();
+ };
+ };
+
+ /**
+ * For use with debugMode
+ * @private
+ * @method _axesIcon
+ * @param {Number} [size] size of axes icon lines
+ * @param {Number} [xOff] offset of icon from origin in X axis
+ * @param {Number} [yOff] offset of icon from origin in Y axis
+ * @param {Number} [zOff] offset of icon from origin in Z axis
+ */
+ _main.default.prototype._axesIcon = function(size, xOff, yOff, zOff) {
+ if (typeof size === 'undefined') {
+ size = this.width / 20 > 40 ? this.width / 20 : 40;
+ }
+ if (typeof xOff === 'undefined') {
+ xOff = -this.width / 4;
+ }
+ if (typeof yOff === 'undefined') {
+ yOff = xOff;
+ }
+ if (typeof zOff === 'undefined') {
+ zOff = xOff;
+ }
+
+ return function() {
+ this.push();
+ this._renderer.uMVMatrix.set(
+ this._renderer._curCamera.cameraMatrix.mat4[0],
+ this._renderer._curCamera.cameraMatrix.mat4[1],
+ this._renderer._curCamera.cameraMatrix.mat4[2],
+ this._renderer._curCamera.cameraMatrix.mat4[3],
+ this._renderer._curCamera.cameraMatrix.mat4[4],
+ this._renderer._curCamera.cameraMatrix.mat4[5],
+ this._renderer._curCamera.cameraMatrix.mat4[6],
+ this._renderer._curCamera.cameraMatrix.mat4[7],
+ this._renderer._curCamera.cameraMatrix.mat4[8],
+ this._renderer._curCamera.cameraMatrix.mat4[9],
+ this._renderer._curCamera.cameraMatrix.mat4[10],
+ this._renderer._curCamera.cameraMatrix.mat4[11],
+ this._renderer._curCamera.cameraMatrix.mat4[12],
+ this._renderer._curCamera.cameraMatrix.mat4[13],
+ this._renderer._curCamera.cameraMatrix.mat4[14],
+ this._renderer._curCamera.cameraMatrix.mat4[15]
+ );
+
+ // X axis
+ this.strokeWeight(2);
+ this.stroke(255, 0, 0);
+ this.beginShape(this.LINES);
+ this.vertex(xOff, yOff, zOff);
+ this.vertex(xOff + size, yOff, zOff);
+ this.endShape();
+ // Y axis
+ this.stroke(0, 255, 0);
+ this.beginShape(this.LINES);
+ this.vertex(xOff, yOff, zOff);
+ this.vertex(xOff, yOff + size, zOff);
+ this.endShape();
+ // Z axis
+ this.stroke(0, 0, 255);
+ this.beginShape(this.LINES);
+ this.vertex(xOff, yOff, zOff);
+ this.vertex(xOff, yOff, zOff + size);
+ this.endShape();
+ this.pop();
+ };
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 72: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /**
+ * @method ambientLight
+ * @param {String} value a color string
+ * @chainable
+ */ /**
+ * @module Lights, Camera
+ * @submodule Lights
+ * @for p5
+ * @requires core
+ */ /**
+ * Creates an ambient light with a color
+ *
+ * @method ambientLight
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @param {Number} [alpha] the alpha value
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * ambientLight(150);
+ * ambientMaterial(250);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * evenly distributed light across a sphere
+ *
+ */
+ /**
+ * @method ambientLight
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ * @chainable
+ */
+
+ /**
+ * @method ambientLight
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+ /**
+ * @method ambientLight
+ * @param {p5.Color} color the ambient light color
+ * @chainable
+ */
+ _main.default.prototype.ambientLight = function(v1, v2, v3, a) {
+ this._assert3d('ambientLight');
+ _main.default._validateParameters('ambientLight', arguments);
+ var color = this.color.apply(this, arguments);
+
+ this._renderer.ambientLightColors.push(
+ color._array[0],
+ color._array[1],
+ color._array[2]
+ );
+
+ this._renderer._enableLighting = true;
+
+ return this;
+ };
+
+ /**
+ * Set's the color of the specular highlight when using a specular material and
+ * specular light.
+ *
+ * This method can be combined with specularMaterial() and shininess()
+ * functions to set specular highlights. The default color is white, ie
+ * (255, 255, 255), which is used if this method is not called before
+ * specularMaterial(). If this method is called without specularMaterial(),
+ * There will be no effect.
+ *
+ * Note: specularColor is equivalent to the processing function
+ * lightSpecular.
+ *
+ * @method specularColor
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * shininess(20);
+ * ambientLight(50);
+ * specularColor(255, 0, 0);
+ * pointLight(255, 0, 0, 0, -50, 50);
+ * specularColor(0, 255, 0);
+ * pointLight(0, 255, 0, 0, 50, 50);
+ * specularMaterial(255);
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * different specular light sources from top and bottom of canvas
+ */
+
+ /**
+ * @method specularColor
+ * @param {String} value a color string
+ * @chainable
+ */
+
+ /**
+ * @method specularColor
+ * @param {Number} gray a gray value
+ * @chainable
+ */
+
+ /**
+ * @method specularColor
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+ /**
+ * @method specularColor
+ * @param {p5.Color} color the ambient light color
+ * @chainable
+ */
+ _main.default.prototype.specularColor = function(v1, v2, v3) {
+ this._assert3d('specularColor');
+ _main.default._validateParameters('specularColor', arguments);
+ var color = this.color.apply(this, arguments);
+
+ this._renderer.specularColors = [
+ color._array[0],
+ color._array[1],
+ color._array[2]
+ ];
+
+ return this;
+ };
+
+ /**
+ * Creates a directional light with a color and a direction
+ * @method directionalLight
+ * @param {Number} v1 red or hue value (depending on the current
+ * color mode),
+ * @param {Number} v2 green or saturation value
+ * @param {Number} v3 blue or brightness value
+ * @param {p5.Vector} position the direction of the light
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * //move your mouse to change light direction
+ * let dirX = (mouseX / width - 0.5) * 2;
+ * let dirY = (mouseY / height - 0.5) * 2;
+ * directionalLight(250, 250, 250, -dirX, -dirY, -1);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * light source on canvas changeable with mouse position
+ *
+ */
+
+ /**
+ * @method directionalLight
+ * @param {Number[]|String|p5.Color} color color Array, CSS color string,
+ * or p5.Color value
+ * @param {Number} x x axis direction
+ * @param {Number} y y axis direction
+ * @param {Number} z z axis direction
+ * @chainable
+ */
+
+ /**
+ * @method directionalLight
+ * @param {Number[]|String|p5.Color} color
+ * @param {p5.Vector} position
+ * @chainable
+ */
+
+ /**
+ * @method directionalLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @chainable
+ */
+ _main.default.prototype.directionalLight = function(v1, v2, v3, x, y, z) {
+ this._assert3d('directionalLight');
+ _main.default._validateParameters('directionalLight', arguments);
+
+ //@TODO: check parameters number
+ var color;
+ if (v1 instanceof _main.default.Color) {
+ color = v1;
+ } else {
+ color = this.color(v1, v2, v3);
+ }
+
+ var _x, _y, _z;
+ var v = arguments[arguments.length - 1];
+ if (typeof v === 'number') {
+ _x = arguments[arguments.length - 3];
+ _y = arguments[arguments.length - 2];
+ _z = arguments[arguments.length - 1];
+ } else {
+ _x = v.x;
+ _y = v.y;
+ _z = v.z;
+ }
+
+ // normalize direction
+ var l = Math.sqrt(_x * _x + _y * _y + _z * _z);
+ this._renderer.directionalLightDirections.push(_x / l, _y / l, _z / l);
+
+ this._renderer.directionalLightDiffuseColors.push(
+ color._array[0],
+ color._array[1],
+ color._array[2]
+ );
+
+ Array.prototype.push.apply(
+ this._renderer.directionalLightSpecularColors,
+ this._renderer.specularColors
+ );
+
+ this._renderer._enableLighting = true;
+
+ return this;
+ };
+
+ /**
+ * Creates a point light with a color and a light position
+ * @method pointLight
+ * @param {Number} v1 red or hue value (depending on the current
+ * color mode),
+ * @param {Number} v2 green or saturation value
+ * @param {Number} v3 blue or brightness value
+ * @param {Number} x x axis position
+ * @param {Number} y y axis position
+ * @param {Number} z z axis position
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * //move your mouse to change light position
+ * let locX = mouseX - width / 2;
+ * let locY = mouseY - height / 2;
+ * // to set the light position,
+ * // think of the world's coordinate as:
+ * // -width/2,-height/2 -------- width/2,-height/2
+ * // | |
+ * // | 0,0 |
+ * // | |
+ * // -width/2,height/2--------width/2,height/2
+ * pointLight(250, 250, 250, locX, locY, 50);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * spot light on canvas changes position with mouse
+ *
+ */
+
+ /**
+ * @method pointLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {p5.Vector} position the position of the light
+ * @chainable
+ */
+
+ /**
+ * @method pointLight
+ * @param {Number[]|String|p5.Color} color color Array, CSS color string,
+ * or p5.Color value
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @chainable
+ */
+
+ /**
+ * @method pointLight
+ * @param {Number[]|String|p5.Color} color
+ * @param {p5.Vector} position
+ * @chainable
+ */
+ _main.default.prototype.pointLight = function(v1, v2, v3, x, y, z) {
+ this._assert3d('pointLight');
+ _main.default._validateParameters('pointLight', arguments);
+
+ //@TODO: check parameters number
+ var color;
+ if (v1 instanceof _main.default.Color) {
+ color = v1;
+ } else {
+ color = this.color(v1, v2, v3);
+ }
+
+ var _x, _y, _z;
+ var v = arguments[arguments.length - 1];
+ if (typeof v === 'number') {
+ _x = arguments[arguments.length - 3];
+ _y = arguments[arguments.length - 2];
+ _z = arguments[arguments.length - 1];
+ } else {
+ _x = v.x;
+ _y = v.y;
+ _z = v.z;
+ }
+
+ this._renderer.pointLightPositions.push(_x, _y, _z);
+ this._renderer.pointLightDiffuseColors.push(
+ color._array[0],
+ color._array[1],
+ color._array[2]
+ );
+
+ Array.prototype.push.apply(
+ this._renderer.pointLightSpecularColors,
+ this._renderer.specularColors
+ );
+
+ this._renderer._enableLighting = true;
+
+ return this;
+ };
+
+ /**
+ * Sets the default ambient and directional light. The defaults are ambientLight(128, 128, 128) and directionalLight(128, 128, 128, 0, 0, -1). Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop.
+ * @method lights
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * lights();
+ * rotateX(millis() / 1000);
+ * rotateY(millis() / 1000);
+ * rotateZ(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ *
+ * @alt
+ * the light is partially ambient and partially directional
+ */
+ _main.default.prototype.lights = function() {
+ this._assert3d('lights');
+ this.ambientLight(128, 128, 128);
+ this.directionalLight(128, 128, 128, 0, 0, -1);
+ return this;
+ };
+
+ /**
+ * Sets the falloff rates for point lights. It affects only the elements which are created after it in the code.
+ * The default value is lightFalloff(1.0, 0.0, 0.0), and the parameters are used to calculate the falloff with the following equation:
+ *
+ * d = distance from light position to vertex position
+ *
+ * falloff = 1 / (CONSTANT + d \* LINEAR + ( d \* d ) \* QUADRATIC)
+ *
+ * @method lightFalloff
+ * @param {Number} constant constant value for determining falloff
+ * @param {Number} linear linear value for determining falloff
+ * @param {Number} quadratic quadratic value for determining falloff
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * }
+ * function draw() {
+ * background(0);
+ * let locX = mouseX - width / 2;
+ * let locY = mouseY - height / 2;
+ * translate(-25, 0, 0);
+ * lightFalloff(1, 0, 0);
+ * pointLight(250, 250, 250, locX, locY, 50);
+ * sphere(20);
+ * translate(50, 0, 0);
+ * lightFalloff(0.9, 0.01, 0);
+ * pointLight(250, 250, 250, locX, locY, 50);
+ * sphere(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Two spheres with different falloff values show different intensity of light
+ *
+ */
+ _main.default.prototype.lightFalloff = function(
+ constantAttenuation,
+ linearAttenuation,
+ quadraticAttenuation
+ ) {
+ this._assert3d('lightFalloff');
+ _main.default._validateParameters('lightFalloff', arguments);
+
+ if (constantAttenuation < 0) {
+ constantAttenuation = 0;
+ console.warn(
+ 'Value of constant argument in lightFalloff() should be never be negative. Set to 0.'
+ );
+ }
+
+ if (linearAttenuation < 0) {
+ linearAttenuation = 0;
+ console.warn(
+ 'Value of linear argument in lightFalloff() should be never be negative. Set to 0.'
+ );
+ }
+
+ if (quadraticAttenuation < 0) {
+ quadraticAttenuation = 0;
+ console.warn(
+ 'Value of quadratic argument in lightFalloff() should be never be negative. Set to 0.'
+ );
+ }
+
+ if (
+ constantAttenuation === 0 &&
+ linearAttenuation === 0 &&
+ quadraticAttenuation === 0
+ ) {
+ constantAttenuation = 1;
+ console.warn(
+ 'Either one of the three arguments in lightFalloff() should be greater than zero. Set constant argument to 1.'
+ );
+ }
+
+ this._renderer.constantAttenuation = constantAttenuation;
+ this._renderer.linearAttenuation = linearAttenuation;
+ this._renderer.quadraticAttenuation = quadraticAttenuation;
+
+ return this;
+ };
+
+ /**
+ * Creates a spotlight with a given color, position, direction of light,
+ * angle and concentration. Here, angle refers to the opening or aperture
+ * of the cone of the spotlight, and concentration is used to focus the
+ * light towards the center. Both angle and concentration are optional, but if
+ * you want to provide concentration, you will also have to specify the angle.
+ *
+ * @method spotLight
+ * @param {Number} v1 red or hue value (depending on the current
+ * color mode),
+ * @param {Number} v2 green or saturation value
+ * @param {Number} v3 blue or brightness value
+ * @param {Number} x x axis position
+ * @param {Number} y y axis position
+ * @param {Number} z z axis position
+ * @param {Number} rx x axis direction of light
+ * @param {Number} ry y axis direction of light
+ * @param {Number} rz z axis direction of light
+ * @param {Number} [angle] optional parameter for angle. Defaults to PI/3
+ * @param {Number} [conc] optional parameter for concentration. Defaults to 100
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('perPixelLighting', true);
+ * }
+ * function draw() {
+ * background(0);
+ * //move your mouse to change light position
+ * let locX = mouseX - width / 2;
+ * let locY = mouseY - height / 2;
+ * // to set the light position,
+ * // think of the world's coordinate as:
+ * // -width/2,-height/2 -------- width/2,-height/2
+ * // | |
+ * // | 0,0 |
+ * // | |
+ * // -width/2,height/2--------width/2,height/2
+ * ambientLight(50);
+ * spotLight(0, 250, 0, locX, locY, 100, 0, 0, -1, Math.PI / 16);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Spot light on a sphere which changes position with mouse
+ */
+ /**
+ * @method spotLight
+ * @param {Number[]|String|p5.Color} color color Array, CSS color string,
+ * or p5.Color value
+ * @param {p5.Vector} position the position of the light
+ * @param {p5.Vector} direction the direction of the light
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ /**
+ * @method spotLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {p5.Vector} position
+ * @param {p5.Vector} direction
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ /**
+ * @method spotLight
+ * @param {Number[]|String|p5.Color} color
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @param {p5.Vector} direction
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ /**
+ * @method spotLight
+ * @param {Number[]|String|p5.Color} color
+ * @param {p5.Vector} position
+ * @param {Number} rx
+ * @param {Number} ry
+ * @param {Number} rz
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ /**
+ * @method spotLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @param {p5.Vector} direction
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ /**
+ * @method spotLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {p5.Vector} position
+ * @param {Number} rx
+ * @param {Number} ry
+ * @param {Number} rz
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ /**
+ * @method spotLight
+ * @param {Number[]|String|p5.Color} color
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @param {Number} rx
+ * @param {Number} ry
+ * @param {Number} rz
+ * @param {Number} [angle]
+ * @param {Number} [conc]
+ */
+ _main.default.prototype.spotLight = function(
+ v1,
+ v2,
+ v3,
+ x,
+ y,
+ z,
+ nx,
+ ny,
+ nz,
+ angle,
+ concentration
+ ) {
+ this._assert3d('spotLight');
+ _main.default._validateParameters('spotLight', arguments);
+
+ var color, position, direction;
+ var length = arguments.length;
+
+ switch (length) {
+ case 11:
+ case 10:
+ color = this.color(v1, v2, v3);
+ position = new _main.default.Vector(x, y, z);
+ direction = new _main.default.Vector(nx, ny, nz);
+ break;
+
+ case 9:
+ if (v1 instanceof _main.default.Color) {
+ color = v1;
+ position = new _main.default.Vector(v2, v3, x);
+ direction = new _main.default.Vector(y, z, nx);
+ angle = ny;
+ concentration = nz;
+ } else if (x instanceof _main.default.Vector) {
+ color = this.color(v1, v2, v3);
+ position = x;
+ direction = new _main.default.Vector(y, z, nx);
+ angle = ny;
+ concentration = nz;
+ } else if (nx instanceof _main.default.Vector) {
+ color = this.color(v1, v2, v3);
+ position = new _main.default.Vector(x, y, z);
+ direction = nx;
+ angle = ny;
+ concentration = nz;
+ } else {
+ color = this.color(v1, v2, v3);
+ position = new _main.default.Vector(x, y, z);
+ direction = new _main.default.Vector(nx, ny, nz);
+ }
+ break;
+
+ case 8:
+ if (v1 instanceof _main.default.Color) {
+ color = v1;
+ position = new _main.default.Vector(v2, v3, x);
+ direction = new _main.default.Vector(y, z, nx);
+ angle = ny;
+ } else if (x instanceof _main.default.Vector) {
+ color = this.color(v1, v2, v3);
+ position = x;
+ direction = new _main.default.Vector(y, z, nx);
+ angle = ny;
+ } else {
+ color = this.color(v1, v2, v3);
+ position = new _main.default.Vector(x, y, z);
+ direction = nx;
+ angle = ny;
+ }
+ break;
+
+ case 7:
+ if (
+ v1 instanceof _main.default.Color &&
+ v2 instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = v2;
+ direction = new _main.default.Vector(v3, x, y);
+ angle = z;
+ concentration = nx;
+ } else if (
+ v1 instanceof _main.default.Color &&
+ y instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = new _main.default.Vector(v2, v3, x);
+ direction = y;
+ angle = z;
+ concentration = nx;
+ } else if (
+ x instanceof _main.default.Vector &&
+ y instanceof _main.default.Vector
+ ) {
+ color = this.color(v1, v2, v3);
+ position = x;
+ direction = y;
+ angle = z;
+ concentration = nx;
+ } else if (v1 instanceof _main.default.Color) {
+ color = v1;
+ position = new _main.default.Vector(v2, v3, x);
+ direction = new _main.default.Vector(y, z, nx);
+ } else if (x instanceof _main.default.Vector) {
+ color = this.color(v1, v2, v3);
+ position = x;
+ direction = new _main.default.Vector(y, z, nx);
+ } else {
+ color = this.color(v1, v2, v3);
+ position = new _main.default.Vector(x, y, z);
+ direction = nx;
+ }
+ break;
+
+ case 6:
+ if (
+ x instanceof _main.default.Vector &&
+ y instanceof _main.default.Vector
+ ) {
+ color = this.color(v1, v2, v3);
+ position = x;
+ direction = y;
+ angle = z;
+ } else if (
+ v1 instanceof _main.default.Color &&
+ y instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = new _main.default.Vector(v2, v3, x);
+ direction = y;
+ angle = z;
+ } else if (
+ v1 instanceof _main.default.Color &&
+ v2 instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = v2;
+ direction = new _main.default.Vector(v3, x, y);
+ angle = z;
+ }
+ break;
+
+ case 5:
+ if (
+ v1 instanceof _main.default.Color &&
+ v2 instanceof _main.default.Vector &&
+ v3 instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = v2;
+ direction = v3;
+ angle = x;
+ concentration = y;
+ } else if (
+ x instanceof _main.default.Vector &&
+ y instanceof _main.default.Vector
+ ) {
+ color = this.color(v1, v2, v3);
+ position = x;
+ direction = y;
+ } else if (
+ v1 instanceof _main.default.Color &&
+ y instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = new _main.default.Vector(v2, v3, x);
+ direction = y;
+ } else if (
+ v1 instanceof _main.default.Color &&
+ v2 instanceof _main.default.Vector
+ ) {
+ color = v1;
+ position = v2;
+ direction = new _main.default.Vector(v3, x, y);
+ }
+ break;
+
+ case 4:
+ color = v1;
+ position = v2;
+ direction = v3;
+ angle = x;
+ break;
+
+ case 3:
+ color = v1;
+ position = v2;
+ direction = v3;
+ break;
+
+ default:
+ console.warn(
+ 'Sorry, input for spotlight() is not in prescribed format. Too '.concat(
+ length < 3 ? 'few' : 'many',
+ ' arguments were provided'
+ )
+ );
+
+ return this;
+ }
+
+ this._renderer.spotLightDiffuseColors.push(
+ color._array[0],
+ color._array[1],
+ color._array[2]
+ );
+
+ Array.prototype.push.apply(
+ this._renderer.spotLightSpecularColors,
+ this._renderer.specularColors
+ );
+
+ this._renderer.spotLightPositions.push(position.x, position.y, position.z);
+ direction.normalize();
+ this._renderer.spotLightDirections.push(direction.x, direction.y, direction.z);
+
+ if (angle === undefined) {
+ angle = Math.PI / 3;
+ }
+
+ if (concentration !== undefined && concentration < 1) {
+ concentration = 1;
+ console.warn(
+ 'Value of concentration needs to be greater than 1. Setting it to 1'
+ );
+ } else if (concentration === undefined) {
+ concentration = 100;
+ }
+
+ angle = this._renderer._pInst._toRadians(angle);
+ this._renderer.spotLightAngle.push(Math.cos(angle));
+ this._renderer.spotLightConc.push(concentration);
+
+ this._renderer._enableLighting = true;
+
+ return this;
+ };
+
+ /**
+ * This function will remove all the lights from the sketch for the
+ * subsequent materials rendered. It affects all the subsequent methods.
+ * Calls to lighting methods made after noLights() will re-enable lights
+ * in the sketch.
+ * @method noLights
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * noStroke();
+ *
+ * ambientLight(150, 0, 0);
+ * translate(-25, 0, 0);
+ * ambientMaterial(250);
+ * sphere(20);
+ *
+ * noLights();
+ * ambientLight(0, 150, 0);
+ * translate(50, 0, 0);
+ * ambientMaterial(250);
+ * sphere(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Two spheres showing different colors
+ */
+ _main.default.prototype.noLights = function() {
+ this._assert3d('noLights');
+ _main.default._validateParameters('noLights', arguments);
+
+ this._renderer.ambientLightColors.length = 0;
+ this._renderer.specularColors = [1, 1, 1];
+
+ this._renderer.directionalLightDirections.length = 0;
+ this._renderer.directionalLightDiffuseColors.length = 0;
+ this._renderer.directionalLightSpecularColors.length = 0;
+
+ this._renderer.pointLightPositions.length = 0;
+ this._renderer.pointLightDiffuseColors.length = 0;
+ this._renderer.pointLightSpecularColors.length = 0;
+
+ this._renderer.spotLightPositions.length = 0;
+ this._renderer.spotLightDirections.length = 0;
+ this._renderer.spotLightDiffuseColors.length = 0;
+ this._renderer.spotLightSpecularColors.length = 0;
+ this._renderer.spotLightAngle.length = 0;
+ this._renderer.spotLightConc.length = 0;
+
+ this._renderer.constantAttenuation = 1;
+ this._renderer.linearAttenuation = 0;
+ this._renderer.quadraticAttenuation = 0;
+ this._renderer._useShininess = 1;
+
+ return this;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 73: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ _dereq_('./p5.Geometry');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Shape
+ * @submodule 3D Models
+ * @for p5
+ * @requires core
+ * @requires p5.Geometry
+ */ /**
+ * Load a 3d model from an OBJ or STL file.
+ *
+ * loadModel() should be placed inside of preload().
+ * This allows the model to load fully before the rest of your code is run.
+ *
+ * One of the limitations of the OBJ and STL format is that it doesn't have a built-in
+ * sense of scale. This means that models exported from different programs might
+ * be very different sizes. If your model isn't displaying, try calling
+ * loadModel() with the normalized parameter set to true. This will resize the
+ * model to a scale appropriate for p5. You can also make additional changes to
+ * the final size of your model with the scale() function.
+ *
+ * Also, the support for colored STL files is not present. STL files with color will be
+ * rendered without color properties.
+ *
+ * @method loadModel
+ * @param {String} path Path of the model to be loaded
+ * @param {Boolean} normalize If true, scale the model to a
+ * standardized size when loading
+ * @param {function(p5.Geometry)} [successCallback] Function to be called
+ * once the model is loaded. Will be passed
+ * the 3D model object.
+ * @param {function(Event)} [failureCallback] called with event error if
+ * the model fails to load.
+ * @return {p5.Geometry} the p5.Geometry object
+ *
+ * @example
+ *
+ *
+ * //draw a spinning octahedron
+ * let octahedron;
+ *
+ * function preload() {
+ * octahedron = loadModel('assets/octahedron.obj');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * model(octahedron);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Vertically rotating 3-d octahedron.
+ *
+ * @example
+ *
+ *
+ * //draw a spinning teapot
+ * let teapot;
+ *
+ * function preload() {
+ * // Load model with normalise parameter set to true
+ * teapot = loadModel('assets/teapot.obj', true);
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * scale(0.4); // Scaled to make model fit into canvas
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * normalMaterial(); // For effect
+ * model(teapot);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Vertically rotating 3-d teapot with red, green and blue gradient.
+ */ /**
+ * @method loadModel
+ * @param {String} path
+ * @param {function(p5.Geometry)} [successCallback]
+ * @param {function(Event)} [failureCallback]
+ * @return {p5.Geometry} the p5.Geometry object
+ */ _main.default.prototype.loadModel = function(path) {
+ _main.default._validateParameters('loadModel', arguments);
+ var normalize;
+ var successCallback;
+ var failureCallback;
+ if (typeof arguments[1] === 'boolean') {
+ normalize = arguments[1];
+ successCallback = arguments[2];
+ failureCallback = arguments[3];
+ } else {
+ normalize = false;
+ successCallback = arguments[1];
+ failureCallback = arguments[2];
+ }
+
+ var fileType = path.slice(-4);
+ var model = new _main.default.Geometry();
+ model.gid = ''.concat(path, '|').concat(normalize);
+ var self = this;
+
+ if (fileType === '.stl') {
+ this.httpDo(
+ path,
+ 'GET',
+ 'arrayBuffer',
+ function(arrayBuffer) {
+ parseSTL(model, arrayBuffer);
+
+ if (normalize) {
+ model.normalize();
+ }
+ self._decrementPreload();
+ if (typeof successCallback === 'function') {
+ successCallback(model);
+ }
+ },
+ failureCallback
+ );
+ } else if (fileType === '.obj') {
+ this.loadStrings(
+ path,
+ function(strings) {
+ parseObj(model, strings);
+
+ if (normalize) {
+ model.normalize();
+ }
+
+ self._decrementPreload();
+ if (typeof successCallback === 'function') {
+ successCallback(model);
+ }
+ },
+ failureCallback
+ );
+ } else {
+ _main.default._friendlyFileLoadError(3, path);
+
+ if (failureCallback) {
+ failureCallback();
+ } else {
+ console.error(
+ 'Sorry, the file type is invalid. Only OBJ and STL files are supported.'
+ );
+ }
+ }
+ return model;
+ };
+
+ /**
+ * Parse OBJ lines into model. For reference, this is what a simple model of a
+ * square might look like:
+ *
+ * v -0.5 -0.5 0.5
+ * v -0.5 -0.5 -0.5
+ * v -0.5 0.5 -0.5
+ * v -0.5 0.5 0.5
+ *
+ * f 4 3 2 1
+ */
+ function parseObj(model, lines) {
+ // OBJ allows a face to specify an index for a vertex (in the above example),
+ // but it also allows you to specify a custom combination of vertex, UV
+ // coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with
+ // UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different
+ // parameters must be a different vertex, so loadedVerts is used to
+ // temporarily store the parsed vertices, normals, etc., and indexedVerts is
+ // used to map a specific combination (keyed on, for example, the string
+ // "3/4/3"), to the actual index of the newly created vertex in the final
+ // object.
+ var loadedVerts = {
+ v: [],
+ vt: [],
+ vn: []
+ };
+
+ var indexedVerts = {};
+
+ for (var line = 0; line < lines.length; ++line) {
+ // Each line is a separate object (vertex, face, vertex normal, etc)
+ // For each line, split it into tokens on whitespace. The first token
+ // describes the type.
+ var tokens = lines[line].trim().split(/\b\s+/);
+
+ if (tokens.length > 0) {
+ if (tokens[0] === 'v' || tokens[0] === 'vn') {
+ // Check if this line describes a vertex or vertex normal.
+ // It will have three numeric parameters.
+ var vertex = new _main.default.Vector(
+ parseFloat(tokens[1]),
+ parseFloat(tokens[2]),
+ parseFloat(tokens[3])
+ );
+
+ loadedVerts[tokens[0]].push(vertex);
+ } else if (tokens[0] === 'vt') {
+ // Check if this line describes a texture coordinate.
+ // It will have two numeric parameters.
+ var texVertex = [parseFloat(tokens[1]), parseFloat(tokens[2])];
+ loadedVerts[tokens[0]].push(texVertex);
+ } else if (tokens[0] === 'f') {
+ // Check if this line describes a face.
+ // OBJ faces can have more than three points. Triangulate points.
+ for (var tri = 3; tri < tokens.length; ++tri) {
+ var face = [];
+
+ var vertexTokens = [1, tri - 1, tri];
+
+ for (var tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) {
+ // Now, convert the given token into an index
+ var vertString = tokens[vertexTokens[tokenInd]];
+ var vertIndex = 0;
+
+ // TODO: Faces can technically use negative numbers to refer to the
+ // previous nth vertex. I haven't seen this used in practice, but
+ // it might be good to implement this in the future.
+
+ if (indexedVerts[vertString] !== undefined) {
+ vertIndex = indexedVerts[vertString];
+ } else {
+ var vertParts = vertString.split('/');
+ for (var i = 0; i < vertParts.length; i++) {
+ vertParts[i] = parseInt(vertParts[i]) - 1;
+ }
+
+ vertIndex = indexedVerts[vertString] = model.vertices.length;
+ model.vertices.push(loadedVerts.v[vertParts[0]].copy());
+ if (loadedVerts.vt[vertParts[1]]) {
+ model.uvs.push(loadedVerts.vt[vertParts[1]].slice());
+ } else {
+ model.uvs.push([0, 0]);
+ }
+
+ if (loadedVerts.vn[vertParts[2]]) {
+ model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy());
+ }
+ }
+
+ face.push(vertIndex);
+ }
+
+ if (face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2]) {
+ model.faces.push(face);
+ }
+ }
+ }
+ }
+ }
+ // If the model doesn't have normals, compute the normals
+ if (model.vertexNormals.length === 0) {
+ model.computeNormals();
+ }
+
+ return model;
+ }
+
+ /**
+ * STL files can be of two types, ASCII and Binary,
+ *
+ * We need to convert the arrayBuffer to an array of strings,
+ * to parse it as an ASCII file.
+ */
+ function parseSTL(model, buffer) {
+ if (isBinary(buffer)) {
+ parseBinarySTL(model, buffer);
+ } else {
+ var reader = new DataView(buffer);
+
+ if (!('TextDecoder' in window)) {
+ console.warn(
+ 'Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)'
+ );
+
+ return model;
+ }
+
+ var decoder = new TextDecoder('utf-8');
+ var lines = decoder.decode(reader);
+ var lineArray = lines.split('\n');
+ parseASCIISTL(model, lineArray);
+ }
+ return model;
+ }
+
+ /**
+ * This function checks if the file is in ASCII format or in Binary format
+ *
+ * It is done by searching keyword `solid` at the start of the file.
+ *
+ * An ASCII STL data must begin with `solid` as the first six bytes.
+ * However, ASCII STLs lacking the SPACE after the `d` are known to be
+ * plentiful. So, check the first 5 bytes for `solid`.
+ *
+ * Several encodings, such as UTF-8, precede the text with up to 5 bytes:
+ * https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
+ * Search for `solid` to start anywhere after those prefixes.
+ */
+ function isBinary(data) {
+ var reader = new DataView(data);
+
+ // US-ASCII ordinal values for `s`, `o`, `l`, `i`, `d`
+ var solid = [115, 111, 108, 105, 100];
+ for (var off = 0; off < 5; off++) {
+ // If "solid" text is matched to the current offset, declare it to be an ASCII STL.
+ if (matchDataViewAt(solid, reader, off)) return false;
+ }
+
+ // Couldn't find "solid" text at the beginning; it is binary STL.
+ return true;
+ }
+
+ /**
+ * This function matches the `query` at the provided `offset`
+ */
+ function matchDataViewAt(query, reader, offset) {
+ // Check if each byte in query matches the corresponding byte from the current offset
+ for (var i = 0, il = query.length; i < il; i++) {
+ if (query[i] !== reader.getUint8(offset + i, false)) return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * This function parses the Binary STL files.
+ * https://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL
+ *
+ * Currently there is no support for the colors provided in STL files.
+ */
+ function parseBinarySTL(model, buffer) {
+ var reader = new DataView(buffer);
+
+ // Number of faces is present following the header
+ var faces = reader.getUint32(80, true);
+ var r,
+ g,
+ b,
+ hasColors = false,
+ colors;
+ var defaultR, defaultG, defaultB;
+
+ // Binary files contain 80-byte header, which is generally ignored.
+ for (var index = 0; index < 80 - 10; index++) {
+ // Check for `COLOR=`
+ if (
+ reader.getUint32(index, false) === 0x434f4c4f /*COLO*/ &&
+ reader.getUint8(index + 4) === 0x52 /*'R'*/ &&
+ reader.getUint8(index + 5) === 0x3d /*'='*/
+ ) {
+ hasColors = true;
+ colors = [];
+
+ defaultR = reader.getUint8(index + 6) / 255;
+ defaultG = reader.getUint8(index + 7) / 255;
+ defaultB = reader.getUint8(index + 8) / 255;
+ // To be used when color support is added
+ // alpha = reader.getUint8(index + 9) / 255;
+ }
+ }
+ var dataOffset = 84;
+ var faceLength = 12 * 4 + 2;
+
+ // Iterate the faces
+ for (var face = 0; face < faces; face++) {
+ var start = dataOffset + face * faceLength;
+ var normalX = reader.getFloat32(start, true);
+ var normalY = reader.getFloat32(start + 4, true);
+ var normalZ = reader.getFloat32(start + 8, true);
+
+ if (hasColors) {
+ var packedColor = reader.getUint16(start + 48, true);
+
+ if ((packedColor & 0x8000) === 0) {
+ // facet has its own unique color
+ r = (packedColor & 0x1f) / 31;
+ g = ((packedColor >> 5) & 0x1f) / 31;
+ b = ((packedColor >> 10) & 0x1f) / 31;
+ } else {
+ r = defaultR;
+ g = defaultG;
+ b = defaultB;
+ }
+ }
+
+ for (var i = 1; i <= 3; i++) {
+ var vertexstart = start + i * 12;
+
+ var newVertex = new _main.default.Vector(
+ reader.getFloat32(vertexstart, true),
+ reader.getFloat32(vertexstart + 8, true),
+ reader.getFloat32(vertexstart + 4, true)
+ );
+
+ model.vertices.push(newVertex);
+
+ if (hasColors) {
+ colors.push(r, g, b);
+ }
+ }
+
+ var newNormal = new _main.default.Vector(normalX, normalY, normalZ);
+
+ model.vertexNormals.push(newNormal, newNormal, newNormal);
+
+ model.faces.push([3 * face, 3 * face + 1, 3 * face + 2]);
+ model.uvs.push([0, 0], [0, 0], [0, 0]);
+ }
+ if (hasColors) {
+ // add support for colors here.
+ }
+ return model;
+ }
+
+ /**
+ * ASCII STL file starts with `solid 'nameOfFile'`
+ * Then contain the normal of the face, starting with `facet normal`
+ * Next contain a keyword indicating the start of face vertex, `outer loop`
+ * Next comes the three vertex, starting with `vertex x y z`
+ * Vertices ends with `endloop`
+ * Face ends with `endfacet`
+ * Next face starts with `facet normal`
+ * The end of the file is indicated by `endsolid`
+ */
+ function parseASCIISTL(model, lines) {
+ var state = '';
+ var curVertexIndex = [];
+ var newNormal, newVertex;
+
+ for (var iterator = 0; iterator < lines.length; ++iterator) {
+ var line = lines[iterator].trim();
+ var parts = line.split(' ');
+
+ for (var partsiterator = 0; partsiterator < parts.length; ++partsiterator) {
+ if (parts[partsiterator] === '') {
+ // Ignoring multiple whitespaces
+ parts.splice(partsiterator, 1);
+ }
+ }
+
+ if (parts.length === 0) {
+ // Remove newline
+ continue;
+ }
+
+ switch (state) {
+ case '': // First run
+ if (parts[0] !== 'solid') {
+ // Invalid state
+ console.error(line);
+ console.error(
+ 'Invalid state "'.concat(parts[0], '", should be "solid"')
+ );
+ return;
+ } else {
+ state = 'solid';
+ }
+ break;
+
+ case 'solid': // First face
+ if (parts[0] !== 'facet' || parts[1] !== 'normal') {
+ // Invalid state
+ console.error(line);
+ console.error(
+ 'Invalid state "'.concat(parts[0], '", should be "facet normal"')
+ );
+
+ return;
+ } else {
+ // Push normal for first face
+ newNormal = new _main.default.Vector(
+ parseFloat(parts[2]),
+ parseFloat(parts[3]),
+ parseFloat(parts[4])
+ );
+
+ model.vertexNormals.push(newNormal, newNormal, newNormal);
+ state = 'facet normal';
+ }
+ break;
+
+ case 'facet normal': // After normal is defined
+ if (parts[0] !== 'outer' || parts[1] !== 'loop') {
+ // Invalid State
+ console.error(line);
+ console.error(
+ 'Invalid state "'.concat(parts[0], '", should be "outer loop"')
+ );
+ return;
+ } else {
+ // Next should be vertices
+ state = 'vertex';
+ }
+ break;
+
+ case 'vertex':
+ if (parts[0] === 'vertex') {
+ //Vertex of triangle
+ newVertex = new _main.default.Vector(
+ parseFloat(parts[1]),
+ parseFloat(parts[2]),
+ parseFloat(parts[3])
+ );
+
+ model.vertices.push(newVertex);
+ model.uvs.push([0, 0]);
+ curVertexIndex.push(model.vertices.indexOf(newVertex));
+ } else if (parts[0] === 'endloop') {
+ // End of vertices
+ model.faces.push(curVertexIndex);
+ curVertexIndex = [];
+ state = 'endloop';
+ } else {
+ // Invalid State
+ console.error(line);
+ console.error(
+ 'Invalid state "'.concat(
+ parts[0],
+ '", should be "vertex" or "endloop"'
+ )
+ );
+
+ return;
+ }
+ break;
+
+ case 'endloop':
+ if (parts[0] !== 'endfacet') {
+ // End of face
+ console.error(line);
+ console.error(
+ 'Invalid state "'.concat(parts[0], '", should be "endfacet"')
+ );
+ return;
+ } else {
+ state = 'endfacet';
+ }
+ break;
+
+ case 'endfacet':
+ if (parts[0] === 'endsolid') {
+ // End of solid
+ } else if (parts[0] === 'facet' && parts[1] === 'normal') {
+ // Next face
+ newNormal = new _main.default.Vector(
+ parseFloat(parts[2]),
+ parseFloat(parts[3]),
+ parseFloat(parts[4])
+ );
+
+ model.vertexNormals.push(newNormal, newNormal, newNormal);
+ state = 'facet normal';
+ } else {
+ // Invalid State
+ console.error(line);
+ console.error(
+ 'Invalid state "'.concat(
+ parts[0],
+ '", should be "endsolid" or "facet normal"'
+ )
+ );
+
+ return;
+ }
+ break;
+
+ default:
+ console.error('Invalid state "'.concat(state, '"'));
+ break;
+ }
+ }
+ return model;
+ }
+
+ /**
+ * Render a 3d model to the screen.
+ *
+ * @method model
+ * @param {p5.Geometry} model Loaded 3d model to be rendered
+ * @example
+ *
+ *
+ * //draw a spinning octahedron
+ * let octahedron;
+ *
+ * function preload() {
+ * octahedron = loadModel('assets/octahedron.obj');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * model(octahedron);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Vertically rotating 3-d octahedron.
+ *
+ */
+ _main.default.prototype.model = function(model) {
+ this._assert3d('model');
+ _main.default._validateParameters('model', arguments);
+ if (model.vertices.length > 0) {
+ if (!this._renderer.geometryInHash(model.gid)) {
+ model._makeTriangleEdges()._edgesToVertices();
+ this._renderer.createBuffers(model.gid, model);
+ }
+
+ this._renderer.drawBuffers(model.gid);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 27, './p5.Geometry': 76 }
+ ],
+ 74: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ _dereq_('./p5.Texture');
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Lights, Camera
+ * @submodule Material
+ * @for p5
+ * @requires core
+ */ /**
+ * Loads a custom shader from the provided vertex and fragment
+ * shader paths. The shader files are loaded asynchronously in the
+ * background, so this method should be used in preload().
+ *
+ * For now, there are three main types of shaders. p5 will automatically
+ * supply appropriate vertices, normals, colors, and lighting attributes
+ * if the parameters defined in the shader match the names.
+ *
+ * @method loadShader
+ * @param {String} vertFilename path to file containing vertex shader
+ * source code
+ * @param {String} fragFilename path to file containing fragment shader
+ * source code
+ * @param {function} [callback] callback to be executed after loadShader
+ * completes. On success, the Shader object is passed as the first argument.
+ * @param {function} [errorCallback] callback to be executed when an error
+ * occurs inside loadShader. On error, the error is passed as the first
+ * argument.
+ * @return {p5.Shader} a shader object created from the provided
+ * vertex and fragment shader files.
+ *
+ * @example
+ *
+ *
+ * let mandel;
+ * function preload() {
+ * // load the shader definitions from files
+ * mandel = loadShader('assets/shader.vert', 'assets/shader.frag');
+ * }
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * // use the shader
+ * shader(mandel);
+ * noStroke();
+ * mandel.setUniform('p', [-0.74364388703, 0.13182590421]);
+ * }
+ *
+ * function draw() {
+ * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * zooming Mandelbrot set. a colorful, infinitely detailed fractal.
+ */ _main.default.prototype.loadShader = function(
+ vertFilename,
+ fragFilename,
+ callback,
+ errorCallback
+ ) {
+ _main.default._validateParameters('loadShader', arguments);
+ if (!errorCallback) {
+ errorCallback = console.error;
+ }
+
+ var loadedShader = new _main.default.Shader();
+
+ var self = this;
+ var loadedFrag = false;
+ var loadedVert = false;
+
+ var onLoad = function onLoad() {
+ self._decrementPreload();
+ if (callback) {
+ callback(loadedShader);
+ }
+ };
+
+ this.loadStrings(
+ vertFilename,
+ function(result) {
+ loadedShader._vertSrc = result.join('\n');
+ loadedVert = true;
+ if (loadedFrag) {
+ onLoad();
+ }
+ },
+ errorCallback
+ );
+
+ this.loadStrings(
+ fragFilename,
+ function(result) {
+ loadedShader._fragSrc = result.join('\n');
+ loadedFrag = true;
+ if (loadedVert) {
+ onLoad();
+ }
+ },
+ errorCallback
+ );
+
+ return loadedShader;
+ };
+
+ /**
+ * @method createShader
+ * @param {String} vertSrc source code for the vertex shader
+ * @param {String} fragSrc source code for the fragment shader
+ * @returns {p5.Shader} a shader object created from the provided
+ * vertex and fragment shaders.
+ *
+ * @example
+ *
+ *
+ * // the 'varying's are shared between both vertex & fragment shaders
+ * let varying = 'precision highp float; varying vec2 vPos;';
+ *
+ * // the vertex shader is called for each vertex
+ * let vs =
+ * varying +
+ * 'attribute vec3 aPosition;' +
+ * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';
+ *
+ * // the fragment shader is called for each pixel
+ * let fs =
+ * varying +
+ * 'uniform vec2 p;' +
+ * 'uniform float r;' +
+ * 'const int I = 500;' +
+ * 'void main() {' +
+ * ' vec2 c = p + vPos * r, z = c;' +
+ * ' float n = 0.0;' +
+ * ' for (int i = I; i > 0; i --) {' +
+ * ' if(z.x*z.x+z.y*z.y > 4.0) {' +
+ * ' n = float(i)/float(I);' +
+ * ' break;' +
+ * ' }' +
+ * ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +
+ * ' }' +
+ * ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +
+ * '}';
+ *
+ * let mandel;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ *
+ * // create and initialize the shader
+ * mandel = createShader(vs, fs);
+ * shader(mandel);
+ * noStroke();
+ *
+ * // 'p' is the center point of the Mandelbrot image
+ * mandel.setUniform('p', [-0.74364388703, 0.13182590421]);
+ * }
+ *
+ * function draw() {
+ * // 'r' is the size of the image in Mandelbrot-space
+ * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * zooming Mandelbrot set. a colorful, infinitely detailed fractal.
+ */
+ _main.default.prototype.createShader = function(vertSrc, fragSrc) {
+ this._assert3d('createShader');
+ _main.default._validateParameters('createShader', arguments);
+ return new _main.default.Shader(this._renderer, vertSrc, fragSrc);
+ };
+
+ /**
+ * The shader() function lets the user provide a custom shader
+ * to fill in shapes in WEBGL mode. Users can create their
+ * own shaders by loading vertex and fragment shaders with
+ * loadShader().
+ *
+ * @method shader
+ * @chainable
+ * @param {p5.Shader} [s] the desired p5.Shader to use for rendering
+ * shapes.
+ *
+ * @example
+ *
+ *
+ * // Click within the image to toggle
+ * // the shader used by the quad shape
+ * // Note: for an alternative approach to the same example,
+ * // involving changing uniforms please refer to:
+ * // https://p5js.org/reference/#/p5.Shader/setUniform
+ *
+ * let redGreen;
+ * let orangeBlue;
+ * let showRedGreen = false;
+ *
+ * function preload() {
+ * // note that we are using two instances
+ * // of the same vertex and fragment shaders
+ * redGreen = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');
+ * orangeBlue = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ *
+ * // initialize the colors for redGreen shader
+ * shader(redGreen);
+ * redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);
+ * redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);
+ *
+ * // initialize the colors for orangeBlue shader
+ * shader(orangeBlue);
+ * orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);
+ * orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);
+ *
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * // update the offset values for each shader,
+ * // moving orangeBlue in vertical and redGreen
+ * // in horizontal direction
+ * orangeBlue.setUniform('offset', [0, sin(millis() / 2000) + 1]);
+ * redGreen.setUniform('offset', [sin(millis() / 2000), 1]);
+ *
+ * if (showRedGreen === true) {
+ * shader(redGreen);
+ * } else {
+ * shader(orangeBlue);
+ * }
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ * function mouseClicked() {
+ * showRedGreen = !showRedGreen;
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.
+ */
+ _main.default.prototype.shader = function(s) {
+ this._assert3d('shader');
+ _main.default._validateParameters('shader', arguments);
+
+ if (s._renderer === undefined) {
+ s._renderer = this._renderer;
+ }
+
+ if (s.isStrokeShader()) {
+ this._renderer.userStrokeShader = s;
+ } else {
+ this._renderer.userFillShader = s;
+ this._renderer._useNormalMaterial = false;
+ }
+
+ s.init();
+
+ return this;
+ };
+
+ /**
+ * This function restores the default shaders in WEBGL mode. Code that runs
+ * after resetShader() will not be affected by previously defined
+ * shaders. Should be run after shader().
+ *
+ * @method resetShader
+ * @chainable
+ */
+ _main.default.prototype.resetShader = function() {
+ this._renderer.userFillShader = this._renderer.userStrokeShader = null;
+ return this;
+ };
+
+ /**
+ * Normal material for geometry. You can view all
+ * possible materials in this
+ * example.
+ * @method normalMaterial
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * normalMaterial();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Red, green and blue gradient.
+ *
+ */
+ _main.default.prototype.normalMaterial = function() {
+ this._assert3d('normalMaterial');
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('normalMaterial', args);
+ this._renderer.drawMode = constants.FILL;
+ this._renderer._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = true;
+ this._renderer.curFillColor = [1, 1, 1, 1];
+ this._renderer._setProperty('_doFill', true);
+ this.noStroke();
+ return this;
+ };
+
+ /**
+ * Texture for geometry. You can view other possible materials in this
+ * example.
+ * @method texture
+ * @param {p5.Image|p5.MediaElement|p5.Graphics} tex 2-dimensional graphics
+ * to render as texture
+ * @chainable
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * rotateZ(frameCount * 0.01);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * //pass image as texture
+ * texture(img);
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let pg;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * pg = createGraphics(200, 200);
+ * pg.textSize(75);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * pg.background(255);
+ * pg.text('hello!', 0, 100);
+ * //pass image as texture
+ * texture(pg);
+ * rotateX(0.5);
+ * noStroke();
+ * plane(50);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let vid;
+ * function preload() {
+ * vid = createVideo('assets/fingers.mov');
+ * vid.hide();
+ * }
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * //pass video frame as texture
+ * texture(vid);
+ * rect(-40, -40, 80, 80);
+ * }
+ *
+ * function mousePressed() {
+ * vid.loop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * Rotating view of many images umbrella and grid roof on a 3d plane
+ * black canvas
+ * black canvas
+ *
+ */
+ _main.default.prototype.texture = function(tex) {
+ this._assert3d('texture');
+ _main.default._validateParameters('texture', arguments);
+ if (tex.gifProperties) {
+ tex._animateGif(this);
+ }
+
+ this._renderer.drawMode = constants.TEXTURE;
+ this._renderer._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._tex = tex;
+ this._renderer._setProperty('_doFill', true);
+
+ return this;
+ };
+
+ /**
+ * Sets the coordinate space for texture mapping. The default mode is IMAGE
+ * which refers to the actual coordinates of the image.
+ * NORMAL refers to a normalized space of values ranging from 0 to 1.
+ * This function only works in WEBGL mode.
+ *
+ * With IMAGE, if an image is 100 x 200 pixels, mapping the image onto the entire
+ * size of a quad would require the points (0,0) (100, 0) (100,200) (0,200).
+ * The same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).
+ * @method textureMode
+ * @param {Constant} mode either IMAGE or NORMAL
+ * @example
+ *
+ *
+ * let img;
+ *
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * texture(img);
+ * textureMode(NORMAL);
+ * beginShape();
+ * vertex(-50, -50, 0, 0);
+ * vertex(50, -50, 1, 0);
+ * vertex(50, 50, 1, 1);
+ * vertex(-50, 50, 0, 1);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * the underside of a white umbrella and gridded ceiling above
+ *
+ *
+ *
+ * let img;
+ *
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * texture(img);
+ * textureMode(NORMAL);
+ * beginShape();
+ * vertex(-50, -50, 0, 0);
+ * vertex(50, -50, img.width, 0);
+ * vertex(50, 50, img.width, img.height);
+ * vertex(-50, 50, 0, img.height);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * the underside of a white umbrella and gridded ceiling above
+ *
+ */
+ _main.default.prototype.textureMode = function(mode) {
+ if (mode !== constants.IMAGE && mode !== constants.NORMAL) {
+ console.warn(
+ 'You tried to set '.concat(
+ mode,
+ ' textureMode only supports IMAGE & NORMAL '
+ )
+ );
+ } else {
+ this._renderer.textureMode = mode;
+ }
+ };
+
+ /**
+ * Sets the global texture wrapping mode. This controls how textures behave
+ * when their uv's go outside of the 0 - 1 range. There are three options:
+ * CLAMP, REPEAT, and MIRROR.
+ *
+ * CLAMP causes the pixels at the edge of the texture to extend to the bounds
+ * REPEAT causes the texture to tile repeatedly until reaching the bounds
+ * MIRROR works similarly to REPEAT but it flips the texture with every new tile
+ *
+ * REPEAT & MIRROR are only available if the texture
+ * is a power of two size (128, 256, 512, 1024, etc.).
+ *
+ * This method will affect all textures in your sketch until a subsequent
+ * textureWrap call is made.
+ *
+ * If only one argument is provided, it will be applied to both the
+ * horizontal and vertical axes.
+ * @method textureWrap
+ * @param {Constant} wrapX either CLAMP, REPEAT, or MIRROR
+ * @param {Constant} [wrapY] either CLAMP, REPEAT, or MIRROR
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies128.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * textureWrap(MIRROR);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ *
+ * let dX = mouseX;
+ * let dY = mouseY;
+ *
+ * let u = lerp(1.0, 2.0, dX);
+ * let v = lerp(1.0, 2.0, dY);
+ *
+ * scale(width / 2);
+ *
+ * texture(img);
+ *
+ * beginShape(TRIANGLES);
+ * vertex(-1, -1, 0, 0, 0);
+ * vertex(1, -1, 0, u, 0);
+ * vertex(1, 1, 0, u, v);
+ *
+ * vertex(1, 1, 0, u, v);
+ * vertex(-1, 1, 0, 0, v);
+ * vertex(-1, -1, 0, 0, 0);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * an image of the rocky mountains repeated in mirrored tiles
+ *
+ */
+ _main.default.prototype.textureWrap = function(wrapX) {
+ var wrapY =
+ arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : wrapX;
+ this._renderer.textureWrapX = wrapX;
+ this._renderer.textureWrapY = wrapY;
+
+ var textures = this._renderer.textures;
+ for (var i = 0; i < textures.length; i++) {
+ textures[i].setWrapMode(wrapX, wrapY);
+ }
+ };
+
+ /**
+ * Ambient material for geometry with a given color. You can view all
+ * possible materials in this
+ * example.
+ * @method ambientMaterial
+ * @param {Number} v1 gray value, red or hue value
+ * (depending on the current color mode),
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @param {Number} [a] opacity
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * ambientLight(200);
+ * ambientMaterial(70, 130, 230);
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * radiating light source from top right of canvas
+ *
+ */
+ /**
+ * @method ambientMaterial
+ * @param {Number[]|String|p5.Color} color color, color Array, or CSS color string
+ * @chainable
+ */
+ _main.default.prototype.ambientMaterial = function(v1, v2, v3, a) {
+ this._assert3d('ambientMaterial');
+ _main.default._validateParameters('ambientMaterial', arguments);
+
+ var color = _main.default.prototype.color.apply(this, arguments);
+ this._renderer.curFillColor = color._array;
+ this._renderer._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._enableLighting = true;
+ this._renderer._tex = null;
+
+ return this;
+ };
+
+ /**
+ * Sets the emissive color of the material used for geometry drawn to
+ * the screen. This is a misnomer in the sense that the material does not
+ * actually emit light that effects surrounding polygons. Instead,
+ * it gives the appearance that the object is glowing. An emissive material
+ * will display at full strength even if there is no light for it to reflect.
+ * @method emissiveMaterial
+ * @param {Number} v1 gray value, red or hue value
+ * (depending on the current color mode),
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @param {Number} [a] opacity
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * ambientLight(0);
+ * emissiveMaterial(130, 230, 0);
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * radiating light source from top right of canvas
+ */
+ /**
+ * @method emissiveMaterial
+ * @param {Number[]|String|p5.Color} color color, color Array, or CSS color string
+ * @chainable
+ */
+ _main.default.prototype.emissiveMaterial = function(v1, v2, v3, a) {
+ this._assert3d('emissiveMaterial');
+ _main.default._validateParameters('emissiveMaterial', arguments);
+
+ var color = _main.default.prototype.color.apply(this, arguments);
+ this._renderer.curFillColor = color._array;
+ this._renderer._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = true;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._enableLighting = true;
+ this._renderer._tex = null;
+
+ return this;
+ };
+
+ /**
+ * Specular material for geometry with a given color. You can view all
+ * possible materials in this
+ * example.
+ * @method specularMaterial
+ * @param {Number} v1 gray value, red or hue value
+ * (depending on the current color mode),
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @param {Number} [a] opacity
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * ambientLight(50);
+ * pointLight(250, 250, 250, 100, 100, 30);
+ * specularMaterial(250);
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * diffused radiating light source from top right of canvas
+ *
+ */
+ /**
+ * @method specularMaterial
+ * @param {Number[]|String|p5.Color} color color Array, or CSS color string
+ * @chainable
+ */
+ _main.default.prototype.specularMaterial = function(v1, v2, v3, a) {
+ this._assert3d('specularMaterial');
+ _main.default._validateParameters('specularMaterial', arguments);
+
+ var color = _main.default.prototype.color.apply(this, arguments);
+ this._renderer.curFillColor = color._array;
+ this._renderer._useSpecularMaterial = true;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._enableLighting = true;
+ this._renderer._tex = null;
+
+ return this;
+ };
+
+ /**
+ * Sets the amount of gloss in the surface of shapes.
+ * Used in combination with specularMaterial() in setting
+ * the material properties of shapes. The default and minimum value is 1.
+ * @method shininess
+ * @param {Number} shine Degree of Shininess.
+ * Defaults to 1.
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * let locX = mouseX - width / 2;
+ * let locY = mouseY - height / 2;
+ * ambientLight(60, 60, 60);
+ * pointLight(255, 255, 255, locX, locY, 50);
+ * specularMaterial(250);
+ * translate(-25, 0, 0);
+ * shininess(1);
+ * sphere(20);
+ * translate(50, 0, 0);
+ * shininess(20);
+ * sphere(20);
+ * }
+ *
+ *
+ * @alt
+ * Shininess on Camera changes position with mouse
+ */
+ _main.default.prototype.shininess = function(shine) {
+ this._assert3d('shininess');
+ _main.default._validateParameters('shininess', arguments);
+
+ if (shine < 1) {
+ shine = 1;
+ }
+ this._renderer._useShininess = shine;
+ return this;
+ };
+
+ /**
+ * @private blends colors according to color components.
+ * If alpha value is less than 1, we need to enable blending
+ * on our gl context. Otherwise opaque objects need to a depthMask.
+ * @param {Number[]} color [description]
+ * @return {Number[]]} Normalized numbers array
+ */
+ _main.default.RendererGL.prototype._applyColorBlend = function(colors) {
+ var gl = this.GL;
+
+ var isTexture = this.drawMode === constants.TEXTURE;
+ if (isTexture || colors[colors.length - 1] < 1.0 || this._isErasing) {
+ gl.depthMask(isTexture);
+ gl.enable(gl.BLEND);
+ this._applyBlendMode();
+ } else {
+ gl.depthMask(true);
+ gl.disable(gl.BLEND);
+ }
+ return colors;
+ };
+
+ /**
+ * @private sets blending in gl context to curBlendMode
+ * @param {Number[]} color [description]
+ * @return {Number[]]} Normalized numbers array
+ */
+ _main.default.RendererGL.prototype._applyBlendMode = function() {
+ var gl = this.GL;
+ switch (this.curBlendMode) {
+ case constants.BLEND:
+ case constants.ADD:
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
+ break;
+ case constants.REMOVE:
+ gl.blendEquation(gl.FUNC_REVERSE_SUBTRACT);
+ gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA);
+ break;
+ case constants.MULTIPLY:
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ONE, gl.ONE);
+ break;
+ case constants.SCREEN:
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ONE, gl.ONE, gl.ONE);
+ break;
+ case constants.EXCLUSION:
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
+ gl.blendFuncSeparate(
+ gl.ONE_MINUS_DST_COLOR,
+ gl.ONE_MINUS_SRC_COLOR,
+ gl.ONE,
+ gl.ONE
+ );
+
+ break;
+ case constants.REPLACE:
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ break;
+ case constants.SUBTRACT:
+ gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE);
+ break;
+ case constants.DARKEST:
+ if (this.blendExt) {
+ gl.blendEquationSeparate(this.blendExt.MIN_EXT, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
+ } else {
+ console.warn(
+ 'blendMode(DARKEST) does not work in your browser in WEBGL mode.'
+ );
+ }
+ break;
+ case constants.LIGHTEST:
+ if (this.blendExt) {
+ gl.blendEquationSeparate(this.blendExt.MAX_EXT, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
+ } else {
+ console.warn(
+ 'blendMode(LIGHTEST) does not work in your browser in WEBGL mode.'
+ );
+ }
+ break;
+ default:
+ console.error(
+ 'Oops! Somehow RendererGL set curBlendMode to an unsupported mode.'
+ );
+
+ break;
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27, './p5.Texture': 82 }
+ ],
+ 75: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /** ////////////////////////////////////////////////////////////////////////////////
+ * @module Lights, Camera
+ * @submodule Camera
+ * @requires core
+ */
+ // p5.Prototype Methods
+ ////////////////////////////////////////////////////////////////////////////////
+ /**
+ * Sets the camera position for a 3D sketch. Parameters for this function define
+ * the position for the camera, the center of the sketch (where the camera is
+ * pointing), and an up direction (the orientation of the camera).
+ *
+ * This function simulates the movements of the camera, allowing objects to be
+ * viewed from various angles. Remember, it does not move the objects themselves
+ * but the camera instead. For example when centerX value is positive, the camera
+ * is rotating to the right side of the sketch, so the object would seem like
+ * moving to the left.
+ *
+ * See this example to view the position of your camera.
+ *
+ * When called with no arguments, this function creates a default camera
+ * equivalent to
+ * camera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);
+ * @method camera
+ * @for p5
+ * @param {Number} [x] camera position value on x axis
+ * @param {Number} [y] camera position value on y axis
+ * @param {Number} [z] camera position value on z axis
+ * @param {Number} [centerX] x coordinate representing center of the sketch
+ * @param {Number} [centerY] y coordinate representing center of the sketch
+ * @param {Number} [centerZ] z coordinate representing center of the sketch
+ * @param {Number} [upX] x component of direction 'up' from camera
+ * @param {Number} [upY] y component of direction 'up' from camera
+ * @param {Number} [upZ] z component of direction 'up' from camera
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(204);
+ * //move the camera away from the plane by a sin wave
+ * camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);
+ * plane(10, 10);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * //move slider to see changes!
+ * //sliders control the first 6 parameters of camera()
+ * let sliderGroup = [];
+ * let X;
+ * let Y;
+ * let Z;
+ * let centerX;
+ * let centerY;
+ * let centerZ;
+ * let h = 20;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * //create sliders
+ * for (var i = 0; i < 6; i++) {
+ * if (i === 2) {
+ * sliderGroup[i] = createSlider(10, 400, 200);
+ * } else {
+ * sliderGroup[i] = createSlider(-400, 400, 0);
+ * }
+ * h = map(i, 0, 6, 5, 85);
+ * sliderGroup[i].position(10, height + h);
+ * sliderGroup[i].style('width', '80px');
+ * }
+ * }
+ *
+ * function draw() {
+ * background(60);
+ * // assigning sliders' value to each parameters
+ * X = sliderGroup[0].value();
+ * Y = sliderGroup[1].value();
+ * Z = sliderGroup[2].value();
+ * centerX = sliderGroup[3].value();
+ * centerY = sliderGroup[4].value();
+ * centerZ = sliderGroup[5].value();
+ * camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);
+ * stroke(255);
+ * fill(255, 102, 94);
+ * box(85);
+ * }
+ *
+ *
+ * @alt
+ * White square repeatedly grows to fill canvas and then shrinks.
+ *
+ */ _main.default.prototype.camera = function() {
+ var _this$_renderer$_curC;
+ this._assert3d('camera');
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('camera', args);
+ (_this$_renderer$_curC = this._renderer._curCamera).camera.apply(
+ _this$_renderer$_curC,
+ args
+ );
+ return this;
+ };
+
+ /**
+ * Sets a perspective projection for the camera in a 3D sketch. This projection
+ * represents depth through foreshortening: objects that are close to the camera
+ * appear their actual size while those that are further away from the camera
+ * appear smaller. The parameters to this function define the viewing frustum
+ * (the truncated pyramid within which objects are seen by the camera) through
+ * vertical field of view, aspect ratio (usually width/height), and near and far
+ * clipping planes.
+ *
+ * When called with no arguments, the defaults
+ * provided are equivalent to
+ * perspective(PI/3.0, width/height, eyeZ/10.0, eyeZ*10.0), where eyeZ
+ * is equal to ((height/2.0) / tan(PI*60.0/360.0));
+ * @method perspective
+ * @for p5
+ * @param {Number} [fovy] camera frustum vertical field of view,
+ * from bottom to top of view, in angleMode units
+ * @param {Number} [aspect] camera frustum aspect ratio
+ * @param {Number} [near] frustum near plane length
+ * @param {Number} [far] frustum far plane length
+ * @chainable
+ * @example
+ *
+ *
+ * //drag the mouse to look around!
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * perspective(PI / 3.0, width / height, 0.1, 500);
+ * }
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * normalMaterial();
+ *
+ * rotateX(-0.3);
+ * rotateY(-0.2);
+ * translate(0, 0, -50);
+ *
+ * push();
+ * translate(-15, 0, sin(frameCount / 30) * 95);
+ * box(30);
+ * pop();
+ * push();
+ * translate(15, 0, sin(frameCount / 30 + PI) * 95);
+ * box(30);
+ * pop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two colored 3D boxes move back and forth, rotating as mouse is dragged.
+ *
+ */
+ _main.default.prototype.perspective = function() {
+ var _this$_renderer$_curC2;
+ this._assert3d('perspective');
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('perspective', args);
+ (_this$_renderer$_curC2 = this._renderer._curCamera).perspective.apply(
+ _this$_renderer$_curC2,
+ args
+ );
+ return this;
+ };
+
+ /**
+ * Sets an orthographic projection for the camera in a 3D sketch and defines a
+ * box-shaped viewing frustum within which objects are seen. In this projection,
+ * all objects with the same dimension appear the same size, regardless of
+ * whether they are near or far from the camera. The parameters to this
+ * function specify the viewing frustum where left and right are the minimum and
+ * maximum x values, top and bottom are the minimum and maximum y values, and near
+ * and far are the minimum and maximum z values. If no parameters are given, the
+ * default is used: ortho(-width/2, width/2, -height/2, height/2).
+ * @method ortho
+ * @for p5
+ * @param {Number} [left] camera frustum left plane
+ * @param {Number} [right] camera frustum right plane
+ * @param {Number} [bottom] camera frustum bottom plane
+ * @param {Number} [top] camera frustum top plane
+ * @param {Number} [near] camera frustum near plane
+ * @param {Number} [far] camera frustum far plane
+ * @chainable
+ * @example
+ *
+ *
+ * //drag the mouse to look around!
+ * //there's no vanishing point
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);
+ * }
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * normalMaterial();
+ *
+ * rotateX(0.2);
+ * rotateY(-0.2);
+ * push();
+ * translate(-15, 0, sin(frameCount / 30) * 65);
+ * box(30);
+ * pop();
+ * push();
+ * translate(15, 0, sin(frameCount / 30 + PI) * 65);
+ * box(30);
+ * pop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ *
+ */
+ _main.default.prototype.ortho = function() {
+ var _this$_renderer$_curC3;
+ this._assert3d('ortho');
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('ortho', args);
+ (_this$_renderer$_curC3 = this._renderer._curCamera).ortho.apply(
+ _this$_renderer$_curC3,
+ args
+ );
+ return this;
+ };
+
+ /**
+ * Sets a perspective matrix as defined by the parameters.
+ *
+ * A frustum is a geometric form: a pyramid with its top
+ * cut off. With the viewer's eye at the imaginary top of
+ * the pyramid, the six planes of the frustum act as clipping
+ * planes when rendering a 3D view. Thus, any form inside the
+ * clipping planes is visible; anything outside
+ * those planes is not visible.
+ *
+ * Setting the frustum changes the perspective of the scene being rendered.
+ * This can be achieved more simply in many cases by using
+ * perspective().
+ *
+ * @method frustum
+ * @for p5
+ * @param {Number} [left] camera frustum left plane
+ * @param {Number} [right] camera frustum right plane
+ * @param {Number} [bottom] camera frustum bottom plane
+ * @param {Number} [top] camera frustum top plane
+ * @param {Number} [near] camera frustum near plane
+ * @param {Number} [far] camera frustum far plane
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200);
+ * }
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * strokeWeight(10);
+ * stroke(0, 0, 255);
+ * noFill();
+ *
+ * rotateY(-0.2);
+ * rotateX(-0.3);
+ * push();
+ * translate(-15, 0, sin(frameCount / 30) * 25);
+ * box(30);
+ * pop();
+ * push();
+ * translate(15, 0, sin(frameCount / 30 + PI) * 25);
+ * box(30);
+ * pop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ *
+ */
+ _main.default.prototype.frustum = function() {
+ var _this$_renderer$_curC4;
+ this._assert3d('frustum');
+ for (
+ var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;
+ _key4 < _len4;
+ _key4++
+ ) {
+ args[_key4] = arguments[_key4];
+ }
+ _main.default._validateParameters('frustum', args);
+ (_this$_renderer$_curC4 = this._renderer._curCamera).frustum.apply(
+ _this$_renderer$_curC4,
+ args
+ );
+ return this;
+ };
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // p5.Camera
+ ////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Creates a new p5.Camera object and tells the
+ * renderer to use that camera.
+ * Returns the p5.Camera object.
+ * @method createCamera
+ * @return {p5.Camera} The newly created camera object.
+ * @for p5
+ */
+ _main.default.prototype.createCamera = function() {
+ this._assert3d('createCamera');
+ var _cam = new _main.default.Camera(this._renderer);
+
+ // compute default camera settings, then set a default camera
+ _cam._computeCameraDefaultSettings();
+ _cam._setDefaultCamera();
+
+ // set renderer current camera to the new camera
+ this._renderer._curCamera = _cam;
+
+ return _cam;
+ };
+
+ /**
+ * This class describes a camera for use in p5's
+ *
+ * WebGL mode. It contains camera position, orientation, and projection
+ * information necessary for rendering a 3D scene.
+ *
+ * New p5.Camera objects can be made through the
+ * createCamera() function and controlled through
+ * the methods described below. A camera created in this way will use a default
+ * position in the scene and a default perspective projection until these
+ * properties are changed through the various methods available. It is possible
+ * to create multiple cameras, in which case the current camera
+ * can be set through the setCamera() method.
+ *
+ *
+ * Note:
+ * The methods below operate in two coordinate systems: the 'world' coordinate
+ * system describe positions in terms of their relationship to the origin along
+ * the X, Y and Z axes whereas the camera's 'local' coordinate system
+ * describes positions from the camera's point of view: left-right, up-down,
+ * and forward-backward. The move() method,
+ * for instance, moves the camera along its own axes, whereas the
+ * setPosition()
+ * method sets the camera's position in world-space.
+ *
+ *
+ * @class p5.Camera
+ * @param {rendererGL} rendererGL instance of WebGL renderer
+ * @example
+ *
+ *
+ * let cam;
+ * let delta = 0.01;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * // set initial pan angle
+ * cam.pan(-0.8);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // pan camera according to angle 'delta'
+ * cam.pan(delta);
+ *
+ * // every 160 frames, switch direction
+ * if (frameCount % 160 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * rotateX(frameCount * 0.01);
+ * translate(-100, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view pans left and right across a series of rotating 3D boxes.
+ *
+ */
+ _main.default.Camera = function(renderer) {
+ this._renderer = renderer;
+
+ this.cameraType = 'default';
+
+ this.cameraMatrix = new _main.default.Matrix();
+ this.projMatrix = new _main.default.Matrix();
+ };
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Camera Projection Methods
+ ////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Sets a perspective projection for a p5.Camera object and sets parameters
+ * for that projection according to perspective()
+ * syntax.
+ * @method perspective
+ * @for p5.Camera
+ */
+ _main.default.Camera.prototype.perspective = function(fovy, aspect, near, far) {
+ this.cameraType = arguments.length > 0 ? 'custom' : 'default';
+ if (typeof fovy === 'undefined') {
+ fovy = this.defaultCameraFOV;
+ // this avoids issue where setting angleMode(DEGREES) before calling
+ // perspective leads to a smaller than expected FOV (because
+ // _computeCameraDefaultSettings computes in radians)
+ this.cameraFOV = fovy;
+ } else {
+ this.cameraFOV = this._renderer._pInst._toRadians(fovy);
+ }
+ if (typeof aspect === 'undefined') {
+ aspect = this.defaultAspectRatio;
+ }
+ if (typeof near === 'undefined') {
+ near = this.defaultCameraNear;
+ }
+ if (typeof far === 'undefined') {
+ far = this.defaultCameraFar;
+ }
+
+ if (near <= 0.0001) {
+ near = 0.01;
+ console.log(
+ 'Avoid perspective near plane values close to or below 0. ' +
+ 'Setting value to 0.01.'
+ );
+ }
+
+ if (far < near) {
+ console.log(
+ 'Perspective far plane value is less than near plane value. ' +
+ 'Nothing will be shown.'
+ );
+ }
+
+ this.aspectRatio = aspect;
+ this.cameraNear = near;
+ this.cameraFar = far;
+
+ this.projMatrix = _main.default.Matrix.identity();
+
+ var f = 1.0 / Math.tan(this.cameraFOV / 2);
+ var nf = 1.0 / (this.cameraNear - this.cameraFar);
+
+ // prettier-ignore
+ this.projMatrix.set(f / aspect, 0, 0, 0,
+ 0, -f, 0, 0,
+ 0, 0, (far + near) * nf, -1,
+ 0, 0, 2 * far * near * nf, 0);
+
+ if (this._isActive()) {
+ this._renderer.uPMatrix.set(
+ this.projMatrix.mat4[0],
+ this.projMatrix.mat4[1],
+ this.projMatrix.mat4[2],
+ this.projMatrix.mat4[3],
+ this.projMatrix.mat4[4],
+ this.projMatrix.mat4[5],
+ this.projMatrix.mat4[6],
+ this.projMatrix.mat4[7],
+ this.projMatrix.mat4[8],
+ this.projMatrix.mat4[9],
+ this.projMatrix.mat4[10],
+ this.projMatrix.mat4[11],
+ this.projMatrix.mat4[12],
+ this.projMatrix.mat4[13],
+ this.projMatrix.mat4[14],
+ this.projMatrix.mat4[15]
+ );
+ }
+ };
+
+ /**
+ * Sets an orthographic projection for a p5.Camera object and sets parameters
+ * for that projection according to ortho() syntax.
+ * @method ortho
+ * @for p5.Camera
+ */
+ _main.default.Camera.prototype.ortho = function(
+ left,
+ right,
+ bottom,
+ top,
+ near,
+ far
+ ) {
+ if (left === undefined) left = -this._renderer.width / 2;
+ if (right === undefined) right = +this._renderer.width / 2;
+ if (bottom === undefined) bottom = -this._renderer.height / 2;
+ if (top === undefined) top = +this._renderer.height / 2;
+ if (near === undefined) near = 0;
+ if (far === undefined)
+ far = Math.max(this._renderer.width, this._renderer.height);
+
+ var w = right - left;
+ var h = top - bottom;
+ var d = far - near;
+
+ var x = +2.0 / w;
+ var y = +2.0 / h;
+ var z = -2.0 / d;
+
+ var tx = -(right + left) / w;
+ var ty = -(top + bottom) / h;
+ var tz = -(far + near) / d;
+
+ this.projMatrix = _main.default.Matrix.identity();
+
+ // prettier-ignore
+ this.projMatrix.set(x, 0, 0, 0,
+ 0, -y, 0, 0,
+ 0, 0, z, 0,
+ tx, ty, tz, 1);
+
+ if (this._isActive()) {
+ this._renderer.uPMatrix.set(
+ this.projMatrix.mat4[0],
+ this.projMatrix.mat4[1],
+ this.projMatrix.mat4[2],
+ this.projMatrix.mat4[3],
+ this.projMatrix.mat4[4],
+ this.projMatrix.mat4[5],
+ this.projMatrix.mat4[6],
+ this.projMatrix.mat4[7],
+ this.projMatrix.mat4[8],
+ this.projMatrix.mat4[9],
+ this.projMatrix.mat4[10],
+ this.projMatrix.mat4[11],
+ this.projMatrix.mat4[12],
+ this.projMatrix.mat4[13],
+ this.projMatrix.mat4[14],
+ this.projMatrix.mat4[15]
+ );
+ }
+
+ this.cameraType = 'custom';
+ };
+
+ /**
+ * @method frustum
+ * @for p5.Camera
+ */
+ _main.default.Camera.prototype.frustum = function(
+ left,
+ right,
+ bottom,
+ top,
+ near,
+ far
+ ) {
+ if (left === undefined) left = -this._renderer.width / 2;
+ if (right === undefined) right = +this._renderer.width / 2;
+ if (bottom === undefined) bottom = -this._renderer.height / 2;
+ if (top === undefined) top = +this._renderer.height / 2;
+ if (near === undefined) near = 0;
+ if (far === undefined)
+ far = Math.max(this._renderer.width, this._renderer.height);
+
+ var w = right - left;
+ var h = top - bottom;
+ var d = far - near;
+
+ var x = +(2.0 * near) / w;
+ var y = +(2.0 * near) / h;
+ var z = -(2.0 * far * near) / d;
+
+ var tx = (right + left) / w;
+ var ty = (top + bottom) / h;
+ var tz = -(far + near) / d;
+
+ this.projMatrix = _main.default.Matrix.identity();
+
+ // prettier-ignore
+ this.projMatrix.set(x, 0, 0, 0,
+ 0, y, 0, 0,
+ tx, ty, tz, -1,
+ 0, 0, z, 0);
+
+ if (this._isActive()) {
+ this._renderer.uPMatrix.set(
+ this.projMatrix.mat4[0],
+ this.projMatrix.mat4[1],
+ this.projMatrix.mat4[2],
+ this.projMatrix.mat4[3],
+ this.projMatrix.mat4[4],
+ this.projMatrix.mat4[5],
+ this.projMatrix.mat4[6],
+ this.projMatrix.mat4[7],
+ this.projMatrix.mat4[8],
+ this.projMatrix.mat4[9],
+ this.projMatrix.mat4[10],
+ this.projMatrix.mat4[11],
+ this.projMatrix.mat4[12],
+ this.projMatrix.mat4[13],
+ this.projMatrix.mat4[14],
+ this.projMatrix.mat4[15]
+ );
+ }
+
+ this.cameraType = 'custom';
+ };
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Camera Orientation Methods
+ ////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Rotate camera view about arbitrary axis defined by x,y,z
+ * based on http://learnwebgl.brown37.net/07_cameras/camera_rotating_motion.html
+ * @method _rotateView
+ * @private
+ */
+ _main.default.Camera.prototype._rotateView = function(a, x, y, z) {
+ var centerX = this.centerX;
+ var centerY = this.centerY;
+ var centerZ = this.centerZ;
+
+ // move center by eye position such that rotation happens around eye position
+ centerX -= this.eyeX;
+ centerY -= this.eyeY;
+ centerZ -= this.eyeZ;
+
+ var rotation = _main.default.Matrix.identity(this._renderer._pInst);
+ rotation.rotate(this._renderer._pInst._toRadians(a), x, y, z);
+
+ // prettier-ignore
+ var rotatedCenter = [
+ centerX * rotation.mat4[0] + centerY * rotation.mat4[4] + centerZ * rotation.mat4[8],
+ centerX * rotation.mat4[1] + centerY * rotation.mat4[5] + centerZ * rotation.mat4[9],
+ centerX * rotation.mat4[2] + centerY * rotation.mat4[6] + centerZ * rotation.mat4[10]];
+
+ // add eye position back into center
+ rotatedCenter[0] += this.eyeX;
+ rotatedCenter[1] += this.eyeY;
+ rotatedCenter[2] += this.eyeZ;
+
+ this.camera(
+ this.eyeX,
+ this.eyeY,
+ this.eyeZ,
+ rotatedCenter[0],
+ rotatedCenter[1],
+ rotatedCenter[2],
+ this.upX,
+ this.upY,
+ this.upZ
+ );
+ };
+
+ /**
+ * Panning rotates the camera view to the left and right.
+ * @method pan
+ * @param {Number} angle amount to rotate camera in current
+ * angleMode units.
+ * Greater than 0 values rotate counterclockwise (to the left).
+ * @example
+ *
+ *
+ * let cam;
+ * let delta = 0.01;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * // set initial pan angle
+ * cam.pan(-0.8);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // pan camera according to angle 'delta'
+ * cam.pan(delta);
+ *
+ * // every 160 frames, switch direction
+ * if (frameCount % 160 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * rotateX(frameCount * 0.01);
+ * translate(-100, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view pans left and right across a series of rotating 3D boxes.
+ *
+ */
+ _main.default.Camera.prototype.pan = function(amount) {
+ var local = this._getLocalAxes();
+ this._rotateView(amount, local.y[0], local.y[1], local.y[2]);
+ };
+
+ /**
+ * Tilting rotates the camera view up and down.
+ * @method tilt
+ * @param {Number} angle amount to rotate camera in current
+ * angleMode units.
+ * Greater than 0 values rotate counterclockwise (to the left).
+ * @example
+ *
+ *
+ * let cam;
+ * let delta = 0.01;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * // set initial tilt
+ * cam.tilt(-0.8);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // pan camera according to angle 'delta'
+ * cam.tilt(delta);
+ *
+ * // every 160 frames, switch direction
+ * if (frameCount % 160 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * rotateY(frameCount * 0.01);
+ * translate(0, -100, 0);
+ * box(20);
+ * translate(0, 35, 0);
+ * box(20);
+ * translate(0, 35, 0);
+ * box(20);
+ * translate(0, 35, 0);
+ * box(20);
+ * translate(0, 35, 0);
+ * box(20);
+ * translate(0, 35, 0);
+ * box(20);
+ * translate(0, 35, 0);
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view tilts up and down across a series of rotating 3D boxes.
+ */
+ _main.default.Camera.prototype.tilt = function(amount) {
+ var local = this._getLocalAxes();
+ this._rotateView(amount, local.x[0], local.x[1], local.x[2]);
+ };
+
+ /**
+ * Reorients the camera to look at a position in world space.
+ * @method lookAt
+ * @for p5.Camera
+ * @param {Number} x x position of a point in world space
+ * @param {Number} y y position of a point in world space
+ * @param {Number} z z position of a point in world space
+ * @example
+ *
+ *
+ * let cam;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // look at a new random point every 60 frames
+ * if (frameCount % 60 === 0) {
+ * cam.lookAt(random(-100, 100), random(-50, 50), 0);
+ * }
+ *
+ * rotateX(frameCount * 0.01);
+ * translate(-100, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view of rotating 3D cubes changes to look at a new random
+ * point every second .
+ */
+ _main.default.Camera.prototype.lookAt = function(x, y, z) {
+ this.camera(
+ this.eyeX,
+ this.eyeY,
+ this.eyeZ,
+ x,
+ y,
+ z,
+ this.upX,
+ this.upY,
+ this.upZ
+ );
+ };
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Camera Position Methods
+ ////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Sets a camera's position and orientation. This is equivalent to calling
+ * camera() on a p5.Camera object.
+ * @method camera
+ * @for p5.Camera
+ */
+ _main.default.Camera.prototype.camera = function(
+ eyeX,
+ eyeY,
+ eyeZ,
+ centerX,
+ centerY,
+ centerZ,
+ upX,
+ upY,
+ upZ
+ ) {
+ if (typeof eyeX === 'undefined') {
+ eyeX = this.defaultEyeX;
+ eyeY = this.defaultEyeY;
+ eyeZ = this.defaultEyeZ;
+ centerX = eyeX;
+ centerY = eyeY;
+ centerZ = 0;
+ upX = 0;
+ upY = 1;
+ upZ = 0;
+ }
+
+ this.eyeX = eyeX;
+ this.eyeY = eyeY;
+ this.eyeZ = eyeZ;
+
+ this.centerX = centerX;
+ this.centerY = centerY;
+ this.centerZ = centerZ;
+
+ this.upX = upX;
+ this.upY = upY;
+ this.upZ = upZ;
+
+ var local = this._getLocalAxes();
+
+ // the camera affects the model view matrix, insofar as it
+ // inverse translates the world to the eye position of the camera
+ // and rotates it.
+ // prettier-ignore
+ this.cameraMatrix.set(local.x[0], local.y[0], local.z[0], 0,
+ local.x[1], local.y[1], local.z[1], 0,
+ local.x[2], local.y[2], local.z[2], 0,
+ 0, 0, 0, 1);
+
+ var tx = -eyeX;
+ var ty = -eyeY;
+ var tz = -eyeZ;
+
+ this.cameraMatrix.translate([tx, ty, tz]);
+
+ if (this._isActive()) {
+ this._renderer.uMVMatrix.set(
+ this.cameraMatrix.mat4[0],
+ this.cameraMatrix.mat4[1],
+ this.cameraMatrix.mat4[2],
+ this.cameraMatrix.mat4[3],
+ this.cameraMatrix.mat4[4],
+ this.cameraMatrix.mat4[5],
+ this.cameraMatrix.mat4[6],
+ this.cameraMatrix.mat4[7],
+ this.cameraMatrix.mat4[8],
+ this.cameraMatrix.mat4[9],
+ this.cameraMatrix.mat4[10],
+ this.cameraMatrix.mat4[11],
+ this.cameraMatrix.mat4[12],
+ this.cameraMatrix.mat4[13],
+ this.cameraMatrix.mat4[14],
+ this.cameraMatrix.mat4[15]
+ );
+ }
+ return this;
+ };
+
+ /**
+ * Move camera along its local axes while maintaining current camera orientation.
+ * @method move
+ * @param {Number} x amount to move along camera's left-right axis
+ * @param {Number} y amount to move along camera's up-down axis
+ * @param {Number} z amount to move along camera's forward-backward axis
+ * @example
+ *
+ *
+ * // see the camera move along its own axes while maintaining its orientation
+ * let cam;
+ * let delta = 0.5;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // move the camera along its local axes
+ * cam.move(delta, delta, 0);
+ *
+ * // every 100 frames, switch direction
+ * if (frameCount % 150 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * translate(-10, -10, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view moves along a series of 3D boxes, maintaining the same
+ * orientation throughout the move
+ */
+ _main.default.Camera.prototype.move = function(x, y, z) {
+ var local = this._getLocalAxes();
+
+ // scale local axes by movement amounts
+ // based on http://learnwebgl.brown37.net/07_cameras/camera_linear_motion.html
+ var dx = [local.x[0] * x, local.x[1] * x, local.x[2] * x];
+ var dy = [local.y[0] * y, local.y[1] * y, local.y[2] * y];
+ var dz = [local.z[0] * z, local.z[1] * z, local.z[2] * z];
+
+ this.camera(
+ this.eyeX + dx[0] + dy[0] + dz[0],
+ this.eyeY + dx[1] + dy[1] + dz[1],
+ this.eyeZ + dx[2] + dy[2] + dz[2],
+ this.centerX + dx[0] + dy[0] + dz[0],
+ this.centerY + dx[1] + dy[1] + dz[1],
+ this.centerZ + dx[2] + dy[2] + dz[2],
+ 0,
+ 1,
+ 0
+ );
+ };
+
+ /**
+ * Set camera position in world-space while maintaining current camera
+ * orientation.
+ * @method setPosition
+ * @param {Number} x x position of a point in world space
+ * @param {Number} y y position of a point in world space
+ * @param {Number} z z position of a point in world space
+ * @example
+ *
+ *
+ * // press '1' '2' or '3' keys to set camera position
+ *
+ * let cam;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // '1' key
+ * if (keyIsDown(49)) {
+ * cam.setPosition(30, 0, 80);
+ * }
+ * // '2' key
+ * if (keyIsDown(50)) {
+ * cam.setPosition(0, 0, 80);
+ * }
+ * // '3' key
+ * if (keyIsDown(51)) {
+ * cam.setPosition(-30, 0, 80);
+ * }
+ *
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera position changes as the user presses keys, altering view of a 3D box
+ */
+ _main.default.Camera.prototype.setPosition = function(x, y, z) {
+ var diffX = x - this.eyeX;
+ var diffY = y - this.eyeY;
+ var diffZ = z - this.eyeZ;
+
+ this.camera(
+ x,
+ y,
+ z,
+ this.centerX + diffX,
+ this.centerY + diffY,
+ this.centerZ + diffZ,
+ 0,
+ 1,
+ 0
+ );
+ };
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Camera Helper Methods
+ ////////////////////////////////////////////////////////////////////////////////
+
+ // @TODO: combine this function with _setDefaultCamera to compute these values
+ // as-needed
+ _main.default.Camera.prototype._computeCameraDefaultSettings = function() {
+ this.defaultCameraFOV = 60 / 180 * Math.PI;
+ this.defaultAspectRatio = this._renderer.width / this._renderer.height;
+ this.defaultEyeX = 0;
+ this.defaultEyeY = 0;
+ this.defaultEyeZ =
+ this._renderer.height / 2.0 / Math.tan(this.defaultCameraFOV / 2.0);
+ this.defaultCenterX = 0;
+ this.defaultCenterY = 0;
+ this.defaultCenterZ = 0;
+ this.defaultCameraNear = this.defaultEyeZ * 0.1;
+ this.defaultCameraFar = this.defaultEyeZ * 10;
+ };
+
+ //detect if user didn't set the camera
+ //then call this function below
+ _main.default.Camera.prototype._setDefaultCamera = function() {
+ this.cameraFOV = this.defaultCameraFOV;
+ this.aspectRatio = this.defaultAspectRatio;
+ this.eyeX = this.defaultEyeX;
+ this.eyeY = this.defaultEyeY;
+ this.eyeZ = this.defaultEyeZ;
+ this.centerX = this.defaultCenterX;
+ this.centerY = this.defaultCenterY;
+ this.centerZ = this.defaultCenterZ;
+ this.upX = 0;
+ this.upY = 1;
+ this.upZ = 0;
+ this.cameraNear = this.defaultCameraNear;
+ this.cameraFar = this.defaultCameraFar;
+
+ this.perspective();
+ this.camera();
+
+ this.cameraType = 'default';
+ };
+
+ _main.default.Camera.prototype._resize = function() {
+ // If we're using the default camera, update the aspect ratio
+ if (this.cameraType === 'default') {
+ this._computeCameraDefaultSettings();
+ this._setDefaultCamera();
+ } else {
+ this.perspective(
+ this.cameraFOV,
+ this._renderer.width / this._renderer.height
+ );
+ }
+ };
+
+ /**
+ * Returns a copy of a camera.
+ * @method copy
+ * @private
+ */
+ _main.default.Camera.prototype.copy = function() {
+ var _cam = new _main.default.Camera(this._renderer);
+ _cam.cameraFOV = this.cameraFOV;
+ _cam.aspectRatio = this.aspectRatio;
+ _cam.eyeX = this.eyeX;
+ _cam.eyeY = this.eyeY;
+ _cam.eyeZ = this.eyeZ;
+ _cam.centerX = this.centerX;
+ _cam.centerY = this.centerY;
+ _cam.centerZ = this.centerZ;
+ _cam.cameraNear = this.cameraNear;
+ _cam.cameraFar = this.cameraFar;
+
+ _cam.cameraType = this.cameraType;
+
+ _cam.cameraMatrix = this.cameraMatrix.copy();
+ _cam.projMatrix = this.projMatrix.copy();
+
+ return _cam;
+ };
+
+ /**
+ * Returns a camera's local axes: left-right, up-down, and forward-backward,
+ * as defined by vectors in world-space.
+ * @method _getLocalAxes
+ * @private
+ */
+ _main.default.Camera.prototype._getLocalAxes = function() {
+ // calculate camera local Z vector
+ var z0 = this.eyeX - this.centerX;
+ var z1 = this.eyeY - this.centerY;
+ var z2 = this.eyeZ - this.centerZ;
+
+ // normalize camera local Z vector
+ var eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
+ if (eyeDist !== 0) {
+ z0 /= eyeDist;
+ z1 /= eyeDist;
+ z2 /= eyeDist;
+ }
+
+ // calculate camera Y vector
+ var y0 = this.upX;
+ var y1 = this.upY;
+ var y2 = this.upZ;
+
+ // compute camera local X vector as up vector (local Y) cross local Z
+ var x0 = y1 * z2 - y2 * z1;
+ var x1 = -y0 * z2 + y2 * z0;
+ var x2 = y0 * z1 - y1 * z0;
+
+ // recompute y = z cross x
+ y0 = z1 * x2 - z2 * x1;
+ y1 = -z0 * x2 + z2 * x0;
+ y2 = z0 * x1 - z1 * x0;
+
+ // cross product gives area of parallelogram, which is < 1.0 for
+ // non-perpendicular unit-length vectors; so normalize x, y here:
+ var xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
+ if (xmag !== 0) {
+ x0 /= xmag;
+ x1 /= xmag;
+ x2 /= xmag;
+ }
+
+ var ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
+ if (ymag !== 0) {
+ y0 /= ymag;
+ y1 /= ymag;
+ y2 /= ymag;
+ }
+
+ return {
+ x: [x0, x1, x2],
+ y: [y0, y1, y2],
+ z: [z0, z1, z2]
+ };
+ };
+
+ /**
+ * Orbits the camera about center point. For use with orbitControl().
+ * @method _orbit
+ * @private
+ * @param {Number} dTheta change in spherical coordinate theta
+ * @param {Number} dPhi change in spherical coordinate phi
+ * @param {Number} dRadius change in radius
+ */
+ _main.default.Camera.prototype._orbit = function(dTheta, dPhi, dRadius) {
+ var diffX = this.eyeX - this.centerX;
+ var diffY = this.eyeY - this.centerY;
+ var diffZ = this.eyeZ - this.centerZ;
+
+ // get spherical coorinates for current camera position about origin
+ var camRadius = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ);
+ // from https://github.com/mrdoob/three.js/blob/dev/src/math/Spherical.js#L72-L73
+ var camTheta = Math.atan2(diffX, diffZ); // equatorial angle
+ var camPhi = Math.acos(Math.max(-1, Math.min(1, diffY / camRadius))); // polar angle
+
+ // add change
+ camTheta += dTheta;
+ camPhi += dPhi;
+ camRadius += dRadius;
+
+ // prevent zooming through the center:
+ if (camRadius < 0) {
+ camRadius = 0.1;
+ }
+
+ // prevent rotation over the zenith / under bottom
+ if (camPhi > Math.PI) {
+ camPhi = Math.PI;
+ } else if (camPhi <= 0) {
+ camPhi = 0.001;
+ }
+
+ // from https://github.com/mrdoob/three.js/blob/dev/src/math/Vector3.js#L628-L632
+ var _x = Math.sin(camPhi) * camRadius * Math.sin(camTheta);
+ var _y = Math.cos(camPhi) * camRadius;
+ var _z = Math.sin(camPhi) * camRadius * Math.cos(camTheta);
+
+ this.camera(
+ _x + this.centerX,
+ _y + this.centerY,
+ _z + this.centerZ,
+ this.centerX,
+ this.centerY,
+ this.centerZ,
+ 0,
+ 1,
+ 0
+ );
+ };
+
+ /**
+ * Returns true if camera is currently attached to renderer.
+ * @method _isActive
+ * @private
+ */
+ _main.default.Camera.prototype._isActive = function() {
+ return this === this._renderer._curCamera;
+ };
+
+ /**
+ * Sets rendererGL's current camera to a p5.Camera object. Allows switching
+ * between multiple cameras.
+ * @method setCamera
+ * @param {p5.Camera} cam p5.Camera object
+ * @for p5
+ * @example
+ *
+ *
+ * let cam1, cam2;
+ * let currentCamera;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ *
+ * cam1 = createCamera();
+ * cam2 = createCamera();
+ * cam2.setPosition(30, 0, 50);
+ * cam2.lookAt(0, 0, 0);
+ * cam2.ortho();
+ *
+ * // set variable for previously active camera:
+ * currentCamera = 1;
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // camera 1:
+ * cam1.lookAt(0, 0, 0);
+ * cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);
+ *
+ * // every 100 frames, switch between the two cameras
+ * if (frameCount % 100 === 0) {
+ * if (currentCamera === 1) {
+ * setCamera(cam1);
+ * currentCamera = 0;
+ * } else {
+ * setCamera(cam2);
+ * currentCamera = 1;
+ * }
+ * }
+ *
+ * drawBoxes();
+ * }
+ *
+ * function drawBoxes() {
+ * rotateX(frameCount * 0.01);
+ * translate(-100, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Canvas switches between two camera views, each showing a series of spinning
+ * 3D boxes.
+ */
+ _main.default.prototype.setCamera = function(cam) {
+ this._renderer._curCamera = cam;
+
+ // set the projection matrix (which is not normally updated each frame)
+ this._renderer.uPMatrix.set(
+ cam.projMatrix.mat4[0],
+ cam.projMatrix.mat4[1],
+ cam.projMatrix.mat4[2],
+ cam.projMatrix.mat4[3],
+ cam.projMatrix.mat4[4],
+ cam.projMatrix.mat4[5],
+ cam.projMatrix.mat4[6],
+ cam.projMatrix.mat4[7],
+ cam.projMatrix.mat4[8],
+ cam.projMatrix.mat4[9],
+ cam.projMatrix.mat4[10],
+ cam.projMatrix.mat4[11],
+ cam.projMatrix.mat4[12],
+ cam.projMatrix.mat4[13],
+ cam.projMatrix.mat4[14],
+ cam.projMatrix.mat4[15]
+ );
+ };
+ var _default = _main.default.Camera;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 76: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } /** //some of the functions are adjusted from Three.js(http://threejs.org)
+ * @module Lights, Camera
+ * @submodule Material
+ * @for p5
+ * @requires core
+ * @requires p5.Geometry
+ */
+ /**
+ * p5 Geometry class
+ * @class p5.Geometry
+ * @constructor
+ * @param {Integer} [detailX] number of vertices on horizontal surface
+ * @param {Integer} [detailY] number of vertices on horizontal surface
+ * @param {function} [callback] function to call upon object instantiation.
+ *
+ */ _main.default.Geometry = function(detailX, detailY, callback) {
+ //an array containing every vertex
+ //@type [p5.Vector]
+ this.vertices = []; //an array containing every vertex for stroke drawing
+ this.lineVertices = []; //an array 1 normal per lineVertex with
+ //final position representing which direction to
+ //displace for strokeWeight
+ //[[0,0,-1,1], [0,1,0,-1] ...];
+ this.lineNormals = [];
+
+ //an array containing 1 normal per vertex
+ //@type [p5.Vector]
+ //[p5.Vector, p5.Vector, p5.Vector,p5.Vector, p5.Vector, p5.Vector,...]
+ this.vertexNormals = [];
+ //an array containing each three vertex indices that form a face
+ //[[0, 1, 2], [2, 1, 3], ...]
+ this.faces = [];
+ //a 2D array containing uvs for every vertex
+ //[[0.0,0.0],[1.0,0.0], ...]
+ this.uvs = [];
+ // a 2D array containing edge connectivity pattern for create line vertices
+ //based on faces for most objects;
+ this.edges = [];
+ this.detailX = detailX !== undefined ? detailX : 1;
+ this.detailY = detailY !== undefined ? detailY : 1;
+
+ this.dirtyFlags = {};
+
+ if (callback instanceof Function) {
+ callback.call(this);
+ }
+ return this; // TODO: is this a constructor?
+ };
+
+ _main.default.Geometry.prototype.reset = function() {
+ this.lineVertices.length = 0;
+ this.lineNormals.length = 0;
+
+ this.vertices.length = 0;
+ this.edges.length = 0;
+ this.vertexColors.length = 0;
+ this.vertexNormals.length = 0;
+ this.uvs.length = 0;
+
+ this.dirtyFlags = {};
+ };
+
+ /**
+ * @method computeFaces
+ * @chainable
+ */
+ _main.default.Geometry.prototype.computeFaces = function() {
+ this.faces.length = 0;
+ var sliceCount = this.detailX + 1;
+ var a, b, c, d;
+ for (var i = 0; i < this.detailY; i++) {
+ for (var j = 0; j < this.detailX; j++) {
+ a = i * sliceCount + j; // + offset;
+ b = i * sliceCount + j + 1; // + offset;
+ c = (i + 1) * sliceCount + j + 1; // + offset;
+ d = (i + 1) * sliceCount + j; // + offset;
+ this.faces.push([a, b, d]);
+ this.faces.push([d, b, c]);
+ }
+ }
+ return this;
+ };
+
+ _main.default.Geometry.prototype._getFaceNormal = function(faceId) {
+ //This assumes that vA->vB->vC is a counter-clockwise ordering
+ var face = this.faces[faceId];
+ var vA = this.vertices[face[0]];
+ var vB = this.vertices[face[1]];
+ var vC = this.vertices[face[2]];
+ var ab = _main.default.Vector.sub(vB, vA);
+ var ac = _main.default.Vector.sub(vC, vA);
+ var n = _main.default.Vector.cross(ab, ac);
+ var ln = _main.default.Vector.mag(n);
+ var sinAlpha =
+ ln / (_main.default.Vector.mag(ab) * _main.default.Vector.mag(ac));
+ if (sinAlpha === 0 || isNaN(sinAlpha)) {
+ console.warn(
+ 'p5.Geometry.prototype._getFaceNormal:',
+ 'face has colinear sides or a repeated vertex'
+ );
+
+ return n;
+ }
+ if (sinAlpha > 1) sinAlpha = 1; // handle float rounding error
+ return n.mult(Math.asin(sinAlpha) / ln);
+ };
+ /**
+ * computes smooth normals per vertex as an average of each
+ * face.
+ * @method computeNormals
+ * @chainable
+ */
+ _main.default.Geometry.prototype.computeNormals = function() {
+ var vertexNormals = this.vertexNormals;
+ var vertices = this.vertices;
+ var faces = this.faces;
+ var iv;
+
+ // initialize the vertexNormals array with empty vectors
+ vertexNormals.length = 0;
+ for (iv = 0; iv < vertices.length; ++iv) {
+ vertexNormals.push(new _main.default.Vector());
+ }
+
+ // loop through all the faces adding its normal to the normal
+ // of each of its vertices
+ for (var f = 0; f < faces.length; ++f) {
+ var face = faces[f];
+ var faceNormal = this._getFaceNormal(f);
+
+ // all three vertices get the normal added
+ for (var fv = 0; fv < 3; ++fv) {
+ var vertexIndex = face[fv];
+ vertexNormals[vertexIndex].add(faceNormal);
+ }
+ }
+
+ // normalize the normals
+ for (iv = 0; iv < vertices.length; ++iv) {
+ vertexNormals[iv].normalize();
+ }
+
+ return this;
+ };
+
+ /**
+ * Averages the vertex normals. Used in curved
+ * surfaces
+ * @method averageNormals
+ * @chainable
+ */
+ _main.default.Geometry.prototype.averageNormals = function() {
+ for (var i = 0; i <= this.detailY; i++) {
+ var offset = this.detailX + 1;
+ var temp = _main.default.Vector.add(
+ this.vertexNormals[i * offset],
+ this.vertexNormals[i * offset + this.detailX]
+ );
+
+ temp = _main.default.Vector.div(temp, 2);
+ this.vertexNormals[i * offset] = temp;
+ this.vertexNormals[i * offset + this.detailX] = temp;
+ }
+ return this;
+ };
+
+ /**
+ * Averages pole normals. Used in spherical primitives
+ * @method averagePoleNormals
+ * @chainable
+ */
+ _main.default.Geometry.prototype.averagePoleNormals = function() {
+ //average the north pole
+ var sum = new _main.default.Vector(0, 0, 0);
+ for (var i = 0; i < this.detailX; i++) {
+ sum.add(this.vertexNormals[i]);
+ }
+ sum = _main.default.Vector.div(sum, this.detailX);
+
+ for (var _i = 0; _i < this.detailX; _i++) {
+ this.vertexNormals[_i] = sum;
+ }
+
+ //average the south pole
+ sum = new _main.default.Vector(0, 0, 0);
+ for (
+ var _i2 = this.vertices.length - 1;
+ _i2 > this.vertices.length - 1 - this.detailX;
+ _i2--
+ ) {
+ sum.add(this.vertexNormals[_i2]);
+ }
+ sum = _main.default.Vector.div(sum, this.detailX);
+
+ for (
+ var _i3 = this.vertices.length - 1;
+ _i3 > this.vertices.length - 1 - this.detailX;
+ _i3--
+ ) {
+ this.vertexNormals[_i3] = sum;
+ }
+ return this;
+ };
+
+ /**
+ * Create a 2D array for establishing stroke connections
+ * @private
+ * @chainable
+ */
+ _main.default.Geometry.prototype._makeTriangleEdges = function() {
+ this.edges.length = 0;
+ if (Array.isArray(this.strokeIndices)) {
+ for (var i = 0, max = this.strokeIndices.length; i < max; i++) {
+ this.edges.push(this.strokeIndices[i]);
+ }
+ } else {
+ for (var j = 0; j < this.faces.length; j++) {
+ this.edges.push([this.faces[j][0], this.faces[j][1]]);
+ this.edges.push([this.faces[j][1], this.faces[j][2]]);
+ this.edges.push([this.faces[j][2], this.faces[j][0]]);
+ }
+ }
+ return this;
+ };
+
+ /**
+ * Create 4 vertices for each stroke line, two at the beginning position
+ * and two at the end position. These vertices are displaced relative to
+ * that line's normal on the GPU
+ * @private
+ * @chainable
+ */
+ _main.default.Geometry.prototype._edgesToVertices = function() {
+ this.lineVertices.length = 0;
+ this.lineNormals.length = 0;
+
+ for (var i = 0; i < this.edges.length; i++) {
+ var begin = this.vertices[this.edges[i][0]];
+ var end = this.vertices[this.edges[i][1]];
+ var dir = end
+ .copy()
+ .sub(begin)
+ .normalize();
+ var a = begin.array();
+ var b = begin.array();
+ var c = end.array();
+ var d = end.array();
+ var dirAdd = dir.array();
+ var dirSub = dir.array();
+ // below is used to displace the pair of vertices at beginning and end
+ // in opposite directions
+ dirAdd.push(1);
+ dirSub.push(-1);
+ this.lineNormals.push(dirAdd, dirSub, dirAdd, dirAdd, dirSub, dirSub);
+ this.lineVertices.push(a, b, c, c, b, d);
+ }
+ return this;
+ };
+
+ /**
+ * Modifies all vertices to be centered within the range -100 to 100.
+ * @method normalize
+ * @chainable
+ */
+ _main.default.Geometry.prototype.normalize = function() {
+ if (this.vertices.length > 0) {
+ // Find the corners of our bounding box
+ var maxPosition = this.vertices[0].copy();
+ var minPosition = this.vertices[0].copy();
+
+ for (var i = 0; i < this.vertices.length; i++) {
+ maxPosition.x = Math.max(maxPosition.x, this.vertices[i].x);
+ minPosition.x = Math.min(minPosition.x, this.vertices[i].x);
+ maxPosition.y = Math.max(maxPosition.y, this.vertices[i].y);
+ minPosition.y = Math.min(minPosition.y, this.vertices[i].y);
+ maxPosition.z = Math.max(maxPosition.z, this.vertices[i].z);
+ minPosition.z = Math.min(minPosition.z, this.vertices[i].z);
+ }
+
+ var center = _main.default.Vector.lerp(maxPosition, minPosition, 0.5);
+ var dist = _main.default.Vector.sub(maxPosition, minPosition);
+ var longestDist = Math.max(Math.max(dist.x, dist.y), dist.z);
+ var scale = 200 / longestDist;
+
+ for (var _i4 = 0; _i4 < this.vertices.length; _i4++) {
+ this.vertices[_i4].sub(center);
+ this.vertices[_i4].mult(scale);
+ }
+ }
+ return this;
+ };
+ var _default = _main.default.Geometry;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 77: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @requires constants
+ * @todo see methods below needing further implementation.
+ * future consideration: implement SIMD optimizations
+ * when browser compatibility becomes available
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/
+ * Reference/Global_Objects/SIMD
+ */ var GLMAT_ARRAY_TYPE = Array;
+ var isMatrixArray = function isMatrixArray(x) {
+ return x instanceof Array;
+ };
+ if (typeof Float32Array !== 'undefined') {
+ GLMAT_ARRAY_TYPE = Float32Array;
+ isMatrixArray = function isMatrixArray(x) {
+ return x instanceof Array || x instanceof Float32Array;
+ };
+ }
+
+ /**
+ * A class to describe a 4x4 matrix
+ * for model and view matrix manipulation in the p5js webgl renderer.
+ * @class p5.Matrix
+ * @private
+ * @constructor
+ * @param {Array} [mat4] array literal of our 4x4 matrix
+ */
+ _main.default.Matrix = function() {
+ var args = new Array(arguments.length);
+ for (var i = 0; i < args.length; ++i) {
+ args[i] = arguments[i];
+ }
+
+ // This is default behavior when object
+ // instantiated using createMatrix()
+ // @todo implement createMatrix() in core/math.js
+ if (args.length && args[args.length - 1] instanceof _main.default) {
+ this.p5 = args[args.length - 1];
+ }
+
+ if (args[0] === 'mat3') {
+ this.mat3 = Array.isArray(args[1])
+ ? args[1]
+ : new GLMAT_ARRAY_TYPE([1, 0, 0, 0, 1, 0, 0, 0, 1]);
+ } else {
+ this.mat4 = Array.isArray(args[0])
+ ? args[0]
+ : new GLMAT_ARRAY_TYPE([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ }
+ return this;
+ };
+
+ /**
+ * Sets the x, y, and z component of the vector using two or three separate
+ * variables, the data from a p5.Matrix, or the values from a float array.
+ *
+ * @method set
+ * @param {p5.Matrix|Float32Array|Number[]} [inMatrix] the input p5.Matrix or
+ * an Array of length 16
+ * @chainable
+ */
+ /**
+ * @method set
+ * @param {Number[]} elements 16 numbers passed by value to avoid
+ * array copying.
+ * @chainable
+ */
+ _main.default.Matrix.prototype.set = function(inMatrix) {
+ if (inMatrix instanceof _main.default.Matrix) {
+ this.mat4 = inMatrix.mat4;
+ return this;
+ } else if (isMatrixArray(inMatrix)) {
+ this.mat4 = inMatrix;
+ return this;
+ } else if (arguments.length === 16) {
+ this.mat4[0] = arguments[0];
+ this.mat4[1] = arguments[1];
+ this.mat4[2] = arguments[2];
+ this.mat4[3] = arguments[3];
+ this.mat4[4] = arguments[4];
+ this.mat4[5] = arguments[5];
+ this.mat4[6] = arguments[6];
+ this.mat4[7] = arguments[7];
+ this.mat4[8] = arguments[8];
+ this.mat4[9] = arguments[9];
+ this.mat4[10] = arguments[10];
+ this.mat4[11] = arguments[11];
+ this.mat4[12] = arguments[12];
+ this.mat4[13] = arguments[13];
+ this.mat4[14] = arguments[14];
+ this.mat4[15] = arguments[15];
+ }
+ return this;
+ };
+
+ /**
+ * Gets a copy of the vector, returns a p5.Matrix object.
+ *
+ * @method get
+ * @return {p5.Matrix} the copy of the p5.Matrix object
+ */
+ _main.default.Matrix.prototype.get = function() {
+ return new _main.default.Matrix(this.mat4, this.p5);
+ };
+
+ /**
+ * return a copy of a matrix
+ * @method copy
+ * @return {p5.Matrix} the result matrix
+ */
+ _main.default.Matrix.prototype.copy = function() {
+ var copied = new _main.default.Matrix(this.p5);
+ copied.mat4[0] = this.mat4[0];
+ copied.mat4[1] = this.mat4[1];
+ copied.mat4[2] = this.mat4[2];
+ copied.mat4[3] = this.mat4[3];
+ copied.mat4[4] = this.mat4[4];
+ copied.mat4[5] = this.mat4[5];
+ copied.mat4[6] = this.mat4[6];
+ copied.mat4[7] = this.mat4[7];
+ copied.mat4[8] = this.mat4[8];
+ copied.mat4[9] = this.mat4[9];
+ copied.mat4[10] = this.mat4[10];
+ copied.mat4[11] = this.mat4[11];
+ copied.mat4[12] = this.mat4[12];
+ copied.mat4[13] = this.mat4[13];
+ copied.mat4[14] = this.mat4[14];
+ copied.mat4[15] = this.mat4[15];
+ return copied;
+ };
+
+ /**
+ * return an identity matrix
+ * @method identity
+ * @return {p5.Matrix} the result matrix
+ */
+ _main.default.Matrix.identity = function(pInst) {
+ return new _main.default.Matrix(pInst);
+ };
+
+ /**
+ * transpose according to a given matrix
+ * @method transpose
+ * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be
+ * based on to transpose
+ * @chainable
+ */
+ _main.default.Matrix.prototype.transpose = function(a) {
+ var a01, a02, a03, a12, a13, a23;
+ if (a instanceof _main.default.Matrix) {
+ a01 = a.mat4[1];
+ a02 = a.mat4[2];
+ a03 = a.mat4[3];
+ a12 = a.mat4[6];
+ a13 = a.mat4[7];
+ a23 = a.mat4[11];
+
+ this.mat4[0] = a.mat4[0];
+ this.mat4[1] = a.mat4[4];
+ this.mat4[2] = a.mat4[8];
+ this.mat4[3] = a.mat4[12];
+ this.mat4[4] = a01;
+ this.mat4[5] = a.mat4[5];
+ this.mat4[6] = a.mat4[9];
+ this.mat4[7] = a.mat4[13];
+ this.mat4[8] = a02;
+ this.mat4[9] = a12;
+ this.mat4[10] = a.mat4[10];
+ this.mat4[11] = a.mat4[14];
+ this.mat4[12] = a03;
+ this.mat4[13] = a13;
+ this.mat4[14] = a23;
+ this.mat4[15] = a.mat4[15];
+ } else if (isMatrixArray(a)) {
+ a01 = a[1];
+ a02 = a[2];
+ a03 = a[3];
+ a12 = a[6];
+ a13 = a[7];
+ a23 = a[11];
+
+ this.mat4[0] = a[0];
+ this.mat4[1] = a[4];
+ this.mat4[2] = a[8];
+ this.mat4[3] = a[12];
+ this.mat4[4] = a01;
+ this.mat4[5] = a[5];
+ this.mat4[6] = a[9];
+ this.mat4[7] = a[13];
+ this.mat4[8] = a02;
+ this.mat4[9] = a12;
+ this.mat4[10] = a[10];
+ this.mat4[11] = a[14];
+ this.mat4[12] = a03;
+ this.mat4[13] = a13;
+ this.mat4[14] = a23;
+ this.mat4[15] = a[15];
+ }
+ return this;
+ };
+
+ /**
+ * invert matrix according to a give matrix
+ * @method invert
+ * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be
+ * based on to invert
+ * @chainable
+ */
+ _main.default.Matrix.prototype.invert = function(a) {
+ var a00, a01, a02, a03, a10, a11, a12, a13;
+ var a20, a21, a22, a23, a30, a31, a32, a33;
+ if (a instanceof _main.default.Matrix) {
+ a00 = a.mat4[0];
+ a01 = a.mat4[1];
+ a02 = a.mat4[2];
+ a03 = a.mat4[3];
+ a10 = a.mat4[4];
+ a11 = a.mat4[5];
+ a12 = a.mat4[6];
+ a13 = a.mat4[7];
+ a20 = a.mat4[8];
+ a21 = a.mat4[9];
+ a22 = a.mat4[10];
+ a23 = a.mat4[11];
+ a30 = a.mat4[12];
+ a31 = a.mat4[13];
+ a32 = a.mat4[14];
+ a33 = a.mat4[15];
+ } else if (isMatrixArray(a)) {
+ a00 = a[0];
+ a01 = a[1];
+ a02 = a[2];
+ a03 = a[3];
+ a10 = a[4];
+ a11 = a[5];
+ a12 = a[6];
+ a13 = a[7];
+ a20 = a[8];
+ a21 = a[9];
+ a22 = a[10];
+ a23 = a[11];
+ a30 = a[12];
+ a31 = a[13];
+ a32 = a[14];
+ a33 = a[15];
+ }
+ var b00 = a00 * a11 - a01 * a10;
+ var b01 = a00 * a12 - a02 * a10;
+ var b02 = a00 * a13 - a03 * a10;
+ var b03 = a01 * a12 - a02 * a11;
+ var b04 = a01 * a13 - a03 * a11;
+ var b05 = a02 * a13 - a03 * a12;
+ var b06 = a20 * a31 - a21 * a30;
+ var b07 = a20 * a32 - a22 * a30;
+ var b08 = a20 * a33 - a23 * a30;
+ var b09 = a21 * a32 - a22 * a31;
+ var b10 = a21 * a33 - a23 * a31;
+ var b11 = a22 * a33 - a23 * a32;
+
+ // Calculate the determinant
+ var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
+ this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
+ this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
+ this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
+ this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
+ this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
+ this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
+ this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
+ this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
+ this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
+ this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
+ this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
+ this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
+ this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
+ this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
+ this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
+
+ return this;
+ };
+
+ /**
+ * Inverts a 3x3 matrix
+ * @method invert3x3
+ * @chainable
+ */
+ _main.default.Matrix.prototype.invert3x3 = function() {
+ var a00 = this.mat3[0];
+ var a01 = this.mat3[1];
+ var a02 = this.mat3[2];
+ var a10 = this.mat3[3];
+ var a11 = this.mat3[4];
+ var a12 = this.mat3[5];
+ var a20 = this.mat3[6];
+ var a21 = this.mat3[7];
+ var a22 = this.mat3[8];
+ var b01 = a22 * a11 - a12 * a21;
+ var b11 = -a22 * a10 + a12 * a20;
+ var b21 = a21 * a10 - a11 * a20;
+
+ // Calculate the determinant
+ var det = a00 * b01 + a01 * b11 + a02 * b21;
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+ this.mat3[0] = b01 * det;
+ this.mat3[1] = (-a22 * a01 + a02 * a21) * det;
+ this.mat3[2] = (a12 * a01 - a02 * a11) * det;
+ this.mat3[3] = b11 * det;
+ this.mat3[4] = (a22 * a00 - a02 * a20) * det;
+ this.mat3[5] = (-a12 * a00 + a02 * a10) * det;
+ this.mat3[6] = b21 * det;
+ this.mat3[7] = (-a21 * a00 + a01 * a20) * det;
+ this.mat3[8] = (a11 * a00 - a01 * a10) * det;
+ return this;
+ };
+
+ /**
+ * transposes a 3x3 p5.Matrix by a mat3
+ * @method transpose3x3
+ * @param {Number[]} mat3 1-dimensional array
+ * @chainable
+ */
+ _main.default.Matrix.prototype.transpose3x3 = function(mat3) {
+ var a01 = mat3[1],
+ a02 = mat3[2],
+ a12 = mat3[5];
+ this.mat3[1] = mat3[3];
+ this.mat3[2] = mat3[6];
+ this.mat3[3] = a01;
+ this.mat3[5] = mat3[7];
+ this.mat3[6] = a02;
+ this.mat3[7] = a12;
+ return this;
+ };
+
+ /**
+ * converts a 4x4 matrix to its 3x3 inverse transform
+ * commonly used in MVMatrix to NMatrix conversions.
+ * @method invertTranspose
+ * @param {p5.Matrix} mat4 the matrix to be based on to invert
+ * @chainable
+ * @todo finish implementation
+ */
+ _main.default.Matrix.prototype.inverseTranspose = function(matrix) {
+ if (this.mat3 === undefined) {
+ console.error('sorry, this function only works with mat3');
+ } else {
+ //convert mat4 -> mat3
+ this.mat3[0] = matrix.mat4[0];
+ this.mat3[1] = matrix.mat4[1];
+ this.mat3[2] = matrix.mat4[2];
+ this.mat3[3] = matrix.mat4[4];
+ this.mat3[4] = matrix.mat4[5];
+ this.mat3[5] = matrix.mat4[6];
+ this.mat3[6] = matrix.mat4[8];
+ this.mat3[7] = matrix.mat4[9];
+ this.mat3[8] = matrix.mat4[10];
+ }
+
+ var inverse = this.invert3x3();
+ // check inverse succeeded
+ if (inverse) {
+ inverse.transpose3x3(this.mat3);
+ } else {
+ // in case of singularity, just zero the matrix
+ for (var i = 0; i < 9; i++) {
+ this.mat3[i] = 0;
+ }
+ }
+ return this;
+ };
+
+ /**
+ * inspired by Toji's mat4 determinant
+ * @method determinant
+ * @return {Number} Determinant of our 4x4 matrix
+ */
+ _main.default.Matrix.prototype.determinant = function() {
+ var d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4],
+ d01 = this.mat4[0] * this.mat4[6] - this.mat4[2] * this.mat4[4],
+ d02 = this.mat4[0] * this.mat4[7] - this.mat4[3] * this.mat4[4],
+ d03 = this.mat4[1] * this.mat4[6] - this.mat4[2] * this.mat4[5],
+ d04 = this.mat4[1] * this.mat4[7] - this.mat4[3] * this.mat4[5],
+ d05 = this.mat4[2] * this.mat4[7] - this.mat4[3] * this.mat4[6],
+ d06 = this.mat4[8] * this.mat4[13] - this.mat4[9] * this.mat4[12],
+ d07 = this.mat4[8] * this.mat4[14] - this.mat4[10] * this.mat4[12],
+ d08 = this.mat4[8] * this.mat4[15] - this.mat4[11] * this.mat4[12],
+ d09 = this.mat4[9] * this.mat4[14] - this.mat4[10] * this.mat4[13],
+ d10 = this.mat4[9] * this.mat4[15] - this.mat4[11] * this.mat4[13],
+ d11 = this.mat4[10] * this.mat4[15] - this.mat4[11] * this.mat4[14];
+
+ // Calculate the determinant
+ return d00 * d11 - d01 * d10 + d02 * d09 + d03 * d08 - d04 * d07 + d05 * d06;
+ };
+
+ /**
+ * multiply two mat4s
+ * @method mult
+ * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix
+ * we want to multiply by
+ * @chainable
+ */
+ _main.default.Matrix.prototype.mult = function(multMatrix) {
+ var _src;
+
+ if (multMatrix === this || multMatrix === this.mat4) {
+ _src = this.copy().mat4; // only need to allocate in this rare case
+ } else if (multMatrix instanceof _main.default.Matrix) {
+ _src = multMatrix.mat4;
+ } else if (isMatrixArray(multMatrix)) {
+ _src = multMatrix;
+ } else if (arguments.length === 16) {
+ _src = arguments;
+ } else {
+ return; // nothing to do.
+ }
+
+ // each row is used for the multiplier
+ var b0 = this.mat4[0],
+ b1 = this.mat4[1],
+ b2 = this.mat4[2],
+ b3 = this.mat4[3];
+ this.mat4[0] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
+ this.mat4[1] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
+ this.mat4[2] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
+ this.mat4[3] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
+
+ b0 = this.mat4[4];
+ b1 = this.mat4[5];
+ b2 = this.mat4[6];
+ b3 = this.mat4[7];
+ this.mat4[4] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
+ this.mat4[5] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
+ this.mat4[6] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
+ this.mat4[7] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
+
+ b0 = this.mat4[8];
+ b1 = this.mat4[9];
+ b2 = this.mat4[10];
+ b3 = this.mat4[11];
+ this.mat4[8] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
+ this.mat4[9] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
+ this.mat4[10] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
+ this.mat4[11] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
+
+ b0 = this.mat4[12];
+ b1 = this.mat4[13];
+ b2 = this.mat4[14];
+ b3 = this.mat4[15];
+ this.mat4[12] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
+ this.mat4[13] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
+ this.mat4[14] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
+ this.mat4[15] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
+
+ return this;
+ };
+
+ _main.default.Matrix.prototype.apply = function(multMatrix) {
+ var _src;
+
+ if (multMatrix === this || multMatrix === this.mat4) {
+ _src = this.copy().mat4; // only need to allocate in this rare case
+ } else if (multMatrix instanceof _main.default.Matrix) {
+ _src = multMatrix.mat4;
+ } else if (isMatrixArray(multMatrix)) {
+ _src = multMatrix;
+ } else if (arguments.length === 16) {
+ _src = arguments;
+ } else {
+ return; // nothing to do.
+ }
+
+ var mat4 = this.mat4;
+
+ // each row is used for the multiplier
+ var m0 = mat4[0];
+ var m4 = mat4[4];
+ var m8 = mat4[8];
+ var m12 = mat4[12];
+ mat4[0] = _src[0] * m0 + _src[1] * m4 + _src[2] * m8 + _src[3] * m12;
+ mat4[4] = _src[4] * m0 + _src[5] * m4 + _src[6] * m8 + _src[7] * m12;
+ mat4[8] = _src[8] * m0 + _src[9] * m4 + _src[10] * m8 + _src[11] * m12;
+ mat4[12] = _src[12] * m0 + _src[13] * m4 + _src[14] * m8 + _src[15] * m12;
+
+ var m1 = mat4[1];
+ var m5 = mat4[5];
+ var m9 = mat4[9];
+ var m13 = mat4[13];
+ mat4[1] = _src[0] * m1 + _src[1] * m5 + _src[2] * m9 + _src[3] * m13;
+ mat4[5] = _src[4] * m1 + _src[5] * m5 + _src[6] * m9 + _src[7] * m13;
+ mat4[9] = _src[8] * m1 + _src[9] * m5 + _src[10] * m9 + _src[11] * m13;
+ mat4[13] = _src[12] * m1 + _src[13] * m5 + _src[14] * m9 + _src[15] * m13;
+
+ var m2 = mat4[2];
+ var m6 = mat4[6];
+ var m10 = mat4[10];
+ var m14 = mat4[14];
+ mat4[2] = _src[0] * m2 + _src[1] * m6 + _src[2] * m10 + _src[3] * m14;
+ mat4[6] = _src[4] * m2 + _src[5] * m6 + _src[6] * m10 + _src[7] * m14;
+ mat4[10] = _src[8] * m2 + _src[9] * m6 + _src[10] * m10 + _src[11] * m14;
+ mat4[14] = _src[12] * m2 + _src[13] * m6 + _src[14] * m10 + _src[15] * m14;
+
+ var m3 = mat4[3];
+ var m7 = mat4[7];
+ var m11 = mat4[11];
+ var m15 = mat4[15];
+ mat4[3] = _src[0] * m3 + _src[1] * m7 + _src[2] * m11 + _src[3] * m15;
+ mat4[7] = _src[4] * m3 + _src[5] * m7 + _src[6] * m11 + _src[7] * m15;
+ mat4[11] = _src[8] * m3 + _src[9] * m7 + _src[10] * m11 + _src[11] * m15;
+ mat4[15] = _src[12] * m3 + _src[13] * m7 + _src[14] * m11 + _src[15] * m15;
+
+ return this;
+ };
+
+ /**
+ * scales a p5.Matrix by scalars or a vector
+ * @method scale
+ * @param {p5.Vector|Float32Array|Number[]} s vector to scale by
+ * @chainable
+ */
+ _main.default.Matrix.prototype.scale = function(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ // x is a vector, extract the components from it.
+ y = x.y;
+ z = x.z;
+ x = x.x; // must be last
+ } else if (x instanceof Array) {
+ // x is an array, extract the components from it.
+ y = x[1];
+ z = x[2];
+ x = x[0]; // must be last
+ }
+
+ this.mat4[0] *= x;
+ this.mat4[1] *= x;
+ this.mat4[2] *= x;
+ this.mat4[3] *= x;
+ this.mat4[4] *= y;
+ this.mat4[5] *= y;
+ this.mat4[6] *= y;
+ this.mat4[7] *= y;
+ this.mat4[8] *= z;
+ this.mat4[9] *= z;
+ this.mat4[10] *= z;
+ this.mat4[11] *= z;
+
+ return this;
+ };
+
+ /**
+ * rotate our Matrix around an axis by the given angle.
+ * @method rotate
+ * @param {Number} a The angle of rotation in radians
+ * @param {p5.Vector|Number[]} axis the axis(es) to rotate around
+ * @chainable
+ * inspired by Toji's gl-matrix lib, mat4 rotation
+ */
+ _main.default.Matrix.prototype.rotate = function(a, x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ // x is a vector, extract the components from it.
+ y = x.y;
+ z = x.z;
+ x = x.x; //must be last
+ } else if (x instanceof Array) {
+ // x is an array, extract the components from it.
+ y = x[1];
+ z = x[2];
+ x = x[0]; //must be last
+ }
+
+ var len = Math.sqrt(x * x + y * y + z * z);
+ x *= 1 / len;
+ y *= 1 / len;
+ z *= 1 / len;
+
+ var a00 = this.mat4[0];
+ var a01 = this.mat4[1];
+ var a02 = this.mat4[2];
+ var a03 = this.mat4[3];
+ var a10 = this.mat4[4];
+ var a11 = this.mat4[5];
+ var a12 = this.mat4[6];
+ var a13 = this.mat4[7];
+ var a20 = this.mat4[8];
+ var a21 = this.mat4[9];
+ var a22 = this.mat4[10];
+ var a23 = this.mat4[11];
+
+ //sin,cos, and tan of respective angle
+ var sA = Math.sin(a);
+ var cA = Math.cos(a);
+ var tA = 1 - cA;
+ // Construct the elements of the rotation matrix
+ var b00 = x * x * tA + cA;
+ var b01 = y * x * tA + z * sA;
+ var b02 = z * x * tA - y * sA;
+ var b10 = x * y * tA - z * sA;
+ var b11 = y * y * tA + cA;
+ var b12 = z * y * tA + x * sA;
+ var b20 = x * z * tA + y * sA;
+ var b21 = y * z * tA - x * sA;
+ var b22 = z * z * tA + cA;
+
+ // rotation-specific matrix multiplication
+ this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02;
+ this.mat4[1] = a01 * b00 + a11 * b01 + a21 * b02;
+ this.mat4[2] = a02 * b00 + a12 * b01 + a22 * b02;
+ this.mat4[3] = a03 * b00 + a13 * b01 + a23 * b02;
+ this.mat4[4] = a00 * b10 + a10 * b11 + a20 * b12;
+ this.mat4[5] = a01 * b10 + a11 * b11 + a21 * b12;
+ this.mat4[6] = a02 * b10 + a12 * b11 + a22 * b12;
+ this.mat4[7] = a03 * b10 + a13 * b11 + a23 * b12;
+ this.mat4[8] = a00 * b20 + a10 * b21 + a20 * b22;
+ this.mat4[9] = a01 * b20 + a11 * b21 + a21 * b22;
+ this.mat4[10] = a02 * b20 + a12 * b21 + a22 * b22;
+ this.mat4[11] = a03 * b20 + a13 * b21 + a23 * b22;
+
+ return this;
+ };
+
+ /**
+ * @todo finish implementing this method!
+ * translates
+ * @method translate
+ * @param {Number[]} v vector to translate by
+ * @chainable
+ */
+ _main.default.Matrix.prototype.translate = function(v) {
+ var x = v[0],
+ y = v[1],
+ z = v[2] || 0;
+ this.mat4[12] += this.mat4[0] * x + this.mat4[4] * y + this.mat4[8] * z;
+ this.mat4[13] += this.mat4[1] * x + this.mat4[5] * y + this.mat4[9] * z;
+ this.mat4[14] += this.mat4[2] * x + this.mat4[6] * y + this.mat4[10] * z;
+ this.mat4[15] += this.mat4[3] * x + this.mat4[7] * y + this.mat4[11] * z;
+ };
+
+ _main.default.Matrix.prototype.rotateX = function(a) {
+ this.rotate(a, 1, 0, 0);
+ };
+ _main.default.Matrix.prototype.rotateY = function(a) {
+ this.rotate(a, 0, 1, 0);
+ };
+ _main.default.Matrix.prototype.rotateZ = function(a) {
+ this.rotate(a, 0, 0, 1);
+ };
+
+ /**
+ * sets the perspective matrix
+ * @method perspective
+ * @param {Number} fovy [description]
+ * @param {Number} aspect [description]
+ * @param {Number} near near clipping plane
+ * @param {Number} far far clipping plane
+ * @chainable
+ */
+ _main.default.Matrix.prototype.perspective = function(fovy, aspect, near, far) {
+ var f = 1.0 / Math.tan(fovy / 2),
+ nf = 1 / (near - far);
+
+ this.mat4[0] = f / aspect;
+ this.mat4[1] = 0;
+ this.mat4[2] = 0;
+ this.mat4[3] = 0;
+ this.mat4[4] = 0;
+ this.mat4[5] = f;
+ this.mat4[6] = 0;
+ this.mat4[7] = 0;
+ this.mat4[8] = 0;
+ this.mat4[9] = 0;
+ this.mat4[10] = (far + near) * nf;
+ this.mat4[11] = -1;
+ this.mat4[12] = 0;
+ this.mat4[13] = 0;
+ this.mat4[14] = 2 * far * near * nf;
+ this.mat4[15] = 0;
+
+ return this;
+ };
+
+ /**
+ * sets the ortho matrix
+ * @method ortho
+ * @param {Number} left [description]
+ * @param {Number} right [description]
+ * @param {Number} bottom [description]
+ * @param {Number} top [description]
+ * @param {Number} near near clipping plane
+ * @param {Number} far far clipping plane
+ * @chainable
+ */
+ _main.default.Matrix.prototype.ortho = function(
+ left,
+ right,
+ bottom,
+ top,
+ near,
+ far
+ ) {
+ var lr = 1 / (left - right),
+ bt = 1 / (bottom - top),
+ nf = 1 / (near - far);
+ this.mat4[0] = -2 * lr;
+ this.mat4[1] = 0;
+ this.mat4[2] = 0;
+ this.mat4[3] = 0;
+ this.mat4[4] = 0;
+ this.mat4[5] = -2 * bt;
+ this.mat4[6] = 0;
+ this.mat4[7] = 0;
+ this.mat4[8] = 0;
+ this.mat4[9] = 0;
+ this.mat4[10] = 2 * nf;
+ this.mat4[11] = 0;
+ this.mat4[12] = (left + right) * lr;
+ this.mat4[13] = (top + bottom) * bt;
+ this.mat4[14] = (far + near) * nf;
+ this.mat4[15] = 1;
+
+ return this;
+ };
+
+ /**
+ * PRIVATE
+ */
+ // matrix methods adapted from:
+ // https://developer.mozilla.org/en-US/docs/Web/WebGL/
+ // gluPerspective
+ //
+ // function _makePerspective(fovy, aspect, znear, zfar){
+ // const ymax = znear * Math.tan(fovy * Math.PI / 360.0);
+ // const ymin = -ymax;
+ // const xmin = ymin * aspect;
+ // const xmax = ymax * aspect;
+ // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar);
+ // }
+
+ ////
+ //// glFrustum
+ ////
+ //function _makeFrustum(left, right, bottom, top, znear, zfar){
+ // const X = 2*znear/(right-left);
+ // const Y = 2*znear/(top-bottom);
+ // const A = (right+left)/(right-left);
+ // const B = (top+bottom)/(top-bottom);
+ // const C = -(zfar+znear)/(zfar-znear);
+ // const D = -2*zfar*znear/(zfar-znear);
+ // const frustrumMatrix =[
+ // X, 0, A, 0,
+ // 0, Y, B, 0,
+ // 0, 0, C, D,
+ // 0, 0, -1, 0
+ //];
+ //return frustrumMatrix;
+ // }
+
+ // function _setMVPMatrices(){
+ ////an identity matrix
+ ////@TODO use the p5.Matrix class to abstract away our MV matrices and
+ ///other math
+ //const _mvMatrix =
+ //[
+ // 1.0,0.0,0.0,0.0,
+ // 0.0,1.0,0.0,0.0,
+ // 0.0,0.0,1.0,0.0,
+ // 0.0,0.0,0.0,1.0
+ //];
+ var _default = _main.default.Matrix;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 78: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * Welcome to RendererGL Immediate Mode.
+ * Immediate mode is used for drawing custom shapes
+ * from a set of vertices. Immediate Mode is activated
+ * when you call beginShape() & de-activated when you call endShape().
+ * Immediate mode is a style of programming borrowed
+ * from OpenGL's (now-deprecated) immediate mode.
+ * It differs from p5.js' default, Retained Mode, which caches
+ * geometries and buffers on the CPU to reduce the number of webgl
+ * draw calls. Retained mode is more efficient & performative,
+ * however, Immediate Mode is useful for sketching quick
+ * geometric ideas.
+ */ /**
+ * Begin shape drawing. This is a helpful way of generating
+ * custom shapes quickly. However in WEBGL mode, application
+ * performance will likely drop as a result of too many calls to
+ * beginShape() / endShape(). As a high performance alternative,
+ * please use p5.js geometry primitives.
+ * @private
+ * @method beginShape
+ * @param {Number} mode webgl primitives mode. beginShape supports the
+ * following modes:
+ * POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES,
+ * TRIANGLE_STRIP,and TRIANGLE_FAN.
+ * @chainable
+ */ _main.default.RendererGL.prototype.beginShape = function(mode) {
+ //default shape mode is line_strip
+ this.immediateMode.shapeMode = mode !== undefined ? mode : constants.LINE_STRIP; //if we haven't yet initialized our
+ //immediateMode vertices & buffers, create them now!
+ if (this.immediateMode.vertices === undefined) {
+ this.immediateMode.vertices = [];
+ this.immediateMode.edges = [];
+ this.immediateMode.lineVertices = [];
+ this.immediateMode.vertexColors = [];
+ this.immediateMode.lineNormals = [];
+ this.immediateMode.uvCoords = [];
+ this.immediateMode.vertexBuffer = this.GL.createBuffer();
+ this.immediateMode.colorBuffer = this.GL.createBuffer();
+ this.immediateMode.uvBuffer = this.GL.createBuffer();
+ this.immediateMode.lineVertexBuffer = this.GL.createBuffer();
+ this.immediateMode.lineNormalBuffer = this.GL.createBuffer();
+ this.immediateMode.pointVertexBuffer = this.GL.createBuffer();
+ this.immediateMode._bezierVertex = [];
+ this.immediateMode._quadraticVertex = [];
+ this.immediateMode._curveVertex = [];
+ this.immediateMode._isCoplanar = true;
+ this.immediateMode._testIfCoplanar = null;
+ } else {
+ this.immediateMode.vertices.length = 0;
+ this.immediateMode.edges.length = 0;
+ this.immediateMode.lineVertices.length = 0;
+ this.immediateMode.lineNormals.length = 0;
+ this.immediateMode.vertexColors.length = 0;
+ this.immediateMode.uvCoords.length = 0;
+ }
+ this.isImmediateDrawing = true;
+ return this;
+ };
+ /**
+ * adds a vertex to be drawn in a custom Shape.
+ * @private
+ * @method vertex
+ * @param {Number} x x-coordinate of vertex
+ * @param {Number} y y-coordinate of vertex
+ * @param {Number} z z-coordinate of vertex
+ * @chainable
+ * @TODO implement handling of p5.Vector args
+ */
+ _main.default.RendererGL.prototype.vertex = function(x, y) {
+ var z, u, v;
+
+ // default to (x, y) mode: all other arugments assumed to be 0.
+ z = u = v = 0;
+
+ if (arguments.length === 3) {
+ // (x, y, z) mode: (u, v) assumed to be 0.
+ z = arguments[2];
+ } else if (arguments.length === 4) {
+ // (x, y, u, v) mode: z assumed to be 0.
+ u = arguments[2];
+ v = arguments[3];
+ } else if (arguments.length === 5) {
+ // (x, y, z, u, v) mode
+ z = arguments[2];
+ u = arguments[3];
+ v = arguments[4];
+ }
+ if (this.immediateMode._testIfCoplanar == null) {
+ this.immediateMode._testIfCoplanar = z;
+ } else if (this.immediateMode._testIfCoplanar !== z) {
+ this.immediateMode._isCoplanar = false;
+ }
+ var vert = new _main.default.Vector(x, y, z);
+ this.immediateMode.vertices.push(vert);
+ var vertexColor = this.curFillColor || [0.5, 0.5, 0.5, 1.0];
+ this.immediateMode.vertexColors.push(
+ vertexColor[0],
+ vertexColor[1],
+ vertexColor[2],
+ vertexColor[3]
+ );
+
+ if (this.textureMode === constants.IMAGE) {
+ if (this._tex !== null) {
+ if (this._tex.width > 0 && this._tex.height > 0) {
+ u /= this._tex.width;
+ v /= this._tex.height;
+ }
+ } else if (this._tex === null && arguments.length >= 4) {
+ // Only throw this warning if custom uv's have been provided
+ console.warn(
+ 'You must first call texture() before using' +
+ ' vertex() with image based u and v coordinates'
+ );
+ }
+ }
+
+ this.immediateMode.uvCoords.push(u, v);
+
+ this.immediateMode._bezierVertex[0] = x;
+ this.immediateMode._bezierVertex[1] = y;
+ this.immediateMode._bezierVertex[2] = z;
+
+ this.immediateMode._quadraticVertex[0] = x;
+ this.immediateMode._quadraticVertex[1] = y;
+ this.immediateMode._quadraticVertex[2] = z;
+
+ return this;
+ };
+
+ /**
+ * End shape drawing and render vertices to screen.
+ * @chainable
+ */
+ _main.default.RendererGL.prototype.endShape = function(
+ mode,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+ ) {
+ if (this.immediateMode.shapeMode === constants.POINTS) {
+ this._drawPoints(
+ this.immediateMode.vertices,
+ this.immediateMode.pointVertexBuffer
+ );
+ } else if (this.immediateMode.vertices.length > 1) {
+ if (this._doStroke && this.drawMode !== constants.TEXTURE) {
+ if (this.immediateMode.shapeMode === constants.TRIANGLE_STRIP) {
+ var i;
+ for (i = 0; i < this.immediateMode.vertices.length - 2; i++) {
+ this.immediateMode.edges.push([i, i + 1]);
+ this.immediateMode.edges.push([i, i + 2]);
+ }
+ this.immediateMode.edges.push([i, i + 1]);
+ } else if (this.immediateMode.shapeMode === constants.TRIANGLES) {
+ for (
+ var _i = 0;
+ _i < this.immediateMode.vertices.length - 2;
+ _i = _i + 3
+ ) {
+ this.immediateMode.edges.push([_i, _i + 1]);
+ this.immediateMode.edges.push([_i + 1, _i + 2]);
+ this.immediateMode.edges.push([_i + 2, _i]);
+ }
+ } else if (this.immediateMode.shapeMode === constants.LINES) {
+ for (
+ var _i2 = 0;
+ _i2 < this.immediateMode.vertices.length - 1;
+ _i2 = _i2 + 2
+ ) {
+ this.immediateMode.edges.push([_i2, _i2 + 1]);
+ }
+ } else {
+ for (var _i3 = 0; _i3 < this.immediateMode.vertices.length - 1; _i3++) {
+ this.immediateMode.edges.push([_i3, _i3 + 1]);
+ }
+ }
+ if (mode === constants.CLOSE) {
+ this.immediateMode.edges.push([
+ this.immediateMode.vertices.length - 1,
+ 0
+ ]);
+ }
+
+ _main.default.Geometry.prototype._edgesToVertices.call(this.immediateMode);
+ this._drawStrokeImmediateMode();
+ }
+
+ if (this._doFill && this.immediateMode.shapeMode !== constants.LINES) {
+ if (
+ this.isBezier ||
+ this.isQuadratic ||
+ this.isCurve ||
+ (this.immediateMode.shapeMode === constants.LINE_STRIP &&
+ this.drawMode === constants.FILL &&
+ this.immediateMode._isCoplanar === true)
+ ) {
+ this.immediateMode.shapeMode = constants.TRIANGLES;
+ var contours = [
+ new Float32Array(this._vToNArray(this.immediateMode.vertices))
+ ];
+
+ var polyTriangles = this._triangulate(contours);
+ this.immediateMode.vertices = [];
+ for (
+ var j = 0, polyTriLength = polyTriangles.length;
+ j < polyTriLength;
+ j = j + 3
+ ) {
+ this.vertex(
+ polyTriangles[j],
+ polyTriangles[j + 1],
+ polyTriangles[j + 2]
+ );
+ }
+ }
+ if (this.immediateMode.vertices.length > 0) {
+ this._drawFillImmediateMode(
+ mode,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+ );
+ }
+ }
+ }
+ //clear out our vertexPositions & colors arrays
+ //after rendering
+ this.immediateMode.vertices.length = 0;
+ this.immediateMode.vertexColors.length = 0;
+ this.immediateMode.uvCoords.length = 0;
+ this.isImmediateDrawing = false;
+ this.isBezier = false;
+ this.isQuadratic = false;
+ this.isCurve = false;
+ this.immediateMode._bezierVertex.length = 0;
+ this.immediateMode._quadraticVertex.length = 0;
+ this.immediateMode._curveVertex.length = 0;
+ this.immediateMode._isCoplanar = true;
+ this.immediateMode._testIfCoplanar = null;
+
+ return this;
+ };
+
+ _main.default.RendererGL.prototype._drawFillImmediateMode = function(
+ mode,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+ ) {
+ var gl = this.GL;
+ var shader = this._getImmediateFillShader();
+ this._setFillUniforms(shader);
+
+ // initialize the fill shader's 'aPosition' buffer
+ if (shader.attributes.aPosition) {
+ //vertex position Attribute
+ this._bindBuffer(
+ this.immediateMode.vertexBuffer,
+ gl.ARRAY_BUFFER,
+ this._vToNArray(this.immediateMode.vertices),
+ Float32Array,
+ gl.DYNAMIC_DRAW
+ );
+
+ shader.enableAttrib(shader.attributes.aPosition, 3);
+ }
+
+ // initialize the fill shader's 'aVertexColor' buffer
+ if (this.drawMode === constants.FILL && shader.attributes.aVertexColor) {
+ this._bindBuffer(
+ this.immediateMode.colorBuffer,
+ gl.ARRAY_BUFFER,
+ this.immediateMode.vertexColors,
+ Float32Array,
+ gl.DYNAMIC_DRAW
+ );
+
+ shader.enableAttrib(shader.attributes.aVertexColor, 4);
+ }
+
+ // initialize the fill shader's 'aTexCoord' buffer
+ if (this.drawMode === constants.TEXTURE && shader.attributes.aTexCoord) {
+ //texture coordinate Attribute
+ this._bindBuffer(
+ this.immediateMode.uvBuffer,
+ gl.ARRAY_BUFFER,
+ this.immediateMode.uvCoords,
+ Float32Array,
+ gl.DYNAMIC_DRAW
+ );
+
+ shader.enableAttrib(shader.attributes.aTexCoord, 2);
+ }
+
+ //if (true || mode) {
+ if (this.drawMode === constants.FILL || this.drawMode === constants.TEXTURE) {
+ switch (this.immediateMode.shapeMode) {
+ case constants.LINE_STRIP:
+ case constants.LINES:
+ this.immediateMode.shapeMode = constants.TRIANGLE_FAN;
+ break;
+ }
+ } else {
+ switch (this.immediateMode.shapeMode) {
+ case constants.LINE_STRIP:
+ case constants.LINES:
+ this.immediateMode.shapeMode = constants.LINE_LOOP;
+ break;
+ }
+ }
+ //}
+ //QUADS & QUAD_STRIP are not supported primitives modes
+ //in webgl.
+ if (
+ this.immediateMode.shapeMode === constants.QUADS ||
+ this.immediateMode.shapeMode === constants.QUAD_STRIP
+ ) {
+ throw new Error(
+ 'sorry, '.concat(
+ this.immediateMode.shapeMode,
+ ' not yet implemented in webgl mode.'
+ )
+ );
+ } else {
+ this._applyColorBlend(this.curFillColor);
+ gl.enable(gl.BLEND);
+ gl.drawArrays(
+ this.immediateMode.shapeMode,
+ 0,
+ this.immediateMode.vertices.length
+ );
+ }
+ // todo / optimizations? leave bound until another shader is set?
+ shader.unbindShader();
+ };
+
+ _main.default.RendererGL.prototype._drawStrokeImmediateMode = function() {
+ var gl = this.GL;
+ var shader = this._getImmediateStrokeShader();
+ this._setStrokeUniforms(shader);
+
+ // initialize the stroke shader's 'aPosition' buffer
+ if (shader.attributes.aPosition) {
+ this._bindBuffer(
+ this.immediateMode.lineVertexBuffer,
+ gl.ARRAY_BUFFER,
+ this._flatten(this.immediateMode.lineVertices),
+ Float32Array,
+ gl.STATIC_DRAW
+ );
+
+ shader.enableAttrib(shader.attributes.aPosition, 3);
+ }
+
+ // initialize the stroke shader's 'aDirection' buffer
+ if (shader.attributes.aDirection) {
+ this._bindBuffer(
+ this.immediateMode.lineNormalBuffer,
+ gl.ARRAY_BUFFER,
+ this._flatten(this.immediateMode.lineNormals),
+ Float32Array,
+ gl.STATIC_DRAW
+ );
+
+ shader.enableAttrib(shader.attributes.aDirection, 4);
+ }
+
+ this._applyColorBlend(this.curStrokeColor);
+ gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.lineVertices.length);
+
+ shader.unbindShader();
+ };
+ var _default = _main.default.RendererGL;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 79: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ _dereq_('./p5.RendererGL');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ } //Retained Mode. The default mode for rendering 3D primitives
+ //in WEBGL.
+ // a render buffer definition
+ function BufferDef(size, src, dst, attr, map) {
+ this.size = size; // the number of FLOATs in each vertex
+ this.src = src; // the name of the model's source array
+ this.dst = dst; // the name of the geometry's buffer
+ this.attr = attr; // the name of the vertex attribute
+ this.map = map; // optional, a transformation function to apply to src
+ }
+
+ var _flatten = _main.default.RendererGL.prototype._flatten;
+ var _vToNArray = _main.default.RendererGL.prototype._vToNArray;
+
+ var strokeBuffers = [
+ new BufferDef(3, 'lineVertices', 'lineVertexBuffer', 'aPosition', _flatten),
+ new BufferDef(4, 'lineNormals', 'lineNormalBuffer', 'aDirection', _flatten)
+ ];
+
+ var fillBuffers = [
+ new BufferDef(3, 'vertices', 'vertexBuffer', 'aPosition', _vToNArray),
+ new BufferDef(3, 'vertexNormals', 'normalBuffer', 'aNormal', _vToNArray),
+ new BufferDef(4, 'vertexColors', 'colorBuffer', 'aMaterialColor'),
+ new BufferDef(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor'),
+ //new BufferDef(3, 'vertexSpeculars', 'specularBuffer', 'aSpecularColor'),
+ new BufferDef(2, 'uvs', 'uvBuffer', 'aTexCoord', _flatten)
+ ];
+
+ _main.default.RendererGL._textBuffers = [
+ new BufferDef(3, 'vertices', 'vertexBuffer', 'aPosition', _vToNArray),
+ new BufferDef(2, 'uvs', 'uvBuffer', 'aTexCoord', _flatten)
+ ];
+
+ var hashCount = 0;
+ /**
+ * _initBufferDefaults
+ * @private
+ * @description initializes buffer defaults. runs each time a new geometry is
+ * registered
+ * @param {String} gId key of the geometry object
+ * @returns {Object} a new buffer object
+ */
+ _main.default.RendererGL.prototype._initBufferDefaults = function(gId) {
+ this._freeBuffers(gId);
+
+ //@TODO remove this limit on hashes in gHash
+ hashCount++;
+ if (hashCount > 1000) {
+ var key = Object.keys(this.gHash)[0];
+ delete this.gHash[key];
+ hashCount--;
+ }
+
+ //create a new entry in our gHash
+ return (this.gHash[gId] = {});
+ };
+
+ _main.default.RendererGL.prototype._freeBuffers = function(gId) {
+ var buffers = this.gHash[gId];
+ if (!buffers) {
+ return;
+ }
+
+ delete this.gHash[gId];
+ hashCount--;
+
+ var gl = this.GL;
+ if (buffers.indexBuffer) {
+ gl.deleteBuffer(buffers.indexBuffer);
+ }
+
+ function freeBuffers(defs) {
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (
+ var _iterator = defs[Symbol.iterator](), _step;
+ !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
+ _iteratorNormalCompletion = true
+ ) {
+ var def = _step.value;
+ if (buffers[def.dst]) {
+ gl.deleteBuffer(buffers[def.dst]);
+ buffers[def.dst] = null;
+ }
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ }
+
+ // free all the buffers
+ freeBuffers(strokeBuffers);
+ freeBuffers(fillBuffers);
+ };
+
+ _main.default.RendererGL.prototype._prepareBuffers = function(
+ buffers,
+ shader,
+ defs
+ ) {
+ var model = buffers.model;
+ var attributes = shader.attributes;
+ var gl = this.GL;
+
+ // loop through each of the buffer definitions
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (
+ var _iterator2 = defs[Symbol.iterator](), _step2;
+ !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
+ _iteratorNormalCompletion2 = true
+ ) {
+ var def = _step2.value;
+ var attr = attributes[def.attr];
+ if (!attr) continue;
+
+ var buffer = buffers[def.dst];
+
+ // check if the model has the appropriate source array
+ var src = model[def.src];
+ if (src) {
+ // check if we need to create the GL buffer
+ var createBuffer = !buffer;
+ if (createBuffer) {
+ // create and remember the buffer
+ buffers[def.dst] = buffer = gl.createBuffer();
+ }
+ // bind the buffer
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+
+ // check if we need to fill the buffer with data
+ if (createBuffer || model.dirtyFlags[def.src] !== false) {
+ var map = def.map;
+ // get the values from the model, possibly transformed
+ var values = map ? map(src) : src;
+
+ // fill the buffer with the values
+ this._bindBuffer(buffer, gl.ARRAY_BUFFER, values);
+
+ // mark the model's source array as clean
+ model.dirtyFlags[def.src] = false;
+ }
+ // enable the attribute
+ shader.enableAttrib(attr, def.size);
+ } else {
+ if (buffer) {
+ // remove the unused buffer
+ gl.deleteBuffer(buffer);
+ buffers[def.dst] = null;
+ }
+ // disable the vertex
+ gl.disableVertexAttribArray(attr.index);
+ }
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ };
+
+ /**
+ * creates a buffers object that holds the WebGL render buffers
+ * for a geometry.
+ * @private
+ * @param {String} gId key of the geometry object
+ * @param {p5.Geometry} model contains geometry data
+ */
+ _main.default.RendererGL.prototype.createBuffers = function(gId, model) {
+ var gl = this.GL;
+ //initialize the gl buffers for our geom groups
+ var buffers = this._initBufferDefaults(gId);
+ buffers.model = model;
+
+ var indexBuffer = buffers.indexBuffer;
+
+ if (model.faces.length) {
+ // allocate space for faces
+ if (!indexBuffer) indexBuffer = buffers.indexBuffer = gl.createBuffer();
+ var vals = _main.default.RendererGL.prototype._flatten(model.faces);
+ this._bindBuffer(indexBuffer, gl.ELEMENT_ARRAY_BUFFER, vals, Uint16Array);
+
+ // the vertex count is based on the number of faces
+ buffers.vertexCount = model.faces.length * 3;
+ } else {
+ // the index buffer is unused, remove it
+ if (indexBuffer) {
+ gl.deleteBuffer(indexBuffer);
+ buffers.indexBuffer = null;
+ }
+ // the vertex count comes directly from the model
+ buffers.vertexCount = model.vertices ? model.vertices.length : 0;
+ }
+
+ buffers.lineVertexCount = model.lineVertices ? model.lineVertices.length : 0;
+
+ return buffers;
+ };
+
+ /**
+ * Draws buffers given a geometry key ID
+ * @private
+ * @param {String} gId ID in our geom hash
+ * @chainable
+ */
+ _main.default.RendererGL.prototype.drawBuffers = function(gId) {
+ var gl = this.GL;
+ var buffers = this.gHash[gId];
+
+ if (this._doStroke && buffers.lineVertexCount > 0) {
+ var strokeShader = this._getRetainedStrokeShader();
+ this._setStrokeUniforms(strokeShader);
+ this._prepareBuffers(buffers, strokeShader, strokeBuffers);
+ this._applyColorBlend(this.curStrokeColor);
+ this._drawArrays(gl.TRIANGLES, gId);
+ strokeShader.unbindShader();
+ }
+
+ if (this._doFill) {
+ var fillShader = this._getRetainedFillShader();
+ this._setFillUniforms(fillShader);
+ this._prepareBuffers(buffers, fillShader, fillBuffers);
+ if (buffers.indexBuffer) {
+ //vertex index buffer
+ this._bindBuffer(buffers.indexBuffer, gl.ELEMENT_ARRAY_BUFFER);
+ }
+ this._applyColorBlend(this.curFillColor);
+ this._drawElements(gl.TRIANGLES, gId);
+ fillShader.unbindShader();
+ }
+ return this;
+ };
+
+ /**
+ * Calls drawBuffers() with a scaled model/view matrix.
+ *
+ * This is used by various 3d primitive methods (in primitives.js, eg. plane,
+ * box, torus, etc...) to allow caching of un-scaled geometries. Those
+ * geometries are generally created with unit-length dimensions, cached as
+ * such, and then scaled appropriately in this method prior to rendering.
+ *
+ * @private
+ * @method drawBuffersScaled
+ * @param {String} gId ID in our geom hash
+ * @param {Number} scaleX the amount to scale in the X direction
+ * @param {Number} scaleY the amount to scale in the Y direction
+ * @param {Number} scaleZ the amount to scale in the Z direction
+ */
+ _main.default.RendererGL.prototype.drawBuffersScaled = function(
+ gId,
+ scaleX,
+ scaleY,
+ scaleZ
+ ) {
+ var uMVMatrix = this.uMVMatrix.copy();
+ try {
+ this.uMVMatrix.scale(scaleX, scaleY, scaleZ);
+ this.drawBuffers(gId);
+ } finally {
+ this.uMVMatrix = uMVMatrix;
+ }
+ };
+
+ _main.default.RendererGL.prototype._drawArrays = function(drawMode, gId) {
+ this.GL.drawArrays(drawMode, 0, this.gHash[gId].lineVertexCount);
+ return this;
+ };
+
+ _main.default.RendererGL.prototype._drawElements = function(drawMode, gId) {
+ var buffers = this.gHash[gId];
+ var gl = this.GL;
+ // render the fill
+ if (buffers.indexBuffer) {
+ // we're drawing faces
+ gl.drawElements(gl.TRIANGLES, buffers.vertexCount, gl.UNSIGNED_SHORT, 0);
+ } else {
+ // drawing vertices
+ gl.drawArrays(drawMode || gl.TRIANGLES, 0, buffers.vertexCount);
+ }
+ };
+
+ _main.default.RendererGL.prototype._drawPoints = function(
+ vertices,
+ vertexBuffer
+ ) {
+ var gl = this.GL;
+ var pointShader = this._getImmediatePointShader();
+ this._setPointUniforms(pointShader);
+
+ this._bindBuffer(
+ vertexBuffer,
+ gl.ARRAY_BUFFER,
+ this._vToNArray(vertices),
+ Float32Array,
+ gl.STATIC_DRAW
+ );
+
+ pointShader.enableAttrib(pointShader.attributes.aPosition, 3);
+
+ gl.drawArrays(gl.Points, 0, vertices.length);
+
+ pointShader.unbindShader();
+ };
+ var _default = _main.default.RendererGL;
+ exports.default = _default;
+ },
+ { '../core/main': 27, './p5.RendererGL': 80 }
+ ],
+ 80: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ var _libtess = _interopRequireDefault(_dereq_('libtess'));
+ _dereq_('./p5.Shader');
+ _dereq_('./p5.Camera');
+ _dereq_('../core/p5.Renderer');
+ _dereq_('./p5.Matrix');
+
+ var _path = _dereq_('path');
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ function _toConsumableArray(arr) {
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
+ }
+ function _nonIterableSpread() {
+ throw new TypeError('Invalid attempt to spread non-iterable instance');
+ }
+ function _iterableToArray(iter) {
+ if (
+ Symbol.iterator in Object(iter) ||
+ Object.prototype.toString.call(iter) === '[object Arguments]'
+ )
+ return Array.from(iter);
+ }
+ function _arrayWithoutHoles(arr) {
+ if (Array.isArray(arr)) {
+ for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
+ arr2[i] = arr[i];
+ }
+ return arr2;
+ }
+ }
+
+ var lightingShader =
+ 'precision mediump float;\n\nuniform mat4 uViewMatrix;\n\nuniform bool uUseLighting;\n\nuniform int uAmbientLightCount;\nuniform vec3 uAmbientColor[8];\n\nuniform int uDirectionalLightCount;\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalDiffuseColors[8];\nuniform vec3 uDirectionalSpecularColors[8];\n\nuniform int uPointLightCount;\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightDiffuseColors[8];\t\nuniform vec3 uPointLightSpecularColors[8];\n\nuniform int uSpotLightCount;\nuniform float uSpotLightAngle[8];\nuniform float uSpotLightConc[8];\nuniform vec3 uSpotLightDiffuseColors[8];\nuniform vec3 uSpotLightSpecularColors[8];\nuniform vec3 uSpotLightLocation[8];\nuniform vec3 uSpotLightDirection[8];\n\nuniform bool uSpecular;\nuniform float uShininess;\n\nuniform float uConstantAttenuation;\nuniform float uLinearAttenuation;\nuniform float uQuadraticAttenuation;\n\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n float specular;\n float diffuse;\n};\n\nfloat _phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = reflect(lightDirection, surfaceNormal);\n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat _lambertDiffuse(vec3 lightDirection, vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult _light(vec3 viewDirection, vec3 normal, vec3 lightVector) {\n\n vec3 lightDir = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = _phongSpecular(lightDir, viewDirection, normal, uShininess);\n lr.diffuse = _lambertDiffuse(lightDir, normal);\n return lr;\n}\n\nvoid totalLight(\n vec3 modelPosition,\n vec3 normal,\n out vec3 totalDiffuse,\n out vec3 totalSpecular\n) {\n\n totalSpecular = vec3(0.0);\n\n if (!uUseLighting) {\n totalDiffuse = vec3(1.0);\n return;\n }\n\n totalDiffuse = vec3(0.0);\n\n vec3 viewDirection = normalize(-modelPosition);\n\n for (int j = 0; j < 8; j++) {\n if (j < uDirectionalLightCount) {\n vec3 lightVector = (uViewMatrix * vec4(uLightingDirection[j], 0.0)).xyz;\n vec3 lightColor = uDirectionalDiffuseColors[j];\n vec3 specularColor = uDirectionalSpecularColors[j];\n LightResult result = _light(viewDirection, normal, lightVector);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if (j < uPointLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n \n //calculate attenuation\n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n vec3 lightColor = lightFalloff * uPointLightDiffuseColors[j];\n vec3 specularColor = lightFalloff * uPointLightSpecularColors[j];\n\n LightResult result = _light(viewDirection, normal, lightVector);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if(j < uSpotLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uSpotLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n \n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n\n vec3 lightDirection = (uViewMatrix * vec4(uSpotLightDirection[j], 0.0)).xyz;\n float spotDot = dot(normalize(lightVector), normalize(lightDirection));\n float spotFalloff;\n if(spotDot < uSpotLightAngle[j]) {\n spotFalloff = 0.0;\n }\n else {\n spotFalloff = pow(spotDot, uSpotLightConc[j]);\n }\n lightFalloff *= spotFalloff;\n\n vec3 lightColor = uSpotLightDiffuseColors[j];\n vec3 specularColor = uSpotLightSpecularColors[j];\n \n LightResult result = _light(viewDirection, normal, lightVector);\n \n totalDiffuse += result.diffuse * lightColor * lightFalloff;\n totalSpecular += result.specular * lightColor * specularColor * lightFalloff;\n }\n }\n\n totalDiffuse *= diffuseFactor;\n totalSpecular *= specularFactor;\n}\n';
+
+ var defaultShaders = {
+ immediateVert:
+ 'attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nvarying vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n',
+
+ vertexColorVert:
+ 'attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n',
+
+ vertexColorFrag:
+ 'precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vColor;\n}',
+
+ normalVert:
+ 'attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n}\n',
+ normalFrag:
+ 'precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}',
+ basicFrag:
+ 'precision mediump float;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}',
+ lightVert:
+ lightingShader +
+ '// include lighting.glgl\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying highp vec2 vVertTexCoord;\nvarying vec3 vDiffuseColor;\nvarying vec3 vSpecularColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n\n vec3 vertexNormal = normalize(uNormalMatrix * aNormal);\n vVertTexCoord = aTexCoord;\n\n totalLight(viewModelPosition.xyz, vertexNormal, vDiffuseColor, vSpecularColor);\n\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vDiffuseColor += uAmbientColor[i];\n }\n }\n}\n',
+
+ lightTextureFrag:
+ 'precision mediump float;\n\nuniform vec4 uMaterialColor;\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nvarying highp vec2 vVertTexCoord;\nvarying vec3 vDiffuseColor;\nvarying vec3 vSpecularColor;\n\nvoid main(void) {\n if(uEmissive && !isTexture) {\n gl_FragColor = uMaterialColor;\n }\n else {\n gl_FragColor = isTexture ? texture2D(uSampler, vVertTexCoord) * (uTint / vec4(255, 255, 255, 255)) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * vDiffuseColor + vSpecularColor;\n }\n}',
+
+ phongVert:
+ 'precision mediump float;\nprecision mediump int;\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform vec3 uAmbientColor[8];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = uNormalMatrix * aNormal;\n vTexCoord = aTexCoord;\n\n // TODO: this should be a uniform\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vAmbientColor += uAmbientColor[i];\n }\n }\n}\n',
+ phongFrag:
+ lightingShader +
+ '// include lighting.glsl\nprecision highp float;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void) {\n\n vec3 diffuse;\n vec3 specular;\n totalLight(vViewPosition, normalize(vNormal), diffuse, specular);\n\n if(uEmissive && !isTexture) {\n gl_FragColor = uMaterialColor;\n }\n else {\n gl_FragColor = isTexture ? texture2D(uSampler, vTexCoord) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * (diffuse + vAmbientColor) + specular;\n }\n}',
+
+ fontVert:
+ "precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nvarying vec2 vTexCoord;\nvarying float w;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph's rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter's line offset\n positionVec4.x += uGlyphOffset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord;\n w = gl_Position.w;\n}\n",
+ fontFrag:
+ "#extension GL_OES_standard_derivatives : enable\nprecision mediump float;\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision highp int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nvarying vec2 vTexCoord;\n\n// some helper functions\nint round(float v) { return ifloor(v + 0.5); }\nivec2 round(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = round(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return texture2D(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of 't' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n gl_FragColor = uMaterialColor;\n gl_FragColor.a *= saturate(max(antialias, cover));\n}",
+ lineVert:
+ "/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n \nvoid main() {\n // using a scale <1 moves the lines towards the camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n vec3 scale = vec3(0.9995);\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posq = uModelViewMatrix * (aPosition + vec4(aDirection.xyz, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posq.xyz = posq.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 q = uProjectionMatrix * posq;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangent = normalize((q.xy*p.w - p.xy*q.w) * uViewport.zw);\n\n // flip tangent to normal (it's already normalized)\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float thickness = aDirection.w * uStrokeWeight;\n vec2 offset = normal * thickness / 2.0;\n\n vec2 curPerspScale;\n\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // invert Y, projections in Processing invert Y\n curPerspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n}\n",
+ lineFrag:
+ 'precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\n\nvoid main() {\n gl_FragColor = uMaterialColor;\n}',
+ pointVert:
+ 'attribute vec3 aPosition;\nuniform float uPointSize;\nvarying float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}',
+ pointFrag:
+ 'precision mediump float;\nprecision mediump int;\nuniform vec4 uMaterialColor;\nvarying float vStrokeWeight;\n\nvoid main(){\n\tfloat mask = 0.0;\n\n\t// make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n\tmask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n\t// if strokeWeight is 1 or less lets just draw a square\n\t// this prevents weird artifacting from carving circles when our points are really small\n\t// if strokeWeight is larger than 1, we just use it as is\n\n\tmask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n\t// throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n\tif(mask > 0.98){\n discard;\n \t}\n\n \tgl_FragColor = vec4(uMaterialColor.rgb * (1.0 - mask), uMaterialColor.a) ;\n}'
+ };
+
+ /**
+ * 3D graphics class
+ * @private
+ * @class p5.RendererGL
+ * @constructor
+ * @extends p5.Renderer
+ * @todo extend class to include public method for offscreen
+ * rendering (FBO).
+ *
+ */
+ _main.default.RendererGL = function(elt, pInst, isMainCanvas, attr) {
+ _main.default.Renderer.call(this, elt, pInst, isMainCanvas);
+ this._setAttributeDefaults(pInst);
+ this._initContext();
+ this.isP3D = true; //lets us know we're in 3d mode
+ this.GL = this.drawingContext;
+
+ // erasing
+ this._isErasing = false;
+
+ // lights
+ this._enableLighting = false;
+
+ this.ambientLightColors = [];
+ this.specularColors = [1, 1, 1];
+
+ this.directionalLightDirections = [];
+ this.directionalLightDiffuseColors = [];
+ this.directionalLightSpecularColors = [];
+
+ this.pointLightPositions = [];
+ this.pointLightDiffuseColors = [];
+ this.pointLightSpecularColors = [];
+
+ this.spotLightPositions = [];
+ this.spotLightDirections = [];
+ this.spotLightDiffuseColors = [];
+ this.spotLightSpecularColors = [];
+ this.spotLightAngle = [];
+ this.spotLightConc = [];
+
+ this.drawMode = constants.FILL;
+
+ this.curFillColor = this._cachedFillStyle = [1, 1, 1, 1];
+ this.curStrokeColor = this._cachedStrokeStyle = [0, 0, 0, 1];
+
+ this.curBlendMode = this._cachedBlendMode = constants.BLEND;
+ this.blendExt = this.GL.getExtension('EXT_blend_minmax');
+
+ this._useSpecularMaterial = false;
+ this._useEmissiveMaterial = false;
+ this._useNormalMaterial = false;
+ this._useShininess = 1;
+
+ this._tint = [255, 255, 255, 255];
+
+ // lightFalloff variables
+ this.constantAttenuation = 1;
+ this.linearAttenuation = 0;
+ this.quadraticAttenuation = 0;
+
+ /**
+ * model view, projection, & normal
+ * matrices
+ */
+ this.uMVMatrix = new _main.default.Matrix();
+ this.uPMatrix = new _main.default.Matrix();
+ this.uNMatrix = new _main.default.Matrix('mat3');
+
+ // Camera
+ this._curCamera = new _main.default.Camera(this);
+ this._curCamera._computeCameraDefaultSettings();
+ this._curCamera._setDefaultCamera();
+
+ //Geometry & Material hashes
+ this.gHash = {};
+
+ this._defaultLightShader = undefined;
+ this._defaultImmediateModeShader = undefined;
+ this._defaultNormalShader = undefined;
+ this._defaultColorShader = undefined;
+ this._defaultPointShader = undefined;
+
+ this._pointVertexBuffer = this.GL.createBuffer();
+
+ this.userFillShader = undefined;
+ this.userStrokeShader = undefined;
+ this.userPointShader = undefined;
+
+ //Imediate Mode
+ //default drawing is done in Retained Mode
+ this.isImmediateDrawing = false;
+ this.immediateMode = {};
+
+ this.pointSize = 5.0; //default point size
+ this.curStrokeWeight = 1;
+
+ // array of textures created in this gl context via this.getTexture(src)
+ this.textures = [];
+
+ this.textureMode = constants.IMAGE;
+ // default wrap settings
+ this.textureWrapX = constants.CLAMP;
+ this.textureWrapY = constants.CLAMP;
+ this._tex = null;
+ this._curveTightness = 6;
+
+ // lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex
+ this._lookUpTableBezier = [];
+ // lookUpTable for coefficients needed to be calculated for quadraticVertex
+ this._lookUpTableQuadratic = [];
+
+ // current curveDetail in the Bezier lookUpTable
+ this._lutBezierDetail = 0;
+ // current curveDetail in the Quadratic lookUpTable
+ this._lutQuadraticDetail = 0;
+
+ this._tessy = this._initTessy();
+
+ this.fontInfos = {};
+
+ return this;
+ };
+
+ _main.default.RendererGL.prototype = Object.create(
+ _main.default.Renderer.prototype
+ );
+
+ //////////////////////////////////////////////
+ // Setting
+ //////////////////////////////////////////////
+
+ _main.default.RendererGL.prototype._setAttributeDefaults = function(pInst) {
+ var defaults = {
+ alpha: true,
+ depth: true,
+ stencil: true,
+ antialias: false,
+ premultipliedAlpha: false,
+ preserveDrawingBuffer: true,
+ perPixelLighting: false
+ };
+
+ if (pInst._glAttributes === null) {
+ pInst._glAttributes = defaults;
+ } else {
+ pInst._glAttributes = Object.assign(defaults, pInst._glAttributes);
+ }
+ return;
+ };
+
+ _main.default.RendererGL.prototype._initContext = function() {
+ try {
+ this.drawingContext =
+ this.canvas.getContext('webgl', this._pInst._glAttributes) ||
+ this.canvas.getContext('experimental-webgl', this._pInst._glAttributes);
+ if (this.drawingContext === null) {
+ throw new Error('Error creating webgl context');
+ } else {
+ var gl = this.drawingContext;
+ gl.enable(gl.DEPTH_TEST);
+ gl.depthFunc(gl.LEQUAL);
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
+ this._viewport = this.drawingContext.getParameter(
+ this.drawingContext.VIEWPORT
+ );
+ }
+ } catch (er) {
+ throw er;
+ }
+ };
+
+ //This is helper function to reset the context anytime the attributes
+ //are changed with setAttributes()
+
+ _main.default.RendererGL.prototype._resetContext = function(options, callback) {
+ var w = this.width;
+ var h = this.height;
+ var defaultId = this.canvas.id;
+ var isPGraphics = this._pInst instanceof _main.default.Graphics;
+
+ if (isPGraphics) {
+ var pg = this._pInst;
+ pg.canvas.parentNode.removeChild(pg.canvas);
+ pg.canvas = document.createElement('canvas');
+ var node = pg._pInst._userNode || document.body;
+ node.appendChild(pg.canvas);
+ _main.default.Element.call(pg, pg.canvas, pg._pInst);
+ pg.width = w;
+ pg.height = h;
+ } else {
+ var c = this.canvas;
+ if (c) {
+ c.parentNode.removeChild(c);
+ }
+ c = document.createElement('canvas');
+ c.id = defaultId;
+ if (this._pInst._userNode) {
+ this._pInst._userNode.appendChild(c);
+ } else {
+ document.body.appendChild(c);
+ }
+ this._pInst.canvas = c;
+ }
+
+ var renderer = new _main.default.RendererGL(
+ this._pInst.canvas,
+ this._pInst,
+ !isPGraphics
+ );
+
+ this._pInst._setProperty('_renderer', renderer);
+ renderer.resize(w, h);
+ renderer._applyDefaults();
+
+ if (!isPGraphics) {
+ this._pInst._elements.push(renderer);
+ }
+
+ if (typeof callback === 'function') {
+ //setTimeout with 0 forces the task to the back of the queue, this ensures that
+ //we finish switching out the renderer
+ setTimeout(function() {
+ callback.apply(window._renderer, options);
+ }, 0);
+ }
+ };
+ /**
+ * @module Rendering
+ * @submodule Rendering
+ * @for p5
+ */
+ /**
+ * Set attributes for the WebGL Drawing context.
+ * This is a way of adjusting how the WebGL
+ * renderer works to fine-tune the display and performance.
+ *
+ * Note that this will reinitialize the drawing context
+ * if called after the WebGL canvas is made.
+ *
+ * If an object is passed as the parameter, all attributes
+ * not declared in the object will be set to defaults.
+ *
+ * The available attributes are:
+ *
+ * alpha - indicates if the canvas contains an alpha buffer
+ * default is true
+ *
+ * depth - indicates whether the drawing buffer has a depth buffer
+ * of at least 16 bits - default is true
+ *
+ * stencil - indicates whether the drawing buffer has a stencil buffer
+ * of at least 8 bits
+ *
+ * antialias - indicates whether or not to perform anti-aliasing
+ * default is false
+ *
+ * premultipliedAlpha - indicates that the page compositor will assume
+ * the drawing buffer contains colors with pre-multiplied alpha
+ * default is false
+ *
+ * preserveDrawingBuffer - if true the buffers will not be cleared and
+ * and will preserve their values until cleared or overwritten by author
+ * (note that p5 clears automatically on draw loop)
+ * default is true
+ *
+ * perPixelLighting - if true, per-pixel lighting will be used in the
+ * lighting shader.
+ * default is false
+ *
+ * @method setAttributes
+ * @for p5
+ * @param {String} key Name of attribute
+ * @param {Boolean} value New value of named attribute
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * push();
+ * rotateZ(frameCount * 0.02);
+ * rotateX(frameCount * 0.02);
+ * rotateY(frameCount * 0.02);
+ * fill(0, 0, 0);
+ * box(50);
+ * pop();
+ * }
+ *
+ *
+ *
+ * Now with the antialias attribute set to true.
+ *
+ *
+ *
+ * function setup() {
+ * setAttributes('antialias', true);
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * push();
+ * rotateZ(frameCount * 0.02);
+ * rotateX(frameCount * 0.02);
+ * rotateY(frameCount * 0.02);
+ * fill(0, 0, 0);
+ * box(50);
+ * pop();
+ * }
+ *
+ *
+ *
+ *
+ *
+ * // press the mouse button to enable perPixelLighting
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * fill(255);
+ * }
+ *
+ * let lights = [
+ * { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },
+ * { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },
+ * { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },
+ * { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },
+ * { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },
+ * { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }
+ * ];
+ *
+ * function draw() {
+ * let t = millis() / 1000 + 1000;
+ * background(0);
+ * directionalLight(color('#222'), 1, 1, 1);
+ *
+ * for (let i = 0; i < lights.length; i++) {
+ * let light = lights[i];
+ * pointLight(
+ * color(light.c),
+ * p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)
+ * );
+ * }
+ *
+ * specularMaterial(255);
+ * sphere(width * 0.1);
+ *
+ * rotateX(t * 0.77);
+ * rotateY(t * 0.83);
+ * rotateZ(t * 0.91);
+ * torus(width * 0.3, width * 0.07, 24, 10);
+ * }
+ *
+ * function mousePressed() {
+ * setAttributes('perPixelLighting', true);
+ * noStroke();
+ * fill(255);
+ * }
+ * function mouseReleased() {
+ * setAttributes('perPixelLighting', false);
+ * noStroke();
+ * fill(255);
+ * }
+ *
+ *
+ *
+ * @alt a rotating cube with smoother edges
+ */
+ /**
+ * @method setAttributes
+ * @for p5
+ * @param {Object} obj object with key-value pairs
+ */
+
+ _main.default.prototype.setAttributes = function(key, value) {
+ if (typeof this._glAttributes === 'undefined') {
+ console.log(
+ 'You are trying to use setAttributes on a p5.Graphics object ' +
+ 'that does not use a WEBGL renderer.'
+ );
+
+ return;
+ }
+ var unchanged = true;
+ if (typeof value !== 'undefined') {
+ //first time modifying the attributes
+ if (this._glAttributes === null) {
+ this._glAttributes = {};
+ }
+ if (this._glAttributes[key] !== value) {
+ //changing value of previously altered attribute
+ this._glAttributes[key] = value;
+ unchanged = false;
+ }
+ //setting all attributes with some change
+ } else if (key instanceof Object) {
+ if (this._glAttributes !== key) {
+ this._glAttributes = key;
+ unchanged = false;
+ }
+ }
+ //@todo_FES
+ if (!this._renderer.isP3D || unchanged) {
+ return;
+ }
+
+ if (!this._setupDone) {
+ for (var x in this._renderer.gHash) {
+ if (this._renderer.gHash.hasOwnProperty(x)) {
+ console.error(
+ 'Sorry, Could not set the attributes, you need to call setAttributes() ' +
+ 'before calling the other drawing methods in setup()'
+ );
+
+ return;
+ }
+ }
+ }
+
+ this.push();
+ this._renderer._resetContext();
+ this.pop();
+
+ if (this._renderer._curCamera) {
+ this._renderer._curCamera._renderer = this._renderer;
+ }
+ };
+
+ /**
+ * @class p5.RendererGL
+ */
+
+ _main.default.RendererGL.prototype._update = function() {
+ // reset model view and apply initial camera transform
+ // (containing only look at info; no projection).
+ this.uMVMatrix.set(
+ this._curCamera.cameraMatrix.mat4[0],
+ this._curCamera.cameraMatrix.mat4[1],
+ this._curCamera.cameraMatrix.mat4[2],
+ this._curCamera.cameraMatrix.mat4[3],
+ this._curCamera.cameraMatrix.mat4[4],
+ this._curCamera.cameraMatrix.mat4[5],
+ this._curCamera.cameraMatrix.mat4[6],
+ this._curCamera.cameraMatrix.mat4[7],
+ this._curCamera.cameraMatrix.mat4[8],
+ this._curCamera.cameraMatrix.mat4[9],
+ this._curCamera.cameraMatrix.mat4[10],
+ this._curCamera.cameraMatrix.mat4[11],
+ this._curCamera.cameraMatrix.mat4[12],
+ this._curCamera.cameraMatrix.mat4[13],
+ this._curCamera.cameraMatrix.mat4[14],
+ this._curCamera.cameraMatrix.mat4[15]
+ );
+
+ // reset light data for new frame.
+
+ this.ambientLightColors.length = 0;
+ this.specularColors = [1, 1, 1];
+
+ this.directionalLightDirections.length = 0;
+ this.directionalLightDiffuseColors.length = 0;
+ this.directionalLightSpecularColors.length = 0;
+
+ this.pointLightPositions.length = 0;
+ this.pointLightDiffuseColors.length = 0;
+ this.pointLightSpecularColors.length = 0;
+
+ this.spotLightPositions.length = 0;
+ this.spotLightDirections.length = 0;
+ this.spotLightDiffuseColors.length = 0;
+ this.spotLightSpecularColors.length = 0;
+ this.spotLightAngle.length = 0;
+ this.spotLightConc.length = 0;
+
+ this._enableLighting = false;
+
+ //reset tint value for new frame
+ this._tint = [255, 255, 255, 255];
+
+ //Clear depth every frame
+ this.GL.clear(this.GL.DEPTH_BUFFER_BIT);
+ };
+
+ /**
+ * [background description]
+ */
+ _main.default.RendererGL.prototype.background = function() {
+ var _this$_pInst;
+ var _col = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments);
+ var _r = _col.levels[0] / 255;
+ var _g = _col.levels[1] / 255;
+ var _b = _col.levels[2] / 255;
+ var _a = _col.levels[3] / 255;
+ this.GL.clearColor(_r, _g, _b, _a);
+ this.GL.depthMask(true);
+ this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT);
+ };
+
+ //////////////////////////////////////////////
+ // COLOR
+ //////////////////////////////////////////////
+ /**
+ * Basic fill material for geometry with a given color
+ * @method fill
+ * @class p5.RendererGL
+ * @param {Number|Number[]|String|p5.Color} v1 gray value,
+ * red or hue value (depending on the current color mode),
+ * or color Array, or CSS color string
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @param {Number} [a] opacity
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(200, 200, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * fill(100, 100, 240);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(75, 75, 75);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black canvas with purple cube spinning
+ *
+ */
+ _main.default.RendererGL.prototype.fill = function(v1, v2, v3, a) {
+ //see material.js for more info on color blending in webgl
+ var color = _main.default.prototype.color.apply(this._pInst, arguments);
+ this.curFillColor = color._array;
+ this.drawMode = constants.FILL;
+ this._useNormalMaterial = false;
+ this._tex = null;
+ };
+
+ /**
+ * Basic stroke material for geometry with a given color
+ * @method stroke
+ * @param {Number|Number[]|String|p5.Color} v1 gray value,
+ * red or hue value (depending on the current color mode),
+ * or color Array, or CSS color string
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @param {Number} [a] opacity
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(200, 200, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * stroke(240, 150, 150);
+ * fill(100, 100, 240);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(75, 75, 75);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black canvas with purple cube with pink outline spinning
+ *
+ */
+ _main.default.RendererGL.prototype.stroke = function(r, g, b, a) {
+ //@todo allow transparency in stroking currently doesn't have
+ //any impact and causes problems with specularMaterial
+ arguments[3] = 255;
+ var color = _main.default.prototype.color.apply(this._pInst, arguments);
+ this.curStrokeColor = color._array;
+ };
+
+ _main.default.RendererGL.prototype.strokeCap = function(cap) {
+ // @TODO : to be implemented
+ console.error('Sorry, strokeCap() is not yet implemented in WEBGL mode');
+ };
+
+ _main.default.RendererGL.prototype.strokeJoin = function(join) {
+ // @TODO : to be implemented
+ // https://processing.org/reference/strokeJoin_.html
+ console.error('Sorry, strokeJoin() is not yet implemented in WEBGL mode');
+ };
+
+ _main.default.RendererGL.prototype.blendMode = function(mode) {
+ if (
+ mode === constants.DARKEST ||
+ mode === constants.LIGHTEST ||
+ mode === constants.ADD ||
+ mode === constants.BLEND ||
+ mode === constants.SUBTRACT ||
+ mode === constants.SCREEN ||
+ mode === constants.EXCLUSION ||
+ mode === constants.REPLACE ||
+ mode === constants.MULTIPLY ||
+ mode === constants.REMOVE
+ )
+ this.curBlendMode = mode;
+ else if (
+ mode === constants.BURN ||
+ mode === constants.OVERLAY ||
+ mode === constants.HARD_LIGHT ||
+ mode === constants.SOFT_LIGHT ||
+ mode === constants.DODGE
+ ) {
+ console.warn(
+ 'BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.'
+ );
+ }
+ };
+
+ _main.default.RendererGL.prototype.erase = function(opacityFill, opacityStroke) {
+ if (!this._isErasing) {
+ this._cachedBlendMode = this.curBlendMode;
+ this.blendMode(constants.REMOVE);
+
+ this._cachedFillStyle = this.curFillColor.slice();
+ this.curFillColor = [1, 1, 1, opacityFill / 255];
+
+ this._cachedStrokeStyle = this.curStrokeColor.slice();
+ this.curStrokeColor = [1, 1, 1, opacityStroke / 255];
+
+ this._isErasing = true;
+ }
+ };
+
+ _main.default.RendererGL.prototype.noErase = function() {
+ if (this._isErasing) {
+ this.curFillColor = this._cachedFillStyle.slice();
+ this.curStrokeColor = this._cachedStrokeStyle.slice();
+
+ this.blendMode(this._cachedBlendMode);
+ this._isErasing = false;
+ }
+ };
+
+ /**
+ * Change weight of stroke
+ * @method strokeWeight
+ * @param {Number} stroke weight to be used for drawing
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(200, 400, WEBGL);
+ * setAttributes('antialias', true);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * translate(0, -100, 0);
+ * stroke(240, 150, 150);
+ * fill(100, 100, 240);
+ * push();
+ * strokeWeight(8);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * sphere(75);
+ * pop();
+ * push();
+ * translate(0, 200, 0);
+ * strokeWeight(1);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * sphere(75);
+ * pop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * black canvas with two purple rotating spheres with pink
+ * outlines the sphere on top has much heavier outlines,
+ *
+ */
+ _main.default.RendererGL.prototype.strokeWeight = function(w) {
+ if (this.curStrokeWeight !== w) {
+ this.pointSize = w;
+ this.curStrokeWeight = w;
+ }
+ };
+
+ // x,y are canvas-relative (pre-scaled by _pixelDensity)
+ _main.default.RendererGL.prototype._getPixel = function(x, y) {
+ var imageData, index;
+ imageData = new Uint8Array(4);
+ // prettier-ignore
+ this.drawingContext.readPixels(
+ x, y, 1, 1,
+ this.drawingContext.RGBA, this.drawingContext.UNSIGNED_BYTE,
+ imageData);
+
+ index = 0;
+ return [
+ imageData[index + 0],
+ imageData[index + 1],
+ imageData[index + 2],
+ imageData[index + 3]
+ ];
+ };
+
+ /**
+ * Loads the pixels data for this canvas into the pixels[] attribute.
+ * Note that updatePixels() and set() do not work.
+ * Any pixel manipulation must be done directly to the pixels[] array.
+ *
+ * @private
+ * @method loadPixels
+ *
+ */
+
+ _main.default.RendererGL.prototype.loadPixels = function() {
+ var pixelsState = this._pixelsState;
+
+ //@todo_FES
+ if (this._pInst._glAttributes.preserveDrawingBuffer !== true) {
+ console.log(
+ 'loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.'
+ );
+
+ return;
+ }
+
+ //if there isn't a renderer-level temporary pixels buffer
+ //make a new one
+ var pixels = pixelsState.pixels;
+ var len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4;
+ if (!(pixels instanceof Uint8Array) || pixels.length !== len) {
+ pixels = new Uint8Array(len);
+ this._pixelsState._setProperty('pixels', pixels);
+ }
+
+ var pd = this._pInst._pixelDensity;
+ // prettier-ignore
+ this.GL.readPixels(
+ 0, 0, this.width * pd, this.height * pd,
+ this.GL.RGBA, this.GL.UNSIGNED_BYTE,
+ pixels);
+ };
+
+ //////////////////////////////////////////////
+ // HASH | for geometry
+ //////////////////////////////////////////////
+
+ _main.default.RendererGL.prototype.geometryInHash = function(gId) {
+ return this.gHash[gId] !== undefined;
+ };
+
+ /**
+ * [resize description]
+ * @private
+ * @param {Number} w [description]
+ * @param {Number} h [description]
+ */
+ _main.default.RendererGL.prototype.resize = function(w, h) {
+ _main.default.Renderer.prototype.resize.call(this, w, h);
+ this.GL.viewport(0, 0, this.GL.drawingBufferWidth, this.GL.drawingBufferHeight);
+
+ this._viewport = this.GL.getParameter(this.GL.VIEWPORT);
+
+ this._curCamera._resize();
+
+ //resize pixels buffer
+ var pixelsState = this._pixelsState;
+ if (typeof pixelsState.pixels !== 'undefined') {
+ pixelsState._setProperty(
+ 'pixels',
+ new Uint8Array(this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4)
+ );
+ }
+ };
+
+ /**
+ * clears color and depth buffers
+ * with r,g,b,a
+ * @private
+ * @param {Number} r normalized red val.
+ * @param {Number} g normalized green val.
+ * @param {Number} b normalized blue val.
+ * @param {Number} a normalized alpha val.
+ */
+ _main.default.RendererGL.prototype.clear = function() {
+ var _r = (arguments.length <= 0 ? undefined : arguments[0]) || 0;
+ var _g = (arguments.length <= 1 ? undefined : arguments[1]) || 0;
+ var _b = (arguments.length <= 2 ? undefined : arguments[2]) || 0;
+ var _a = (arguments.length <= 3 ? undefined : arguments[3]) || 0;
+ this.GL.clearColor(_r, _g, _b, _a);
+ this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT);
+ };
+
+ _main.default.RendererGL.prototype.applyMatrix = function(a, b, c, d, e, f) {
+ if (arguments.length === 16) {
+ _main.default.Matrix.prototype.apply.apply(this.uMVMatrix, arguments);
+ } else {
+ // prettier-ignore
+ this.uMVMatrix.apply([
+ a, b, 0, 0,
+ c, d, 0, 0,
+ 0, 0, 1, 0,
+ e, f, 0, 1]);
+ }
+ };
+
+ /**
+ * [translate description]
+ * @private
+ * @param {Number} x [description]
+ * @param {Number} y [description]
+ * @param {Number} z [description]
+ * @chainable
+ * @todo implement handle for components or vector as args
+ */
+ _main.default.RendererGL.prototype.translate = function(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ z = x.z;
+ y = x.y;
+ x = x.x;
+ }
+ this.uMVMatrix.translate([x, y, z]);
+ return this;
+ };
+
+ /**
+ * Scales the Model View Matrix by a vector
+ * @private
+ * @param {Number | p5.Vector | Array} x [description]
+ * @param {Number} [y] y-axis scalar
+ * @param {Number} [z] z-axis scalar
+ * @chainable
+ */
+ _main.default.RendererGL.prototype.scale = function(x, y, z) {
+ this.uMVMatrix.scale(x, y, z);
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.rotate = function(rad, axis) {
+ if (typeof axis === 'undefined') {
+ return this.rotateZ(rad);
+ }
+ _main.default.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments);
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.rotateX = function(rad) {
+ this.rotate(rad, 1, 0, 0);
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.rotateY = function(rad) {
+ this.rotate(rad, 0, 1, 0);
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.rotateZ = function(rad) {
+ this.rotate(rad, 0, 0, 1);
+ return this;
+ };
+
+ _main.default.RendererGL.prototype.push = function() {
+ // get the base renderer style
+ var style = _main.default.Renderer.prototype.push.apply(this);
+
+ // add webgl-specific style properties
+ var properties = style.properties;
+
+ properties.uMVMatrix = this.uMVMatrix.copy();
+ properties.uPMatrix = this.uPMatrix.copy();
+ properties._curCamera = this._curCamera;
+
+ // make a copy of the current camera for the push state
+ // this preserves any references stored using 'createCamera'
+ this._curCamera = this._curCamera.copy();
+
+ properties.ambientLightColors = this.ambientLightColors.slice();
+ properties.specularColors = this.specularColors.slice();
+
+ properties.directionalLightDirections = this.directionalLightDirections.slice();
+ properties.directionalLightDiffuseColors = this.directionalLightDiffuseColors.slice();
+ properties.directionalLightSpecularColors = this.directionalLightSpecularColors.slice();
+
+ properties.pointLightPositions = this.pointLightPositions.slice();
+ properties.pointLightDiffuseColors = this.pointLightDiffuseColors.slice();
+ properties.pointLightSpecularColors = this.pointLightSpecularColors.slice();
+
+ properties.spotLightPositions = this.spotLightPositions.slice();
+ properties.spotLightDirections = this.spotLightDirections.slice();
+ properties.spotLightDiffuseColors = this.spotLightDiffuseColors.slice();
+ properties.spotLightSpecularColors = this.spotLightSpecularColors.slice();
+ properties.spotLightAngle = this.spotLightAngle.slice();
+ properties.spotLightConc = this.spotLightConc.slice();
+
+ properties.userFillShader = this.userFillShader;
+ properties.userStrokeShader = this.userStrokeShader;
+ properties.userPointShader = this.userPointShader;
+
+ properties.pointSize = this.pointSize;
+ properties.curStrokeWeight = this.curStrokeWeight;
+ properties.curStrokeColor = this.curStrokeColor;
+ properties.curFillColor = this.curFillColor;
+
+ properties._useSpecularMaterial = this._useSpecularMaterial;
+ properties._useEmissiveMaterial = this._useEmissiveMaterial;
+ properties._useShininess = this._useShininess;
+
+ properties.constantAttenuation = this.constantAttenuation;
+ properties.linearAttenuation = this.linearAttenuation;
+ properties.quadraticAttenuation = this.quadraticAttenuation;
+
+ properties._enableLighting = this._enableLighting;
+ properties._useNormalMaterial = this._useNormalMaterial;
+ properties._tex = this._tex;
+ properties.drawMode = this.drawMode;
+
+ return style;
+ };
+
+ _main.default.RendererGL.prototype.resetMatrix = function() {
+ this.uMVMatrix = _main.default.Matrix.identity(this._pInst);
+ return this;
+ };
+
+ //////////////////////////////////////////////
+ // SHADER
+ //////////////////////////////////////////////
+
+ /*
+ * shaders are created and cached on a per-renderer basis,
+ * on the grounds that each renderer will have its own gl context
+ * and the shader must be valid in that context.
+ */
+
+ _main.default.RendererGL.prototype._getImmediateStrokeShader = function() {
+ // select the stroke shader to use
+ var stroke = this.userStrokeShader;
+ if (!stroke || !stroke.isStrokeShader()) {
+ return this._getLineShader();
+ }
+ return stroke;
+ };
+
+ _main.default.RendererGL.prototype._getRetainedStrokeShader =
+ _main.default.RendererGL.prototype._getImmediateStrokeShader;
+
+ /*
+ * selects which fill shader should be used based on renderer state,
+ * for use with begin/endShape and immediate vertex mode.
+ */
+ _main.default.RendererGL.prototype._getImmediateFillShader = function() {
+ if (this._useNormalMaterial) {
+ console.log(
+ 'Sorry, normalMaterial() does not currently work with custom WebGL geometry' +
+ ' created with beginShape(). Falling back to standard fill material.'
+ );
+
+ return this._getImmediateModeShader();
+ }
+
+ var fill = this.userFillShader;
+ if (this._enableLighting) {
+ if (!fill || !fill.isLightShader()) {
+ return this._getLightShader();
+ }
+ } else if (this._tex) {
+ if (!fill || !fill.isTextureShader()) {
+ return this._getLightShader();
+ }
+ } else if (!fill /*|| !fill.isColorShader()*/) {
+ return this._getImmediateModeShader();
+ }
+ return fill;
+ };
+
+ /*
+ * selects which fill shader should be used based on renderer state
+ * for retained mode.
+ */
+ _main.default.RendererGL.prototype._getRetainedFillShader = function() {
+ if (this._useNormalMaterial) {
+ return this._getNormalShader();
+ }
+
+ var fill = this.userFillShader;
+ if (this._enableLighting) {
+ if (!fill || !fill.isLightShader()) {
+ return this._getLightShader();
+ }
+ } else if (this._tex) {
+ if (!fill || !fill.isTextureShader()) {
+ return this._getLightShader();
+ }
+ } else if (!fill /* || !fill.isColorShader()*/) {
+ return this._getColorShader();
+ }
+ return fill;
+ };
+
+ _main.default.RendererGL.prototype._getImmediatePointShader = function() {
+ // select the point shader to use
+ var point = this.userPointShader;
+ if (!point || !point.isPointShader()) {
+ return this._getPointShader();
+ }
+ return point;
+ };
+
+ _main.default.RendererGL.prototype._getRetainedLineShader =
+ _main.default.RendererGL.prototype._getImmediateLineShader;
+
+ _main.default.RendererGL.prototype._getLightShader = function() {
+ if (!this._defaultLightShader) {
+ if (this._pInst._glAttributes.perPixelLighting) {
+ this._defaultLightShader = new _main.default.Shader(
+ this,
+ defaultShaders.phongVert,
+ defaultShaders.phongFrag
+ );
+ } else {
+ this._defaultLightShader = new _main.default.Shader(
+ this,
+ defaultShaders.lightVert,
+ defaultShaders.lightTextureFrag
+ );
+ }
+ }
+
+ return this._defaultLightShader;
+ };
+
+ _main.default.RendererGL.prototype._getImmediateModeShader = function() {
+ if (!this._defaultImmediateModeShader) {
+ this._defaultImmediateModeShader = new _main.default.Shader(
+ this,
+ defaultShaders.immediateVert,
+ defaultShaders.vertexColorFrag
+ );
+ }
+
+ return this._defaultImmediateModeShader;
+ };
+
+ _main.default.RendererGL.prototype._getNormalShader = function() {
+ if (!this._defaultNormalShader) {
+ this._defaultNormalShader = new _main.default.Shader(
+ this,
+ defaultShaders.normalVert,
+ defaultShaders.normalFrag
+ );
+ }
+
+ return this._defaultNormalShader;
+ };
+
+ _main.default.RendererGL.prototype._getColorShader = function() {
+ if (!this._defaultColorShader) {
+ this._defaultColorShader = new _main.default.Shader(
+ this,
+ defaultShaders.normalVert,
+ defaultShaders.basicFrag
+ );
+ }
+
+ return this._defaultColorShader;
+ };
+
+ _main.default.RendererGL.prototype._getPointShader = function() {
+ if (!this._defaultPointShader) {
+ this._defaultPointShader = new _main.default.Shader(
+ this,
+ defaultShaders.pointVert,
+ defaultShaders.pointFrag
+ );
+ }
+ return this._defaultPointShader;
+ };
+
+ _main.default.RendererGL.prototype._getLineShader = function() {
+ if (!this._defaultLineShader) {
+ this._defaultLineShader = new _main.default.Shader(
+ this,
+ defaultShaders.lineVert,
+ defaultShaders.lineFrag
+ );
+ }
+
+ return this._defaultLineShader;
+ };
+
+ _main.default.RendererGL.prototype._getFontShader = function() {
+ if (!this._defaultFontShader) {
+ this.GL.getExtension('OES_standard_derivatives');
+ this._defaultFontShader = new _main.default.Shader(
+ this,
+ defaultShaders.fontVert,
+ defaultShaders.fontFrag
+ );
+ }
+ return this._defaultFontShader;
+ };
+
+ _main.default.RendererGL.prototype._getEmptyTexture = function() {
+ if (!this._emptyTexture) {
+ // a plain white texture RGBA, full alpha, single pixel.
+ var im = new _main.default.Image(1, 1);
+ im.set(0, 0, 255);
+ this._emptyTexture = new _main.default.Texture(this, im);
+ }
+ return this._emptyTexture;
+ };
+
+ _main.default.RendererGL.prototype.getTexture = function(img) {
+ var textures = this.textures;
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (
+ var _iterator = textures[Symbol.iterator](), _step;
+ !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
+ _iteratorNormalCompletion = true
+ ) {
+ var texture = _step.value;
+ if (texture.src === img) return texture;
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ var tex = new _main.default.Texture(this, img);
+ textures.push(tex);
+ return tex;
+ };
+
+ _main.default.RendererGL.prototype._setStrokeUniforms = function(strokeShader) {
+ strokeShader.bindShader();
+
+ // set the uniform values
+ strokeShader.setUniform('uMaterialColor', this.curStrokeColor);
+ strokeShader.setUniform('uStrokeWeight', this.curStrokeWeight);
+ };
+
+ _main.default.RendererGL.prototype._setFillUniforms = function(fillShader) {
+ fillShader.bindShader();
+
+ // TODO: optimize
+ fillShader.setUniform('uMaterialColor', this.curFillColor);
+ fillShader.setUniform('isTexture', !!this._tex);
+ if (this._tex) {
+ fillShader.setUniform('uSampler', this._tex);
+ }
+ fillShader.setUniform('uTint', this._tint);
+
+ fillShader.setUniform('uSpecular', this._useSpecularMaterial);
+ fillShader.setUniform('uEmissive', this._useEmissiveMaterial);
+ fillShader.setUniform('uShininess', this._useShininess);
+
+ fillShader.setUniform('uUseLighting', this._enableLighting);
+
+ var pointLightCount = this.pointLightDiffuseColors.length / 3;
+ fillShader.setUniform('uPointLightCount', pointLightCount);
+ fillShader.setUniform('uPointLightLocation', this.pointLightPositions);
+ fillShader.setUniform('uPointLightDiffuseColors', this.pointLightDiffuseColors);
+
+ fillShader.setUniform(
+ 'uPointLightSpecularColors',
+ this.pointLightSpecularColors
+ );
+
+ var directionalLightCount = this.directionalLightDiffuseColors.length / 3;
+ fillShader.setUniform('uDirectionalLightCount', directionalLightCount);
+ fillShader.setUniform('uLightingDirection', this.directionalLightDirections);
+ fillShader.setUniform(
+ 'uDirectionalDiffuseColors',
+ this.directionalLightDiffuseColors
+ );
+
+ fillShader.setUniform(
+ 'uDirectionalSpecularColors',
+ this.directionalLightSpecularColors
+ );
+
+ // TODO: sum these here...
+ var ambientLightCount = this.ambientLightColors.length / 3;
+ fillShader.setUniform('uAmbientLightCount', ambientLightCount);
+ fillShader.setUniform('uAmbientColor', this.ambientLightColors);
+
+ var spotLightCount = this.spotLightDiffuseColors.length / 3;
+ fillShader.setUniform('uSpotLightCount', spotLightCount);
+ fillShader.setUniform('uSpotLightAngle', this.spotLightAngle);
+ fillShader.setUniform('uSpotLightConc', this.spotLightConc);
+ fillShader.setUniform('uSpotLightDiffuseColors', this.spotLightDiffuseColors);
+ fillShader.setUniform('uSpotLightSpecularColors', this.spotLightSpecularColors);
+
+ fillShader.setUniform('uSpotLightLocation', this.spotLightPositions);
+ fillShader.setUniform('uSpotLightDirection', this.spotLightDirections);
+
+ fillShader.setUniform('uConstantAttenuation', this.constantAttenuation);
+ fillShader.setUniform('uLinearAttenuation', this.linearAttenuation);
+ fillShader.setUniform('uQuadraticAttenuation', this.quadraticAttenuation);
+
+ fillShader.bindTextures();
+ };
+
+ _main.default.RendererGL.prototype._setPointUniforms = function(pointShader) {
+ pointShader.bindShader();
+
+ // set the uniform values
+ pointShader.setUniform('uMaterialColor', this.curStrokeColor);
+ // @todo is there an instance where this isn't stroke weight?
+ // should be they be same var?
+ pointShader.setUniform('uPointSize', this.pointSize);
+ };
+
+ /* Binds a buffer to the drawing context
+ * when passed more than two arguments it also updates or initializes
+ * the data associated with the buffer
+ */
+ _main.default.RendererGL.prototype._bindBuffer = function(
+ buffer,
+ target,
+ values,
+ type,
+ usage
+ ) {
+ if (!target) target = this.GL.ARRAY_BUFFER;
+ this.GL.bindBuffer(target, buffer);
+ if (values !== undefined) {
+ var data = new (type || Float32Array)(values);
+ this.GL.bufferData(target, data, usage || this.GL.STATIC_DRAW);
+ }
+ };
+
+ ///////////////////////////////
+ //// UTILITY FUNCTIONS
+ //////////////////////////////
+ /**
+ * turn a two dimensional array into one dimensional array
+ * @private
+ * @param {Array} arr 2-dimensional array
+ * @return {Array} 1-dimensional array
+ * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6]
+ */
+ _main.default.RendererGL.prototype._flatten = function(arr) {
+ //when empty, return empty
+ if (arr.length === 0) {
+ return [];
+ } else if (arr.length > 20000) {
+ //big models , load slower to avoid stack overflow
+ //faster non-recursive flatten via axelduch
+ //stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript
+ var _toString = Object.prototype.toString;
+ var arrayTypeStr = '[object Array]';
+ var result = [];
+ var nodes = arr.slice();
+ var node;
+ node = nodes.pop();
+ do {
+ if (_toString.call(node) === arrayTypeStr) {
+ nodes.push.apply(nodes, _toConsumableArray(node));
+ } else {
+ result.push(node);
+ }
+ } while (nodes.length && (node = nodes.pop()) !== undefined);
+ result.reverse(); // we reverse result to restore the original order
+ return result;
+ } else {
+ var _ref;
+ //otherwise if model within limits for browser
+ //use faster recursive loading
+ return (_ref = []).concat.apply(_ref, _toConsumableArray(arr));
+ }
+ };
+
+ /**
+ * turn a p5.Vector Array into a one dimensional number array
+ * @private
+ * @param {p5.Vector[]} arr an array of p5.Vector
+ * @return {Number[]} a one dimensional array of numbers
+ * [p5.Vector(1, 2, 3), p5.Vector(4, 5, 6)] ->
+ * [1, 2, 3, 4, 5, 6]
+ */
+ _main.default.RendererGL.prototype._vToNArray = function(arr) {
+ var ret = [];
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (
+ var _iterator2 = arr[Symbol.iterator](), _step2;
+ !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
+ _iteratorNormalCompletion2 = true
+ ) {
+ var item = _step2.value;
+ ret.push(item.x, item.y, item.z);
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+
+ return ret;
+ };
+
+ /**
+ * ensures that p5 is using a 3d renderer. throws an error if not.
+ */
+ _main.default.prototype._assert3d = function(name) {
+ if (!this._renderer.isP3D)
+ throw new Error(
+ ''.concat(
+ name,
+ "() is only supported in WEBGL mode. If you'd like to use 3D graphics and WebGL, see https://p5js.org/examples/form-3d-primitives.html for more information."
+ )
+ );
+ };
+
+ // function to initialize GLU Tesselator
+
+ _main.default.RendererGL.prototype._initTessy = function initTesselator() {
+ // function called for each vertex of tesselator output
+ function vertexCallback(data, polyVertArray) {
+ polyVertArray[polyVertArray.length] = data[0];
+ polyVertArray[polyVertArray.length] = data[1];
+ polyVertArray[polyVertArray.length] = data[2];
+ }
+
+ function begincallback(type) {
+ if (type !== _libtess.default.primitiveType.GL_TRIANGLES) {
+ console.log('expected TRIANGLES but got type: '.concat(type));
+ }
+ }
+
+ function errorcallback(errno) {
+ console.log('error callback');
+ console.log('error number: '.concat(errno));
+ }
+ // callback for when segments intersect and must be split
+ function combinecallback(coords, data, weight) {
+ return [coords[0], coords[1], coords[2]];
+ }
+
+ function edgeCallback(flag) {
+ // don't really care about the flag, but need no-strip/no-fan behavior
+ }
+
+ var tessy = new _libtess.default.GluTesselator();
+ tessy.gluTessCallback(
+ _libtess.default.gluEnum.GLU_TESS_VERTEX_DATA,
+ vertexCallback
+ );
+ tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_BEGIN, begincallback);
+ tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_ERROR, errorcallback);
+ tessy.gluTessCallback(
+ _libtess.default.gluEnum.GLU_TESS_COMBINE,
+ combinecallback
+ );
+ tessy.gluTessCallback(
+ _libtess.default.gluEnum.GLU_TESS_EDGE_FLAG,
+ edgeCallback
+ );
+
+ return tessy;
+ };
+
+ _main.default.RendererGL.prototype._triangulate = function(contours) {
+ // libtess will take 3d verts and flatten to a plane for tesselation
+ // since only doing 2d tesselation here, provide z=1 normal to skip
+ // iterating over verts only to get the same answer.
+ // comment out to test normal-generation code
+ this._tessy.gluTessNormal(0, 0, 1);
+
+ var triangleVerts = [];
+ this._tessy.gluTessBeginPolygon(triangleVerts);
+
+ for (var i = 0; i < contours.length; i++) {
+ this._tessy.gluTessBeginContour();
+ var contour = contours[i];
+ for (var j = 0; j < contour.length; j += 3) {
+ var coords = [contour[j], contour[j + 1], contour[j + 2]];
+ this._tessy.gluTessVertex(coords, coords);
+ }
+ this._tessy.gluTessEndContour();
+ }
+
+ // finish polygon
+ this._tessy.gluTessEndPolygon();
+
+ return triangleVerts;
+ };
+
+ // function to calculate BezierVertex Coefficients
+ _main.default.RendererGL.prototype._bezierCoefficients = function(t) {
+ var t2 = t * t;
+ var t3 = t2 * t;
+ var mt = 1 - t;
+ var mt2 = mt * mt;
+ var mt3 = mt2 * mt;
+ return [mt3, 3 * mt2 * t, 3 * mt * t2, t3];
+ };
+
+ // function to calculate QuadraticVertex Coefficients
+ _main.default.RendererGL.prototype._quadraticCoefficients = function(t) {
+ var t2 = t * t;
+ var mt = 1 - t;
+ var mt2 = mt * mt;
+ return [mt2, 2 * mt * t, t2];
+ };
+
+ // function to convert Bezier coordinates to Catmull Rom Splines
+ _main.default.RendererGL.prototype._bezierToCatmull = function(w) {
+ var p1 = w[1];
+ var p2 = w[1] + (w[2] - w[0]) / this._curveTightness;
+ var p3 = w[2] - (w[3] - w[1]) / this._curveTightness;
+ var p4 = w[2];
+ var p = [p1, p2, p3, p4];
+ return p;
+ };
+ var _default = _main.default.RendererGL;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 21,
+ '../core/main': 27,
+ '../core/p5.Renderer': 30,
+ './p5.Camera': 75,
+ './p5.Matrix': 77,
+ './p5.Shader': 81,
+ libtess: 10,
+ path: 13
+ }
+ ],
+ 81: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * This module defines the p5.Shader class
+ * @module Lights, Camera
+ * @submodule Material
+ * @for p5
+ * @requires core
+ */ /**
+ * Shader class for WEBGL Mode
+ * @class p5.Shader
+ * @param {p5.RendererGL} renderer an instance of p5.RendererGL that
+ * will provide the GL context for this new p5.Shader
+ * @param {String} vertSrc source code for the vertex shader (as a string)
+ * @param {String} fragSrc source code for the fragment shader (as a string)
+ */ _main.default.Shader = function(renderer, vertSrc, fragSrc) {
+ // TODO: adapt this to not take ids, but rather,
+ // to take the source for a vertex and fragment shader
+ // to enable custom shaders at some later date
+ this._renderer = renderer;
+ this._vertSrc = vertSrc;
+ this._fragSrc = fragSrc;
+ this._vertShader = -1;
+ this._fragShader = -1;
+ this._glProgram = 0;
+ this._loadedAttributes = false;
+ this.attributes = {};
+ this._loadedUniforms = false;
+ this.uniforms = {};
+ this._bound = false;
+ this.samplers = [];
+ };
+
+ /**
+ * Creates, compiles, and links the shader based on its
+ * sources for the vertex and fragment shaders (provided
+ * to the constructor). Populates known attributes and
+ * uniforms from the shader.
+ * @method init
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.init = function() {
+ if (this._glProgram === 0 /* or context is stale? */) {
+ var gl = this._renderer.GL;
+
+ // @todo: once custom shading is allowed,
+ // friendly error messages should be used here to share
+ // compiler and linker errors.
+
+ //set up the shader by
+ // 1. creating and getting a gl id for the shader program,
+ // 2. compliling its vertex & fragment sources,
+ // 3. linking the vertex and fragment shaders
+ this._vertShader = gl.createShader(gl.VERTEX_SHADER);
+ //load in our default vertex shader
+ gl.shaderSource(this._vertShader, this._vertSrc);
+ gl.compileShader(this._vertShader);
+ // if our vertex shader failed compilation?
+ if (!gl.getShaderParameter(this._vertShader, gl.COMPILE_STATUS)) {
+ console.error(
+ 'Yikes! An error occurred compiling the vertex shader:'.concat(
+ gl.getShaderInfoLog(this._vertShader)
+ )
+ );
+
+ return null;
+ }
+
+ this._fragShader = gl.createShader(gl.FRAGMENT_SHADER);
+ //load in our material frag shader
+ gl.shaderSource(this._fragShader, this._fragSrc);
+ gl.compileShader(this._fragShader);
+ // if our frag shader failed compilation?
+ if (!gl.getShaderParameter(this._fragShader, gl.COMPILE_STATUS)) {
+ console.error(
+ 'Darn! An error occurred compiling the fragment shader:'.concat(
+ gl.getShaderInfoLog(this._fragShader)
+ )
+ );
+
+ return null;
+ }
+
+ this._glProgram = gl.createProgram();
+ gl.attachShader(this._glProgram, this._vertShader);
+ gl.attachShader(this._glProgram, this._fragShader);
+ gl.linkProgram(this._glProgram);
+ if (!gl.getProgramParameter(this._glProgram, gl.LINK_STATUS)) {
+ console.error(
+ 'Snap! Error linking shader program: '.concat(
+ gl.getProgramInfoLog(this._glProgram)
+ )
+ );
+ }
+
+ this._loadAttributes();
+ this._loadUniforms();
+ }
+ return this;
+ };
+
+ /**
+ * Queries the active attributes for this shader and loads
+ * their names and locations into the attributes array.
+ * @method _loadAttributes
+ * @private
+ */
+ _main.default.Shader.prototype._loadAttributes = function() {
+ if (this._loadedAttributes) {
+ return;
+ }
+
+ this.attributes = {};
+
+ var gl = this._renderer.GL;
+
+ var numAttributes = gl.getProgramParameter(
+ this._glProgram,
+ gl.ACTIVE_ATTRIBUTES
+ );
+
+ for (var i = 0; i < numAttributes; ++i) {
+ var attributeInfo = gl.getActiveAttrib(this._glProgram, i);
+ var name = attributeInfo.name;
+ var location = gl.getAttribLocation(this._glProgram, name);
+ var attribute = {};
+ attribute.name = name;
+ attribute.location = location;
+ attribute.index = i;
+ attribute.type = attributeInfo.type;
+ attribute.size = attributeInfo.size;
+ this.attributes[name] = attribute;
+ }
+
+ this._loadedAttributes = true;
+ };
+
+ /**
+ * Queries the active uniforms for this shader and loads
+ * their names and locations into the uniforms array.
+ * @method _loadUniforms
+ * @private
+ */
+ _main.default.Shader.prototype._loadUniforms = function() {
+ if (this._loadedUniforms) {
+ return;
+ }
+
+ var gl = this._renderer.GL;
+
+ // Inspect shader and cache uniform info
+ var numUniforms = gl.getProgramParameter(this._glProgram, gl.ACTIVE_UNIFORMS);
+
+ var samplerIndex = 0;
+ for (var i = 0; i < numUniforms; ++i) {
+ var uniformInfo = gl.getActiveUniform(this._glProgram, i);
+ var uniform = {};
+ uniform.location = gl.getUniformLocation(this._glProgram, uniformInfo.name);
+ uniform.size = uniformInfo.size;
+ var uniformName = uniformInfo.name;
+ //uniforms thats are arrays have their name returned as
+ //someUniform[0] which is a bit silly so we trim it
+ //off here. The size property tells us that its an array
+ //so we dont lose any information by doing this
+ if (uniformInfo.size > 1) {
+ uniformName = uniformName.substring(0, uniformName.indexOf('[0]'));
+ }
+ uniform.name = uniformName;
+ uniform.type = uniformInfo.type;
+ if (uniform.type === gl.SAMPLER_2D) {
+ uniform.samplerIndex = samplerIndex;
+ samplerIndex++;
+ this.samplers.push(uniform);
+ }
+ this.uniforms[uniformName] = uniform;
+ }
+ this._loadedUniforms = true;
+ };
+
+ _main.default.Shader.prototype.compile = function() {
+ // TODO
+ };
+
+ /**
+ * initializes (if needed) and binds the shader program.
+ * @method bindShader
+ * @private
+ */
+ _main.default.Shader.prototype.bindShader = function() {
+ this.init();
+ if (!this._bound) {
+ this.useProgram();
+ this._bound = true;
+
+ this._setMatrixUniforms();
+
+ this.setUniform('uViewport', this._renderer._viewport);
+ }
+ };
+
+ /**
+ * @method unbindShader
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.unbindShader = function() {
+ if (this._bound) {
+ this.unbindTextures();
+ //this._renderer.GL.useProgram(0); ??
+ this._bound = false;
+ }
+ return this;
+ };
+
+ _main.default.Shader.prototype.bindTextures = function() {
+ var gl = this._renderer.GL;
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (
+ var _iterator = this.samplers[Symbol.iterator](), _step;
+ !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
+ _iteratorNormalCompletion = true
+ ) {
+ var uniform = _step.value;
+ var tex = uniform.texture;
+ if (tex === undefined) {
+ // user hasn't yet supplied a texture for this slot.
+ // (or there may not be one--maybe just lighting),
+ // so we supply a default texture instead.
+ tex = this._renderer._getEmptyTexture();
+ }
+ gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex);
+ tex.bindTexture();
+ tex.update();
+ gl.uniform1i(uniform.location, uniform.samplerIndex);
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ };
+
+ _main.default.Shader.prototype.updateTextures = function() {
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (
+ var _iterator2 = this.samplers[Symbol.iterator](), _step2;
+ !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
+ _iteratorNormalCompletion2 = true
+ ) {
+ var uniform = _step2.value;
+ var tex = uniform.texture;
+ if (tex) {
+ tex.update();
+ }
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ };
+
+ _main.default.Shader.prototype.unbindTextures = function() {
+ // TODO: migrate stuff from material.js here
+ // - OR - have material.js define this function
+ };
+
+ _main.default.Shader.prototype._setMatrixUniforms = function() {
+ this.setUniform('uProjectionMatrix', this._renderer.uPMatrix.mat4);
+ if (this.isStrokeShader()) {
+ if (this._renderer._curCamera.cameraType === 'default') {
+ // strokes scale up as they approach camera, default
+ this.setUniform('uPerspective', 1);
+ } else {
+ // strokes have uniform scale regardless of distance from camera
+ this.setUniform('uPerspective', 0);
+ }
+ }
+ this.setUniform('uModelViewMatrix', this._renderer.uMVMatrix.mat4);
+ this.setUniform('uViewMatrix', this._renderer._curCamera.cameraMatrix.mat4);
+ if (this.uniforms.uNormalMatrix) {
+ this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix);
+ this.setUniform('uNormalMatrix', this._renderer.uNMatrix.mat3);
+ }
+ };
+
+ /**
+ * @method useProgram
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.useProgram = function() {
+ var gl = this._renderer.GL;
+ gl.useProgram(this._glProgram);
+ return this;
+ };
+
+ /**
+ * Wrapper around gl.uniform functions.
+ * As we store uniform info in the shader we can use that
+ * to do type checking on the supplied data and call
+ * the appropriate function.
+ * @method setUniform
+ * @chainable
+ * @param {String} uniformName the name of the uniform in the
+ * shader program
+ * @param {Object|Number|Boolean|Number[]} data the data to be associated
+ * with that uniform; type varies (could be a single numerical value, array,
+ * matrix, or texture / sampler reference)
+ *
+ * @example
+ *
+ *
+ * // Click within the image to toggle the value of uniforms
+ * // Note: for an alternative approach to the same example,
+ * // involving toggling between shaders please refer to:
+ * // https://p5js.org/reference/#/p5/shader
+ *
+ * let grad;
+ * let showRedGreen = false;
+ *
+ * function preload() {
+ * // note that we are using two instances
+ * // of the same vertex and fragment shaders
+ * grad = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * shader(grad);
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * // update the offset values for each scenario,
+ * // moving the "grad" shader in either vertical or
+ * // horizontal direction each with differing colors
+ *
+ * if (showRedGreen === true) {
+ * grad.setUniform('colorCenter', [1, 0, 0]);
+ * grad.setUniform('colorBackground', [0, 1, 0]);
+ * grad.setUniform('offset', [sin(millis() / 2000), 1]);
+ * } else {
+ * grad.setUniform('colorCenter', [1, 0.5, 0]);
+ * grad.setUniform('colorBackground', [0.226, 0, 0.615]);
+ * grad.setUniform('offset', [0, sin(millis() / 2000) + 1]);
+ * }
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ * function mouseClicked() {
+ * showRedGreen = !showRedGreen;
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.
+ */
+ _main.default.Shader.prototype.setUniform = function(uniformName, data) {
+ //@todo update all current gl.uniformXX calls
+
+ var uniform = this.uniforms[uniformName];
+ if (!uniform) {
+ return;
+ }
+
+ var location = uniform.location;
+
+ var gl = this._renderer.GL;
+ this.useProgram();
+
+ switch (uniform.type) {
+ case gl.BOOL:
+ if (data === true) {
+ gl.uniform1i(location, 1);
+ } else {
+ gl.uniform1i(location, 0);
+ }
+ break;
+ case gl.INT:
+ if (uniform.size > 1) {
+ data.length && gl.uniform1iv(location, data);
+ } else {
+ gl.uniform1i(location, data);
+ }
+ break;
+ case gl.FLOAT:
+ if (uniform.size > 1) {
+ data.length && gl.uniform1fv(location, data);
+ } else {
+ gl.uniform1f(location, data);
+ }
+ break;
+ case gl.FLOAT_MAT3:
+ gl.uniformMatrix3fv(location, false, data);
+ break;
+ case gl.FLOAT_MAT4:
+ gl.uniformMatrix4fv(location, false, data);
+ break;
+ case gl.FLOAT_VEC2:
+ if (uniform.size > 1) {
+ data.length && gl.uniform2fv(location, data);
+ } else {
+ gl.uniform2f(location, data[0], data[1]);
+ }
+ break;
+ case gl.FLOAT_VEC3:
+ if (uniform.size > 1) {
+ data.length && gl.uniform3fv(location, data);
+ } else {
+ gl.uniform3f(location, data[0], data[1], data[2]);
+ }
+ break;
+ case gl.FLOAT_VEC4:
+ if (uniform.size > 1) {
+ data.length && gl.uniform4fv(location, data);
+ } else {
+ gl.uniform4f(location, data[0], data[1], data[2], data[3]);
+ }
+ break;
+ case gl.INT_VEC2:
+ if (uniform.size > 1) {
+ data.length && gl.uniform2iv(location, data);
+ } else {
+ gl.uniform2i(location, data[0], data[1]);
+ }
+ break;
+ case gl.INT_VEC3:
+ if (uniform.size > 1) {
+ data.length && gl.uniform3iv(location, data);
+ } else {
+ gl.uniform3i(location, data[0], data[1], data[2]);
+ }
+ break;
+ case gl.INT_VEC4:
+ if (uniform.size > 1) {
+ data.length && gl.uniform4iv(location, data);
+ } else {
+ gl.uniform4i(location, data[0], data[1], data[2], data[3]);
+ }
+ break;
+ case gl.SAMPLER_2D:
+ gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex);
+ uniform.texture = this._renderer.getTexture(data);
+ gl.uniform1i(uniform.location, uniform.samplerIndex);
+ break;
+ //@todo complete all types
+ }
+ return this;
+ };
+
+ /* NONE OF THIS IS FAST OR EFFICIENT BUT BEAR WITH ME
+ *
+ * these shader "type" query methods are used by various
+ * facilities of the renderer to determine if changing
+ * the shader type for the required action (for example,
+ * do we need to load the default lighting shader if the
+ * current shader cannot handle lighting?)
+ *
+ **/
+
+ _main.default.Shader.prototype.isLightShader = function() {
+ return (
+ this.attributes.aNormal !== undefined ||
+ this.uniforms.uUseLighting !== undefined ||
+ this.uniforms.uAmbientLightCount !== undefined ||
+ this.uniforms.uDirectionalLightCount !== undefined ||
+ this.uniforms.uPointLightCount !== undefined ||
+ this.uniforms.uAmbientColor !== undefined ||
+ this.uniforms.uDirectionalDiffuseColors !== undefined ||
+ this.uniforms.uDirectionalSpecularColors !== undefined ||
+ this.uniforms.uPointLightLocation !== undefined ||
+ this.uniforms.uPointLightDiffuseColors !== undefined ||
+ this.uniforms.uPointLightSpecularColors !== undefined ||
+ this.uniforms.uLightingDirection !== undefined ||
+ this.uniforms.uSpecular !== undefined
+ );
+ };
+
+ _main.default.Shader.prototype.isTextureShader = function() {
+ return this.samplerIndex > 0;
+ };
+
+ _main.default.Shader.prototype.isColorShader = function() {
+ return (
+ this.attributes.aVertexColor !== undefined ||
+ this.uniforms.uMaterialColor !== undefined
+ );
+ };
+
+ _main.default.Shader.prototype.isTexLightShader = function() {
+ return this.isLightShader() && this.isTextureShader();
+ };
+
+ _main.default.Shader.prototype.isStrokeShader = function() {
+ return this.uniforms.uStrokeWeight !== undefined;
+ };
+
+ /**
+ * @method enableAttrib
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.enableAttrib = function(
+ attr,
+ size,
+ type,
+ normalized,
+ stride,
+ offset
+ ) {
+ if (attr) {
+ if (
+ typeof IS_MINIFIED === 'undefined' &&
+ this.attributes[attr.name] !== attr
+ ) {
+ console.warn(
+ 'The attribute "'.concat(
+ attr.name,
+ '"passed to enableAttrib does not belong to this shader.'
+ )
+ );
+ }
+ var loc = attr.location;
+ if (loc !== -1) {
+ var gl = this._renderer.GL;
+ gl.enableVertexAttribArray(loc);
+ gl.vertexAttribPointer(
+ loc,
+ size,
+ type || gl.FLOAT,
+ normalized || false,
+ stride || 0,
+ offset || 0
+ );
+ }
+ }
+ return this;
+ };
+ var _default = _main.default.Shader;
+ exports.default = _default;
+ },
+ { '../core/main': 27 }
+ ],
+ 82: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * This module defines the p5.Texture class
+ * @module Lights, Camera
+ * @submodule Material
+ * @for p5
+ * @requires core
+ */ /**
+ * Texture class for WEBGL Mode
+ * @private
+ * @class p5.Texture
+ * @param {p5.RendererGL} renderer an instance of p5.RendererGL that
+ * will provide the GL context for this new p5.Texture
+ * @param {p5.Image|p5.Graphics|p5.Element|p5.MediaElement|ImageData} [obj] the
+ * object containing the image data to store in the texture.
+ */ _main.default.Texture = function(renderer, obj) {
+ this._renderer = renderer;
+ var gl = this._renderer.GL;
+
+ this.src = obj;
+ this.glTex = undefined;
+ this.glTarget = gl.TEXTURE_2D;
+ this.glFormat = gl.RGBA;
+ this.mipmaps = false;
+ this.glMinFilter = gl.LINEAR;
+ this.glMagFilter = gl.LINEAR;
+ this.glWrapS = gl.CLAMP_TO_EDGE;
+ this.glWrapT = gl.CLAMP_TO_EDGE;
+
+ // used to determine if this texture might need constant updating
+ // because it is a video or gif.
+ this.isSrcMediaElement =
+ typeof _main.default.MediaElement !== 'undefined' &&
+ obj instanceof _main.default.MediaElement;
+ this._videoPrevUpdateTime = 0;
+ this.isSrcHTMLElement =
+ typeof _main.default.Element !== 'undefined' &&
+ obj instanceof _main.default.Element &&
+ !(obj instanceof _main.default.Graphics);
+ this.isSrcP5Image = obj instanceof _main.default.Image;
+ this.isSrcP5Graphics = obj instanceof _main.default.Graphics;
+ this.isImageData = typeof ImageData !== 'undefined' && obj instanceof ImageData;
+
+ var textureData = this._getTextureDataFromSource();
+ this.width = textureData.width;
+ this.height = textureData.height;
+
+ this.init(textureData);
+ return this;
+ };
+
+ _main.default.Texture.prototype._getTextureDataFromSource = function() {
+ var textureData;
+ if (this.isSrcP5Image) {
+ // param is a p5.Image
+ textureData = this.src.canvas;
+ } else if (
+ this.isSrcMediaElement ||
+ this.isSrcP5Graphics ||
+ this.isSrcHTMLElement
+ ) {
+ // if param is a video HTML element
+ textureData = this.src.elt;
+ } else if (this.isImageData) {
+ textureData = this.src;
+ }
+ return textureData;
+ };
+
+ /**
+ * Initializes common texture parameters, creates a gl texture,
+ * tries to upload the texture for the first time if data is
+ * already available.
+ * @private
+ * @method init
+ */
+ _main.default.Texture.prototype.init = function(data) {
+ var gl = this._renderer.GL;
+ this.glTex = gl.createTexture();
+
+ this.glWrapS = this._renderer.textureWrapX;
+ this.glWrapT = this._renderer.textureWrapY;
+
+ this.setWrapMode(this.glWrapS, this.glWrapT);
+ this.bindTexture();
+
+ //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter);
+
+ if (
+ this.width === 0 ||
+ this.height === 0 ||
+ (this.isSrcMediaElement && !this.src.loadedmetadata)
+ ) {
+ // assign a 1x1 empty texture initially, because data is not yet ready,
+ // so that no errors occur in gl console!
+ var tmpdata = new Uint8Array([1, 1, 1, 1]);
+ gl.texImage2D(
+ this.glTarget,
+ 0,
+ gl.RGBA,
+ 1,
+ 1,
+ 0,
+ this.glFormat,
+ gl.UNSIGNED_BYTE,
+ tmpdata
+ );
+ } else {
+ // data is ready: just push the texture!
+ gl.texImage2D(
+ this.glTarget,
+ 0,
+ this.glFormat,
+ this.glFormat,
+ gl.UNSIGNED_BYTE,
+ data
+ );
+ }
+ };
+
+ /**
+ * Checks if the source data for this texture has changed (if it's
+ * easy to do so) and reuploads the texture if necessary. If it's not
+ * possible or to expensive to do a calculation to determine wheter or
+ * not the data has occurred, this method simply re-uploads the texture.
+ * @method update
+ */
+ _main.default.Texture.prototype.update = function() {
+ var data = this.src;
+ if (data.width === 0 || data.height === 0) {
+ return false; // nothing to do!
+ }
+
+ var textureData = this._getTextureDataFromSource();
+ var updated = false;
+
+ var gl = this._renderer.GL;
+ // pull texture from data, make sure width & height are appropriate
+ if (textureData.width !== this.width || textureData.height !== this.height) {
+ updated = true;
+
+ // make sure that if the width and height of this.src have changed
+ // for some reason, we update our metadata and upload the texture again
+ this.width = textureData.width;
+ this.height = textureData.height;
+
+ if (this.isSrcP5Image) {
+ data.setModified(false);
+ } else if (this.isSrcMediaElement || this.isSrcHTMLElement) {
+ // on the first frame the metadata comes in, the size will be changed
+ // from 0 to actual size, but pixels may not be available.
+ // flag for update in a future frame.
+ // if we don't do this, a paused video, for example, may not
+ // send the first frame to texture memory.
+ data.setModified(true);
+ }
+ } else if (this.isSrcP5Image) {
+ // for an image, we only update if the modified field has been set,
+ // for example, by a call to p5.Image.set
+ if (data.isModified()) {
+ updated = true;
+ data.setModified(false);
+ }
+ } else if (this.isSrcMediaElement) {
+ // for a media element (video), we'll check if the current time in
+ // the video frame matches the last time. if it doesn't match, the
+ // video has advanced or otherwise been taken to a new frame,
+ // and we need to upload it.
+ if (data.isModified()) {
+ // p5.MediaElement may have also had set/updatePixels, etc. called
+ // on it and should be updated, or may have been set for the first
+ // time!
+ updated = true;
+ data.setModified(false);
+ } else if (data.loadedmetadata) {
+ // if the meta data has been loaded, we can ask the video
+ // what it's current position (in time) is.
+ if (this._videoPrevUpdateTime !== data.time()) {
+ // update the texture in gpu mem only if the current
+ // video timestamp does not match the timestamp of the last
+ // time we uploaded this texture (and update the time we
+ // last uploaded, too)
+ this._videoPrevUpdateTime = data.time();
+ updated = true;
+ }
+ }
+ } else if (this.isImageData) {
+ if (data._dirty) {
+ data._dirty = false;
+ updated = true;
+ }
+ } else {
+ /* data instanceof p5.Graphics, probably */
+ // there is not enough information to tell if the texture can be
+ // conditionally updated; so to be safe, we just go ahead and upload it.
+ updated = true;
+ }
+
+ if (updated) {
+ this.bindTexture();
+ gl.texImage2D(
+ this.glTarget,
+ 0,
+ this.glFormat,
+ this.glFormat,
+ gl.UNSIGNED_BYTE,
+ textureData
+ );
+ }
+
+ return updated;
+ };
+
+ /**
+ * Binds the texture to the appropriate GL target.
+ * @method bindTexture
+ */
+ _main.default.Texture.prototype.bindTexture = function() {
+ // bind texture using gl context + glTarget and
+ // generated gl texture object
+ var gl = this._renderer.GL;
+ gl.bindTexture(this.glTarget, this.glTex);
+
+ return this;
+ };
+
+ /**
+ * Unbinds the texture from the appropriate GL target.
+ * @method unbindTexture
+ */
+ _main.default.Texture.prototype.unbindTexture = function() {
+ // unbind per above, disable texturing on glTarget
+ var gl = this._renderer.GL;
+ gl.bindTexture(this.glTarget, null);
+ };
+
+ /**
+ * Sets how a texture is be interpolated when upscaled or downscaled.
+ * Nearest filtering uses nearest neighbor scaling when interpolating
+ * Linear filtering uses WebGL's linear scaling when interpolating
+ * @method setInterpolation
+ * @param {String} downScale Specifies the texture filtering when
+ * textures are shrunk. Options are LINEAR or NEAREST
+ * @param {String} upScale Specifies the texture filtering when
+ * textures are magnified. Options are LINEAR or NEAREST
+ * @todo implement mipmapping filters
+ */
+ _main.default.Texture.prototype.setInterpolation = function(downScale, upScale) {
+ var gl = this._renderer.GL;
+
+ if (downScale === constants.NEAREST) {
+ this.glMinFilter = gl.NEAREST;
+ } else {
+ this.glMinFilter = gl.LINEAR;
+ }
+
+ if (upScale === constants.NEAREST) {
+ this.glMagFilter = gl.NEAREST;
+ } else {
+ this.glMagFilter = gl.LINEAR;
+ }
+
+ this.bindTexture();
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter);
+ this.unbindTexture();
+ };
+
+ /**
+ * Sets the texture wrapping mode. This controls how textures behave
+ * when their uv's go outside of the 0 - 1 range. There are three options:
+ * CLAMP, REPEAT, and MIRROR. REPEAT & MIRROR are only available if the texture
+ * is a power of two size (128, 256, 512, 1024, etc.).
+ * @method setWrapMode
+ * @param {String} wrapX Controls the horizontal texture wrapping behavior
+ * @param {String} wrapY Controls the vertical texture wrapping behavior
+ */
+ _main.default.Texture.prototype.setWrapMode = function(wrapX, wrapY) {
+ var gl = this._renderer.GL;
+
+ // for webgl 1 we need to check if the texture is power of two
+ // if it isn't we will set the wrap mode to CLAMP
+ // webgl2 will support npot REPEAT and MIRROR but we don't check for it yet
+ var isPowerOfTwo = function isPowerOfTwo(x) {
+ return (x & (x - 1)) === 0;
+ };
+
+ var widthPowerOfTwo = isPowerOfTwo(this.width);
+ var heightPowerOfTwo = isPowerOfTwo(this.height);
+
+ if (wrapX === constants.REPEAT) {
+ if (widthPowerOfTwo && heightPowerOfTwo) {
+ this.glWrapS = gl.REPEAT;
+ } else {
+ console.warn(
+ 'You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'
+ );
+
+ this.glWrapS = gl.CLAMP_TO_EDGE;
+ }
+ } else if (wrapX === constants.MIRROR) {
+ if (widthPowerOfTwo && heightPowerOfTwo) {
+ this.glWrapS = gl.MIRRORED_REPEAT;
+ } else {
+ console.warn(
+ 'You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead'
+ );
+
+ this.glWrapS = gl.CLAMP_TO_EDGE;
+ }
+ } else {
+ // falling back to default if didn't get a proper mode
+ this.glWrapS = gl.CLAMP_TO_EDGE;
+ }
+
+ if (wrapY === constants.REPEAT) {
+ if (widthPowerOfTwo && heightPowerOfTwo) {
+ this.glWrapT = gl.REPEAT;
+ } else {
+ console.warn(
+ 'You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'
+ );
+
+ this.glWrapT = gl.CLAMP_TO_EDGE;
+ }
+ } else if (wrapY === constants.MIRROR) {
+ if (widthPowerOfTwo && heightPowerOfTwo) {
+ this.glWrapT = gl.MIRRORED_REPEAT;
+ } else {
+ console.warn(
+ 'You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead'
+ );
+
+ this.glWrapT = gl.CLAMP_TO_EDGE;
+ }
+ } else {
+ // falling back to default if didn't get a proper mode
+ this.glWrapT = gl.CLAMP_TO_EDGE;
+ }
+
+ this.bindTexture();
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.glWrapS);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.glWrapT);
+ this.unbindTexture();
+ };
+ var _default = _main.default.Texture;
+ exports.default = _default;
+ },
+ { '../core/constants': 21, '../core/main': 27 }
+ ],
+ 83: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ var constants = _interopRequireWildcard(_dereq_('../core/constants'));
+ _dereq_('./p5.Shader');
+ _dereq_('./p5.RendererGL.Retained');
+ function _interopRequireWildcard(obj) {
+ if (obj && obj.__esModule) {
+ return obj;
+ } else {
+ var newObj = {};
+ if (obj != null) {
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ var desc =
+ Object.defineProperty && Object.getOwnPropertyDescriptor
+ ? Object.getOwnPropertyDescriptor(obj, key)
+ : {};
+ if (desc.get || desc.set) {
+ Object.defineProperty(newObj, key, desc);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+ }
+ newObj.default = obj;
+ return newObj;
+ }
+ }
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+
+ // Text/Typography
+ // @TODO:
+ _main.default.RendererGL.prototype._applyTextProperties = function() {
+ //@TODO finish implementation
+ //console.error('text commands not yet implemented in webgl');
+ };
+
+ _main.default.RendererGL.prototype.textWidth = function(s) {
+ if (this._isOpenType()) {
+ return this._textFont._textWidth(s, this._textSize);
+ }
+
+ return 0; // TODO: error
+ };
+
+ // rendering constants
+
+ // the number of rows/columns dividing each glyph
+ var charGridWidth = 9;
+ var charGridHeight = charGridWidth;
+
+ // size of the image holding the bezier stroke info
+ var strokeImageWidth = 64;
+ var strokeImageHeight = 64;
+
+ // size of the image holding the stroke indices for each row/col
+ var gridImageWidth = 64;
+ var gridImageHeight = 64;
+
+ // size of the image holding the offset/length of each row/col stripe
+ var cellImageWidth = 64;
+ var cellImageHeight = 64;
+
+ /**
+ * @private
+ * @class ImageInfos
+ * @param {Integer} width
+ * @param {Integer} height
+ *
+ * the ImageInfos class holds a list of ImageDatas of a given size.
+ */
+ function ImageInfos(width, height) {
+ this.width = width;
+ this.height = height;
+ this.infos = []; // the list of images
+
+ /**
+ *
+ * @method findImage
+ * @param {Integer} space
+ * @return {Object} contains the ImageData, and pixel index into that
+ * ImageData where the free space was allocated.
+ *
+ * finds free space of a given size in the ImageData list
+ */
+ this.findImage = function(space) {
+ var imageSize = this.width * this.height;
+ if (space > imageSize) throw new Error('font is too complex to render in 3D');
+
+ // search through the list of images, looking for one with
+ // anough unused space.
+ var imageInfo, imageData;
+ for (var ii = this.infos.length - 1; ii >= 0; --ii) {
+ var imageInfoTest = this.infos[ii];
+ if (imageInfoTest.index + space < imageSize) {
+ // found one
+ imageInfo = imageInfoTest;
+ imageData = imageInfoTest.imageData;
+ break;
+ }
+ }
+
+ if (!imageInfo) {
+ try {
+ // create a new image
+ imageData = new ImageData(this.width, this.height);
+ } catch (err) {
+ // for browsers that don't support ImageData constructors (ie IE11)
+ // create an ImageData using the old method
+ var canvas = document.getElementsByTagName('canvas')[0];
+ var created = !canvas;
+ if (!canvas) {
+ // create a temporary canvas
+ canvas = document.createElement('canvas');
+ canvas.style.display = 'none';
+ document.body.appendChild(canvas);
+ }
+ var ctx = canvas.getContext('2d');
+ if (ctx) {
+ imageData = ctx.createImageData(this.width, this.height);
+ }
+ if (created) {
+ // distroy the temporary canvas, if necessary
+ document.body.removeChild(canvas);
+ }
+ }
+ // construct & dd the new image info
+ imageInfo = { index: 0, imageData: imageData };
+ this.infos.push(imageInfo);
+ }
+
+ var index = imageInfo.index;
+ imageInfo.index += space; // move to the start of the next image
+ imageData._dirty = true;
+ return { imageData: imageData, index: index };
+ };
+ }
+
+ /**
+ * @function setPixel
+ * @param {Object} imageInfo
+ * @param {Number} r
+ * @param {Number} g
+ * @param {Number} b
+ * @param {Number} a
+ *
+ * writes the next pixel into an indexed ImageData
+ */
+ function setPixel(imageInfo, r, g, b, a) {
+ var imageData = imageInfo.imageData;
+ var pixels = imageData.data;
+ var index = imageInfo.index++ * 4;
+ pixels[index++] = r;
+ pixels[index++] = g;
+ pixels[index++] = b;
+ pixels[index++] = a;
+ }
+
+ var SQRT3 = Math.sqrt(3);
+
+ /**
+ * @private
+ * @class FontInfo
+ * @param {Object} font an opentype.js font object
+ *
+ * contains cached images and glyph information for an opentype font
+ */
+ var FontInfo = function FontInfo(font) {
+ this.font = font;
+ // the bezier curve coordinates
+ this.strokeImageInfos = new ImageInfos(strokeImageWidth, strokeImageHeight);
+ // lists of curve indices for each row/column slice
+ this.colDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight);
+ this.rowDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight);
+ // the offset & length of each row/col slice in the glyph
+ this.colCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight);
+ this.rowCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight);
+
+ // the cached information for each glyph
+ this.glyphInfos = {};
+
+ /**
+ * @method getGlyphInfo
+ * @param {Glyph} glyph the x positions of points in the curve
+ * @returns {Object} the glyphInfo for that glyph
+ *
+ * calculates rendering info for a glyph, including the curve information,
+ * row & column stripes compiled into textures.
+ */
+
+ this.getGlyphInfo = function(glyph) {
+ // check the cache
+ var gi = this.glyphInfos[glyph.index];
+ if (gi) return gi;
+
+ // get the bounding box of the glyph from opentype.js
+ var bb = glyph.getBoundingBox();
+ var xMin = bb.x1;
+ var yMin = bb.y1;
+ var gWidth = bb.x2 - xMin;
+ var gHeight = bb.y2 - yMin;
+ var cmds = glyph.path.commands;
+ // don't bother rendering invisible glyphs
+ if (gWidth === 0 || gHeight === 0 || !cmds.length) {
+ return (this.glyphInfos[glyph.index] = {});
+ }
+
+ var i;
+ var strokes = []; // the strokes in this glyph
+ var rows = []; // the indices of strokes in each row
+ var cols = []; // the indices of strokes in each column
+ for (i = charGridWidth - 1; i >= 0; --i) {
+ cols.push([]);
+ }
+ for (i = charGridHeight - 1; i >= 0; --i) {
+ rows.push([]);
+ }
+
+ /**
+ * @function push
+ * @param {Number[]} xs the x positions of points in the curve
+ * @param {Number[]} ys the y positions of points in the curve
+ * @param {Object} v the curve information
+ *
+ * adds a curve to the rows & columns that it intersects with
+ */
+ function push(xs, ys, v) {
+ var index = strokes.length; // the index of this stroke
+ strokes.push(v); // add this stroke to the list
+
+ /**
+ * @function minMax
+ * @param {Number[]} rg the list of values to compare
+ * @param {Number} min the initial minimum value
+ * @param {Number} max the initial maximum value
+ *
+ * find the minimum & maximum value in a list of values
+ */
+ function minMax(rg, min, max) {
+ for (var _i = rg.length; _i-- > 0; ) {
+ var _v = rg[_i];
+ if (min > _v) min = _v;
+ if (max < _v) max = _v;
+ }
+ return { min: min, max: max };
+ }
+
+ // loop through the rows & columns that the curve intersects
+ // adding the curve to those slices
+ var mmX = minMax(xs, 1, 0);
+ var ixMin = Math.max(Math.floor(mmX.min * charGridWidth), 0);
+ var ixMax = Math.min(Math.ceil(mmX.max * charGridWidth), charGridWidth);
+ for (var iCol = ixMin; iCol < ixMax; ++iCol) {
+ cols[iCol].push(index);
+ }
+
+ var mmY = minMax(ys, 1, 0);
+ var iyMin = Math.max(Math.floor(mmY.min * charGridHeight), 0);
+ var iyMax = Math.min(Math.ceil(mmY.max * charGridHeight), charGridHeight);
+
+ for (var iRow = iyMin; iRow < iyMax; ++iRow) {
+ rows[iRow].push(index);
+ }
+ }
+
+ /**
+ * @function clamp
+ * @param {Number} v the value to clamp
+ * @param {Number} min the minimum value
+ * @param {Number} max the maxmimum value
+ *
+ * clamps a value between a minimum & maximum value
+ */
+ function clamp(v, min, max) {
+ if (v < min) return min;
+ if (v > max) return max;
+ return v;
+ }
+
+ /**
+ * @function byte
+ * @param {Number} v the value to scale
+ *
+ * converts a floating-point number in the range 0-1 to a byte 0-255
+ */
+ function byte(v) {
+ return clamp(255 * v, 0, 255);
+ }
+
+ /**
+ * @private
+ * @class Cubic
+ * @param {Number} p0 the start point of the curve
+ * @param {Number} c0 the first control point
+ * @param {Number} c1 the second control point
+ * @param {Number} p1 the end point
+ *
+ * a cubic curve
+ */
+ function Cubic(p0, c0, c1, p1) {
+ this.p0 = p0;
+ this.c0 = c0;
+ this.c1 = c1;
+ this.p1 = p1;
+
+ /**
+ * @method toQuadratic
+ * @return {Object} the quadratic approximation
+ *
+ * converts the cubic to a quadtratic approximation by
+ * picking an appropriate quadratic control point
+ */
+ this.toQuadratic = function() {
+ return {
+ x: this.p0.x,
+ y: this.p0.y,
+ x1: this.p1.x,
+ y1: this.p1.y,
+ cx: ((this.c0.x + this.c1.x) * 3 - (this.p0.x + this.p1.x)) / 4,
+ cy: ((this.c0.y + this.c1.y) * 3 - (this.p0.y + this.p1.y)) / 4
+ };
+ };
+
+ /**
+ * @method quadError
+ * @return {Number} the error
+ *
+ * calculates the magnitude of error of this curve's
+ * quadratic approximation.
+ */
+ this.quadError = function() {
+ return (
+ _main.default.Vector.sub(
+ _main.default.Vector.sub(this.p1, this.p0),
+ _main.default.Vector.mult(
+ _main.default.Vector.sub(this.c1, this.c0),
+ 3
+ )
+ ).mag() / 2
+ );
+ };
+
+ /**
+ * @method split
+ * @param {Number} t the value (0-1) at which to split
+ * @return {Cubic} the second part of the curve
+ *
+ * splits the cubic into two parts at a point 't' along the curve.
+ * this cubic keeps its start point and its end point becomes the
+ * point at 't'. the 'end half is returned.
+ */
+ this.split = function(t) {
+ var m1 = _main.default.Vector.lerp(this.p0, this.c0, t);
+ var m2 = _main.default.Vector.lerp(this.c0, this.c1, t);
+ var mm1 = _main.default.Vector.lerp(m1, m2, t);
+
+ this.c1 = _main.default.Vector.lerp(this.c1, this.p1, t);
+ this.c0 = _main.default.Vector.lerp(m2, this.c1, t);
+ var pt = _main.default.Vector.lerp(mm1, this.c0, t);
+ var part1 = new Cubic(this.p0, m1, mm1, pt);
+ this.p0 = pt;
+ return part1;
+ };
+
+ /**
+ * @method splitInflections
+ * @return {Cubic[]} the non-inflecting pieces of this cubic
+ *
+ * returns an array containing 0, 1 or 2 cubics split resulting
+ * from splitting this cubic at its inflection points.
+ * this cubic is (potentially) altered and returned in the list.
+ */
+ this.splitInflections = function() {
+ var a = _main.default.Vector.sub(this.c0, this.p0);
+ var b = _main.default.Vector.sub(
+ _main.default.Vector.sub(this.c1, this.c0),
+ a
+ );
+ var c = _main.default.Vector.sub(
+ _main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.c1), a),
+ _main.default.Vector.mult(b, 2)
+ );
+
+ var cubics = [];
+
+ // find the derivative coefficients
+ var A = b.x * c.y - b.y * c.x;
+ if (A !== 0) {
+ var B = a.x * c.y - a.y * c.x;
+ var C = a.x * b.y - a.y * b.x;
+ var disc = B * B - 4 * A * C;
+ if (disc >= 0) {
+ if (A < 0) {
+ A = -A;
+ B = -B;
+ C = -C;
+ }
+
+ var Q = Math.sqrt(disc);
+ var t0 = (-B - Q) / (2 * A); // the first inflection point
+ var t1 = (-B + Q) / (2 * A); // the second inflection point
+
+ // test if the first inflection point lies on the curve
+ if (t0 > 0 && t0 < 1) {
+ // split at the first inflection point
+ cubics.push(this.split(t0));
+ // scale t2 into the second part
+ t1 = 1 - (1 - t1) / (1 - t0);
+ }
+
+ // test if the second inflection point lies on the curve
+ if (t1 > 0 && t1 < 1) {
+ // split at the second inflection point
+ cubics.push(this.split(t1));
+ }
+ }
+ }
+
+ cubics.push(this);
+ return cubics;
+ };
+ }
+
+ /**
+ * @function cubicToQuadratics
+ * @param {Number} x0
+ * @param {Number} y0
+ * @param {Number} cx0
+ * @param {Number} cy0
+ * @param {Number} cx1
+ * @param {Number} cy1
+ * @param {Number} x1
+ * @param {Number} y1
+ * @returns {Cubic[]} an array of cubics whose quadratic approximations
+ * closely match the civen cubic.
+ *
+ * converts a cubic curve to a list of quadratics.
+ */
+ function cubicToQuadratics(x0, y0, cx0, cy0, cx1, cy1, x1, y1) {
+ // create the Cubic object and split it at its inflections
+ var cubics = new Cubic(
+ new _main.default.Vector(x0, y0),
+ new _main.default.Vector(cx0, cy0),
+ new _main.default.Vector(cx1, cy1),
+ new _main.default.Vector(x1, y1)
+ ).splitInflections();
+
+ var qs = []; // the final list of quadratics
+ var precision = 30 / SQRT3;
+
+ // for each of the non-inflected pieces of the original cubic
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (
+ var _iterator = cubics[Symbol.iterator](), _step;
+ !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
+ _iteratorNormalCompletion = true
+ ) {
+ var cubic = _step.value;
+ // the cubic is iteratively split in 3 pieces:
+ // the first piece is accumulated in 'qs', the result.
+ // the last piece is accumulated in 'tail', temporarily.
+ // the middle piece is repeatedly split again, while necessary.
+ var tail = [];
+
+ var t3 = void 0;
+ for (;;) {
+ // calculate this cubic's precision
+ t3 = precision / cubic.quadError();
+ if (t3 >= 0.5 * 0.5 * 0.5) {
+ break; // not too bad, we're done
+ }
+
+ // find a split point based on the error
+ var t = Math.pow(t3, 1.0 / 3.0);
+ // split the cubic in 3
+ var start = cubic.split(t);
+ var middle = cubic.split(1 - t / (1 - t));
+
+ qs.push(start); // the first part
+ tail.push(cubic); // the last part
+ cubic = middle; // iterate on the middle piece
+ }
+
+ if (t3 < 1) {
+ // a little excess error, split the middle in two
+ qs.push(cubic.split(0.5));
+ }
+ // add the middle piece to the result
+ qs.push(cubic);
+
+ // finally add the tail, reversed, onto the result
+ Array.prototype.push.apply(qs, tail.reverse());
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ return qs;
+ }
+
+ /**
+ * @function pushLine
+ * @param {Number} x0
+ * @param {Number} y0
+ * @param {Number} x1
+ * @param {Number} y1
+ *
+ * add a straight line to the row/col grid of a glyph
+ */
+ function pushLine(x0, y0, x1, y1) {
+ var mx = (x0 + x1) / 2;
+ var my = (y0 + y1) / 2;
+ push([x0, x1], [y0, y1], { x: x0, y: y0, cx: mx, cy: my });
+ }
+
+ /**
+ * @function samePoint
+ * @param {Number} x0
+ * @param {Number} y0
+ * @param {Number} x1
+ * @param {Number} y1
+ * @return {Boolean} true if the two points are sufficiently close
+ *
+ * tests if two points are close enough to be considered the same
+ */
+ function samePoint(x0, y0, x1, y1) {
+ return Math.abs(x1 - x0) < 0.00001 && Math.abs(y1 - y0) < 0.00001;
+ }
+
+ var x0, y0, xs, ys;
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (
+ var _iterator2 = cmds[Symbol.iterator](), _step2;
+ !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
+ _iteratorNormalCompletion2 = true
+ ) {
+ var cmd = _step2.value;
+ // scale the coordinates to the range 0-1
+ var x1 = (cmd.x - xMin) / gWidth;
+ var y1 = (cmd.y - yMin) / gHeight;
+
+ // don't bother if this point is the same as the last
+ if (samePoint(x0, y0, x1, y1)) continue;
+
+ switch (cmd.type) {
+ case 'M': {
+ // move
+ xs = x1;
+ ys = y1;
+ break;
+ }
+ case 'L': {
+ // line
+ pushLine(x0, y0, x1, y1);
+ break;
+ }
+ case 'Q': {
+ // quadratic
+ var cx = (cmd.x1 - xMin) / gWidth;
+ var cy = (cmd.y1 - yMin) / gHeight;
+ push([x0, x1, cx], [y0, y1, cy], { x: x0, y: y0, cx: cx, cy: cy });
+ break;
+ }
+ case 'Z': {
+ // end
+ if (!samePoint(x0, y0, xs, ys)) {
+ // add an extra line closing the loop, if necessary
+ pushLine(x0, y0, xs, ys);
+ strokes.push({ x: xs, y: ys });
+ } else {
+ strokes.push({ x: x0, y: y0 });
+ }
+ break;
+ }
+ case 'C': {
+ // cubic
+ var cx1 = (cmd.x1 - xMin) / gWidth;
+ var cy1 = (cmd.y1 - yMin) / gHeight;
+ var cx2 = (cmd.x2 - xMin) / gWidth;
+ var cy2 = (cmd.y2 - yMin) / gHeight;
+ var qs = cubicToQuadratics(x0, y0, cx1, cy1, cx2, cy2, x1, y1);
+ for (var iq = 0; iq < qs.length; iq++) {
+ var q = qs[iq].toQuadratic();
+ push([q.x, q.x1, q.cx], [q.y, q.y1, q.cy], q);
+ }
+ break;
+ }
+ default:
+ throw new Error('unknown command type: '.concat(cmd.type));
+ }
+
+ x0 = x1;
+ y0 = y1;
+ }
+
+ // allocate space for the strokes
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ var strokeCount = strokes.length;
+ var strokeImageInfo = this.strokeImageInfos.findImage(strokeCount);
+ var strokeOffset = strokeImageInfo.index;
+
+ // fill the stroke image
+ for (var il = 0; il < strokeCount; ++il) {
+ var s = strokes[il];
+ setPixel(strokeImageInfo, byte(s.x), byte(s.y), byte(s.cx), byte(s.cy));
+ }
+
+ /**
+ * @function layout
+ * @param {Number[][]} dim
+ * @param {ImageInfo[]} dimImageInfos
+ * @param {ImageInfo[]} cellImageInfos
+ * @return {Object}
+ *
+ * lays out the curves in a dimension (row or col) into two
+ * images, one for the indices of the curves themselves, and
+ * one containing the offset and length of those index spans.
+ */
+ function layout(dim, dimImageInfos, cellImageInfos) {
+ var dimLength = dim.length; // the number of slices in this dimension
+ var dimImageInfo = dimImageInfos.findImage(dimLength);
+ var dimOffset = dimImageInfo.index;
+ // calculate the total number of stroke indices in this dimension
+ var totalStrokes = 0;
+ for (var id = 0; id < dimLength; ++id) {
+ totalStrokes += dim[id].length;
+ }
+
+ // allocate space for the stroke indices
+ var cellImageInfo = cellImageInfos.findImage(totalStrokes);
+
+ // for each slice in the glyph
+ for (var _i2 = 0; _i2 < dimLength; ++_i2) {
+ var strokeIndices = dim[_i2];
+ var _strokeCount = strokeIndices.length;
+ var cellLineIndex = cellImageInfo.index;
+
+ // write the offset and count into the glyph slice image
+ setPixel(
+ dimImageInfo,
+ cellLineIndex >> 7,
+ cellLineIndex & 0x7f,
+ _strokeCount >> 7,
+ _strokeCount & 0x7f
+ );
+
+ // for each stroke index in that slice
+ for (var iil = 0; iil < _strokeCount; ++iil) {
+ // write the stroke index into the slice's image
+ var strokeIndex = strokeIndices[iil] + strokeOffset;
+ setPixel(cellImageInfo, strokeIndex >> 7, strokeIndex & 0x7f, 0, 0);
+ }
+ }
+
+ return {
+ cellImageInfo: cellImageInfo,
+ dimOffset: dimOffset,
+ dimImageInfo: dimImageInfo
+ };
+ }
+
+ // initialize the info for this glyph
+ gi = this.glyphInfos[glyph.index] = {
+ glyph: glyph,
+ uGlyphRect: [bb.x1, -bb.y1, bb.x2, -bb.y2],
+ strokeImageInfo: strokeImageInfo,
+ strokes: strokes,
+ colInfo: layout(cols, this.colDimImageInfos, this.colCellImageInfos),
+ rowInfo: layout(rows, this.rowDimImageInfos, this.rowCellImageInfos)
+ };
+
+ gi.uGridOffset = [gi.colInfo.dimOffset, gi.rowInfo.dimOffset];
+ return gi;
+ };
+ };
+
+ _main.default.RendererGL.prototype._renderText = function(p, line, x, y, maxY) {
+ if (!this._textFont || typeof this._textFont === 'string') {
+ console.log(
+ 'WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.'
+ );
+
+ return;
+ }
+ if (y >= maxY || !this._doFill) {
+ return; // don't render lines beyond our maxY position
+ }
+
+ if (!this._isOpenType()) {
+ console.log(
+ 'WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts are supported'
+ );
+
+ return p;
+ }
+
+ p.push(); // fix to #803
+
+ // remember this state, so it can be restored later
+ var doStroke = this._doStroke;
+ var drawMode = this.drawMode;
+
+ this._doStroke = false;
+ this.drawMode = constants.TEXTURE;
+
+ // get the cached FontInfo object
+ var font = this._textFont.font;
+ var fontInfo = this._textFont._fontInfo;
+ if (!fontInfo) {
+ fontInfo = this._textFont._fontInfo = new FontInfo(font);
+ }
+
+ // calculate the alignment and move/scale the view accordingly
+ var pos = this._textFont._handleAlignment(this, line, x, y);
+ var fontSize = this._textSize;
+ var scale = fontSize / font.unitsPerEm;
+ this.translate(pos.x, pos.y, 0);
+ this.scale(scale, scale, 1);
+
+ // initialize the font shader
+ var gl = this.GL;
+ var initializeShader = !this._defaultFontShader;
+ var sh = this._getFontShader();
+ sh.init();
+ sh.bindShader(); // first time around, bind the shader fully
+
+ if (initializeShader) {
+ // these are constants, really. just initialize them one-time.
+ sh.setUniform('uGridImageSize', [gridImageWidth, gridImageHeight]);
+ sh.setUniform('uCellsImageSize', [cellImageWidth, cellImageHeight]);
+ sh.setUniform('uStrokeImageSize', [strokeImageWidth, strokeImageHeight]);
+ sh.setUniform('uGridSize', [charGridWidth, charGridHeight]);
+ }
+ this._applyColorBlend(this.curFillColor);
+
+ var g = this.gHash['glyph'];
+ if (!g) {
+ // create the geometry for rendering a quad
+ var geom = (this._textGeom = new _main.default.Geometry(1, 1, function() {
+ for (var i = 0; i <= 1; i++) {
+ for (var j = 0; j <= 1; j++) {
+ this.vertices.push(new _main.default.Vector(j, i, 0));
+ this.uvs.push(j, i);
+ }
+ }
+ }));
+ geom.computeFaces().computeNormals();
+ g = this.createBuffers('glyph', geom);
+ }
+
+ // bind the shader buffers
+ this._prepareBuffers(g, sh, _main.default.RendererGL._textBuffers);
+ this._bindBuffer(g.indexBuffer, gl.ELEMENT_ARRAY_BUFFER);
+
+ // this will have to do for now...
+ sh.setUniform('uMaterialColor', this.curFillColor);
+
+ try {
+ var dx = 0; // the x position in the line
+ var glyphPrev = null; // the previous glyph, used for kerning
+ // fetch the glyphs in the line of text
+ var glyphs = font.stringToGlyphs(line);
+ var _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+ try {
+ for (
+ var _iterator3 = glyphs[Symbol.iterator](), _step3;
+ !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done);
+ _iteratorNormalCompletion3 = true
+ ) {
+ var glyph = _step3.value;
+ // kern
+ if (glyphPrev) dx += font.getKerningValue(glyphPrev, glyph);
+
+ var gi = fontInfo.getGlyphInfo(glyph);
+ if (gi.uGlyphRect) {
+ var rowInfo = gi.rowInfo;
+ var colInfo = gi.colInfo;
+ sh.setUniform('uSamplerStrokes', gi.strokeImageInfo.imageData);
+ sh.setUniform('uSamplerRowStrokes', rowInfo.cellImageInfo.imageData);
+ sh.setUniform('uSamplerRows', rowInfo.dimImageInfo.imageData);
+ sh.setUniform('uSamplerColStrokes', colInfo.cellImageInfo.imageData);
+ sh.setUniform('uSamplerCols', colInfo.dimImageInfo.imageData);
+ sh.setUniform('uGridOffset', gi.uGridOffset);
+ sh.setUniform('uGlyphRect', gi.uGlyphRect);
+ sh.setUniform('uGlyphOffset', dx);
+
+ sh.bindTextures(); // afterwards, only textures need updating
+
+ // draw it
+ gl.drawElements(gl.TRIANGLES, 6, this.GL.UNSIGNED_SHORT, 0);
+ }
+ dx += glyph.advanceWidth;
+ glyphPrev = glyph;
+ }
+ } catch (err) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
+ _iterator3.return();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+ } finally {
+ // clean up
+ sh.unbindShader();
+
+ this._doStroke = doStroke;
+ this.drawMode = drawMode;
+
+ p.pop();
+ }
+
+ return p;
+ };
+ },
+ {
+ '../core/constants': 21,
+ '../core/main': 27,
+ './p5.RendererGL.Retained': 79,
+ './p5.Shader': 81
+ }
+ ]
+ },
+ {},
+ [16]
+ )(16);
+});
diff --git a/creator/src/templates/files/p5.sound.min.js b/creator/src/templates/files/p5.sound.min.js
new file mode 100644
index 0000000..899f447
--- /dev/null
+++ b/creator/src/templates/files/p5.sound.min.js
@@ -0,0 +1,28 @@
+/*! p5.sound.min.js v0.3.11 2019-03-14 */
+
+/**
+ * p5.sound
+ * https://p5js.org/reference/#/libraries/p5.sound
+ *
+ * From the Processing Foundation and contributors
+ * https://github.com/processing/p5.js-sound/graphs/contributors
+ *
+ * MIT License (MIT)
+ * https://github.com/processing/p5.js-sound/blob/master/LICENSE
+ *
+ * Some of the many audio libraries & resources that inspire p5.sound:
+ * - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js
+ * - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/
+ * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0
+ * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js
+ * - Web Audio Components by Jordan Santell https://github.com/web-audio-components
+ * - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound
+ *
+ * Web Audio API: http://w3.org/TR/webaudio/
+ */
+
+!function(t,e){"function"==typeof define&&define.amd?define("p5.sound",["p5"],function(t){e(t)}):e("object"==typeof exports?require("../p5"):t.p5)}(this,function(t){var e;e=function(){!function(){function t(t){t&&(t.setTargetAtTime||(t.setTargetAtTime=t.setTargetValueAtTime))}window.hasOwnProperty("webkitAudioContext")&&!window.hasOwnProperty("AudioContext")&&(window.AudioContext=window.webkitAudioContext,"function"!=typeof AudioContext.prototype.createGain&&(AudioContext.prototype.createGain=AudioContext.prototype.createGainNode),"function"!=typeof AudioContext.prototype.createDelay&&(AudioContext.prototype.createDelay=AudioContext.prototype.createDelayNode),"function"!=typeof AudioContext.prototype.createScriptProcessor&&(AudioContext.prototype.createScriptProcessor=AudioContext.prototype.createJavaScriptNode),"function"!=typeof AudioContext.prototype.createPeriodicWave&&(AudioContext.prototype.createPeriodicWave=AudioContext.prototype.createWaveTable),AudioContext.prototype.internal_createGain=AudioContext.prototype.createGain,AudioContext.prototype.createGain=function(){var e=this.internal_createGain();return t(e.gain),e},AudioContext.prototype.internal_createDelay=AudioContext.prototype.createDelay,AudioContext.prototype.createDelay=function(e){var i=e?this.internal_createDelay(e):this.internal_createDelay();return t(i.delayTime),i},AudioContext.prototype.internal_createBufferSource=AudioContext.prototype.createBufferSource,AudioContext.prototype.createBufferSource=function(){var e=this.internal_createBufferSource();return e.start?(e.internal_start=e.start,e.start=function(t,i,n){"undefined"!=typeof n?e.internal_start(t||0,i,n):e.internal_start(t||0,i||0)}):e.start=function(t,e,i){e||i?this.noteGrainOn(t||0,e,i):this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},t(e.playbackRate),e},AudioContext.prototype.internal_createDynamicsCompressor=AudioContext.prototype.createDynamicsCompressor,AudioContext.prototype.createDynamicsCompressor=function(){var e=this.internal_createDynamicsCompressor();return t(e.threshold),t(e.knee),t(e.ratio),t(e.reduction),t(e.attack),t(e.release),e},AudioContext.prototype.internal_createBiquadFilter=AudioContext.prototype.createBiquadFilter,AudioContext.prototype.createBiquadFilter=function(){var e=this.internal_createBiquadFilter();return t(e.frequency),t(e.detune),t(e.Q),t(e.gain),e},"function"!=typeof AudioContext.prototype.createOscillator&&(AudioContext.prototype.internal_createOscillator=AudioContext.prototype.createOscillator,AudioContext.prototype.createOscillator=function(){var e=this.internal_createOscillator();return e.start?(e.internal_start=e.start,e.start=function(t){e.internal_start(t||0)}):e.start=function(t){this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},e.setPeriodicWave||(e.setPeriodicWave=e.setWaveTable),t(e.frequency),t(e.detune),e})),window.hasOwnProperty("webkitOfflineAudioContext")&&!window.hasOwnProperty("OfflineAudioContext")&&(window.OfflineAudioContext=window.webkitOfflineAudioContext)}(window),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var e=document.createElement("audio");t.prototype.isSupported=function(){return!!e.canPlayType};var i=function(){return!!e.canPlayType&&e.canPlayType('audio/ogg; codecs="vorbis"')},n=function(){return!!e.canPlayType&&e.canPlayType("audio/mpeg;")},o=function(){return!!e.canPlayType&&e.canPlayType('audio/wav; codecs="1"')},r=function(){return!!e.canPlayType&&(e.canPlayType("audio/x-m4a;")||e.canPlayType("audio/aac;"))},s=function(){return!!e.canPlayType&&e.canPlayType("audio/x-aiff;")};t.prototype.isFileSupported=function(t){switch(t.toLowerCase()){case"mp3":return n();case"wav":return o();case"ogg":return i();case"aac":case"m4a":case"mp4":return r();case"aif":case"aiff":return s();default:return!1}}}();var i;!function(t,e){i=function(){return e()}()}(this,function(){function t(t){var e=t.createBuffer(1,1,t.sampleRate),i=t.createBufferSource();i.buffer=e,i.connect(t.destination),i.start(0),t.resume&&t.resume()}function e(t){return"running"===t.state}function i(t,i){function n(){e(t)?i():(requestAnimationFrame(n),t.resume&&t.resume())}e(t)?i():n()}function n(t,e,i){if(Array.isArray(t)||NodeList&&t instanceof NodeList)for(var o=0;o1&&(this.input=new Array(t)),this.isUndef(e)||1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(t))};t.prototype.set=function(e,i,n){if(this.isObject(e))n=i;else if(this.isString(e)){var o={};o[e]=i,e=o}t:for(var r in e){i=e[r];var s=this;if(-1!==r.indexOf(".")){for(var a=r.split("."),u=0;u1)for(var t=arguments[0],e=1;e0)for(var t=this,e=0;e0)for(var t=0;tn;n++)i[n].apply(this,e)}return this},t.Emitter.mixin=function(e){var i=["on","off","emit"];e._events={};for(var n=0;n1?t.getChannelData(1):e;var s=i(e,r),a=new window.ArrayBuffer(44+2*s.length),u=new window.DataView(a);n(u,0,"RIFF"),u.setUint32(4,36+2*s.length,!0),n(u,8,"WAVE"),n(u,12,"fmt "),u.setUint32(16,16,!0),u.setUint16(20,1,!0),u.setUint16(22,2,!0),u.setUint32(24,o.audiocontext.sampleRate,!0),u.setUint32(28,4*o.audiocontext.sampleRate,!0),u.setUint16(32,4,!0),u.setUint16(34,16,!0),n(u,36,"data"),u.setUint32(40,2*s.length,!0);for(var c=s.length,p=44,h=1,l=0;c>l;l++)u.setInt16(p,s[l]*(32767*h),!0),p+=2;return u}function i(t,e){for(var i=t.length+e.length,n=new Float32Array(i),o=0,r=0;i>r;)n[r++]=t[o],n[r++]=e[o],o++;return n}function n(t,e,i){for(var n=i.length,o=0;n>o;o++)t.setUint8(e+o,i.charCodeAt(o))}var o=a;t.prototype.sampleRate=function(){return o.audiocontext.sampleRate},t.prototype.freqToMidi=function(t){var e=Math.log(t/440)/Math.log(2),i=Math.round(12*e)+69;return i};var r=t.prototype.midiToFreq=function(t){return 440*Math.pow(2,(t-69)/12)},s=function(t){if("string"!=typeof t)return t;var e={A:21,B:23,C:24,D:26,E:28,F:29,G:31},i=e[t[0].toUpperCase()],n=~~t.slice(-1);switch(i+=12*(n-1),t[1]){case"#":i+=1;break;case"b":i-=1}return r(i)};return t.prototype.soundFormats=function(){o.extensions=[];for(var t=0;t-1))throw arguments[t]+" is not a valid sound format!";o.extensions.push(arguments[t])}},t.prototype.disposeSound=function(){for(var t=0;t-1)if(t.prototype.isFileSupported(n))i=i;else for(var r=i.split("."),s=r[r.length-1],a=0;a1?(this.splitter=i.createChannelSplitter(2),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0)):(this.input.connect(this.left),this.input.connect(this.right)),this.output=i.createChannelMerger(2),this.left.connect(this.output,0,1),this.right.connect(this.output,0,0),this.output.connect(e)},t.Panner.prototype.pan=function(t,e){var n=e||0,o=i.currentTime+n,r=(t+1)/2,s=Math.cos(r*Math.PI/2),a=Math.sin(r*Math.PI/2);this.left.gain.linearRampToValueAtTime(a,o),this.right.gain.linearRampToValueAtTime(s,o)},t.Panner.prototype.inputChannels=function(t){1===t?(this.input.disconnect(),this.input.connect(this.left),this.input.connect(this.right)):2===t&&(this.splitter=i.createChannelSplitter(2),this.input.disconnect(),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0))},t.Panner.prototype.connect=function(t){this.output.connect(t)},t.Panner.prototype.disconnect=function(){this.output&&this.output.disconnect()})}(a);var h;h=function(){function e(t,e){for(var i={},n=t.length,o=0;n>o;o++){if(t[o]>e){var r=t[o],s=new v(r,o);i[o]=s,o+=6e3}o++}return i}function i(t){for(var e=[],i=Object.keys(t).sort(),n=0;no;o++){var r=t[i[n]],s=t[i[n+o]];if(r&&s){var a=r.sampleIndex,u=s.sampleIndex,c=u-a;c>0&&r.intervals.push(c);var p=e.some(function(t){return t.interval===c?(t.count++,t):void 0});p||e.push({interval:c,count:1})}}return e}function n(t,e){var i=[];return t.forEach(function(t){try{var n=Math.abs(60/(t.interval/e));n=r(n);var o=i.some(function(e){return e.tempo===n?e.count+=t.count:void 0});if(!o){if(isNaN(n))return;i.push({tempo:Math.round(n),count:t.count})}}catch(s){throw s}}),i}function o(t,e,i,n){for(var o=[],s=Object.keys(t).sort(),a=0;a.01?!0:void 0})}function r(t){if(isFinite(t)&&0!==t){for(;90>t;)t*=2;for(;t>180&&t>90;)t/=2;return t}}function s(t){var e=t.inputBuffer.getChannelData(0);this._lastPos=e[e.length-1]||0,this._onTimeUpdate(self._lastPos)}function p(t){const e=t.target,i=this;e._playing=!1,e.removeEventListener("ended",i._clearOnEnd),i._onended(i),i.bufferSourceNodes.forEach(function(t,e){t._playing===!1&&i.bufferSourceNodes.splice(e)}),0===i.bufferSourceNodes.length&&(i._playing=!1)}var h=c,l=a,f=l.audiocontext,d=u.midiToFreq,m=u.convertToWav;t.SoundFile=function(e,i,n,o){if("undefined"!=typeof e){if("string"==typeof e||"string"==typeof e[0]){var r=t.prototype._checkFileFormats(e);this.url=r}else if("object"==typeof e&&!(window.File&&window.FileReader&&window.FileList&&window.Blob))throw"Unable to load file because the File API is not supported";e.file&&(e=e.file),this.file=e}this._onended=function(){},this._looping=!1,this._playing=!1,this._paused=!1,this._pauseTime=0,this._cues=[],this._cueIDCounter=0,this._lastPos=0,this._counterNode=null,this._scopeNode=null,this.bufferSourceNodes=[],this.bufferSourceNode=null,this.buffer=null,this.playbackRate=1,this.input=l.audiocontext.createGain(),this.output=l.audiocontext.createGain(),this.reversed=!1,this.startTime=0,this.endTime=null,this.pauseTime=0,this.mode="sustain",this.startMillis=null,this.panPosition=0,this.panner=new t.Panner(this.output,l.input,2),(this.url||this.file)&&this.load(i,n),l.soundArray.push(this),"function"==typeof o?this._whileLoading=o:this._whileLoading=function(){},this._onAudioProcess=s.bind(this),this._clearOnEnd=p.bind(this)},t.prototype.registerPreloadMethod("loadSound",t.prototype),t.prototype.loadSound=function(e,i,n,o){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&window.alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var r=this,s=new t.SoundFile(e,function(){"function"==typeof i&&i.apply(r,arguments),"function"==typeof r._decrementPreload&&r._decrementPreload()},n,o);return s},t.SoundFile.prototype.load=function(t,e){var i=this,n=(new Error).stack;if(void 0!==this.url&&""!==this.url){var o=new XMLHttpRequest;o.addEventListener("progress",function(t){i._updateProgress(t)},!1),o.open("GET",this.url,!0),o.responseType="arraybuffer",o.onload=function(){if(200===o.status){if(!i.panner)return;f.decodeAudioData(o.response,function(e){i.panner&&(i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i))},function(){if(i.panner){var t=new h("decodeAudioData",n,i.url),o="AudioContext error at decodeAudioData for "+i.url;e?(t.msg=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)}})}else{if(!i.panner)return;var r=new h("loadSound",n,i.url),s="Unable to load "+i.url+". The request status was: "+o.status+" ("+o.statusText+")";e?(r.message=s,e(r)):console.error(s+"\n The error stack trace includes: \n"+r.stack)}},o.onerror=function(){var t=new h("loadSound",n,i.url),o="There was no response from the server at "+i.url+". Check the url and internet connectivity.";e?(t.message=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)},o.send()}else if(void 0!==this.file){var r=new FileReader;r.onload=function(){i.panner&&f.decodeAudioData(r.result,function(e){i.panner&&(i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i))})},r.onerror=function(t){i.panner&&onerror&&onerror(t)},r.readAsArrayBuffer(this.file)}},t.SoundFile.prototype._updateProgress=function(t){if(t.lengthComputable){var e=t.loaded/t.total*.99;this._whileLoading(e,t)}else this._whileLoading("size unknown")},t.SoundFile.prototype.isLoaded=function(){return this.buffer?!0:!1},t.SoundFile.prototype.play=function(t,e,i,n,o){if(!this.output)return void console.warn("SoundFile.play() called after dispose");var r,s,a=l.audiocontext.currentTime,u=t||0;if(0>u&&(u=0),u+=a,"undefined"!=typeof e&&this.rate(e),"undefined"!=typeof i&&this.setVolume(i),!this.buffer)throw"not ready to play file, buffer has yet to load. Try preload()";if(this._pauseTime=0,"restart"===this.mode&&this.buffer&&this.bufferSourceNode&&(this.bufferSourceNode.stop(u),this._counterNode.stop(u)),"untildone"!==this.mode||!this.isPlaying()){if(this.bufferSourceNode=this._initSourceNode(),delete this._counterNode,this._counterNode=this._initCounterNode(),n){if(!(n>=0&&nt&&!this.reversed?(t=Math.abs(t),e=!0):t>0&&this.reversed&&(e=!0),this.bufferSourceNode){var i=l.audiocontext.currentTime;this.bufferSourceNode.playbackRate.cancelScheduledValues(i),this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i),this._counterNode.playbackRate.cancelScheduledValues(i),this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i)}return e&&this.reverseBuffer(),this.playbackRate},t.SoundFile.prototype.setPitch=function(t){var e=d(t)/d(60);this.rate(e)},t.SoundFile.prototype.getPlaybackRate=function(){return this.playbackRate},t.SoundFile.prototype.duration=function(){return this.buffer?this.buffer.duration:0},t.SoundFile.prototype.currentTime=function(){return this.reversed?Math.abs(this._lastPos-this.buffer.length)/f.sampleRate:this._lastPos/f.sampleRate},t.SoundFile.prototype.jump=function(t,e){if(0>t||t>this.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var i=t||0,n=e||void 0;this.isPlaying()&&this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,i,n);
+},t.SoundFile.prototype.channels=function(){return this.buffer.numberOfChannels},t.SoundFile.prototype.sampleRate=function(){return this.buffer.sampleRate},t.SoundFile.prototype.frames=function(){return this.buffer.length},t.SoundFile.prototype.getPeaks=function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t||(t=5*window.width),this.buffer){for(var e=this.buffer,i=e.length/t,n=~~(i/10)||1,o=e.numberOfChannels,r=new Float32Array(Math.round(t)),s=0;o>s;s++)for(var a=e.getChannelData(s),u=0;t>u;u++){for(var c=~~(u*i),p=~~(c+i),h=0,l=c;p>l;l+=n){var f=a[l];f>h?h=f:-f>h&&(h=f)}(0===s||Math.abs(h)>r[u])&&(r[u]=h)}return r}},t.SoundFile.prototype.reverseBuffer=function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/f.sampleRate,e=this.getVolume();this.setVolume(0,.001);const i=this.buffer.numberOfChannels;for(var n=0;i>n;n++)this.buffer.getChannelData(n).reverse();this.reversed=!this.reversed,t&&this.jump(this.duration()-t),this.setVolume(e,.001)},t.SoundFile.prototype.onended=function(t){return this._onended=t,this},t.SoundFile.prototype.add=function(){},t.SoundFile.prototype.dispose=function(){var t=l.audiocontext.currentTime,e=l.soundArray.indexOf(this);if(l.soundArray.splice(e,1),this.stop(t),this.buffer&&this.bufferSourceNode){for(var i=0;io;o++){var r=n.getChannelData(o);r.set(t[o])}this.buffer=n,this.panner.inputChannels(e)};var y=function(t){const e=t.length,i=f.createBuffer(1,t.length,f.sampleRate),n=i.getChannelData(0);for(var o=0;e>o;o++)n[o]=o;return i};t.SoundFile.prototype._initCounterNode=function(){var e=this,i=f.currentTime,n=f.createBufferSource();return e._scopeNode&&(e._scopeNode.disconnect(),e._scopeNode.removeEventListener("audioprocess",e._onAudioProcess),delete e._scopeNode),e._scopeNode=f.createScriptProcessor(256,1,1),n.buffer=y(e.buffer),n.playbackRate.setValueAtTime(e.playbackRate,i),n.connect(e._scopeNode),e._scopeNode.connect(t.soundOut._silentNode),e._scopeNode.addEventListener("audioprocess",e._onAudioProcess),n},t.SoundFile.prototype._initSourceNode=function(){var t=f.createBufferSource();return t.buffer=this.buffer,t.playbackRate.value=this.playbackRate,t.connect(this.output),t},t.SoundFile.prototype.processPeaks=function(t,r,s,a){var u=this.buffer.length,c=this.buffer.sampleRate,p=this.buffer,h=[],l=r||.9,f=l,d=s||.22,m=a||200,y=new window.OfflineAudioContext(1,u,c),v=y.createBufferSource();v.buffer=p;var g=y.createBiquadFilter();g.type="lowpass",v.connect(g),g.connect(y.destination),v.start(0),y.startRendering(),y.oncomplete=function(r){if(self.panner){var s=r.renderedBuffer,a=s.getChannelData(0);do h=e(a,f),f-=.005;while(Object.keys(h).length=d);var u=i(h),c=n(u,s.sampleRate),p=c.sort(function(t,e){return e.count-t.count}).splice(0,5);this.tempo=p[0].tempo;var l=5,y=o(h,p[0].tempo,s.sampleRate,l);t(y)}}};var v=function(t,e){this.sampleIndex=e,this.amplitude=t,this.tempos=[],this.intervals=[]},g=function(t,e,i,n){this.callback=t,this.time=e,this.id=i,this.val=n};t.SoundFile.prototype.addCue=function(t,e,i){var n=this._cueIDCounter++,o=new g(e,t,n,i);return this._cues.push(o),n},t.SoundFile.prototype.removeCue=function(t){for(var e=this._cues.length,i=0;e>i;i++){var n=this._cues[i];if(n.id===t){this._cues.splice(i,1);break}}0===this._cues.length},t.SoundFile.prototype.clearCues=function(){this._cues=[]},t.SoundFile.prototype._onTimeUpdate=function(t){for(var e=t/this.buffer.sampleRate,i=this._cues.length,n=0;i>n;n++){var o=this._cues[n],r=o.time,s=o.val;this._prevTime=r&&o.callback(s)}this._prevTime=e},t.SoundFile.prototype.save=function(e){const i=m(this.buffer);t.prototype.saveSound([i],e,"wav")},t.SoundFile.prototype.getBlob=function(){const t=m(this.buffer);return new Blob([t],{type:"audio/wav"})}}(c,a,u,u);var l;l=function(){var e=a;t.Amplitude=function(t){this.bufferSize=2048,this.audiocontext=e.audiocontext,this.processor=this.audiocontext.createScriptProcessor(this.bufferSize,2,1),this.input=this.processor,this.output=this.audiocontext.createGain(),this.smoothing=t||0,this.volume=0,this.average=0,this.stereoVol=[0,0],this.stereoAvg=[0,0],this.stereoVolNorm=[0,0],this.volMax=.001,this.normalize=!1,this.processor.onaudioprocess=this._audioProcess.bind(this),this.processor.connect(this.output),this.output.gain.value=0,this.output.connect(this.audiocontext.destination),e.meter.connect(this.processor),e.soundArray.push(this)},t.Amplitude.prototype.setInput=function(i,n){e.meter.disconnect(),n&&(this.smoothing=n),null==i?(console.log("Amplitude input source is not ready! Connecting to master output instead"),e.meter.connect(this.processor)):i instanceof t.Signal?i.output.connect(this.processor):i?(i.connect(this.processor),this.processor.disconnect(),this.processor.connect(this.output)):e.meter.connect(this.processor)},t.Amplitude.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):this.output.connect(t):this.output.connect(this.panner.connect(e.input))},t.Amplitude.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Amplitude.prototype._audioProcess=function(t){for(var e=0;ea;a++)i=n[a],this.normalize?(r+=Math.max(Math.min(i/this.volMax,1),-1),s+=Math.max(Math.min(i/this.volMax,1),-1)*Math.max(Math.min(i/this.volMax,1),-1)):(r+=i,s+=i*i);var u=r/o,c=Math.sqrt(s/o);this.stereoVol[e]=Math.max(c,this.stereoVol[e]*this.smoothing),this.stereoAvg[e]=Math.max(u,this.stereoVol[e]*this.smoothing),this.volMax=Math.max(this.stereoVol[e],this.volMax)}var p=this,h=this.stereoVol.reduce(function(t,e,i){return p.stereoVolNorm[i-1]=Math.max(Math.min(p.stereoVol[i-1]/p.volMax,1),0),p.stereoVolNorm[i]=Math.max(Math.min(p.stereoVol[i]/p.volMax,1),0),t+e});this.volume=h/this.stereoVol.length,this.volNorm=Math.max(Math.min(this.volume/this.volMax,1),0)},t.Amplitude.prototype.getLevel=function(t){return"undefined"!=typeof t?this.normalize?this.stereoVolNorm[t]:this.stereoVol[t]:this.normalize?this.volNorm:this.volume},t.Amplitude.prototype.toggleNormalize=function(t){"boolean"==typeof t?this.normalize=t:this.normalize=!this.normalize},t.Amplitude.prototype.smooth=function(t){t>=0&&1>t?this.smoothing=t:console.log("Error: smoothing must be between 0 and 1")},t.Amplitude.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.input&&(this.input.disconnect(),delete this.input),this.output&&(this.output.disconnect(),delete this.output),delete this.processor}}(a);var f;f=function(){var e=a;t.FFT=function(t,i){this.input=this.analyser=e.audiocontext.createAnalyser(),Object.defineProperties(this,{bins:{get:function(){return this.analyser.fftSize/2},set:function(t){this.analyser.fftSize=2*t},configurable:!0,enumerable:!0},smoothing:{get:function(){return this.analyser.smoothingTimeConstant},set:function(t){this.analyser.smoothingTimeConstant=t},configurable:!0,enumerable:!0}}),this.smooth(t),this.bins=i||1024,e.fftMeter.connect(this.analyser),this.freqDomain=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomain=new Uint8Array(this.analyser.frequencyBinCount),this.bass=[20,140],this.lowMid=[140,400],this.mid=[400,2600],this.highMid=[2600,5200],this.treble=[5200,14e3],e.soundArray.push(this)},t.FFT.prototype.setInput=function(t){t?(t.output?t.output.connect(this.analyser):t.connect&&t.connect(this.analyser),e.fftMeter.disconnect()):e.fftMeter.connect(this.analyser)},t.FFT.prototype.waveform=function(){for(var e,i,n,s=0;si){var o=i;i=t,t=o}for(var r=Math.round(t/n*this.freqDomain.length),s=Math.round(i/n*this.freqDomain.length),a=0,u=0,c=r;s>=c;c++)a+=this.freqDomain[c],u+=1;var p=a/u;return p}throw"invalid input for getEnergy()"}var h=Math.round(t/n*this.freqDomain.length);return this.freqDomain[h]},t.FFT.prototype.getFreq=function(t,e){console.log("getFreq() is deprecated. Please use getEnergy() instead.");var i=this.getEnergy(t,e);return i},t.FFT.prototype.getCentroid=function(){for(var t=e.audiocontext.sampleRate/2,i=0,n=0,o=0;os;s++)o[r]=void 0!==o[r]?(o[r]+e[s])/2:e[s],s%n===n-1&&r++;return o},t.FFT.prototype.logAverages=function(t){for(var i=e.audiocontext.sampleRate/2,n=this.freqDomain,o=n.length,r=new Array(t.length),s=0,a=0;o>a;a++){var u=Math.round(a*i/this.freqDomain.length);u>t[s].hi&&s++,r[s]=void 0!==r[s]?(r[s]+n[a])/2:n[a]}return r},t.FFT.prototype.getOctaveBands=function(t,i){var t=t||3,i=i||15.625,n=[],o={lo:i/Math.pow(2,1/(2*t)),ctr:i,hi:i*Math.pow(2,1/(2*t))};n.push(o);for(var r=e.audiocontext.sampleRate/2;o.hie;e++){var n=e/(i-1)*2-1;this._curve[e]=t(n,e)}return this._shaper.curve=this._curve,this},Object.defineProperty(t.WaveShaper.prototype,"curve",{get:function(){return this._shaper.curve},set:function(t){this._curve=new Float32Array(t),this._shaper.curve=this._curve}}),Object.defineProperty(t.WaveShaper.prototype,"oversample",{get:function(){return this._shaper.oversample},set:function(t){if(-1===["none","2x","4x"].indexOf(t))throw new RangeError("Tone.WaveShaper: oversampling must be either 'none', '2x', or '4x'");this._shaper.oversample=t}}),t.WaveShaper.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.disconnect(),this._shaper=null,this._curve=null,this},t.WaveShaper}(n);var y;y=function(t){return t.TimeBase=function(e,i){if(!(this instanceof t.TimeBase))return new t.TimeBase(e,i);if(this._expr=this._noOp,e instanceof t.TimeBase)this.copy(e);else if(!this.isUndef(i)||this.isNumber(e)){i=this.defaultArg(i,this._defaultUnits);var n=this._primaryExpressions[i].method;this._expr=n.bind(this,e)}else this.isString(e)?this.set(e):this.isUndef(e)&&(this._expr=this._defaultExpr())},t.extend(t.TimeBase),t.TimeBase.prototype.set=function(t){return this._expr=this._parseExprString(t),this},t.TimeBase.prototype.clone=function(){var t=new this.constructor;return t.copy(this),t},t.TimeBase.prototype.copy=function(t){var e=t._expr();return this.set(e)},t.TimeBase.prototype._primaryExpressions={n:{regexp:/^(\d+)n/i,method:function(t){return t=parseInt(t),1===t?this._beatsToUnits(this._timeSignature()):this._beatsToUnits(4/t)}},t:{regexp:/^(\d+)t/i,method:function(t){return t=parseInt(t),this._beatsToUnits(8/(3*parseInt(t)))}},m:{regexp:/^(\d+)m/i,method:function(t){return this._beatsToUnits(parseInt(t)*this._timeSignature())}},i:{regexp:/^(\d+)i/i,method:function(t){return this._ticksToUnits(parseInt(t))}},hz:{regexp:/^(\d+(?:\.\d+)?)hz/i,method:function(t){return this._frequencyToUnits(parseFloat(t))}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n+=this._beatsToUnits(parseFloat(i)/4)),n}},s:{regexp:/^(\d+(?:\.\d+)?s)/,method:function(t){return this._secondsToUnits(parseFloat(t))}},samples:{regexp:/^(\d+)samples/,method:function(t){return parseInt(t)/this.context.sampleRate}},"default":{regexp:/^(\d+(?:\.\d+)?)/,method:function(t){return this._primaryExpressions[this._defaultUnits].method.call(this,t)}}},t.TimeBase.prototype._binaryExpressions={"+":{regexp:/^\+/,precedence:2,method:function(t,e){return t()+e()}},"-":{regexp:/^\-/,precedence:2,method:function(t,e){return t()-e()}},"*":{regexp:/^\*/,precedence:1,method:function(t,e){return t()*e()}},"/":{regexp:/^\//,precedence:1,method:function(t,e){return t()/e()}}},t.TimeBase.prototype._unaryExpressions={neg:{regexp:/^\-/,method:function(t){return-t()}}},t.TimeBase.prototype._syntaxGlue={"(":{regexp:/^\(/},")":{regexp:/^\)/}},t.TimeBase.prototype._tokenize=function(t){function e(t,e){for(var i=["_binaryExpressions","_unaryExpressions","_primaryExpressions","_syntaxGlue"],n=0;n0;){t=t.trim();var o=e(t,this);n.push(o),t=t.substr(o.value.length)}return{next:function(){return n[++i]},peek:function(){return n[i+1]}}},t.TimeBase.prototype._matchGroup=function(t,e,i){var n=!1;if(!this.isUndef(t))for(var o in e){var r=e[o];if(r.regexp.test(t.value)){if(this.isUndef(i))return r;if(r.precedence===i)return r}}return n},t.TimeBase.prototype._parseBinary=function(t,e){this.isUndef(e)&&(e=2);var i;i=0>e?this._parseUnary(t):this._parseBinary(t,e-1);for(var n=t.peek();n&&this._matchGroup(n,this._binaryExpressions,e);)n=t.next(),i=n.method.bind(this,i,this._parseBinary(t,e-1)),n=t.peek();return i},t.TimeBase.prototype._parseUnary=function(t){var e,i;e=t.peek();var n=this._matchGroup(e,this._unaryExpressions);return n?(e=t.next(),i=this._parseUnary(t),n.method.bind(this,i)):this._parsePrimary(t)},t.TimeBase.prototype._parsePrimary=function(t){var e,i;if(e=t.peek(),this.isUndef(e))throw new SyntaxError("Tone.TimeBase: Unexpected end of expression");if(this._matchGroup(e,this._primaryExpressions)){e=t.next();var n=e.value.match(e.regexp);return e.method.bind(this,n[1],n[2],n[3])}if(e&&"("===e.value){if(t.next(),i=this._parseBinary(t),e=t.next(),!e||")"!==e.value)throw new SyntaxError("Expected )");return i}throw new SyntaxError("Tone.TimeBase: Cannot process token "+e.value)},t.TimeBase.prototype._parseExprString=function(t){this.isString(t)||(t=t.toString());var e=this._tokenize(t),i=this._parseBinary(e);return i},t.TimeBase.prototype._noOp=function(){return 0},t.TimeBase.prototype._defaultExpr=function(){return this._noOp},t.TimeBase.prototype._defaultUnits="s",t.TimeBase.prototype._frequencyToUnits=function(t){return 1/t},t.TimeBase.prototype._beatsToUnits=function(e){return 60/t.Transport.bpm.value*e},t.TimeBase.prototype._secondsToUnits=function(t){return t},t.TimeBase.prototype._ticksToUnits=function(e){return e*(this._beatsToUnits(1)/t.Transport.PPQ)},t.TimeBase.prototype._timeSignature=function(){return t.Transport.timeSignature},t.TimeBase.prototype._pushExpr=function(e,i,n){return e instanceof t.TimeBase||(e=new this.constructor(e,n)),this._expr=this._binaryExpressions[i].method.bind(this,this._expr,e._expr),this},t.TimeBase.prototype.add=function(t,e){return this._pushExpr(t,"+",e)},t.TimeBase.prototype.sub=function(t,e){return this._pushExpr(t,"-",e)},t.TimeBase.prototype.mult=function(t,e){return this._pushExpr(t,"*",e)},t.TimeBase.prototype.div=function(t,e){return this._pushExpr(t,"/",e)},t.TimeBase.prototype.valueOf=function(){return this._expr()},t.TimeBase.prototype.dispose=function(){this._expr=null},t.TimeBase}(n);var v;v=function(t){return t.Time=function(e,i){return this instanceof t.Time?(this._plusNow=!1,void t.TimeBase.call(this,e,i)):new t.Time(e,i)},t.extend(t.Time,t.TimeBase),t.Time.prototype._unaryExpressions=Object.create(t.TimeBase.prototype._unaryExpressions),t.Time.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){return t.Transport.nextSubdivision(e())}},t.Time.prototype._unaryExpressions.now={regexp:/^\+/,method:function(t){return this._plusNow=!0,t()}},t.Time.prototype.quantize=function(t,e){return e=this.defaultArg(e,1),this._expr=function(t,e,i){t=t(),e=e.toSeconds();var n=Math.round(t/e),o=n*e,r=o-t;return t+r*i}.bind(this,this._expr,new this.constructor(t),e),this},t.Time.prototype.addNow=function(){return this._plusNow=!0,this},t.Time.prototype._defaultExpr=function(){return this._plusNow=!0,this._noOp},t.Time.prototype.copy=function(e){return t.TimeBase.prototype.copy.call(this,e),this._plusNow=e._plusNow,this},t.Time.prototype.toNotation=function(){var t=this.toSeconds(),e=["1m","2n","4n","8n","16n","32n","64n","128n"],i=this._toNotationHelper(t,e),n=["1m","2n","2t","4n","4t","8n","8t","16n","16t","32n","32t","64n","64t","128n"],o=this._toNotationHelper(t,n);return o.split("+").length1-s%1&&(s+=a),s=Math.floor(s),s>0){if(n+=1===s?e[o]:s.toString()+"*"+e[o],t-=s*r,i>t)break;n+=" + "}}return""===n&&(n="0"),n},t.Time.prototype._notationToUnits=function(t){for(var e=this._primaryExpressions,i=[e.n,e.t,e.m],n=0;n3&&(n=parseFloat(n).toFixed(3));var o=[i,e,n];return o.join(":")},t.Time.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Time.prototype.toSamples=function(){return this.toSeconds()*this.context.sampleRate},t.Time.prototype.toFrequency=function(){return 1/this.toSeconds()},t.Time.prototype.toSeconds=function(){return this.valueOf()},t.Time.prototype.toMilliseconds=function(){return 1e3*this.toSeconds()},t.Time.prototype.valueOf=function(){var t=this._expr();return t+(this._plusNow?this.now():0)},t.Time}(n);var g;g=function(t){t.Frequency=function(e,i){return this instanceof t.Frequency?void t.TimeBase.call(this,e,i):new t.Frequency(e,i)},t.extend(t.Frequency,t.TimeBase),t.Frequency.prototype._primaryExpressions=Object.create(t.TimeBase.prototype._primaryExpressions),t.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},t.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,i){var n=e[t.toLowerCase()],o=n+12*(parseInt(i)+1);return this.midiToFrequency(o)}},t.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=1;return t&&"0"!==t&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n*=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n*=this._beatsToUnits(parseFloat(i)/4)),n}},t.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){var i=t();return i*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},t.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var i=t(),n=[],o=0;or&&(o+=-12*r);var s=i[o%12];return s+r.toString()},t.Frequency.prototype.toSeconds=function(){return 1/this.valueOf()},t.Frequency.prototype.toFrequency=function(){return this.valueOf()},t.Frequency.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Frequency.prototype._frequencyToUnits=function(t){return t},t.Frequency.prototype._ticksToUnits=function(e){return 1/(60*e/(t.Transport.bpm.value*t.Transport.PPQ))},t.Frequency.prototype._beatsToUnits=function(e){return 1/t.TimeBase.prototype._beatsToUnits.call(this,e)},t.Frequency.prototype._secondsToUnits=function(t){return 1/t},t.Frequency.prototype._defaultUnits="hz";var e={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},i=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t.Frequency.A4=440,t.Frequency.prototype.midiToFrequency=function(e){return t.Frequency.A4*Math.pow(2,(e-69)/12)},t.Frequency.prototype.frequencyToMidi=function(e){return 69+12*Math.log(e/t.Frequency.A4)/Math.LN2},t.Frequency}(n);var _;_=function(t){return t.TransportTime=function(e,i){return this instanceof t.TransportTime?void t.Time.call(this,e,i):new t.TransportTime(e,i)},t.extend(t.TransportTime,t.Time),t.TransportTime.prototype._unaryExpressions=Object.create(t.Time.prototype._unaryExpressions),t.TransportTime.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){var i=this._secondsToTicks(e()),n=Math.ceil(t.Transport.ticks/i);return this._ticksToUnits(n*i)}},t.TransportTime.prototype._secondsToTicks=function(e){var i=this._beatsToUnits(1),n=e/i;return Math.round(n*t.Transport.PPQ)},t.TransportTime.prototype.valueOf=function(){var e=this._secondsToTicks(this._expr());return e+(this._plusNow?t.Transport.ticks:0)},t.TransportTime.prototype.toTicks=function(){return this.valueOf()},t.TransportTime.prototype.toSeconds=function(){var e=this._expr();return e+(this._plusNow?t.Transport.seconds:0)},t.TransportTime.prototype.toFrequency=function(){return 1/this.toSeconds()},t.TransportTime}(n);var T;T=function(t){return t.Type={Default:"number",Time:"time",Frequency:"frequency",TransportTime:"transportTime",Ticks:"ticks",NormalRange:"normalRange",AudioRange:"audioRange",Decibels:"db",Interval:"interval",BPM:"bpm",Positive:"positive",Cents:"cents",Degrees:"degrees",MIDI:"midi",BarsBeatsSixteenths:"barsBeatsSixteenths",Samples:"samples",Hertz:"hertz",Note:"note",Milliseconds:"milliseconds",Seconds:"seconds",Notation:"notation"},t.prototype.toSeconds=function(e){return this.isNumber(e)?e:this.isUndef(e)?this.now():this.isString(e)?new t.Time(e).toSeconds():e instanceof t.TimeBase?e.toSeconds():void 0},t.prototype.toFrequency=function(e){return this.isNumber(e)?e:this.isString(e)||this.isUndef(e)?new t.Frequency(e).valueOf():e instanceof t.TimeBase?e.toFrequency():void 0},t.prototype.toTicks=function(e){return this.isNumber(e)||this.isString(e)?new t.TransportTime(e).toTicks():this.isUndef(e)?t.Transport.ticks:e instanceof t.TimeBase?e.toTicks():void 0},t}(n,v,g,_);var b;b=function(t){"use strict";return t.Param=function(){var e=this.optionsObject(arguments,["param","units","convert"],t.Param.defaults);this._param=this.input=e.param,this.units=e.units,this.convert=e.convert,this.overridden=!1,this._lfo=null,this.isObject(e.lfo)?this.value=e.lfo:this.isUndef(e.value)||(this.value=e.value)},t.extend(t.Param),t.Param.defaults={units:t.Type.Default,convert:!0,param:void 0},Object.defineProperty(t.Param.prototype,"value",{get:function(){return this._toUnits(this._param.value)},set:function(e){if(this.isObject(e)){if(this.isUndef(t.LFO))throw new Error("Include 'Tone.LFO' to use an LFO as a Param value.");this._lfo&&this._lfo.dispose(),this._lfo=new t.LFO(e).start(),this._lfo.connect(this.input)}else{var i=this._fromUnits(e);this._param.cancelScheduledValues(0),this._param.value=i}}}),t.Param.prototype._fromUnits=function(e){if(!this.convert&&!this.isUndef(this.convert))return e;switch(this.units){case t.Type.Time:return this.toSeconds(e);case t.Type.Frequency:return this.toFrequency(e);case t.Type.Decibels:return this.dbToGain(e);case t.Type.NormalRange:return Math.min(Math.max(e,0),1);case t.Type.AudioRange:return Math.min(Math.max(e,-1),1);case t.Type.Positive:return Math.max(e,0);default:return e}},t.Param.prototype._toUnits=function(e){if(!this.convert&&!this.isUndef(this.convert))return e;switch(this.units){case t.Type.Decibels:return this.gainToDb(e);default:return e}},t.Param.prototype._minOutput=1e-5,t.Param.prototype.setValueAtTime=function(t,e){return t=this._fromUnits(t),e=this.toSeconds(e),e<=this.now()+this.blockTime?this._param.value=t:this._param.setValueAtTime(t,e),this},t.Param.prototype.setRampPoint=function(t){t=this.defaultArg(t,this.now());var e=this._param.value;return 0===e&&(e=this._minOutput),this._param.setValueAtTime(e,t),this},t.Param.prototype.linearRampToValueAtTime=function(t,e){return t=this._fromUnits(t),this._param.linearRampToValueAtTime(t,this.toSeconds(e)),this},t.Param.prototype.exponentialRampToValueAtTime=function(t,e){return t=this._fromUnits(t),t=Math.max(this._minOutput,t),this._param.exponentialRampToValueAtTime(t,this.toSeconds(e)),this},t.Param.prototype.exponentialRampToValue=function(t,e,i){return i=this.toSeconds(i),this.setRampPoint(i),this.exponentialRampToValueAtTime(t,i+this.toSeconds(e)),this},t.Param.prototype.linearRampToValue=function(t,e,i){return i=this.toSeconds(i),this.setRampPoint(i),this.linearRampToValueAtTime(t,i+this.toSeconds(e)),this},t.Param.prototype.setTargetAtTime=function(t,e,i){return t=this._fromUnits(t),t=Math.max(this._minOutput,t),i=Math.max(this._minOutput,i),this._param.setTargetAtTime(t,this.toSeconds(e),i),this},t.Param.prototype.setValueCurveAtTime=function(t,e,i){for(var n=0;n1&&(this.input=new Array(e)),1===i?this.output=new t.Gain:i>1&&(this.output=new Array(e))},t.Gain}(n,b);var S;S=function(t){"use strict";return t.Signal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this.output=this._gain=this.context.createGain(),e.param=this._gain.gain,t.Param.call(this,e),this.input=this._param=this._gain.gain,this.context.getConstant(1).chain(this._gain)},t.extend(t.Signal,t.Param),t.Signal.defaults={value:0,units:t.Type.Default,convert:!0},t.Signal.prototype.connect=t.SignalBase.prototype.connect,t.Signal.prototype.dispose=function(){return t.Param.prototype.dispose.call(this),this._param=null,this._gain.disconnect(),this._gain=null,this},t.Signal}(n,m,T,b);var w;w=function(t){"use strict";return t.Add=function(e){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new t.Gain,this._param=this.input[1]=new t.Signal(e),this._param.connect(this._sum)},t.extend(t.Add,t.Signal),t.Add.prototype.dispose=function(){return t.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},t.Add}(n,S);var A;A=function(t){"use strict";return t.Multiply=function(e){this.createInsOuts(2,0),this._mult=this.input[0]=this.output=new t.Gain,this._param=this.input[1]=this.output.gain,this._param.value=this.defaultArg(e,0)},t.extend(t.Multiply,t.Signal),t.Multiply.prototype.dispose=function(){return t.prototype.dispose.call(this),this._mult.dispose(),this._mult=null,
+this._param=null,this},t.Multiply}(n,S);var P;P=function(t){"use strict";return t.Scale=function(e,i){this._outputMin=this.defaultArg(e,0),this._outputMax=this.defaultArg(i,1),this._scale=this.input=new t.Multiply(1),this._add=this.output=new t.Add(0),this._scale.connect(this._add),this._setRange()},t.extend(t.Scale,t.SignalBase),Object.defineProperty(t.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(t.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),t.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},t.Scale.prototype.dispose=function(){return t.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},t.Scale}(n,w,A);var k;k=function(){var e=S,i=w,n=A,o=P;t.Signal=function(t){var i=new e(t);return i},e.prototype.fade=e.prototype.linearRampToValueAtTime,n.prototype.fade=e.prototype.fade,i.prototype.fade=e.prototype.fade,o.prototype.fade=e.prototype.fade,e.prototype.setInput=function(t){t.connect(this)},n.prototype.setInput=e.prototype.setInput,i.prototype.setInput=e.prototype.setInput,o.prototype.setInput=e.prototype.setInput,e.prototype.add=function(t){var e=new i(t);return this.connect(e),e},n.prototype.add=e.prototype.add,i.prototype.add=e.prototype.add,o.prototype.add=e.prototype.add,e.prototype.mult=function(t){var e=new n(t);return this.connect(e),e},n.prototype.mult=e.prototype.mult,i.prototype.mult=e.prototype.mult,o.prototype.mult=e.prototype.mult,e.prototype.scale=function(e,i,n,r){var s,a;4===arguments.length?(s=t.prototype.map(n,e,i,0,1)-.5,a=t.prototype.map(r,e,i,0,1)-.5):(s=arguments[0],a=arguments[1]);var u=new o(s,a);return this.connect(u),u},n.prototype.scale=e.prototype.scale,i.prototype.scale=e.prototype.scale,o.prototype.scale=e.prototype.scale}(S,w,A,P);var O;O=function(){var e=a,i=w,n=A,o=P;t.Oscillator=function(i,n){if("string"==typeof i){var o=n;n=i,i=o}if("number"==typeof n){var o=n;n=i,i=o}this.started=!1,this.phaseAmount=void 0,this.oscillator=e.audiocontext.createOscillator(),this.f=i||440,this.oscillator.type=n||"sine",this.oscillator.frequency.setValueAtTime(this.f,e.audiocontext.currentTime),this.output=e.audiocontext.createGain(),this._freqMods=[],this.output.gain.value=.5,this.output.gain.setValueAtTime(.5,e.audiocontext.currentTime),this.oscillator.connect(this.output),this.panPosition=0,this.connection=e.input,this.panner=new t.Panner(this.output,this.connection,1),this.mathOps=[this.output],e.soundArray.push(this)},t.Oscillator.prototype.start=function(t,i){if(this.started){var n=e.audiocontext.currentTime;this.stop(n)}if(!this.started){var o=i||this.f,r=this.oscillator.type;this.oscillator&&(this.oscillator.disconnect(),delete this.oscillator),this.oscillator=e.audiocontext.createOscillator(),this.oscillator.frequency.value=Math.abs(o),this.oscillator.type=r,this.oscillator.connect(this.output),t=t||0,this.oscillator.start(t+e.audiocontext.currentTime),this.freqNode=this.oscillator.frequency;for(var s in this._freqMods)"undefined"!=typeof this._freqMods[s].connect&&this._freqMods[s].connect(this.oscillator.frequency);this.started=!0}},t.Oscillator.prototype.stop=function(t){if(this.started){var i=t||0,n=e.audiocontext.currentTime;this.oscillator.stop(i+n),this.started=!1}},t.Oscillator.prototype.amp=function(t,i,n){var o=this;if("number"==typeof t){var i=i||0,n=n||0,r=e.audiocontext.currentTime;this.output.gain.linearRampToValueAtTime(t,r+n+i)}else{if(!t)return this.output.gain;t.connect(o.output.gain)}},t.Oscillator.prototype.fade=t.Oscillator.prototype.amp,t.Oscillator.prototype.getAmp=function(){return this.output.gain.value},t.Oscillator.prototype.freq=function(t,i,n){if("number"!=typeof t||isNaN(t)){if(!t)return this.oscillator.frequency;t.output&&(t=t.output),t.connect(this.oscillator.frequency),this._freqMods.push(t)}else{this.f=t;var o=e.audiocontext.currentTime,i=i||0,n=n||0;0===i?this.oscillator.frequency.setValueAtTime(t,n+o):t>0?this.oscillator.frequency.exponentialRampToValueAtTime(t,n+i+o):this.oscillator.frequency.linearRampToValueAtTime(t,n+i+o),this.phaseAmount&&this.phase(this.phaseAmount)}},t.Oscillator.prototype.getFreq=function(){return this.oscillator.frequency.value},t.Oscillator.prototype.setType=function(t){this.oscillator.type=t},t.Oscillator.prototype.getType=function(){return this.oscillator.type},t.Oscillator.prototype.connect=function(t){t?t.hasOwnProperty("input")?(this.panner.connect(t.input),this.connection=t.input):(this.panner.connect(t),this.connection=t):this.panner.connect(e.input)},t.Oscillator.prototype.disconnect=function(){this.output&&this.output.disconnect(),this.panner&&(this.panner.disconnect(),this.output&&this.output.connect(this.panner)),this.oscMods=[]},t.Oscillator.prototype.pan=function(t,e){this.panPosition=t,this.panner.pan(t,e)},t.Oscillator.prototype.getPan=function(){return this.panPosition},t.Oscillator.prototype.dispose=function(){var t=e.soundArray.indexOf(this);if(e.soundArray.splice(t,1),this.oscillator){var i=e.audiocontext.currentTime;this.stop(i),this.disconnect(),this.panner=null,this.oscillator=null}this.osc2&&this.osc2.dispose()},t.Oscillator.prototype.phase=function(i){var n=t.prototype.map(i,0,1,0,1/this.f),o=e.audiocontext.currentTime;this.phaseAmount=i,this.dNode||(this.dNode=e.audiocontext.createDelay(),this.oscillator.disconnect(),this.oscillator.connect(this.dNode),this.dNode.connect(this.output)),this.dNode.delayTime.setValueAtTime(n,o)};var r=function(t,e,i,n,o){var r=t.oscillator;for(var s in t.mathOps)t.mathOps[s]instanceof o&&(r.disconnect(),t.mathOps[s].dispose(),i=s,i0&&(r=t.mathOps[s-1]),r.disconnect(),r.connect(e),e.connect(n),t.mathOps[i]=e,t};t.Oscillator.prototype.add=function(t){var e=new i(t),n=this.mathOps.length-1,o=this.output;return r(this,e,n,o,i)},t.Oscillator.prototype.mult=function(t){var e=new n(t),i=this.mathOps.length-1,o=this.output;return r(this,e,i,o,n)},t.Oscillator.prototype.scale=function(e,i,n,s){var a,u;4===arguments.length?(a=t.prototype.map(n,e,i,0,1)-.5,u=t.prototype.map(s,e,i,0,1)-.5):(a=arguments[0],u=arguments[1]);var c=new o(a,u),p=this.mathOps.length-1,h=this.output;return r(this,c,p,h,o)},t.SinOsc=function(e){t.Oscillator.call(this,e,"sine")},t.SinOsc.prototype=Object.create(t.Oscillator.prototype),t.TriOsc=function(e){t.Oscillator.call(this,e,"triangle")},t.TriOsc.prototype=Object.create(t.Oscillator.prototype),t.SawOsc=function(e){t.Oscillator.call(this,e,"sawtooth")},t.SawOsc.prototype=Object.create(t.Oscillator.prototype),t.SqrOsc=function(e){t.Oscillator.call(this,e,"square")},t.SqrOsc.prototype=Object.create(t.Oscillator.prototype)}(a,w,A,P);var F;F=function(t){"use strict";return t.Timeline=function(){var e=this.optionsObject(arguments,["memory"],t.Timeline.defaults);this._timeline=[],this._toRemove=[],this._iterating=!1,this.memory=e.memory},t.extend(t.Timeline),t.Timeline.defaults={memory:1/0},Object.defineProperty(t.Timeline.prototype,"length",{get:function(){return this._timeline.length}}),t.Timeline.prototype.add=function(t){if(this.isUndef(t.time))throw new Error("Tone.Timeline: events must have a time attribute");if(this._timeline.length){var e=this._search(t.time);this._timeline.splice(e+1,0,t)}else this._timeline.push(t);if(this.length>this.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},t.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},t.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},t.Timeline.prototype.peek=function(){return this._timeline[0]},t.Timeline.prototype.shift=function(){return this._timeline.shift()},t.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+10&&this._timeline[e-1].time=0?this._timeline[i-1]:null},t.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},t.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);e>=0&&(this._timeline=this._timeline.slice(e+1))}return this},t.Timeline.prototype._search=function(t){var e=0,i=this._timeline.length,n=i;if(i>0&&this._timeline[i-1].time<=t)return i-1;for(;n>e;){var o=Math.floor(e+(n-e)/2),r=this._timeline[o],s=this._timeline[o+1];if(r.time===t){for(var a=o;at)return o;r.time>t?n=o:r.time=n;n++)t(this._timeline[n]);if(this._iterating=!1,this._toRemove.length>0){for(var o=0;o=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},t.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e(i)},0,i),this},t.Timeline.prototype.dispose=function(){t.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},t.Timeline}(n);var q;q=function(t){"use strict";return t.TimelineSignal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this._events=new t.Timeline(10),t.Signal.apply(this,e),e.param=this._param,t.Param.call(this,e),this._initial=this._fromUnits(this._param.value)},t.extend(t.TimelineSignal,t.Param),t.TimelineSignal.Type={Linear:"linear",Exponential:"exponential",Target:"target",Curve:"curve",Set:"set"},Object.defineProperty(t.TimelineSignal.prototype,"value",{get:function(){var t=this.now(),e=this.getValueAtTime(t);return this._toUnits(e)},set:function(t){var e=this._fromUnits(t);this._initial=e,this.cancelScheduledValues(),this._param.value=e}}),t.TimelineSignal.prototype.setValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Set,value:e,time:i}),this._param.setValueAtTime(e,i),this},t.TimelineSignal.prototype.linearRampToValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Linear,value:e,time:i}),this._param.linearRampToValueAtTime(e,i),this},t.TimelineSignal.prototype.exponentialRampToValueAtTime=function(e,i){i=this.toSeconds(i);var n=this._searchBefore(i);n&&0===n.value&&this.setValueAtTime(this._minOutput,n.time),e=this._fromUnits(e);var o=Math.max(e,this._minOutput);return this._events.add({type:t.TimelineSignal.Type.Exponential,value:o,time:i}),ee)this.cancelScheduledValues(e),this.linearRampToValueAtTime(i,e);else{var o=this._searchAfter(e);o&&(this.cancelScheduledValues(e),o.type===t.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(i,e):o.type===t.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(i,e)),this.setValueAtTime(i,e)}return this},t.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.linearRampToValueAtTime(t,i),this},t.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,i),this},t.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},t.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},t.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var i=this._searchAfter(e),n=this._searchBefore(e),o=this._initial;if(null===n)o=this._initial;else if(n.type===t.TimelineSignal.Type.Target){var r,s=this._events.getBefore(n.time);r=null===s?this._initial:s.value,o=this._exponentialApproach(n.time,r,n.value,n.constant,e)}else o=n.type===t.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,e):null===i?n.value:i.type===t.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,i.time,i.value,e):i.type===t.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,i.time,i.value,e):n.value;return o},t.TimelineSignal.prototype.connect=t.SignalBase.prototype.connect,t.TimelineSignal.prototype._exponentialApproach=function(t,e,i,n,o){return i+(e-i)*Math.exp(-(o-t)/n)},t.TimelineSignal.prototype._linearInterpolate=function(t,e,i,n,o){return e+(n-e)*((o-t)/(i-t))},t.TimelineSignal.prototype._exponentialInterpolate=function(t,e,i,n,o){return e=Math.max(this._minOutput,e),e*Math.pow(n/e,(o-t)/(i-t))},t.TimelineSignal.prototype._curveInterpolate=function(t,e,i,n){var o=e.length;if(n>=t+i)return e[o-1];if(t>=n)return e[0];var r=(n-t)/i,s=Math.floor((o-1)*r),a=Math.ceil((o-1)*r),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,r*(o-1))},t.TimelineSignal.prototype.dispose=function(){t.Signal.prototype.dispose.call(this),t.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},t.TimelineSignal}(n,S);var M;M=function(){var e=a,i=w,n=A,o=P,r=q;t.Envelope=function(t,i,n,o,s,a){this.aTime=t||.1,this.aLevel=i||1,this.dTime=n||.5,this.dLevel=o||0,this.rTime=s||0,this.rLevel=a||0,this._rampHighPercentage=.98,this._rampLowPercentage=.02,this.output=e.audiocontext.createGain(),this.control=new r,this._init(),this.control.connect(this.output),this.connection=null,this.mathOps=[this.control],this.isExponential=!1,this.sourceToClear=null,this.wasTriggered=!1,e.soundArray.push(this)},t.Envelope.prototype._init=function(){var t=e.audiocontext.currentTime,i=t;this.control.setTargetAtTime(1e-5,i,.001),this._setRampAD(this.aTime,this.dTime)},t.Envelope.prototype.set=function(t,e,i,n,o,r){this.aTime=t,this.aLevel=e,this.dTime=i||0,this.dLevel=n||0,this.rTime=o||0,this.rLevel=r||0,this._setRampAD(t,i)},t.Envelope.prototype.setADSR=function(t,e,i,n){this.aTime=t,this.dTime=e||0,this.sPercent=i||0,this.dLevel="undefined"!=typeof i?i*(this.aLevel-this.rLevel)+this.rLevel:0,this.rTime=n||0,this._setRampAD(t,e)},t.Envelope.prototype.setRange=function(t,e){this.aLevel=t||1,this.rLevel=e||0},t.Envelope.prototype._setRampAD=function(t,e){this._rampAttackTime=this.checkExpInput(t),this._rampDecayTime=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=t/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=e/this.checkExpInput(i)},t.Envelope.prototype.setRampPercentages=function(t,e){this._rampHighPercentage=this.checkExpInput(t),this._rampLowPercentage=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=this._rampAttackTime/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=this._rampDecayTime/this.checkExpInput(i)},t.Envelope.prototype.setInput=function(){for(var t=0;t=t&&(t=1e-8),t},t.Envelope.prototype.play=function(t,e,i){var n=e||0,i=i||0;t&&this.connection!==t&&this.connect(t),this.triggerAttack(t,n),this.triggerRelease(t,n+this.aTime+this.dTime+i)},t.Envelope.prototype.triggerAttack=function(t,i){var n=e.audiocontext.currentTime,o=i||0,r=n+o;this.lastAttack=r,this.wasTriggered=!0,t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.aTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.aLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),r+=this.dTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.dLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r))},t.Envelope.prototype.triggerRelease=function(t,i){if(this.wasTriggered){var n=e.audiocontext.currentTime,o=i||0,r=n+o;t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.rTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.rLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),this.wasTriggered=!1}},t.Envelope.prototype.ramp=function(t,i,n,o){var r=e.audiocontext.currentTime,s=i||0,a=r+s,u=this.checkExpInput(n),c="undefined"!=typeof o?this.checkExpInput(o):void 0;t&&this.connection!==t&&this.connect(t);var p=this.checkExpInput(this.control.getValueAtTime(a));u>p?(this.control.setTargetAtTime(u,a,this._rampAttackTC),a+=this._rampAttackTime):p>u&&(this.control.setTargetAtTime(u,a,this._rampDecayTC),a+=this._rampDecayTime),void 0!==c&&(c>u?this.control.setTargetAtTime(c,a,this._rampAttackTC):u>c&&this.control.setTargetAtTime(c,a,this._rampDecayTC))},t.Envelope.prototype.connect=function(i){this.connection=i,(i instanceof t.Oscillator||i instanceof t.SoundFile||i instanceof t.AudioIn||i instanceof t.Reverb||i instanceof t.Noise||i instanceof t.Filter||i instanceof t.Delay)&&(i=i.output.gain),i instanceof AudioParam&&i.setValueAtTime(0,e.audiocontext.currentTime),i instanceof t.Signal&&i.setValue(0),this.output.connect(i)},t.Envelope.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Envelope.prototype.add=function(e){var n=new i(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,n,o,r,i)},t.Envelope.prototype.mult=function(e){var i=new n(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,o,r,n)},t.Envelope.prototype.scale=function(e,i,n,r){var s=new o(e,i,n,r),a=this.mathOps.length,u=this.output;return t.prototype._mathChain(this,s,a,u,o)},t.Envelope.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.disconnect(),this.control&&(this.control.dispose(),this.control=null);for(var i=1;io;o++)n[o]=1;var r=t.createBufferSource();return r.buffer=e,r.loop=!0,r}var i=a;t.Pulse=function(n,o){t.Oscillator.call(this,n,"sawtooth"),this.w=o||0,this.osc2=new t.SawOsc(n),this.dNode=i.audiocontext.createDelay(),this.dcOffset=e(),this.dcGain=i.audiocontext.createGain(),this.dcOffset.connect(this.dcGain),this.dcGain.connect(this.output),this.f=n||440;var r=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=r,this.dcGain.gain.value=1.7*(.5-this.w),this.osc2.disconnect(),this.osc2.panner.disconnect(),this.osc2.amp(-1),this.osc2.output.connect(this.dNode),this.dNode.connect(this.output),this.output.gain.value=1,this.output.connect(this.panner)},t.Pulse.prototype=Object.create(t.Oscillator.prototype),t.Pulse.prototype.width=function(e){if("number"==typeof e){if(1>=e&&e>=0){this.w=e;var i=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=i}this.dcGain.gain.value=1.7*(.5-this.w)}else{e.connect(this.dNode.delayTime);var n=new t.SignalAdd(-.5);n.setInput(e),n=n.mult(-1),n=n.mult(1.7),n.connect(this.dcGain.gain)}},t.Pulse.prototype.start=function(t,n){var o=i.audiocontext.currentTime,r=n||0;if(!this.started){var s=t||this.f,a=this.oscillator.type;this.oscillator=i.audiocontext.createOscillator(),this.oscillator.frequency.setValueAtTime(s,o),this.oscillator.type=a,this.oscillator.connect(this.output),this.oscillator.start(r+o),this.osc2.oscillator=i.audiocontext.createOscillator(),this.osc2.oscillator.frequency.setValueAtTime(s,r+o),this.osc2.oscillator.type=a,this.osc2.oscillator.connect(this.osc2.output),this.osc2.start(r+o),this.freqNode=[this.oscillator.frequency,this.osc2.oscillator.frequency],this.dcOffset=e(),this.dcOffset.connect(this.dcGain),this.dcOffset.start(r+o),void 0!==this.mods&&void 0!==this.mods.frequency&&(this.mods.frequency.connect(this.freqNode[0]),this.mods.frequency.connect(this.freqNode[1])),this.started=!0,this.osc2.started=!0}},t.Pulse.prototype.stop=function(t){if(this.started){var e=t||0,n=i.audiocontext.currentTime;this.oscillator.stop(e+n),this.osc2.oscillator&&this.osc2.oscillator.stop(e+n),this.dcOffset.stop(e+n),this.started=!1,this.osc2.started=!1}},t.Pulse.prototype.freq=function(t,e,n){if("number"==typeof t){this.f=t;var o=i.audiocontext.currentTime,e=e||0,n=n||0,r=this.oscillator.frequency.value;this.oscillator.frequency.cancelScheduledValues(o),this.oscillator.frequency.setValueAtTime(r,o+n),this.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.osc2.oscillator.frequency.cancelScheduledValues(o),this.osc2.oscillator.frequency.setValueAtTime(r,o+n),this.osc2.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.freqMod&&(this.freqMod.output.disconnect(),this.freqMod=null)}else t.output&&(t.output.disconnect(),t.output.connect(this.oscillator.frequency),t.output.connect(this.osc2.oscillator.frequency),this.freqMod=t)}}(a,O);var V;V=function(){var e=a;t.Noise=function(e){var r;t.Oscillator.call(this),delete this.f,delete this.freq,delete this.oscillator,r="brown"===e?o:"pink"===e?n:i,this.buffer=r},t.Noise.prototype=Object.create(t.Oscillator.prototype);var i=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0;t>o;o++)n[o]=2*Math.random()-1;return i.type="white",i}(),n=function(){var t,i,n,o,r,s,a,u=2*e.audiocontext.sampleRate,c=e.audiocontext.createBuffer(1,u,e.audiocontext.sampleRate),p=c.getChannelData(0);t=i=n=o=r=s=a=0;for(var h=0;u>h;h++){var l=2*Math.random()-1;t=.99886*t+.0555179*l,i=.99332*i+.0750759*l,n=.969*n+.153852*l,o=.8665*o+.3104856*l,r=.55*r+.5329522*l,s=-.7616*s-.016898*l,p[h]=t+i+n+o+r+s+a+.5362*l,p[h]*=.11,a=.115926*l}return c.type="pink",c}(),o=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0,r=0;t>r;r++){var s=2*Math.random()-1;n[r]=(o+.02*s)/1.02,o=n[r],n[r]*=3.5}return i.type="brown",i}();t.Noise.prototype.setType=function(t){switch(t){case"white":this.buffer=i;break;case"pink":this.buffer=n;break;case"brown":this.buffer=o;break;default:this.buffer=i}if(this.started){var r=e.audiocontext.currentTime;this.stop(r),this.start(r+.01)}},t.Noise.prototype.getType=function(){return this.buffer.type},t.Noise.prototype.start=function(){this.started&&this.stop(),this.noise=e.audiocontext.createBufferSource(),this.noise.buffer=this.buffer,this.noise.loop=!0,this.noise.connect(this.output);var t=e.audiocontext.currentTime;this.noise.start(t),this.started=!0},t.Noise.prototype.stop=function(){var t=e.audiocontext.currentTime;this.noise&&(this.noise.stop(t),this.started=!1)},t.Noise.prototype.dispose=function(){var t=e.audiocontext.currentTime,i=e.soundArray.indexOf(this);e.soundArray.splice(i,1),this.noise&&(this.noise.disconnect(),this.stop(t)),this.output&&this.output.disconnect(),this.panner&&this.panner.disconnect(),this.output=null,this.panner=null,this.buffer=null,this.noise=null}}(a);var R;R=function(){var e=a;e.inputSources=[],t.AudioIn=function(i){this.input=e.audiocontext.createGain(),this.output=e.audiocontext.createGain(),this.stream=null,this.mediaStream=null,this.currentSource=null,this.enabled=!1,this.amplitude=new t.Amplitude,this.output.connect(this.amplitude.input),window.MediaStreamTrack&&window.navigator.mediaDevices&&window.navigator.mediaDevices.getUserMedia||(i?i():window.alert("This browser does not support MediaStreamTrack and mediaDevices")),e.soundArray.push(this)},t.AudioIn.prototype.start=function(t,i){var n=this;this.stream&&this.stop();var o=e.inputSources[n.currentSource],r={audio:{sampleRate:e.audiocontext.sampleRate,echoCancellation:!1}};e.inputSources[this.currentSource]&&(r.audio.deviceId=o.deviceId),window.navigator.mediaDevices.getUserMedia(r).then(function(i){n.stream=i,n.enabled=!0,n.mediaStream=e.audiocontext.createMediaStreamSource(i),n.mediaStream.connect(n.output),n.amplitude.setInput(n.output),t&&t()})["catch"](function(t){i?i(t):console.error(t)})},t.AudioIn.prototype.stop=function(){this.stream&&(this.stream.getTracks().forEach(function(t){t.stop()}),this.mediaStream.disconnect(),delete this.mediaStream,delete this.stream)},t.AudioIn.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):t.hasOwnProperty("analyser")?this.output.connect(t.analyser):this.output.connect(t):this.output.connect(e.input)},t.AudioIn.prototype.disconnect=function(){this.output&&(this.output.disconnect(),this.output.connect(this.amplitude.input))},t.AudioIn.prototype.getLevel=function(t){return t&&(this.amplitude.smoothing=t),this.amplitude.getLevel()},t.AudioIn.prototype.amp=function(t,i){if(i){var n=i||0,o=this.output.gain.value;this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(o,e.audiocontext.currentTime),this.output.gain.linearRampToValueAtTime(t,n+e.audiocontext.currentTime)}else this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(t,e.audiocontext.currentTime)},t.AudioIn.prototype.getSources=function(t,i){return new Promise(function(n,o){window.navigator.mediaDevices.enumerateDevices().then(function(i){e.inputSources=i.filter(function(t){return"audioinput"===t.kind}),n(e.inputSources),t&&t(e.inputSources)})["catch"](function(t){o(t),i?i(t):console.error("This browser does not support MediaStreamTrack.getSources()")})})},t.AudioIn.prototype.setSource=function(t){e.inputSources.length>0&&t=t?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}(n,S,A);var B;B=function(t){"use strict";return t.GreaterThan=function(e){this.createInsOuts(2,0),this._param=this.input[0]=new t.Subtract(e),this.input[1]=this._param.input[1],this._gtz=this.output=new t.GreaterThanZero,this._param.connect(this._gtz)},t.extend(t.GreaterThan,t.Signal),t.GreaterThan.prototype.dispose=function(){return t.prototype.dispose.call(this),this._param.dispose(),this._param=null,this._gtz.dispose(),this._gtz=null,this},t.GreaterThan}(n,N,D);var U;U=function(t){"use strict";return t.Abs=function(){this._abs=this.input=this.output=new t.WaveShaper(function(t){return 0===t?0:Math.abs(t)},127)},t.extend(t.Abs,t.SignalBase),t.Abs.prototype.dispose=function(){return t.prototype.dispose.call(this),this._abs.dispose(),this._abs=null,this},t.Abs}(n,m);var I;I=function(t){"use strict";return t.Modulo=function(e){this.createInsOuts(1,0),this._shaper=new t.WaveShaper(Math.pow(2,16)),this._multiply=new t.Multiply,this._subtract=this.output=new t.Subtract,this._modSignal=new t.Signal(e),this.input.fan(this._shaper,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(e)},t.extend(t.Modulo,t.SignalBase),t.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){var i=Math.floor((e+1e-4)/t);return i;
+})},Object.defineProperty(t.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),t.Modulo.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},t.Modulo}(n,m,A);var G;G=function(t){"use strict";return t.Pow=function(e){this._exp=this.defaultArg(e,1),this._expScaler=this.input=this.output=new t.WaveShaper(this._expFunc(this._exp),8192)},t.extend(t.Pow,t.SignalBase),Object.defineProperty(t.Pow.prototype,"value",{get:function(){return this._exp},set:function(t){this._exp=t,this._expScaler.setMap(this._expFunc(this._exp))}}),t.Pow.prototype._expFunc=function(t){return function(e){return Math.pow(Math.abs(e),t)}},t.Pow.prototype.dispose=function(){return t.prototype.dispose.call(this),this._expScaler.dispose(),this._expScaler=null,this},t.Pow}(n);var L;L=function(t){"use strict";return t.AudioToGain=function(){this._norm=this.input=this.output=new t.WaveShaper(function(t){return(t+1)/2})},t.extend(t.AudioToGain,t.SignalBase),t.AudioToGain.prototype.dispose=function(){return t.prototype.dispose.call(this),this._norm.dispose(),this._norm=null,this},t.AudioToGain}(n,m);var j;j=function(t){"use strict";function e(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),i._eval(e[1]).connect(n,0,1),n}function i(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),n}function n(t){return t?parseFloat(t):void 0}function o(t){return t&&t.args?parseFloat(t.args):void 0}return t.Expr=function(){var t=this._replacements(Array.prototype.slice.call(arguments)),e=this._parseInputs(t);this._nodes=[],this.input=new Array(e);for(var i=0;e>i;i++)this.input[i]=this.context.createGain();var n,o=this._parseTree(t);try{n=this._eval(o)}catch(r){throw this._disposeNodes(),new Error("Tone.Expr: Could evaluate expression: "+t)}this.output=n},t.extend(t.Expr,t.SignalBase),t.Expr._Expressions={value:{signal:{regexp:/^\d+\.\d+|^\d+/,method:function(e){var i=new t.Signal(n(e));return i}},input:{regexp:/^\$\d/,method:function(t,e){return e.input[n(t.substr(1))]}}},glue:{"(":{regexp:/^\(/},")":{regexp:/^\)/},",":{regexp:/^,/}},func:{abs:{regexp:/^abs/,method:i.bind(this,t.Abs)},mod:{regexp:/^mod/,method:function(e,i){var n=o(e[1]),r=new t.Modulo(n);return i._eval(e[0]).connect(r),r}},pow:{regexp:/^pow/,method:function(e,i){var n=o(e[1]),r=new t.Pow(n);return i._eval(e[0]).connect(r),r}},a2g:{regexp:/^a2g/,method:function(e,i){var n=new t.AudioToGain;return i._eval(e[0]).connect(n),n}}},binary:{"+":{regexp:/^\+/,precedence:1,method:e.bind(this,t.Add)},"-":{regexp:/^\-/,precedence:1,method:function(n,o){return 1===n.length?i(t.Negate,n,o):e(t.Subtract,n,o)}},"*":{regexp:/^\*/,precedence:0,method:e.bind(this,t.Multiply)}},unary:{"-":{regexp:/^\-/,method:i.bind(this,t.Negate)},"!":{regexp:/^\!/,method:i.bind(this,t.NOT)}}},t.Expr.prototype._parseInputs=function(t){var e=t.match(/\$\d/g),i=0;if(null!==e)for(var n=0;n0;){e=e.trim();var r=i(e);o.push(r),e=e.substr(r.value.length)}return{next:function(){return o[++n]},peek:function(){return o[n+1]}}},t.Expr.prototype._parseTree=function(e){function i(t,e){return!p(t)&&"glue"===t.type&&t.value===e}function n(e,i,n){var o=!1,r=t.Expr._Expressions[i];if(!p(e))for(var s in r){var a=r[s];if(a.regexp.test(e.value)){if(p(n))return!0;if(a.precedence===n)return!0}}return o}function o(t){p(t)&&(t=5);var e;e=0>t?r():o(t-1);for(var i=c.peek();n(i,"binary",t);)i=c.next(),e={operator:i.value,method:i.method,args:[e,o(t-1)]},i=c.peek();return e}function r(){var t,e;return t=c.peek(),n(t,"unary")?(t=c.next(),e=r(),{operator:t.value,method:t.method,args:[e]}):s()}function s(){var t,e;if(t=c.peek(),p(t))throw new SyntaxError("Tone.Expr: Unexpected termination of expression");if("func"===t.type)return t=c.next(),a(t);if("value"===t.type)return t=c.next(),{method:t.method,args:t.value};if(i(t,"(")){if(c.next(),e=o(),t=c.next(),!i(t,")"))throw new SyntaxError("Expected )");return e}throw new SyntaxError("Tone.Expr: Parse error, cannot process token "+t.value)}function a(t){var e,n=[];if(e=c.next(),!i(e,"("))throw new SyntaxError('Tone.Expr: Expected ( in a function call "'+t.value+'"');if(e=c.peek(),i(e,")")||(n=u()),e=c.next(),!i(e,")"))throw new SyntaxError('Tone.Expr: Expected ) in a function call "'+t.value+'"');return{method:t.method,args:n,name:name}}function u(){for(var t,e,n=[];;){if(e=o(),p(e))break;if(n.push(e),t=c.peek(),!i(t,","))break;c.next()}return n}var c=this._tokenize(e),p=this.isUndef.bind(this);return o()},t.Expr.prototype._eval=function(t){if(!this.isUndef(t)){var e=t.method(t.args,this);return this._nodes.push(e),e}},t.Expr.prototype._disposeNodes=function(){for(var t=0;t0){this.connect(arguments[0]);for(var t=1;t=t&&(t=1),"number"==typeof t?(this.biquad.frequency.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.frequency.exponentialRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.frequency),this.biquad.frequency.value},t.Filter.prototype.res=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.Q.value=t,this.biquad.Q.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.Q.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.Q),this.biquad.Q.value},t.Filter.prototype.gain=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.gain.value=t,this.biquad.gain.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.gain.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.gain),this.biquad.gain.value},t.Filter.prototype.toggle=function(){return this._on=!this._on,this._on===!0?this.biquad.type=this._untoggledType:this._on===!1&&(this.biquad.type="allpass"),this._on},t.Filter.prototype.setType=function(t){this.biquad.type=t,this._untoggledType=this.biquad.type},t.Filter.prototype.dispose=function(){e.prototype.dispose.apply(this),this.biquad&&(this.biquad.disconnect(),delete this.biquad)},t.LowPass=function(){t.Filter.call(this,"lowpass")},t.LowPass.prototype=Object.create(t.Filter.prototype),t.HighPass=function(){t.Filter.call(this,"highpass")},t.HighPass.prototype=Object.create(t.Filter.prototype),t.BandPass=function(){t.Filter.call(this,"bandpass")},t.BandPass.prototype=Object.create(t.Filter.prototype),t.Filter}(a,Y);var W;W=function(){var e=z,i=a,n=function(t,i){e.call(this,"peaking"),this.disconnect(),this.set(t,i),this.biquad.gain.value=0,delete this.input,delete this.output,delete this._drywet,delete this.wet};return n.prototype=Object.create(e.prototype),n.prototype.amp=function(){console.warn("`amp()` is not available for p5.EQ bands. Use `.gain()`")},n.prototype.drywet=function(){console.warn("`drywet()` is not available for p5.EQ bands.")},n.prototype.connect=function(e){var i=e||t.soundOut.input;this.biquad?this.biquad.connect(i.input?i.input:i):this.output.connect(i.input?i.input:i)},n.prototype.disconnect=function(){this.biquad&&this.biquad.disconnect()},n.prototype.dispose=function(){var t=i.soundArray.indexOf(this);i.soundArray.splice(t,1),this.disconnect(),delete this.biquad},n}(z,a);var Q;Q=function(){var e=Y,i=W;return t.EQ=function(t){e.call(this),t=3===t||8===t?t:3;var i;i=3===t?Math.pow(2,3):2,this.bands=[];for(var n,o,r=0;t>r;r++)r===t-1?(n=21e3,o=.01):0===r?(n=100,o=.1):1===r?(n=3===t?360*i:360,o=1):(n=this.bands[r-1].freq()*i,o=1),this.bands[r]=this._newBand(n,o),r>0?this.bands[r-1].connect(this.bands[r].biquad):this.input.connect(this.bands[r].biquad);this.bands[t-1].connect(this.output)},t.EQ.prototype=Object.create(e.prototype),t.EQ.prototype.process=function(t){t.connect(this.input)},t.EQ.prototype.set=function(){if(arguments.length===2*this.bands.length)for(var t=0;t0;)delete this.bands.pop().dispose();delete this.bands}},t.EQ}(Y,W);var H;H=function(){var e=Y;return t.Panner3D=function(){e.call(this),this.panner=this.ac.createPanner(),this.panner.panningModel="HRTF",this.panner.distanceModel="linear",this.panner.connect(this.output),this.input.connect(this.panner)},t.Panner3D.prototype=Object.create(e.prototype),t.Panner3D.prototype.process=function(t){t.connect(this.input)},t.Panner3D.prototype.set=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.panner.positionX.value,this.panner.positionY.value,this.panner.positionZ.value]},t.Panner3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionX.value=t,this.panner.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionX),this.panner.positionX.value},t.Panner3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionY.value=t,this.panner.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionY),this.panner.positionY.value},t.Panner3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionZ.value=t,this.panner.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionZ),this.panner.positionZ.value},t.Panner3D.prototype.orient=function(t,e,i,n){return this.orientX(t,n),this.orientY(e,n),this.orientZ(i,n),[this.panner.orientationX.value,this.panner.orientationY.value,this.panner.orientationZ.value]},t.Panner3D.prototype.orientX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationX.value=t,this.panner.orientationX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationX),this.panner.orientationX.value},t.Panner3D.prototype.orientY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationY.value=t,this.panner.orientationY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationY),this.panner.orientationY.value},t.Panner3D.prototype.orientZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationZ.value=t,this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationZ),this.panner.orientationZ.value},t.Panner3D.prototype.setFalloff=function(t,e){this.maxDist(t),this.rolloff(e)},t.Panner3D.prototype.maxDist=function(t){return"number"==typeof t&&(this.panner.maxDistance=t),this.panner.maxDistance},t.Panner3D.prototype.rolloff=function(t){return"number"==typeof t&&(this.panner.rolloffFactor=t),this.panner.rolloffFactor},t.Panner3D.dispose=function(){e.prototype.dispose.apply(this),this.panner&&(this.panner.disconnect(),delete this.panner)},t.Panner3D}(a,Y);var $;$=function(){var e=a;return t.Listener3D=function(t){this.ac=e.audiocontext,this.listener=this.ac.listener},t.Listener3D.prototype.process=function(t){t.connect(this.input)},t.Listener3D.prototype.position=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.listener.positionX.value,this.listener.positionY.value,this.listener.positionZ.value]},t.Listener3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionX.value=t,this.listener.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionX),this.listener.positionX.value},t.Listener3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionY.value=t,this.listener.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionY),this.listener.positionY.value},t.Listener3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionZ.value=t,this.listener.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionZ),this.listener.positionZ.value},t.Listener3D.prototype.orient=function(t,e,i,n,o,r,s){return 3===arguments.length||4===arguments.length?(s=arguments[3],this.orientForward(t,e,i,s)):(6===arguments.length||7===arguments)&&(this.orientForward(t,e,i),this.orientUp(n,o,r,s)),[this.listener.forwardX.value,this.listener.forwardY.value,this.listener.forwardZ.value,this.listener.upX.value,this.listener.upY.value,this.listener.upZ.value]},t.Listener3D.prototype.orientForward=function(t,e,i,n){return this.forwardX(t,n),this.forwardY(e,n),this.forwardZ(i,n),[this.listener.forwardX,this.listener.forwardY,this.listener.forwardZ]},t.Listener3D.prototype.orientUp=function(t,e,i,n){return this.upX(t,n),this.upY(e,n),this.upZ(i,n),[this.listener.upX,this.listener.upY,this.listener.upZ]},t.Listener3D.prototype.forwardX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardX.value=t,this.listener.forwardX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardX),this.listener.forwardX.value},t.Listener3D.prototype.forwardY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardY.value=t,this.listener.forwardY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardY),this.listener.forwardY.value},t.Listener3D.prototype.forwardZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardZ.value=t,this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardZ),this.listener.forwardZ.value},t.Listener3D.prototype.upX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upX.value=t,this.listener.upX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upX),this.listener.upX.value},t.Listener3D.prototype.upY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upY.value=t,this.listener.upY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upY),this.listener.upY.value},t.Listener3D.prototype.upZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upZ.value=t,this.listener.upZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upZ),this.listener.upZ.value},t.Listener3D}(a,Y);var J;J=function(){var e=z,i=Y;t.Delay=function(){i.call(this),this._split=this.ac.createChannelSplitter(2),this._merge=this.ac.createChannelMerger(2),this._leftGain=this.ac.createGain(),this._rightGain=this.ac.createGain(),this.leftDelay=this.ac.createDelay(),this.rightDelay=this.ac.createDelay(),this._leftFilter=new e,this._rightFilter=new e,this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._leftFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._rightFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._leftFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this._rightFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this.input.connect(this._split),this.leftDelay.connect(this._leftGain),this.rightDelay.connect(this._rightGain),this._leftGain.connect(this._leftFilter.input),this._rightGain.connect(this._rightFilter.input),this._merge.connect(this.wet),this._leftFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this._rightFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this.setType(0),this._maxDelay=this.leftDelay.delayTime.maxValue,this.feedback(.5)},t.Delay.prototype=Object.create(i.prototype),t.Delay.prototype.process=function(t,e,i,n){var o=i||0,r=e||0;if(o>=1)throw new Error("Feedback value will force a positive feedback loop.");if(r>=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this._leftGain.gain.value=o,this._rightGain.gain.value=o,n&&(this._leftFilter.freq(n),this._rightFilter.freq(n))},t.Delay.prototype.delayTime=function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))},t.Delay.prototype.feedback=function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(t>=1)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value},t.Delay.prototype.filter=function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)},t.Delay.prototype.setType=function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}},t.Delay.prototype.dispose=function(){i.prototype.dispose.apply(this),this._split.disconnect(),this._leftFilter.dispose(),this._rightFilter.dispose(),this._merge.disconnect(),this._leftGain.disconnect(),this._rightGain.disconnect(),this.leftDelay.disconnect(),this.rightDelay.disconnect(),this._split=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}(z,Y);var K;K=function(){var e=c,i=Y;t.Reverb=function(){i.call(this),this._initConvolverNode(),this.input.gain.value=.5,this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse()},t.Reverb.prototype=Object.create(i.prototype),t.Reverb.prototype._initConvolverNode=function(){this.convolverNode=this.ac.createConvolver(),this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet)},t.Reverb.prototype._teardownConvolverNode=function(){this.convolverNode&&(this.convolverNode.disconnect(),delete this.convolverNode)},t.Reverb.prototype._setBuffer=function(t){this._teardownConvolverNode(),this._initConvolverNode(),this.convolverNode.buffer=t},t.Reverb.prototype.process=function(t,e,i,n){t.connect(this.input);var o=!1;e&&(this._seconds=e,o=!0),i&&(this._decay=i),n&&(this._reverse=n),o&&this._buildImpulse()},t.Reverb.prototype.set=function(t,e,i){var n=!1;t&&(this._seconds=t,n=!0),e&&(this._decay=e),i&&(this._reverse=i),n&&this._buildImpulse()},t.Reverb.prototype._buildImpulse=function(){var t,e,i=this.ac.sampleRate,n=i*this._seconds,o=this._decay,r=this.ac.createBuffer(2,n,i),s=r.getChannelData(0),a=r.getChannelData(1);for(e=0;n>e;e++)t=this._reverse?n-e:e,s[e]=(2*Math.random()-1)*Math.pow(1-t/n,o),a[e]=(2*Math.random()-1)*Math.pow(1-t/n,o);this._setBuffer(r)},t.Reverb.prototype.dispose=function(){i.prototype.dispose.apply(this),this._teardownConvolverNode()},t.Convolver=function(e,i,n){t.Reverb.call(this),this._initConvolverNode(),this.input.gain.value=.5,e?(this.impulses=[],this._loadBuffer(e,i,n)):(this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse())},t.Convolver.prototype=Object.create(t.Reverb.prototype),t.prototype.registerPreloadMethod("createConvolver",t.prototype),t.prototype.createConvolver=function(e,i,n){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var o=this,r=new t.Convolver(e,function(t){"function"==typeof i&&i(t),"function"==typeof o._decrementPreload&&o._decrementPreload()},n);return r.impulses=[],r},t.Convolver.prototype._loadBuffer=function(i,n,o){var i=t.prototype._checkFileFormats(i),r=this,s=(new Error).stack,a=t.prototype.getAudioContext(),u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=function(){if(200===u.status)a.decodeAudioData(u.response,function(t){var e={},o=i.split("/");e.name=o[o.length-1],e.audioBuffer=t,r.impulses.push(e),r._setBuffer(e.audioBuffer),n&&n(e)},function(){var t=new e("decodeAudioData",s,r.url),i="AudioContext error at decodeAudioData for "+r.url;o?(t.msg=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)});else{var t=new e("loadConvolver",s,r.url),c="Unable to load "+r.url+". The request status was: "+u.status+" ("+u.statusText+")";o?(t.message=c,o(t)):console.error(c+"\n The error stack trace includes: \n"+t.stack)}},u.onerror=function(){var t=new e("loadConvolver",s,r.url),i="There was no response from the server at "+r.url+". Check the url and internet connectivity.";o?(t.message=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)},u.send()},t.Convolver.prototype.set=null,t.Convolver.prototype.process=function(t){t.connect(this.input)},t.Convolver.prototype.impulses=[],t.Convolver.prototype.addImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this._loadBuffer(t,e,i)},t.Convolver.prototype.resetImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this.impulses=[],this._loadBuffer(t,e,i)},t.Convolver.prototype.toggleImpulse=function(t){if("number"==typeof t&&tthis._nextTick&&this._state;){var s=this._state.getValueAtTime(this._nextTick);if(s!==this._lastState){this._lastState=s;var a=this._state.get(this._nextTick);s===t.State.Started?(this._nextTick=a.time,this.isUndef(a.offset)||(this.ticks=a.offset),this.emit("start",a.time,this.ticks)):s===t.State.Stopped?(this.ticks=0,this.emit("stop",a.time)):s===t.State.Paused&&this.emit("pause",a.time)}var u=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),s===t.State.Started&&(this.callback(u),this.ticks++))}},t.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},t.Clock.prototype.dispose=function(){t.Emitter.prototype.dispose.call(this),this.context.off("tick",this._boundLoop),this._writable("frequency"),this.frequency.dispose(),this.frequency=null,this._boundLoop=null,this._nextTick=1/0,this.callback=null,this._state.dispose(),this._state=null},t.Clock}(n,q,tt,o);var it;it=function(){var e=a,i=et;t.Metro=function(){this.clock=new i({callback:this.ontick.bind(this)}),this.syncedParts=[],this.bpm=120,this._init(),this.prevTick=0,this.tatumTime=0,this.tickCallback=function(){}},t.Metro.prototype.ontick=function(t){var i=t-this.prevTick,n=t-e.audiocontext.currentTime;if(!(i-this.tatumTime<=-.02)){this.prevTick=t;var o=this;this.syncedParts.forEach(function(t){t.isPlaying&&(t.incrementStep(n),t.phrases.forEach(function(t){var e=t.sequence,i=o.metroTicks%e.length;0!==e[i]&&(o.metroTicks=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}var i=a,n=120;t.prototype.setBPM=function(t,e){n=t;for(var o in i.parts)i.parts[o]&&i.parts[o].setBPM(t,e)},t.Phrase=function(t,e,i){this.phraseStep=0,this.name=t,this.callback=e,this.sequence=i},t.Part=function(e,o){this.length=e||0,this.partStep=0,
+this.phrases=[],this.isPlaying=!1,this.noLoop(),this.tatums=o||.0625,this.metro=new t.Metro,this.metro._init(),this.metro.beatLength(this.tatums),this.metro.setBPM(n),i.parts.push(this),this.callback=function(){}},t.Part.prototype.setBPM=function(t,e){this.metro.setBPM(t,e)},t.Part.prototype.getBPM=function(){return this.metro.getBPM()},t.Part.prototype.start=function(t){if(!this.isPlaying){this.isPlaying=!0,this.metro.resetSync(this);var e=t||0;this.metro.start(e)}},t.Part.prototype.loop=function(t){this.looping=!0,this.onended=function(){this.partStep=0};var e=t||0;this.start(e)},t.Part.prototype.noLoop=function(){this.looping=!1,this.onended=function(){this.stop()}},t.Part.prototype.stop=function(t){this.partStep=0,this.pause(t)},t.Part.prototype.pause=function(t){this.isPlaying=!1;var e=t||0;this.metro.stop(e)},t.Part.prototype.addPhrase=function(e,i,n){var o;if(3===arguments.length)o=new t.Phrase(e,i,n);else{if(!(arguments[0]instanceof t.Phrase))throw"invalid input. addPhrase accepts name, callback, array or a p5.Phrase";o=arguments[0]}this.phrases.push(o),o.sequence.length>this.length&&(this.length=o.sequence.length)},t.Part.prototype.removePhrase=function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)},t.Part.prototype.getPhrase=function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]},t.Part.prototype.replaceSequence=function(t,e){for(var i in this.phrases)this.phrases[i].name===t&&(this.phrases[i].sequence=e)},t.Part.prototype.incrementStep=function(t){this.partStep0&&o.iterations<=o.maxIterations&&o.callback(i)},frequency:this._calcFreq()})},t.SoundLoop.prototype.start=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying||(this.clock.start(n+i),this.isPlaying=!0)},t.SoundLoop.prototype.stop=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.stop(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.pause=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.pause(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.syncedStart=function(t,i){var n=i||0,o=e.audiocontext.currentTime;if(t.isPlaying){if(t.isPlaying){var r=t.clock._nextTick-e.audiocontext.currentTime;this.clock.start(o+r),this.isPlaying=!0}}else t.clock.start(o+n),t.isPlaying=!0,this.clock.start(o+n),this.isPlaying=!0},t.SoundLoop.prototype._update=function(){this.clock.frequency.value=this._calcFreq()},t.SoundLoop.prototype._calcFreq=function(){return"number"==typeof this._interval?(this.musicalTimeMode=!1,1/this._interval):"string"==typeof this._interval?(this.musicalTimeMode=!0,this._bpm/60/this._convertNotation(this._interval)*(this._timeSignature/4)):void 0},t.SoundLoop.prototype._convertNotation=function(t){var e=t.slice(-1);switch(t=Number(t.slice(0,-1)),e){case"m":return this._measure(t);case"n":return this._note(t);default:console.warn("Specified interval is not formatted correctly. See Tone.js timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time")}},t.SoundLoop.prototype._measure=function(t){return t*this._timeSignature},t.SoundLoop.prototype._note=function(t){return this._timeSignature/t},Object.defineProperty(t.SoundLoop.prototype,"bpm",{get:function(){return this._bpm},set:function(t){this.musicalTimeMode||console.warn('Changing the BPM in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._bpm=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){this.musicalTimeMode||console.warn('Changing the timeSignature in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._timeSignature=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"interval",{get:function(){return this._interval},set:function(t){this.musicalTimeMode="Number"==typeof t?!1:!0,this._interval=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"iterations",{get:function(){return this.clock.ticks}}),t.SoundLoop}(a,et);var rt;rt=function(){"use strict";var e=Y;return t.Compressor=function(){e.call(this),this.compressor=this.ac.createDynamicsCompressor(),this.input.connect(this.compressor),this.compressor.connect(this.wet)},t.Compressor.prototype=Object.create(e.prototype),t.Compressor.prototype.process=function(t,e,i,n,o,r){t.connect(this.input),this.set(e,i,n,o,r)},t.Compressor.prototype.set=function(t,e,i,n,o){"undefined"!=typeof t&&this.attack(t),"undefined"!=typeof e&&this.knee(e),"undefined"!=typeof i&&this.ratio(i),"undefined"!=typeof n&&this.threshold(n),"undefined"!=typeof o&&this.release(o)},t.Compressor.prototype.attack=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.attack.value=t,this.compressor.attack.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.attack.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.attack),this.compressor.attack.value},t.Compressor.prototype.knee=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.knee.value=t,this.compressor.knee.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.knee.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.knee),this.compressor.knee.value},t.Compressor.prototype.ratio=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.ratio.value=t,this.compressor.ratio.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.ratio.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.ratio),this.compressor.ratio.value},t.Compressor.prototype.threshold=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.threshold.value=t,this.compressor.threshold.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.threshold.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.threshold),this.compressor.threshold.value},t.Compressor.prototype.release=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.release.value=t,this.compressor.release.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.release.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof number&&t.connect(this.compressor.release),this.compressor.release.value},t.Compressor.prototype.reduction=function(){return this.compressor.reduction.value},t.Compressor.prototype.dispose=function(){e.prototype.dispose.apply(this),this.compressor&&(this.compressor.disconnect(),delete this.compressor)},t.Compressor}(a,Y,c);var st;st=function(){var e=a,i=u.convertToWav,n=e.audiocontext;t.SoundRecorder=function(){this.input=n.createGain(),this.output=n.createGain(),this.recording=!1,this.bufferSize=1024,this._channels=2,this._clear(),this._jsNode=n.createScriptProcessor(this.bufferSize,this._channels,2),this._jsNode.onaudioprocess=this._audioprocess.bind(this),this._callback=function(){},this._jsNode.connect(t.soundOut._silentNode),this.setInput(),e.soundArray.push(this)},t.SoundRecorder.prototype.setInput=function(e){this.input.disconnect(),this.input=null,this.input=n.createGain(),this.input.connect(this._jsNode),this.input.connect(this.output),e?e.connect(this.input):t.soundOut.output.connect(this.input)},t.SoundRecorder.prototype.record=function(t,e,i){this.recording=!0,e&&(this.sampleLimit=Math.round(e*n.sampleRate)),t&&i?this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer),i()}:t&&(this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer)})},t.SoundRecorder.prototype.stop=function(){this.recording=!1,this._callback(),this._clear()},t.SoundRecorder.prototype._clear=function(){this._leftBuffers=[],this._rightBuffers=[],this.recordedSamples=0,this.sampleLimit=null},t.SoundRecorder.prototype._audioprocess=function(t){if(this.recording!==!1&&this.recording===!0)if(this.sampleLimit&&this.recordedSamples>=this.sampleLimit)this.stop();else{var e=t.inputBuffer.getChannelData(0),i=t.inputBuffer.getChannelData(1);this._leftBuffers.push(new Float32Array(e)),this._rightBuffers.push(new Float32Array(i)),this.recordedSamples+=this.bufferSize}},t.SoundRecorder.prototype._getBuffer=function(){var t=[];return t.push(this._mergeBuffers(this._leftBuffers)),t.push(this._mergeBuffers(this._rightBuffers)),t},t.SoundRecorder.prototype._mergeBuffers=function(t){for(var e=new Float32Array(this.recordedSamples),i=0,n=t.length,o=0;n>o;o++){var r=t[o];e.set(r,i),i+=r.length}return e},t.SoundRecorder.prototype.dispose=function(){this._clear();var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this._callback=function(){},this.input&&this.input.disconnect(),this.input=null,this._jsNode=null},t.prototype.saveSound=function(e,n){const o=i(e.buffer);t.prototype.writeFile([o],n,"wav")}}(a,u);var at;at=function(){t.PeakDetect=function(t,e,i,n){this.framesPerPeak=n||20,this.framesSinceLastPeak=0,this.decayRate=.95,this.threshold=i||.35,this.cutoff=0,this.cutoffMult=1.5,this.energy=0,this.penergy=0,this.currentValue=0,this.isDetected=!1,this.f1=t||40,this.f2=e||2e4,this._onPeak=function(){}},t.PeakDetect.prototype.update=function(t){var e=this.energy=t.getEnergy(this.f1,this.f2)/255;e>this.cutoff&&e>this.threshold&&e-this.penergy>0?(this._onPeak(),this.isDetected=!0,this.cutoff=e*this.cutoffMult,this.framesSinceLastPeak=0):(this.isDetected=!1,this.framesSinceLastPeak<=this.framesPerPeak?this.framesSinceLastPeak++:(this.cutoff*=this.decayRate,this.cutoff=Math.max(this.cutoff,this.threshold))),this.currentValue=e,this.penergy=e},t.PeakDetect.prototype.onPeak=function(t,e){var i=this;i._onPeak=function(){t(i.energy,e)}}}();var ut;ut=function(){var e=a;t.Gain=function(){this.ac=e.audiocontext,this.input=this.ac.createGain(),this.output=this.ac.createGain(),this.input.gain.value=.5,this.input.connect(this.output),e.soundArray.push(this)},t.Gain.prototype.setInput=function(t){t.connect(this.input)},t.Gain.prototype.connect=function(e){var i=e||t.soundOut.input;this.output.connect(i.input?i.input:i)},t.Gain.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Gain.prototype.amp=function(t,i,n){var i=i||0,n=n||0,o=e.audiocontext.currentTime,r=this.output.gain.value;this.output.gain.cancelScheduledValues(o),this.output.gain.linearRampToValueAtTime(r,o+n),this.output.gain.linearRampToValueAtTime(t,o+n+i)},t.Gain.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.output&&(this.output.disconnect(),delete this.output),this.input&&(this.input.disconnect(),delete this.input)}}(a);var ct;ct=function(){var e=a;return t.AudioVoice=function(){this.ac=e.audiocontext,this.output=this.ac.createGain(),this.connect(),e.soundArray.push(this)},t.AudioVoice.prototype.play=function(t,e,i,n){},t.AudioVoice.prototype.triggerAttack=function(t,e,i){},t.AudioVoice.prototype.triggerRelease=function(t){},t.AudioVoice.prototype.amp=function(t,e){},t.AudioVoice.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.AudioVoice.prototype.disconnect=function(){this.output.disconnect()},t.AudioVoice.prototype.dispose=function(){this.output&&(this.output.disconnect(),delete this.output)},t.AudioVoice}(a);var pt;pt=function(){var e=a,i=ct,n=u.noteToFreq,o=.15;t.MonoSynth=function(){i.call(this),this.oscillator=new t.Oscillator,this.env=new t.Envelope,this.env.setRange(1,0),this.env.setExp(!0),this.setADSR(.02,.25,.05,.35),this.oscillator.disconnect(),this.oscillator.connect(this.output),this.env.disconnect(),this.env.setInput(this.output.gain),this.oscillator.output.gain.value=1,this.oscillator.start(),this.connect(),e.soundArray.push(this)},t.MonoSynth.prototype=Object.create(t.AudioVoice.prototype),t.MonoSynth.prototype.play=function(t,e,i,n){this.triggerAttack(t,e,~~i),this.triggerRelease(~~i+(n||o))},t.MonoSynth.prototype.triggerAttack=function(t,e,i){var i=~~i,o=n(t),r=e||.1;this.oscillator.freq(o,0,i),this.env.ramp(this.output.gain,i,r)},t.MonoSynth.prototype.triggerRelease=function(t){var t=t||0;this.env.ramp(this.output.gain,t,0)},t.MonoSynth.prototype.setADSR=function(t,e,i,n){this.env.setADSR(t,e,i,n)},Object.defineProperties(t.MonoSynth.prototype,{attack:{get:function(){return this.env.aTime},set:function(t){this.env.setADSR(t,this.env.dTime,this.env.sPercent,this.env.rTime)}},decay:{get:function(){return this.env.dTime},set:function(t){this.env.setADSR(this.env.aTime,t,this.env.sPercent,this.env.rTime)}},sustain:{get:function(){return this.env.sPercent},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,t,this.env.rTime)}},release:{get:function(){return this.env.rTime},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,this.env.sPercent,t)}}}),t.MonoSynth.prototype.amp=function(t,e){var i=e||0;return"undefined"!=typeof t&&this.oscillator.amp(t,i),this.oscillator.amp().value},t.MonoSynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.MonoSynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.MonoSynth.prototype.dispose=function(){i.prototype.dispose.apply(this),this.env&&this.env.dispose(),this.oscillator&&this.oscillator.dispose()}}(a,ct,u);var ht;ht=function(){var e=a,i=q,n=u.noteToFreq;t.PolySynth=function(n,o){this.audiovoices=[],this.notes={},this._newest=0,this._oldest=0,this.maxVoices=o||8,this.AudioVoice=void 0===n?t.MonoSynth:n,this._voicesInUse=new i(0),this.output=e.audiocontext.createGain(),this.connect(),this._allocateVoices(),e.soundArray.push(this)},t.PolySynth.prototype._allocateVoices=function(){for(var t=0;tf?f:p}this.audiovoices[a].triggerAttack(c,p,s)},t.PolySynth.prototype._updateAfter=function(t,e){if(null!==this._voicesInUse._searchAfter(t)){this._voicesInUse._searchAfter(t).value+=e;var i=this._voicesInUse._searchAfter(t).time;this._updateAfter(i,e)}},t.PolySynth.prototype.noteRelease=function(t,i){var o=e.audiocontext.currentTime,r=i||0,s=o+r;if(t){var a=n(t);if(this.notes[a]&&null!==this.notes[a].getValueAtTime(s)){var u=Math.max(~~this._voicesInUse.getValueAtTime(s).value,1);this._voicesInUse.setValueAtTime(u-1,s),u>0&&this._updateAfter(s,-1),this.audiovoices[this.notes[a].getValueAtTime(s)].triggerRelease(r),this.notes[a].dispose(),delete this.notes[a],this._newest=0===this._newest?0:(this._newest-1)%(this.maxVoices-1)}else console.warn("Cannot release a note that is not already playing")}else{this.audiovoices.forEach(function(t){t.triggerRelease(r)}),this._voicesInUse.setValueAtTime(0,s);for(var c in this.notes)this.notes[c].dispose(),delete this.notes[c]}},t.PolySynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.PolySynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.PolySynth.prototype.dispose=function(){this.audiovoices.forEach(function(t){t.dispose()}),this.output&&(this.output.disconnect(),delete this.output)}}(a,q,u);var lt;lt=function(){function e(t){for(var e,i="number"==typeof t?t:50,n=44100,o=new Float32Array(n),r=Math.PI/180,s=0;n>s;++s)e=2*s/n-1,o[s]=(3+i)*e*20*r/(Math.PI+i*Math.abs(e));return o}var i=Y;t.Distortion=function(n,o){if(i.call(this),"undefined"==typeof n&&(n=.25),"number"!=typeof n)throw new Error("amount must be a number");if("undefined"==typeof o&&(o="2x"),"string"!=typeof o)throw new Error("oversample must be a String");var r=t.prototype.map(n,0,1,0,2e3);this.waveShaperNode=this.ac.createWaveShaper(),this.amount=r,this.waveShaperNode.curve=e(r),this.waveShaperNode.oversample=o,this.input.connect(this.waveShaperNode),this.waveShaperNode.connect(this.wet)},t.Distortion.prototype=Object.create(i.prototype),t.Distortion.prototype.process=function(t,e,i){t.connect(this.input),this.set(e,i)},t.Distortion.prototype.set=function(i,n){if(i){var o=t.prototype.map(i,0,1,0,2e3);this.amount=o,this.waveShaperNode.curve=e(o)}n&&(this.waveShaperNode.oversample=n)},t.Distortion.prototype.getAmount=function(){return this.amount},t.Distortion.prototype.getOversample=function(){return this.waveShaperNode.oversample},t.Distortion.prototype.dispose=function(){i.prototype.dispose.apply(this),this.waveShaperNode&&(this.waveShaperNode.disconnect(),this.waveShaperNode=null)}}(Y);var ft;ft=function(){var t=a;return t}(e,s,a,u,c,p,h,l,f,k,O,M,E,V,R,z,Q,H,$,J,K,it,nt,ot,rt,st,at,ut,pt,ht,lt,ct,pt,ht)});
\ No newline at end of file
diff --git a/creator/src/templates/static.js b/creator/src/templates/static.js
index bbcc7e6..4968a1c 100644
--- a/creator/src/templates/static.js
+++ b/creator/src/templates/static.js
@@ -1,12 +1,16 @@
-module.exports = name => ({
+const { TEXT } = require("../writer");
+
+module.exports = (name) => ({
// =============== index.html ==============
- "index.html": `
+ "index.html": {
+ type: TEXT,
+ content: `
-
-
+
+
${name}
@@ -15,9 +19,12 @@ module.exports = name => ({