Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
Documentation and comments JSDoc
Alejandro58c55d2df937
diff --git a/examples.js b/examples.jsindex 6ab0358..02e80fd 100644--- a/examples.js+++ b/examples.js@@ -43,12 +43,12 @@ brush.config({// YOU CAN CREATE YOU OWN BRUSHESbrush.addBrush("watercolor", {type: "image", // this is the TIP TYPE: choose standard / spray / marker / custom / image- weight: 20, // Base weight of the brush tip+ weight: 15, // Base weight of the brush tipvibration: 2, // Vibration of the lines, spreaddefinition: 0.5, // Between 0 and 1quality: 8, // + quality = more continuous line- opacity: 28, // Base opacity of the brush (this will be affected by pressure)- spacing: 1, // Spacing between the points that compose the brush stroke+ opacity: 30, // Base opacity of the brush (this will be affected by pressure)+ spacing: 1.5, // Spacing between the points that compose the brush strokeblend: true, // Activate / Disable realistic color mixing. By default, this is active for marker-custom-image brushespressure: {type: "custom", // "standard" or "custom". Use "custom"" for custom pressure curves. Use standard for simple gauss bell curve@@ -204,7 +204,7 @@ function setup () {]);brush.set("marker","#9c2128",1)// You can also atch these polygons .hath(distance_between_lines, angle_of_lines, options)- //polygon.hatch(1,45,{rand: 0.2, continuous: true, gradient: 0.5})+ polygon.hatch(1, 45, {rand: 0.2, continuous: true, gradient: 0.5})//polygon.draw()brush.noField()@@ -215,14 +215,7 @@ function setup () {brush.circle(100,100,50)brush.fill("#002185",120)brush.circle(150,100,50)-- brush.bleed(0.05)- brush.polygon([- [20,80],- [100,80],- [100,120],- [30,140],- ])+}diff --git a/index.html b/index.htmlindex 45e710a..bcbdca6 100644--- a/index.html+++ b/index.html@@ -3,6 +3,7 @@<head><title>Brushbox - Examples</title><script src="./p5.min.js"></script>+ <script src="./spectral.js"></script><script src="./p5.brush.js"></script><link rel="stylesheet" href="./style.css"></head>diff --git a/p5.brush.js b/p5.brush.jsindex 67faf6e..dcab9e3 100644--- a/p5.brush.js+++ b/p5.brush.js@@ -32,248 +32,617 @@} (this, (function (exports) {'use strict';- //////////////////////////////////////////////////- // CONFIG AND LOAD FUNCTIONS- let _r, isReady = false;- function _config (objct = {}) {if (objct.R) R.source = objct.R}+// =============================================================================+// Section: Configure and Initiate+// =============================================================================++ /**+ * Reference to the renderer or canvas object.+ * @type {Object}+ */+ let _r;++ /**+ * Flag to indicate if the system is ready for rendering.+ * @type {boolean}+ */+ let isReady = false;++ /**+ * Configures the drawing system with custom options.+ * @param {Object} [objct={}] - Optional configuration object.+ */+ function _config(objct = {}) {+ if (objct.R) R.source = objct.R; // Overrides the default random source if provided+ }++ /**+ * Initializes the drawing system and sets up the environment.+ * @param {string|boolean} [canvasID=false] - Optional ID of the canvas element to use.+ * If false, it uses the current window as the rendering context.+ */function _load (canvasID = false) {isReady = true;- _r = (!canvasID) ? window.self : canvasID; // Set buffer+ // Set the renderer to the specified canvas or to the window if no ID is given+ _r = (!canvasID) ? window.self : canvasID;+ // Load realistic color blendingMix.load();+ // Load flowfield systemFF.create();- globalScale(_r.width / 250) // Adjust standard brushes to match canvas+ // Adjust standard brushes to match canvas size+ _globalScale(_r.width / 250) // Adjust standard brushes to match canvas+ }++ /**+ * Preloads necessary assets or configurations.+ * This function should be called before setup to ensure all assets are loaded.+ */+ function _preload () {+ // Load custom image tips+ T.load();+ }++ /**+ * Ensures that the drawing system is ready before any drawing operation.+ * Loads the system if it hasn't been loaded already.+ */+ function _ensureReady () {+ if (!isReady) _load();}- function _preload () {T.load()}- //////////////////////////////////////////////////- // AUXILIARY FUNCTIONS AND RNG+// =============================================================================+// Section: Randomness and other auxiliary functions+// =============================================================================++ /**+ * Object for random number generation and related utility functions.+ * @property {function} source - Function that returns a random number from the base random generator.+ * @property {function} random - Function to generate a random number within a specified range.+ * @property {function} randInt - Function to generate a random integer within a specified range.+ * @property {function} weightedRand - Function to generate a random value based on weighted probabilities.+ * @property {function} map - Function to remap a number from one range to another.+ * @property {function} constrain - Function to constrain a number within a range.+ * @property {function} cos - Function to get the cosine of an angle from precalculated values.+ * @property {function} sin - Function to get the sine of an angle from precalculated values.+ * @property {boolean} isPrecalculationDone - Flag to check if precalculation of trigonometric values is complete.+ * @property {function} preCalculation - Function to precalculate trigonometric values.+ */const R = {++ /**+ * The basic source of randomness, can be replaced with a deterministic alternative for testing.+ * @returns {number} A random number between 0 and 1.+ */source: () => random(),++ /**+ * Generates a random number within a specified range.+ * @param {number} [min=0] - The lower bound of the range.+ * @param {number} [max=1] - The upper bound of the range.+ * @returns {number} A random number within the specified range.+ */random(e = 0, r = 1) {if (arguments.length === 1) {return this.map(this.source(), 0, 1, 0, e); }else {return this.map(this.source(), 0, 1, e, r)}- },- randInt(e, r) {return Math.floor(this.random(e,r))},+ },++ /**+ * Generates a random integer within a specified range.+ * @param {number} min - The lower bound of the range.+ * @param {number} max - The upper bound of the range.+ * @returns {number} A random integer within the specified range.+ */+ randInt(e, r) {+ return Math.floor(this.random(e,r))+ },++ /**+ * Generates a random value based on weighted probabilities.+ * @param {Object} weights - An object containing values as keys and their probabilities as values.+ * @returns {string} A key randomly chosen based on its weight.+ */weightedRand(e) {- var r, a, n = [];+ let r, a, n = [];for (r in e)for (a = 0; a < 10 * e[r]; a++)n.push(r);return n[Math.floor(this.source() * n.length)]},- map(value, a, b, c, d, bool = false) {++ /**+ * Remaps a number from one range to another.+ * @param {number} value - The number to remap.+ * @param {number} a - The lower bound of the value's current range.+ * @param {number} b- The upper bound of the value's current range.+ * @param {number} c - The lower bound of the value's target range.+ * @param {number} d - The upper bound of the value's target range.+ * @param {boolean} [withinBounds=false] - Whether to constrain the value to the target range.+ * @returns {number} The remapped number.+ */+ map(value, a, b, c, d, withinBounds = false) {let r = c + (value - a) / (b - a) * (d - c);- if (!bool) return r;+ if (!withinBounds) return r;if (c < d) {return this.constrain(r, c, d)}else {return this.constrain(r, d, c)}},++ /**+ * Constrains a number to be within a range.+ * @param {number} n - The number to constrain.+ * @param {number} low - The lower bound of the range.+ * @param {number} high - The upper bound of the range.+ * @returns {number} The constrained number.+ */constrain (n, low, high) {return Math.max(Math.min(n, high), low);},- c: [], s: [],- cos(a) {return this.c[Math.floor(4 * ((a % 360 + 360) % 360))]},- sin(a) {return this.s[Math.floor(4 * ((a % 360 + 360) % 360))]},- }- // Calculate sin and cos for 1440 angles- for (let i = 0; i < 1440; i++) {- const radians = i * Math.PI / 720;- R.c[i] = Math.cos(radians)- R.s[i] = Math.sin(radians)++ /**+ * Calculates the cosine for a given angle using precalculated values.+ * @param {number} angle - The angle in degrees.+ * @returns {number} The cosine of the angle.+ */+ cos(angle) {+ return this.c[Math.floor(4 * ((angle % 360 + 360) % 360))];+ },++ /**+ * Calculates the sine for a given angle using precalculated values.+ * @param {number} angle - The angle in degrees.+ * @returns {number} The sine of the angle.+ */+ sin(angle) {+ return this.s[Math.floor(4 * ((angle % 360 + 360) % 360))];+ },+ // Flag to indicate if the trigonometric tables have been precalculated+ isPrecalculationDone: false,++ /**+ * Precalculates trigonometric values for improved performance.+ * This function should be called before any trigonometric calculations are performed.+ */+ preCalculation() {+ if (this.isPrecalculationDone) return;+ const totalDegrees = 1440;+ const radiansPerIndex = 2 * Math.PI / totalDegrees;+ this.c = new Float64Array(totalDegrees);+ this.s = new Float64Array(totalDegrees);+ for (let i = 0; i < totalDegrees; i++) {+ const radians = i * radiansPerIndex;+ R.c[i] = Math.cos(radians);+ R.s[i] = Math.sin(radians);+ }+ this.isPrecalculationDone = true;+ }}- // Keep track of transformation matrix+ // Perform the precalculation of trigonometric values for the R object+ R.preCalculation();++ /**+ * Captures the current translation values from the renderer's transformation matrix.+ *+ * Assumes that the renderer's transformation matrix (`uMVMatrix`) is a 4x4 matrix+ * where the translation components are in the 13th (index 12) and 14th (index 13) positions.+ *+ * @returns {number[]} An array containing the x (horizontal) and y (vertical) translation values.+ */let matrix = [0,0];- const trans = function () {+ const _trans = function () {+ // Access the renderer's current model-view matrix and extract the translation componentsmatrix = [_r._renderer.uMVMatrix.mat4[12],_r._renderer.uMVMatrix.mat4[13]]+ // Return the translation components as a two-element arrayreturn matrix;}- //////////////////////////////////////////////////- // COLOR-MIX FUNCTIONS (Using Spectral.js)+ /**+ * Calculates the intersection point between two line segments if it exists.+ *+ * @param {Object} seg1Start - The start point of the first line segment.+ * @param {Object} seg1End - The end point of the first line segment.+ * @param {Object} seg2Start - The start point of the second line segment.+ * @param {Object} seg2End - The end point of the second line segment.+ * @param {boolean} [includeSegmentExtension=false] - Whether to include points of intersection not lying on the segments.+ * @returns {Object|boolean} The intersection point as an object with 'x' and 'y' properties, or 'false' if there is no intersection.+ */+ function intersectar(seg1Start, seg1End, seg2Start, seg2End, includeSegmentExtension = false) {+ // Extract coordinates from points+ let x1 = seg1Start.x, y1 = seg1Start.y;+ let x2 = seg1End.x, y2 = seg1End.y;+ let x3 = seg2Start.x, y3 = seg2Start.y;+ let x4 = seg2End.x, y4 = seg2End.y;+ // Early return if line segments are points or if the lines are parallel+ if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {+ return false; // Segments are points+ }+ let deltaX1 = x2 - x1, deltaY1 = y2 - y1;+ let deltaX2 = x4 - x3, deltaY2 = y4 - y3;+ let denominator = (deltaY2 * deltaX1 - deltaX2 * deltaY1);+ if (denominator === 0) {+ return false; // Lines are parallel+ }+ // Calculate the intersection point+ let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;+ let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;+ // Check if the intersection is within the bounds of the line segments+ if (!includeSegmentExtension && (ub < 0 || ub > 1)) {+ return false;+ }+ // Calculate the intersection coordinates+ let x = x1 + ua * deltaX1;+ let y = y1 + ua * deltaY1;+ return { x: x, y: y };+ }++ /**+ * Calculates the angle in degrees between two points in 2D space.+ * The angle is measured in a clockwise direction from the positive X-axis.+ *+ * @param {number} x1 - The x-coordinate of the first point.+ * @param {number} y1 - The y-coordinate of the first point.+ * @param {number} x2 - The x-coordinate of the second point.+ * @param {number} y2 - The y-coordinate of the second point.+ * @returns {number} The angle in degrees between the two points.+ */+ function calcAngle(x1,y1,x2,y2) {+ // Calculate the angle based on the quadrant in which the second point lies+ let angleRadians = Math.atan2(-(y2 - y1), (x2 - x1));++ // Convert radians to degrees and normalize the angle between 0 and 360+ let angleDegrees = angleRadians * (180 / Math.PI);+ return (angleDegrees % 360 + 360) % 360;+ }+++// =============================================================================+// Section: Color Blending - Uses spectral.js as a module+// =============================================================================++ /**+ * Object handling blending operations with WebGL shaders.+ * @property {boolean} loaded - Flag indicating if the blend shaders have been loaded.+ * @property {Float32Array} pigmentTypedArray - Typed array to hold color values for shaders.+ * @property {function} load - Loads resources and initializes blend operations.+ * @property {function} blend - Applies blending effects using the initialized shader.+ * @property {string} vert - Vertex shader source code.+ * @property {string} frag - Fragment shader source code with blending logic.+ */const Mix = {loaded: false,+ pigmentTypedArray: new Float32Array(3),++ /**+ * Loads necessary resources and prepares the framebuffer and shader for blending.+ */load() {- this.mask = _r.createFramebuffer({width: _r.width, height: _r.height, density: _r.pixelDensity()});- this.mask.begin(), _r.clear(), this.mask.end();- if (!Mix.loaded) {this.frag = this.frag.replace('#include "spectral.glsl"', glsl());}+ // Create a framebuffer to be used as a mask+ this.mask = _r.createFramebuffer({+ width: _r.width,+ height: _r.height,+ density: _r.pixelDensity(),+ depth: false,+ antialias: false+ });+ // Clear the mask to start fresh+ this.mask.begin(), _r.clear(), this.mask.end();+ // Load the spectral.js shader code only once+ if (!Mix.loaded) {+ this.frag = this.frag.replace('#include "spectral.glsl"', spectral.glsl());+ }+ // Create the shader program from the vertex and fragment shadersthis.shader = _r.createShader(this.vert, this.frag);Mix.loaded = true;},++ /**+ * Applies the blend shader to the current rendering context.+ * @param {string} _c - The color used for blending, in any CSS color format.+ */blend (_c) {- this.pigment = [float(red(color(_c))),float(green(color(_c))),float(blue(color(_c)))];+ this.pigmentTypedArray[0] = red(color(_c)) / 255.0;+ this.pigmentTypedArray[1] = green(color(_c)) / 255.0;+ this.pigmentTypedArray[2] = blue(color(_c)) / 255.0;_r.push();- _r.translate(-trans()[0],-trans()[1])+ // Use the blend shader for rendering_r.shader(this.shader);- this.shader.setUniform('addColor', this.pigment);+ _r.translate(-_trans()[0],-_trans()[1])+ // Set shader uniforms: color to add, source texture, and mask texture+ this.shader.setUniform('addColor', this.pigmentTypedArray);this.shader.setUniform('source', _r._renderer);this.shader.setUniform('mask', this.mask);+ // Draw a rectangle covering the whole canvas to apply the shader_r.fill(0,0,0,0);_r.noStroke();_r.rect(-_r.width/2, -_r.height/2, _r.width, _r.height);- this.mask.draw(function () {_r.clear()})_r.pop();+ // Clear the mask after drawing+ this.mask.draw(function () {_r.clear()})},++ // Vertex shader source codevert: `precision highp float;attribute vec3 aPosition;attribute vec2 aTexCoord;uniform mat4 uModelViewMatrix,uProjectionMatrix;varying vec2 vVertTexCoord;void main(){gl_Position=uProjectionMatrix*uModelViewMatrix*vec4(aPosition,1);vVertTexCoord=aTexCoord;}`,++ // Fragment shader source code with blending operationsfrag: `precision highp float;varying vec2 vVertTexCoord;uniform sampler2D source;uniform sampler2D mask;uniform vec4 addColor;#include "spectral.glsl"-- vec3 rgb(float r, float g, float b){return vec3(r / 255.0, g / 255.0, b / 255.0);}float rand(vec2 co, float a, float b, float c){return fract(sin(dot(co, vec2(a, b))) * c);}- float map(float value, float min1, float max1, float min2, float max2) {return min2 + (value - min1) * (max2 - min2) / (max1 - min1);}-void main() {vec4 maskColor = texture2D(mask, vVertTexCoord);if (maskColor.r > 0.0) {- float r1 = map(rand(vVertTexCoord,12.9898,78.233,43358.5453),0.0,1.0,-1.0,1.0);- float r2 = map(rand(vVertTexCoord,7.9898,58.233,43213.5453),0.0,1.0,-1.0,1.0);- float r3 = map(rand(vVertTexCoord,17.9898,3.233,33358.5453),0.0,1.0,-1.0,1.0);- float d;+ vec2 randParams1 = vec2(12.9898, 78.233);+ vec2 randParams2 = vec2(7.9898, 58.233);+ vec2 randParams3 = vec2(17.9898, 3.233);+ float r1 = rand(vVertTexCoord, randParams1.x, randParams1.y, 43358.5453) * 2.0 - 1.0;+ float r2 = rand(vVertTexCoord, randParams2.x, randParams2.y, 43213.5453) * 2.0 - 1.0;+ float r3 = rand(vVertTexCoord, randParams3.x, randParams3.y, 33358.5453) * 2.0 - 1.0;vec4 canvasColor = texture2D(source, vVertTexCoord);- vec3 mixedColor = spectral_mix(vec3(canvasColor.r,canvasColor.g,canvasColor.b), rgb(addColor.r,addColor.g,addColor.b), maskColor.a * 0.7);- if (maskColor.a > 0.7) {mixedColor = spectral_mix(mixedColor,vec3(0.0,0.0,0.0),(maskColor.a - 0.7) * 0.7);}- gl_FragColor = vec4(mixedColor.r + 0.02 * r1 ,mixedColor.g + 0.02 * r2,mixedColor.b + 0.02 * r3,1.0);- }- else {- gl_FragColor = vec4(0.0,0.0,0.0,0.0);+ vec3 mixedColor = spectral_mix(canvasColor.rgb, addColor.rgb, maskColor.a * 0.8);+ if (maskColor.a > 0.8) {+ mixedColor = spectral_mix(mixedColor, vec3(0.0), (maskColor.a - 0.8) / 0.6);+ }+ gl_FragColor = vec4(mixedColor + 0.02 * vec3(r1, r2, r3), 1.0);+ } else {+ gl_FragColor = vec4(0.0);}}`}- //////////////////////////////////////////////////- // FLOWFIELD- function flowField (a) {- if (!isReady) _load();- FF.isActive = true- if (FF.current !== a) FF.current = a;+// =============================================================================+// Section: FlowField+// =============================================================================++ /**+ * Activates a specific vector field by name, ensuring it's ready for use.+ * @param {string} a - The name of the vector field to activate.+ */+ function _field (a) {+ _ensureReady();+ FF.isActive = true; // Mark the field framework as active+ if (FF.current !== a) FF.current = a; // Update the current field if a different one is selected}- function disableField () {FF.isActive = false}- function addField(name,funct) {- if (!isReady) _load();- FF.list.set(name,{gen: funct});- FF.current = name;- FF.refresh()++ /**+ * Deactivates the current vector field.+ */+ function _disableField () {FF.isActive = false}++ /**+ * Adds a new vector field to the field list with a unique name and a generator function.+ * @param {string} name - The unique name for the new vector field.+ * @param {Function} funct - The function that generates the field values.+ */+ function _addField(name,funct) {+ _ensureReady();+ FF.list.set(name,{gen: funct}); // Map the field name to its generator function+ FF.current = name; // Set the newly added field as the current one to be used+ FF.refresh(); // Refresh the field values using the generator function+ }++ /**+ * Refreshes the current vector field based on the generator function, which can be time-dependent.+ * @param {number} [t=0] - An optional time parameter that can affect field generation.+ */+ function _refreshField(t) {+ FF.refresh(t)}- function refreshField(t) {FF.refresh(t)}- function listFields() {return FF.list.keys()}++ /**+ * Retrieves a list of all available vector field names.+ * @returns {Iterator<string>} An iterator that provides the names of all the fields.+ */+ function _listFields() {return FF.list.keys()}++ /**+ * Represents a framework for managing vector fields used in dynamic simulations or visualizations.+ * @property {boolean} isActive - Indicates whether any vector field is currently active.+ * @property {Map} list - A map associating field names to their respective generator functions and current states.+ * @property {Array} field - An array representing the current vector field grid with values.+ */const FF = {isActive: false,list: new Map(),- step_length() {return Math.min(_r.width,_r.height) / 1000},+ current: '',++ /**+ * Calculates a relative step length based on the renderer's dimensions, used in field grid calculations.+ * @returns {number} The relative step length value.+ */+ step_length() {+ return Math.min(_r.width,_r.height) / 1000+ },++ /**+ * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.+ */create() {- this.R = _r.width * 0.01, this.left_x = -1 * _r.width, this.top_y = -1 * _r.height;- this.num_columns = Math.round(2 * _r.width / this.R), this.num_rows = Math.round(2 * _r.height / this.R);- this.addStandard();+ this.R = _r.width * 0.01; // Determine the resolution of the field grid+ this.left_x = -1 * _r.width; // Left boundary of the field+ this.top_y = -1 * _r.height; // Top boundary of the field+ this.num_columns = Math.round(2 * _r.width / this.R); // Number of columns in the grid+ this.num_rows = Math.round(2 * _r.height / this.R); // Number of columns in the grid+ this.field = new Array(FF.num_columns); // Initialize the field array+ for (let i = 0; i < this.num_columns; i++) {+ this.field[i] = new Float64Array(this.num_rows);+ }+ this.addStandard(); // Add default vector fields+ },++ /**+ * Retrieves the field values for the current vector field.+ * @returns {Float64Array[]} The current vector field grid.+ */+ flow_field() {+ return this.list.get(this.current).field+ },++ /**+ * Regenerates the current vector field using its associated generator function.+ * @param {number} [t=0] - An optional time parameter that can affect field generation.+ */+ refresh(t = 0) {+ this.list.get(this.current).field = this.list.get(this.current).gen(t)},- flow_field() {return this.list.get(this.current).field},- refresh(t = 0) {this.list.get(this.current).field = this.list.get(this.current).gen(t)},++ /**+ * Adds standard predefined vector fields to the list with unique behaviors.+ */addStandard() {- addField("curved", function(t) {- let field = []- var angleRange = R.randInt(-25,-15);- if (R.randInt(0,100)%2 == 0) {angleRange = angleRange * -1}- for (var column=0;column<FF.num_columns;column++){- field.push([0]);- for (var row=0;row<FF.num_rows;row++) {- var noise_val = noise(column * 0.02 + t * 0.03, row * 0.02 + t * 0.03)- var angle = R.map(noise_val, 0.0, 1.0, -angleRange, angleRange)- field[column][row] = 3 * angle;- }+ _addField("curved", function(t) {+ let angleRange = R.randInt(-25,-15);+ if (R.randInt(0,100)%2 == 0) {angleRange = angleRange * -1}+ for (let column=0;column<FF.num_columns;column++){+ for (let row=0;row<FF.num_rows;row++) {+ let noise_val = noise(column * 0.02 + t * 0.03, row * 0.02 + t * 0.03)+ let angle = R.map(noise_val, 0.0, 1.0, -angleRange, angleRange)+ FF.field[column][row] = 3 * angle;}- return field;- })- addField("truncated", function(t) {- let field = []- var angleRange = R.randInt(-25,-15) + 5 * R.sin(t);+ }+ return FF.field;+ })+ _addField("truncated", function(t) {+ let angleRange = R.randInt(-25,-15) + 5 * R.sin(t);if (R.randInt(0,100)%2 == 0) {angleRange=angleRange*-1}- var truncate = R.randInt(5,10);- for (var column=0;column<FF.num_columns;column++){- field.push([0]);- for (var row=0;row<FF.num_rows;row++) {- var noise_val = noise(column * 0.02, row * 0.02)- var angle = Math.round(R.map(noise_val, 0.0, 1.0, -angleRange, angleRange)/truncate)*truncate;- field[column][row] = 4 * angle;+ let truncate = R.randInt(5,10);+ for (let column=0;column<FF.num_columns;column++){+ for (let row=0;row<FF.num_rows;row++) {+ let noise_val = noise(column * 0.02, row * 0.02)+ let angle = Math.round(R.map(noise_val, 0.0, 1.0, -angleRange, angleRange)/truncate)*truncate;+ FF.field[column][row] = 4 * angle;}}- return field;+ return FF.field;})- addField("zigzag", function(t) {- let field = []- var angleRange = R.randInt(-30,-15) + Math.abs(44 * R.sin(t));+ _addField("zigzag", function(t) {+ let angleRange = R.randInt(-30,-15) + Math.abs(44 * R.sin(t));if (R.randInt(0,100)%2 == 0) {angleRange=angleRange*-1}- var dif = angleRange;- var angle = 0;- for (var column=0;column<FF.num_columns;column++){- field.push([0]);- for (var row=0;row<FF.num_rows;row++) {- field[column][row] = angle;+ let dif = angleRange;+ let angle = 0;+ for (let column=0;column<FF.num_columns;column++){+ for (let row=0;row<FF.num_rows;row++) {+ FF.field[column][row] = angle;angle = angle + dif;dif = -1*dif;}angle = angle + dif;dif = -1*dif;}- return field;+ return FF.field;})- addField("waves", function(t) {- let field = []- var sinrange = R.randInt(10,15) + 5 * R.sin(t);- var cosrange = R.randInt(3,6) + 3 * R.cos(t);- var baseAngle = R.randInt(20,35);- for (var column=0;column<FF.num_columns;column++){- field.push([0]);- for (var row=0;row<FF.num_rows;row++) {- var angle = R.sin(sinrange*column)*(baseAngle * R.cos(row*cosrange)) + R.randInt(-3,3);- field[column][row] = angle;+ _addField("waves", function(t) {+ let sinrange = R.randInt(10,15) + 5 * R.sin(t);+ let cosrange = R.randInt(3,6) + 3 * R.cos(t);+ let baseAngle = R.randInt(20,35);+ for (let column=0;column<FF.num_columns;column++){+ for (let row=0;row<FF.num_rows;row++) {+ let angle = R.sin(sinrange*column)*(baseAngle * R.cos(row*cosrange)) + R.randInt(-3,3);+ FF.field[column][row] = angle;}}- return field;+ return FF.field;})- addField("seabed", function(t) {- let field = []- var baseSize = R.random(0.4,0.8)- var baseAngle = R.randInt(18,26) ;- for (var column=0;column<FF.num_columns;column++){- field.push([0]);- for (var row=0;row<FF.num_rows;row++) {- var addition = R.randInt(15,20)- var angle = baseAngle*R.sin(baseSize*row*column+addition);- field[column][row] = 1.1*angle * R.cos(t);+ _addField("seabed", function(t) {+ let baseSize = R.random(0.4,0.8)+ let baseAngle = R.randInt(18,26) ;+ for (let column=0;column<FF.num_columns;column++){+ for (let row=0;row<FF.num_rows;row++) {+ let addition = R.randInt(15,20)+ let angle = baseAngle*R.sin(baseSize*row*column+addition);+ FF.field[column][row] = 1.1*angle * R.cos(t);}}- return field;+ return FF.field;})}}++ /**+ * The Position class represents a point within a two-dimensional space, which can interact with a vector field.+ * It provides methods to update the position based on the field's flow and to check whether the position is+ * within certain bounds (e.g., within the field or canvas).+ */class Position {- constructor (x,y) {this.update(x, y), this.plotted = 0;}++ /**+ * Constructs a new Position instance.+ * @param {number} x - The initial x-coordinate.+ * @param {number} y - The initial y-coordinate.+ */+ constructor (x,y) {+ this.update(x, y);+ this.plotted = 0;+ }++ /**+ * Updates the position's coordinates and calculates its offsets and indices within the flow field if active.+ * @param {number} x - The new x-coordinate.+ * @param {number} y - The new y-coordinate.+ */update (x,y) {this.x = x , this.y = y;if (FF.isActive) {- this.x_offset = this.x - FF.left_x + trans()[0];- this.y_offset = this.y - FF.top_y + trans()[1];+ this.x_offset = this.x - FF.left_x + _trans()[0];+ this.y_offset = this.y - FF.top_y + _trans()[1];this.column_index = Math.round(this.x_offset / FF.R);this.row_index = Math.round(this.y_offset / FF.R);}}- reset() {this.plotted = 0}++ /**+ * Resets the 'plotted' property to 0.+ */+ reset() {+ this.plotted = 0;+ }++ /**+ * Checks if the position is within the active flow field's bounds.+ * @returns {boolean} - True if the position is within the flow field, false otherwise.+ */isIn() {return (FF.isActive) ? ((this.column_index >= 0 && this.row_index >= 0) && (this.column_index < FF.num_columns && this.row_index < FF.num_rows)) : this.isInCanvas()}++ /**+ * Checks if the position is within the canvas bounds.+ * @returns {boolean} - True if the position is within the canvas, false otherwise.+ */isInCanvas() {- return (this.x >= -0.55 * _r.width - trans()[0] && this.x <= 0.55 * _r.width - trans()[0]) && (this.y >= -0.55 * _r.height - trans()[1] && this.y <= 0.55 * _r.height - trans()[1])+ let w = 0.55 * _r.width, h = 0.55 * _r.height;+ return (this.x >= -w - _trans()[0] && this.x <= w - _trans()[0]) && (this.y >= -h - _trans()[1] && this.y <= h - _trans()[1])}++ /**+ * Calculates the angle of the flow field at the position's current coordinates.+ * @returns {number} - The angle in radians, or 0 if the position is not in the flow field or if the flow field is not active.+ */angle () {return (this.isIn() && FF.isActive) ? FF.flow_field()[this.column_index][this.row_index] : 0}- moveTo (_length, _dir, _step_length = FF.step_length(), straight = false) {++ /**+ * Moves the position along the flow field by a certain length.+ * @param {number} _length - The length to move along the field.+ * @param {number} _dir - The direction of movement.+ * @param {number} _step_length - The length of each step.+ * @param {boolean} isFlow - Whether to use the flow field for movement.+ */+ moveTo (_length, _dir, _step_length = FF.step_length(), isFlow = true) {if (this.isIn()) {+ let a, b;+ if (!isFlow) {+ a = R.cos(-_dir);+ b = R.sin(-_dir);+ }for (let i = 0; i < _length / _step_length; i++) {- let a = straight? R.cos(-_dir) : R.cos(this.angle() - _dir);- let b = straight? R.sin(-_dir) : R.sin(this.angle() - _dir);+ if (isFlow) {+ let angle = this.angle();+ a = R.cos(angle - _dir);+ b = R.sin(angle - _dir);+ }let x_step = (_step_length * a), y_step = (_step_length * b);this.plotted += _step_length;this.update(this.x + x_step, this.y + y_step);@@ -282,13 +651,24 @@this.plotted += _step_length;}}++ /**+ * Plots a point to another position within the flow field, following a Plot object+ * @param {Position} _plot - The Plot path object.+ * @param {number} _length - The length to move towards the target position.+ * @param {number} _step_length - The length of each step.+ * @param {number} _scale - The scaling factor for the plotting path.+ */plotTo (_plot, _length, _step_length, _scale) {if (this.isIn()) {+ const inverse_scale = 1 / _scale;for (let i = 0; i < _length / _step_length; i++) {- let x_step = (_step_length * R.cos(this.angle() - _plot.angle(this.plotted)));- let y_step = (_step_length * R.sin(this.angle() - _plot.angle(this.plotted)));- this.plotted += _step_length / _scale;- this.update(this.x + x_step, this.y + y_step);+ let current_angle = this.angle();+ let plot_angle = _plot.angle(this.plotted);+ let x_step = (_step_length * R.cos(current_angle - plot_angle));+ let y_step = (_step_length * R.sin(current_angle - plot_angle));+ this.plotted += _step_length * inverse_scale;+ this.update(this.x + x_step, this.y + y_step);}} else {this.plotted += _step_length / scale;@@ -296,216 +676,382 @@}}- //////////////////////////////////////////////////- // BRUSHES + HATCH SYSTEM++// =============================================================================+// Section: Brushes+// =============================================================================+function _noStroke() {B.isActive = false}const B = {isActive: true,list: new Map(),- add(a,b) {- if (b.type === "image") { // Image tip types+ // Default Values+ c: "#000000",+ w: 1,+ cr: null,+ name: "HB",+ // Add and set functions (Exported)+ add: (a, b) => {+ const isBlendableType = b.type === "marker" || b.type === "custom" || b.type === "image";+ if (b.type === "image") {T.add(b.image.src);- b.tip = function() {_r.image(T.tips.get(B.p.image.src),-B.p.weight/2,-B.p.weight/2,B.p.weight,B.p.weight)}+ b.tip = () => _r.image(T.tips.get(B.p.image.src), -B.p.weight / 2, -B.p.weight / 2, B.p.weight, B.p.weight);}- if ((b.blend !== false) && (b.type === "marker" || b.type === "custom" || b.type === "image" )) { b.blend = true } else {b.blend = false}- B.list.set(a,{param:b,colors:[],buffers:[]})+ b.blend = isBlendableType && b.blend !== false;+ B.list.set(a, { param: b, colors: [], buffers: [] });+ },+ set(brushName, color, weight) {+ B.name = brushName;+ B.c = color;+ B.w = weight;+ },+ setBrush(brushName) {+ B.name = brushName;},- c: "#000000", w: 1, cr: null, name: "HB",- set(a,c,w) {B.name = a, B.c = c, B.w = w},- setBrush(a) {B.name = a},- setColor(r,g,b) {B.c = (arguments.length < 2) ? r : [r,g,b]; B.isActive = true},- setWeight(w) {B.w = w},- spacing() {B.p = B.list.get(B.name).param; return B.p.spacing * B.w},- clip(a) {B.cr = a},+ setColor(r,g,b) {+ B.c = (arguments.length < 2) ? r : [r,g,b];+ B.isActive = true;+ },+ setWeight(weight) {+ B.w = weight;+ },+ // Define clipping region (Exported)+ clip(clippingRegion) {+ B.cr = clippingRegion;+ },+ // Line and Plot functions (Exported)line(x1,y1,x2,y2) {- if (!isReady) _load();- B.l = dist(x1,y1,x2,y2), B.position = new Position(x1,y1), B.flow = false, B.plot = false;- B.draw(calcAngle(x1,y1,x2,y2),true)+ _ensureReady();+ B.initializeDrawingState(x1, y1, dist(x1,y1,x2,y2), false, false);+ let angle = calcAngle(x1,y1,x2,y2);+ B.draw(angle, false);},flowLine(x,y,length,dir) {- if (!isReady) _load();- if (angleMode() === "radians") dir = dir * 180 / Math.PI- B.l = length, B.position = new Position(x,y), B.flow = true, B.plot = false;- B.draw(dir,false)+ _ensureReady();+ if (angleMode() === "radians") dir = dir * 180 / Math.PI;+ B.initializeDrawingState(x, y, length, true, false);+ B.draw(dir, false);},flowShape(p,x,y,scale) {- if (!isReady) _load();- B.l = p.length, B.position = new Position(x,y), B.plot = p, p.calcIndex(0);- B.push();- let st = B.p.spacing * B.w;- for (let steps = 0; steps < Math.round(B.l * scale / st); steps++) {- B.tip(), B.position.plotTo(p,st,st,scale)- }- B.pop();+ _ensureReady();+ B.initializeDrawingState(x, y, p.length, true, p);+ B.draw(scale, true);},- draw(dir,bool) {- B.dir = dir- B.push()- let st = B.p.spacing * B.w- for (let steps = 0; steps < Math.round(B.l / st); steps++) {B.tip(), B.position.moveTo(st,dir,st,bool)}- B.pop()+ // Internal Functions+ spacing() {+ return this.p.spacing * this.w;},- push() {- B.p = B.list.get(B.name).param- if (B.p.pressure.type !== "custom") {B.a = R.random(-1,1), B.b = R.random(1,1.5), B.cp = R.random(3,3.5);}- else {B.cp = R.random(-0.2,0.2)}- B.min = B.p.pressure.min_max[0], B.max = B.p.pressure.min_max[1];- if (B.p.blend) trans(), Mix.mask.begin();- _r.push(), B.c = _r.color(B.c), _r.noStroke();- if (B.p.blend) _r.translate(matrix[0],matrix[1]), B.markerTip();++ initializeDrawingState(x, y, length, flow, plot) {+ this.position = new Position(x, y);+ this.length = length;+ this.flow = flow;+ this.plot = plot;+ if (plot) plot.calcIndex(0);},- tip() {- let pressure = B.plot ? B.simPressure() * B.plot.pressure(B.position.plotted) : B.simPressure(); // Pressure- let alpha = Math.floor(B.p.opacity * Math.pow(pressure,B.p.type === "marker" ? 1 : 1.5)); // Alpha- if (B.p.blend) {_r.fill(255,0,0,alpha/2)} else {B.c.setAlpha(alpha), _r.fill(B.c)}; // Color- if (B.crop()) {- if (B.p.type === "spray") {- let vibration = (B.w * B.p.vibration * pressure) + B.w * randomGaussian() * B.p.vibration / 3;- let sw = B.p.weight * R.random(0.9,1.1);- for (let j = 0; j < B.p.quality / pressure; j++) {- let r = R.random(0.9,1.1);- let rX = r * vibration * R.random(-1,1);- _r.circle(B.position.x + rX, B.position.y + R.random(-1, 1) * Math.sqrt(Math.pow(r * vibration,2) - Math.pow(rX,2)), sw);- }- } else if (B.p.type === "marker") {- let vibration = B.w * B.p.vibration;- _r.circle(B.position.x + vibration * R.random(-1,1), B.position.y + vibration * R.random(-1,1), B.w * B.p.weight * pressure)- } else if (B.p.type === "custom" || B.p.type === "image") {- _r.push();- let vibration = B.w * B.p.vibration;- _r.translate(B.position.x + vibration * R.random(-1,1), B.position.y + vibration * R.random(-1,1)),- B.adjust_tip(B.w * pressure, alpha)- B.p.tip();- _r.pop();- } else {- let vibration = B.w * B.p.vibration * (B.p.definition + (1-B.p.definition) * randomGaussian() * B.gauss(0.5,0.9,5,0.2,1.2) / pressure);- if (R.random(0,B.p.quality) > 0.4) {- _r.circle(B.position.x + 0.7 * vibration * R.random(-1,1),B.position.y + vibration * R.random(-1,1), pressure * B.p.weight * B.w * R.random(0.85,1.15));++ draw(angle_scale, isPlot) {+ if (!isPlot) this.dir = angle_scale;+ this.pushState();+ const st = this.spacing();+ const total_steps = isPlot ? Math.round(this.length * angle_scale / st) : Math.round(this.length / st);+ for (let steps = 0; steps < total_steps; steps++) {+ this.tip();+ if (isPlot) {+ this.position.plotTo(this.plot, st, st, angle_scale);+ } else {+ this.position.moveTo(st, angle_scale, st, this.flow);}}- }+ this.popState();},- adjust_tip(pressure, alpha) {- _r.scale(pressure);- if (B.p.type === "image") (B.p.blend) ? _r.tint(255, 0, 0, alpha/2) : _r.tint(_r.red(B.c),_r.green(B.c),_r.blue(B.c),alpha);- if (B.p.rotate === "random") _r.rotate(R.randInt(0,360));- if (B.p.rotate === "natural") _r.rotate(((B.plot) ? - B.plot.angle(B.position.plotted) : - B.dir) + (B.flow ? B.position.angle() : 0))++ pushState() {+ this.p = this.list.get(this.name).param+ // Pressure values for the stroke+ this.a = this.p.pressure.type !== "custom" ? R.random(-1, 1) : 0;+ this.b = this.p.pressure.type !== "custom" ? R.random(1, 1.5) : 0;+ this.cp = this.p.pressure.type !== "custom" ? R.random(3, 3.5) : R.random(-0.2, 0.2);+ const [min, max] = this.p.pressure.min_max;+ this.min = min;+ this.max = max;+ // Blend Mode+ this.c = _r.color(this.c);+ if (this.p.blend) _trans(), Mix.mask.begin();+ _r.push();+ _r.noStroke();+ if (this.p.blend) _r.translate(matrix[0],matrix[1]), this.markerTip();},- pop() {- if (B.p.blend) B.markerTip();++ popState() {+ if (this.p.blend) this.markerTip();_r.pop();- if (B.p.blend) Mix.mask.end(), Mix.blend(B.c);+ if (this.p.blend) Mix.mask.end(), Mix.blend(this.c);},- markerTip() {- if (B.crop()) {- let pressure = B.plot ? B.simPressure() * B.plot.pressure(B.position.plotted) : B.simPressure();- let alpha = Math.floor(B.p.opacity * Math.pow(pressure,B.p.type === "marker" ? 1 : 1.5));- _r.fill(255, 0, 0, alpha / 1.5);- for (let s = 0; s < 5; s++) {- if (B.p.type === "marker") {- _r.circle(B.position.x,B.position.y, s/5 * B.w * B.p.weight * pressure)- } else if (B.p.type === "custom" || B.p.type === "image") {- _r.push();- _r.translate(B.position.x, B.position.y),- B.adjust_tip(B.w * s/5 * pressure,alpha)- B.p.tip();- _r.pop();- }++ tip() {+ let pressure = this.calculatePressure(); // Calculate Pressure+ let alpha = this.calculateAlpha(pressure); // Calcula Alpha+ this.applyColor(alpha); // Apply Color+ if (this.isInsideClippingArea()) { // Check if it's inside clipping area+ switch (this.p.type) { // Draw different tip types+ case "spray":+ this.drawSpray(pressure);+ break;+ case "marker":+ this.drawMarker(pressure);+ break;+ case "custom":+ case "image":+ this.drawCustomOrImage(pressure, alpha);+ break;+ default:+ this.drawDefault(pressure);+ break;}}},- crop() {- if (B.cr) return B.position.x >= B.cr[0] && B.position.x <= B.cr[2] && B.position.y >= B.cr[1] && B.position.y <= B.cr[3];- else return true;+ // Pressure Functions+ calculatePressure() {+ return this.plot+ ? this.simPressure() * this.plot.pressure(this.position.plotted)+ : this.simPressure();+ },+ simPressure () {+ if (this.p.pressure.type === "custom") {+ return R.map(this.p.pressure.curve(this.position.plotted / this.length) + this.cp, 0, 1, this.min, this.max, true);+ }+ return this.gauss()},gauss(a = 0.5 + B.p.pressure.curve[0] * B.a, b = 1 - B.p.pressure.curve[1] * B.b, c = B.cp, min = B.min, max = B.max) {- return R.map((1 / ( 1 + Math.pow(Math.abs( ( B.position.plotted - a * B.l ) / ( b * B.l / 2 ) ), 2 * c))), 0, 1, min, max);+ return R.map((1 / ( 1 + Math.pow(Math.abs( ( this.position.plotted - a * this.length ) / ( b * this.length / 2 ) ), 2 * c))), 0, 1, min, max);},- simPressure () {- if (B.p.pressure.type === "custom") return R.map(B.p.pressure.curve(B.position.plotted / B.l)+B.cp,0,1,B.min,B.max,true);- else return this.gauss()+ // Color functions+ calculateAlpha(pressure) {+ return Math.floor(this.p.opacity * Math.pow(pressure, this.p.type === "marker" ? 1 : 1.5));},- hatch(polygons, dist, angle, options = {rand: false, continuous: false, gradient: false}) {- if (!isReady) _load();- if (angleMode() === "radians") angle = angle * 180 / Math.PI- angle = angle % 180;- let dots = [];- let minX = 999999, maxX = -999999, minY = 999999, maxY = -999999;- if (!Array.isArray(polygons)) {polygons = [polygons]}- for (let p of polygons) {- for (let a of p.a) {minX = Math.min(a[0],minX), maxX = Math.max(a[0],maxX), minY = Math.min(a[1],minY), maxY = Math.max(a[1],maxY)}+ applyColor(alpha) {+ if (this.p.blend) {+ _r.fill(255, 0, 0, alpha / 2);+ } else {+ this.c.setAlpha(alpha);+ _r.fill(this.c);}- minX -= 1, minY -= 1, maxX += 1, maxY += 1;- let ventana = new Polygon([[minX,minY],[maxX,minY],[maxX,maxY],[minX,maxY]])- let startY = (angle <= 90 && angle >= 0) ? minY : maxY;- let i = 0;- let linea = {- point1: { x: minX, y: startY },- point2: { x: minX + R.cos(-angle), y: startY + R.sin(-angle) }+ },+ // Clipping function+ isInsideClippingArea() {+ if (B.cr) return this.position.x >= B.cr[0] && this.position.x <= B.cr[2] && this.position.y >= B.cr[1] && this.position.y <= B.cr[3];+ else return true;+ },+ // Spray Tip+ drawSpray(pressure) {+ let vibration = (this.w * this.p.vibration * pressure) + this.w * randomGaussian() * this.p.vibration / 3;+ let sw = this.p.weight * R.random(0.9,1.1);+ const iterations = this.p.quality / pressure;+ for (let j = 0; j < iterations; j++) {+ let r = R.random(0.9,1.1);+ let rX = r * vibration * R.random(-1,1);+ let yRandomFactor = R.random(-1, 1);+ let rVibrationSquared = Math.pow(r * vibration, 2);+ let sqrtPart = Math.sqrt(rVibrationSquared - Math.pow(rX, 2));+ _r.circle(this.position.x + rX, this.position.y + yRandomFactor * sqrtPart, sw);}- let dist1 = dist;- while (ventana.intersect(linea).length > 0) {- let tempArray = [];- for (let p of polygons) {tempArray.push(p.intersect(linea))};- tempArray = tempArray.flat();- tempArray.sort(function(a,b) {- if(a.x == b.x) return a.y-b.y;- return a.x-b.x;- });- dots[i] = []- dots[i] = dots[i].concat(tempArray)- if (options.gradient) dist1 *= map(options.gradient,0,1,1,1.1,true)- i++- linea = {- point1 : {x: minX + dist1*i*R.cos(-angle+90), y: startY + dist1*i*R.sin(-angle+90)},- point2 : {x: minX + dist1*i*R.cos(-angle+90)+R.cos(-angle), y: startY + dist1*i*R.sin(-angle+90)+R.sin(-angle)}- }+ },+ // Marker Tip+ drawMarker(pressure, vibrate = true) {+ let vibration = vibrate ? this.w * this.p.vibration : 0;+ let rx = vibrate ? vibration * R.random(-1,1) : 0;+ let ry = vibrate ? vibration * R.random(-1,1) : 0;+ _r.circle(this.position.x + rx, this.position.y + ry, this.w * this.p.weight * pressure)+ },+ // Custom Tip of Image Tip+ drawCustomOrImage(pressure, alpha, vibrate = true) {+ _r.push();+ let vibration = vibrate ? this.w * this.p.vibration : 0;+ let rx = vibrate ? vibration * R.random(-1,1) : 0;+ let ry = vibrate ? vibration * R.random(-1,1) : 0;+ _r.translate(this.position.x + rx, this.position.y + ry),+ this.adjustSizeAndRotation(this.w * pressure, alpha)+ this.p.tip();+ _r.pop();+ },+ // Default Tip+ drawDefault(pressure) {+ let vibration = this.w * this.p.vibration * (this.p.definition + (1-this.p.definition) * randomGaussian() * this.gauss(0.5,0.9,5,0.2,1.2) / pressure);+ if (R.random(0, this.p.quality) > 0.4) {+ _r.circle(this.position.x + 0.7 * vibration * R.random(-1,1),this.position.y + vibration * R.random(-1,1), pressure * this.p.weight * this.w * R.random(0.85,1.15));}- let gdots = []- for (let dd of dots) {if (typeof dd[0] !== "undefined") { gdots.push(dd)}}- for (let j = 0; j < gdots.length; j++) {- let dd = gdots[j]- let r = options.rand ? options.rand : 0;- for (let i = 0; i < dd.length-1; i++) {- if (i % 2 == 0) {- dd[i].x += r * dist * R.random(-1,1), dd[i].y += r * dist * R.random(-1,1);- dd[i+1].x += r * dist * R.random(-1,1), dd[i+1].y += r * dist * R.random(-1,1);- B.line(dd[i].x,dd[i].y,dd[i+1].x,dd[i+1].y);- if (j > 0 && options.continuous) B.line(gdots[j-1][1].x,gdots[j-1][1].y,dd[i].x,dd[i].y);+ },++ adjustSizeAndRotation(pressure, alpha) {+ _r.scale(pressure);+ if (this.p.type === "image") (this.p.blend) ? _r.tint(255, 0, 0, alpha / 2) : _r.tint(_r.red(this.c), _r.green(this.c), _r.blue(this.c), alpha);+ if (this.p.rotate === "random") _r.rotate(R.randInt(0,360));+ if (this.p.rotate === "natural") _r.rotate(((this.plot) ? - this.plot.angle(this.position.plotted) : - this.dir) + (this.flow ? this.position.angle() : 0))+ },++ markerTip() {+ if (this.isInsideClippingArea()) {+ let pressure = this.calculatePressure();+ let alpha = this.calculateAlpha(pressure);+ _r.fill(255, 0, 0, alpha / 1.5);+ if (B.p.type === "marker") {+ for (let s = 1; s < 5; s++) {+ this.drawMarker(pressure * s/5, false)+ }+ } else if (B.p.type === "custom" || B.p.type === "image") {+ for (let s = 1; s < 5; s++) {+ this.drawCustomOrImage(pressure * s/5, alpha, false)}}}- }+ },}function brushes() {return Array.from(B.list.keys())}- //////////////////////////////////////////////////- // IMAGE TIPS++// =============================================================================+// Section: Hatching+// =============================================================================++ /**+ * Creates a hatching pattern across the given polygons.+ *+ * @param {Array|Object} polygons - A single polygon or an array of polygons to apply the hatching.+ * @param {number} dist - The distance between hatching lines.+ * @param {number} angle - The angle at which hatching lines are drawn.+ * @param {Object} options - An object containing optional parameters to affect the hatching style:+ * - rand: Introduces randomness to the line placement.+ * - continuous: Connects the end of a line with the start of the next.+ * - gradient: Changes the distance between lines to create a gradient effect.+ * Defaults to {rand: false, continuous: false, gradient: false}.+ */+ B.hatch = function (polygons, dist, angle, options = {rand: false, continuous: false, gradient: false}) {+ _ensureReady();+ angle = ((angleMode() === "radians") ? angle * 180 / Math.PI : angle) % 180+ // Calculate the bounding area of the provided polygons+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ let processPolygonPoints = (p) => {+ for (let a of p.a) {+ // (process points of a single polygon to find bounding area)+ minX = a[0] < minX ? a[0] : minX;+ maxX = a[0] > maxX ? a[0] : maxX;+ minY = a[1] < minY ? a[1] : minY;+ maxY = a[1] > maxY ? a[1] : maxY;+ }+ };+ // Ensure polygons is an array and find overall bounding area+ if (!Array.isArray(polygons)) {polygons = [polygons]}+ for (let p of polygons) {processPolygonPoints(p);}+ // Create a bounding polygon+ let ventana = new Polygon([[minX,minY],[maxX,minY],[maxX,maxY],[minX,maxY]])+ // Set initial values for line generation+ let startY = (angle <= 90 && angle >= 0) ? minY : maxY;+ let gradient = options.gradient ? map(options.gradient,0,1,1,1.1,true) : 1+ let dots = [], i = 0, dist1 = dist;+ let linea = (i) => {+ return {+ point1 : { x: minX + dist1 * i * R.cos(-angle+90), y: startY + dist1 * i * R.sin(-angle+90) },+ point2 : { x: minX + dist1 * i * R.cos(-angle+90) + R.cos(-angle), y: startY + dist1 * i * R.sin(-angle+90) + R.sin(-angle) }+ }+ }+ // Generate lines and calculate intersections with polygons+ // Loop through the lines based on the distance and angle to calculate intersections with the polygons+ // The loop continues until a line does not intersect with the bounding window polygon+ // Each iteration accounts for the gradient effect by adjusting the distance between lines+ while (ventana.intersect(linea(i)).length > 0) {+ let tempArray = [];+ for (let p of polygons) {tempArray.push(p.intersect(linea(i)))};+ dots[i] = tempArray.flat().sort((a, b) => (a.x === b.x) ? (a.y - b.y) : (a.x - b.x));+ dist1 *= gradient+ i+++ }+ // Filter out empty arrays to avoid drawing unnecessary lines+ let gdots = []+ for (let dd of dots) {if (typeof dd[0] !== "undefined") { gdots.push(dd)} }+ // Draw the hatching lines using the calculated intersections+ // If the 'rand' option is enabled, add randomness to the start and end points of the lines+ // If the 'continuous' option is set, connect the end of one line to the start of the next+ for (let j = 0; j < gdots.length; j++) {+ let dd = gdots[j]+ let r = options.rand || 0;+ let shouldDrawContinuousLine = j > 0 && options.continuous;+ for (let i = 0; i < dd.length-1; i += 2) {+ if (r !== 0) {+ dd[i].x += r * dist * R.random(-1, 1);+ dd[i].y += r * dist * R.random(-1, 1);+ dd[i + 1].x += r * dist * R.random(-1, 1);+ dd[i + 1].y += r * dist * R.random(-1, 1);+ }+ B.line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);+ if (shouldDrawContinuousLine) {+ B.line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);+ }+ }+ }+ }++// =============================================================================+// Section: Loading Custom Image Tips+// =============================================================================++ /**+ * A utility object for loading images, converting them to a red tint, and managing their states.+ */const T = {tips: new Map(),++ /**+ * Adds an image to the tips Map and sets up loading and processing.+ *+ * @param {string} src - The source URL of the image to be added and processed.+ */add (src) {+ // Create a new Image objectconst myImage = new Image();+ // Initially set the source as not processedthis.tips.set(src,false)+ // Define the onload handler for the imagemyImage.onload = function(){- T.tips.set(src,(T.imageToRed(myImage)))- };+ // Once the image is loaded, convert it to white and update the Map+ T.tips.set(src,(T.imageToWhite(myImage)))+ };+ // Set the source of the Image object, which begins the loading processmyImage.src = src;},- imageToRed (image) {++ /**+ * Converts the given image to a white tint by setting all color channels to white and adjusting the alpha channel.+ *+ * @param {Image} image - The image to be converted.+ * @returns {string} - The data URL of the converted canvas image.+ */+ imageToWhite (image) {+ // Create a canvas element to manipulate the imagelet canvas = document.createElement("canvas");canvas.width = image.width, canvas.height = image.height;let context = canvas.getContext("2d");+ // Draw the image onto the canvascontext.drawImage(image,0,0);+ // Get the image data from the canvaslet imageData=context.getImageData(0,0, image.width, image.height);+ // Modify the image data to create a white tint effectfor (let i = 0; i < 4 * image.width * image.height; i += 4) {- let a = (imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3;- imageData.data[i] = 255;- imageData.data[i + 1] = 255;- imageData.data[i + 2] = 255;- imageData.data[i + 3] = 255 - a;+ // Calculate the average for the grayscale value+ let average = (imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3;+ // Set all color channels to white+ imageData.data[i] = imageData.data[i + 1] = imageData.data[i + 2] = 255;+ // Adjust the alpha channel to the inverse of the average, creating the white tint effect+ imageData.data[i + 3] = 255 - average;}+ // Put the modified image data back onto the canvascontext.putImageData(imageData,0,0);+ // Return a data URL representing the canvas imagereturn canvas.toDataURL();},+ /**+ * Loads all processed images into the p5.js environment.+ * If no images are in the tips Map, logs a warning message.+ */load() {if (this.tips.size === 0) return console.log("ojo");for (let key of this.tips.keys()){@@ -513,92 +1059,162 @@}}}- //////////////////////////////////////////////////- // OTHER BRUSH FUNCTIONS++// =============================================================================+// Section: Polygon management. Basic geometries+// =============================================================================++ /**+ * Represents a polygon with a set of vertices.+ */class Polygon {++ /**+ * Constructs the Polygon object from an array of points.+ *+ * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].+ */constructor (array) {this.a = array;- this.vertices = [];- this.sides = [];- for (let a of array) {this.vertices.push({x:a[0],y:a[1]})}- for (let i = 0; i < this.vertices.length; i++) {- if (i < this.vertices.length-1) {this.sides[i] = [this.vertices[i],this.vertices[i+1]]}- else {this.sides[i] = [this.vertices[i],this.vertices[0]]}- }+ this.vertices = array.map(a => ({ x: a[0], y: a[1] }));+ this.sides = this.vertices.map((v, i, arr) => [v, arr[(i + 1) % arr.length]]);}+ /**+ * Intersects a given line with the polygon, returning all intersection points.+ *+ * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.+ * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.+ */intersect (line) {+ // Check if the result has been cached+ let cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;+ if (this._intersectionCache && this._intersectionCache[cacheKey]) {+ return this._intersectionCache[cacheKey];+ }let points = []for (let s of this.sides) {let intersection = intersectar(line.point1,line.point2,s[0],s[1])if (intersection !== false) {points.push(intersection)}}+ // Cache the result+ if (!this._intersectionCache) this._intersectionCache = {};+ this._intersectionCache[cacheKey] = points;+return points;}+ /**+ * Draws the polygon by iterating over its sides and drawing lines between the vertices.+ */draw () {- if (!isReady) _load();+ _ensureReady();if (B.isActive) {for (let s of this.sides) {B.line(s[0].x,s[0].y,s[1].x,s[1].y)}}}- fill () {if (!isReady) _load(); F.fill(this)}+ /**+ * Fills the polygon using the current fill state.+ */+ fill () {+ _ensureReady();+ F.fill(this);+ }+ /**+ * Creates hatch lines across the polygon based on a given distance and angle.+ *+ * @param {number} dist - The distance between hatch lines.+ * @param {number} angle - The angle of the hatch lines.+ * @param {Object} options - Additional options for hatching.+ * @param {number} [options.rand=0] - The vibration of the lines, between 0 (none) and 1 (a lot)+ * @param {number} [options.gradient=0] - Gradually increase distance between lines, between 0 (none) and 1 (a lot)+ * @param {boolean} [options.continuous=false] - If true, hatches the polygon with a single, continuous line+ */hatch (dist, angle, options) {- if (!isReady) _load();+ _ensureReady();B.hatch(this,dist,angle,options)}}- function _polygon (array) {- let p = new Polygon(array)- if (B.isActive) p.draw()- if (F.isActive) p.fill()- }- // line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/- function intersectar(point1,point2,point3,point4,bool = false) {- var x1 = point1.x, y1 = point1.y, x2 = point2.x, y2 = point2.y, x3 = point3.x, y3 = point3.y, x4 = point4.x, y4 = point4.y;- if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) return false;- let denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));- if (denominator === 0) return false;- let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator- let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator- if (!bool) if (ub < 0 || ub > 1) return false;- let x = x1 + ua * (x2 - x1)- let y = y1 + ua * (y2 - y1)- return {x: x,y: y}- }- function calcAngle(x1,y1,x2,y2) {- let a = (x2-x1 >= 0) ? Math.atan(-(y2-y1)/(x2-x1)) / (Math.PI / 180) : 180 + Math.atan(-(y2-y1)/(x2-x1)) / (Math.PI / 180)- return (a % 360 + 360) % 360++ /**+ * Creates a Polygon from a given array of points and performs drawing and filling+ * operations based on active states.+ *+ * @param {Array} pointsArray - An array of points where each point is an array of two numbers [x, y].+ */+ function _polygon(pointsArray) {+ if (!Array.isArray(pointsArray) || pointsArray.length < 3) {+ console.error('Invalid input for _polygon: An array with at least 3 points is required.');+ return;+ }+ // Create a new Polygon instance+ let polygon = new Polygon(pointsArray);+ // Draw the polygon if the B state is active+ if (B.isActive) {+ polygon.draw();+ }+ // Fill the polygon if the F state is active+ if (F.isActive) {+ polygon.fill();+ }}- //////////////////////////////////////////////////- // BASIC GEOMETRIES+ /**+ * Draws a rectangle on the canvas and fills it with the current fill color.+ *+ * @param {number} x - The x-coordinate of the rectangle.+ * @param {number} y - The y-coordinate of the rectangle.+ * @param {number} w - The width of the rectangle.+ * @param {number} h - The height of the rectangle.+ * @param {boolean} [mode=false] - If true, the rectangle is drawn centered at (x, y).+ */function _rect(x,y,w,h,mode = false) {- if (!isReady) _load();+ _ensureReady();if (mode) x = x - w / 2, y = y - h / 2;let p = new Polygon([[x,y],[x+w,y],[x+w,y+h],[x,y+h]])p.draw();p.fill();}++ /**+ * Draws a circle on the canvas and fills it with the current fill color.+ *+ * @param {number} x - The x-coordinate of the center of the circle.+ * @param {number} y - The y-coordinate of the center of the circle.+ * @param {number} radius - The radius of the circle.+ * @param {boolean} [r=false] - If true, applies a random factor to the radius for each segment.+ */function _circle(x,y,radius,r = false) {- if (!isReady) _load();+ _ensureReady();+ // Create a new Plot instance for a curve shapelet p = new Plot("curve")+ // Calculate the length of the arc for each quarter of the circlelet l = Math.PI * radius / 2;+ // Initialize the angle for the drawing segmentslet angle = 0- let rr = function() {return (r ? R.random(-1,1) : 0)}+ // Define a function to optionally add randomness to the segment length+ let rr = () => (r ? R.random(-1,1) : 0)+ // Add segments for each quarter of the circle with optional randomnessp.addSegment(0 + angle + rr(), l + rr(), 1, true)p.addSegment(-90 + angle + rr(), l + rr(), 1, true)p.addSegment(-180 + angle + rr(), l + rr(), 1, true)p.addSegment(-270 + angle + rr(), l + rr(), 1, true)+ // Optionally add a random final angle for the last segmentlet angle2 = r ? R.randInt(-5,5) : 0;if (r) p.addSegment(0 + angle, angle2 * (Math.PI/180) * radius, true)+ // Finalize the plotp.endPlot(angle2 + angle,1, true)+ // If the fill is active, generate a polygon from the plot and fill itif (F.isActive) {let pol = p.genPol(x - radius * R.sin(angle),y - radius * R.cos(-angle))pol.fill()}+ // If the border is active, draw the plotif (B.isActive) p.draw(x - radius * R.sin(angle),y - radius * R.cos(-angle),1)}- //////////////////////////////////////////////////- // PLOT SYSTEM (beginShape + beginStroke)++// =============================================================================+// Section: Shape, Stroke, and Spline. Plot System+// =============================================================================+class Plot {constructor (_type) {this.segments = [], this.angles = [], this.pres = [];@@ -648,7 +1264,7 @@while (d <= _d) {this.suma = d; d += this.segments[this.index+1]; this.index++;}}genPol (_x,_y) {- if (!isReady) _load();+ _ensureReady();let max = 0;let min = 9999;for (let o of this.segments) {@@ -668,60 +1284,129 @@return new Polygon(vertices);}draw (x,y,scale) {- if (!isReady) _load();+ _ensureReady();if (this.origin) x = this.origin[0], y = this.origin[1], scale = 1;B.flowShape(this,x,y,scale)}}- // beginShape and beginStroke- let strokeArray = false, strokeOption;++ // Holds the array of vertices for the custom shape being defined. Each vertex includes position and optional pressure.+ let strokeArray = false;+ // Holds options for the stroke, such as curvature, that can influence the shape's rendering.+ let strokeOption;++ /**+ * Starts recording vertices for a custom shape. Optionally, a curvature can be defined.+ * @param {number} [curvature] - Defines the curvature for the vertices being recorded (optional).+ */function _beginShape(curvature) {- if (!isReady) _load();- strokeOption = curvature;- strokeArray = [];+ _ensureReady(); // Ensure that the drawing context is ready+ strokeOption = curvature; // Set the curvature option for the shape+ strokeArray = []; // Initialize the array to store vertices}++ /**+ * Records a vertex in the custom shape being defined between _beginShape and _endShape.+ * @param {number} x - The x-coordinate of the vertex.+ * @param {number} y - The y-coordinate of the vertex.+ * @param {number} [pressure] - The pressure at the vertex (optional).+ */function _vertex(x, y, pressure) {- strokeArray.push([x,y,pressure])+ strokeArray.push([x, y, pressure]); // Add the vertex to the array}++ /**+ * Finishes recording vertices for a custom shape and either closes it or leaves it open.+ * It also triggers the drawing of the shape if the brush state is active.+ * @param {string} [a] - An optional argument to close the shape if set to CLOSE.+ */function _endShape(a) {- if (a === CLOSE) strokeArray.push(strokeArray[0])- let sp = new Spline(strokeArray, strokeOption)- if (F.isActive) {sp.p.genPol(sp.origin[0],sp.origin[1]).fill()}- if (B.isActive) sp.draw()- strokeArray = false;+ if (a === CLOSE) {+ strokeArray.push(strokeArray[0]); // Close the shape by connecting the last vertex to the first+ }+ let sp = new Spline(strokeArray, strokeOption); // Create a new Spline with the recorded vertices and curvature option+ if (F.isActive) {+ sp.p.genPol(sp.origin[0], sp.origin[1]).fill(); // Fill the shape if the fill state is active+ }+ if (B.isActive) {+ sp.draw(); // Draw the shape if the brush state is active+ }+ strokeArray = false; // Clear the array after the shape has been drawn}- function _beginStroke(type,x,y) {- if (!isReady) _load();- strokeOption = [x,y];- strokeArray = new Plot(type)++ /**+ * Begins a new stroke with a given type and starting position. This initializes+ * a new Plot to record the stroke's path.+ * @param {string} type - The type of the stroke, which defines the kind of Plot to create.+ * @param {number} x - The x-coordinate of the starting point of the stroke.+ * @param {number} y - The y-coordinate of the starting point of the stroke.+ */+ function _beginStroke(type, x, y) {+ _ensureReady(); // Ensure that the drawing environment is prepared+ strokeOption = [x, y]; // Store the starting position for later use+ strokeArray = new Plot(type); // Initialize a new Plot with the specified type}++ /**+ * Adds a segment to the stroke with a given angle, length, and pressure. This function+ * is called between _beginStroke and _endStroke to define the stroke's path.+ * @param {number} angle - The initial angle of the segment, relative to the canvas.+ * @param {number} length - The length of the segment.+ * @param {number} pressure - The pressure at the start of the segment, affecting properties like width.+ */function _move(angle, length, pressure) {- strokeArray.addSegment(angle, length, pressure)+ strokeArray.addSegment(angle, length, pressure); // Add the new segment to the Plot}- function _endStroke(angle,pressure) {- strokeArray.endPlot(angle,pressure)- strokeArray.draw(strokeOption[0],strokeOption[1],1)- strokeArray = false;++ /**+ * Completes the stroke path and triggers the rendering of the stroke.+ * @param {number} angle - The angle of the curve at the last point of the stroke path.+ * @param {number} pressure - The pressure at the end of the stroke.+ */+ function _endStroke(angle, pressure) {+ strokeArray.endPlot(angle, pressure); // Finalize the Plot with the end angle and pressure+ strokeArray.draw(strokeOption[0], strokeOption[1], 1); // Draw the stroke using the stored starting position+ strokeArray = false; // Clear the strokeArray to indicate the end of this stroke}- // Spline class++ /**+ * Represents a spline curve, which is a type of smooth curve defined by a series of points.+ */class Spline {++ /**+ * Constructs a new Spline object.+ * @param {Array<Array<number>>} array_points - An array of points defining the spline curve.+ * @param {number} [curvature=0.5] - The curvature of the spline curve, beterrn 0 and 1. A curvature of 0 will create a series of straight segments.+ */constructor (array_points, curvature = 0.5) {- let p = new Plot((curvature === 0)? "segments" : "curve")- if (array_points) {- this.origin = [array_points[0][0],array_points[0][1]]- p.origin = this.origin+ // Initialize the plot type based on curvature+ this.plotType = (curvature === 0) ? "segments" : "curve";+ this.p = new Plot(this.plotType);++ // Proceed only if there are points provided+ if (array_points && array_points.length > 0) {+ // Set the origin point from the first point in the array+ this.setOrigin(array_points[0]);++ // Add each segment to the plotlet done = 0;for (let i = 0; i < array_points.length - 1; i++) {if (curvature > 0 && i < array_points.length - 2) {+ // Get the current and next pointslet p1 = array_points[i], p2 = array_points[i+1], p3 = array_points[i+2];+ // Calculate distances and angles between pointslet d1 = dist(p1[0],p1[1],p2[0],p2[1]), d2 = dist(p2[0],p2[1],p3[0],p3[1]);let a1 = calcAngle(p1[0],p1[1],p2[0],p2[1]), a2 = calcAngle(p2[0],p2[1],p3[0],p3[1]);+ // Calculate curvature based on the minimum distancelet dd = curvature * Math.min(Math.min(d1,d2),0.5 * Math.min(d1,d2)), dmax = Math.max(d1,d2)let s1 = d1 - dd, s2 = d2 - dd;+ // If the angles are approximately the same, create a straight segmentif (Math.floor(a1) === Math.floor(a2)) {- p.addSegment(a1,s1,p1[2],true)- p.addSegment(a2,d2,p2[2],true)+ this.p.addSegment(a1,s1,p1[2],true)+ this.p.addSegment(a2,d2,p2[2],true)} else {+ // If the angles are not the same, create curves, etc (this is a too complex...)let point1 = {x: p2[0] - dd * R.cos(-a1), y: p2[1] - dd * R.sin(-a1)}let point2 = {x: point1.x + dmax * R.cos(-a1+90), y: point1.y + dmax * R.sin(-a1+90)}let point3 = {x: p2[0] + dd * R.cos(-a2), y: p2[1] + dd * R.sin(-a2)}@@ -731,68 +1416,119 @@let disti = dist(point1.x,point1.y,point3.x,point3.y)/2let a3 = 2*asin(disti/radius)let s3 = 2 * Math.PI * radius * a3 / 360;- p.addSegment(a1,s1-done, p1[2],true)- p.addSegment(a1,s3, p1[2],true)- p.addSegment(a2,i === array_points.length - 3 ? s2 : 0, p2[2],true)+ this.p.addSegment(a1,s1-done, p1[2],true)+ this.p.addSegment(a1,s3, p1[2],true)+ this.p.addSegment(a2,i === array_points.length - 3 ? s2 : 0, p2[2],true)done = dd;}if (i == array_points.length - 3) {- p.endPlot(a2,p2[2],true)+ this.p.endPlot(a2,p2[2],true)}} else if (curvature === 0) {+ // If curvature is 0, simply create segmentslet p1 = array_points[i], p2 = array_points[i+1]let d = dist(p1[0],p1[1],p2[0],p2[1]);let a = calcAngle(p1[0],p1[1],p2[0],p2[1]);- p.addSegment(a,d,1,true)+ this.p.addSegment(a,d,1,true)if (i == array_points.length - 2) {- p.endPlot(a,1,true)+ this.p.endPlot(a,1,true)}}}}- this.p = p}+ setOrigin(point) {+ this.p.origin = [point[0], point[1]];+ }+ /**+ * Draws the spline curve on the canvas.+ */draw () {this.p.draw()}}+ /**+ * Creates and draws a spline curve with the given points and curvature.+ * @param {Array<Array<number>>} array_points - An array of points defining the spline curve.+ * @param {number} [curvature=0.5] - The curvature of the spline curve, between 0 and 1. A curvature of 0 will create a series of straight segments.+ */function _spline(array_points, curvature = 0.5) {- if (!isReady) _load();- let p = new Spline(array_points, curvature)- p.draw()+ _ensureReady(); // Ensure that the drawing environment is prepared+ let p = new Spline(array_points, curvature); // Create a new Spline instance+ p.draw(); // Draw the spline}- //////////////////////////////////////////////////- // FILL SYSTEM+// =============================================================================+// Section: Fill Management+// =============================================================================+// This section manages the fill properties, allowing for complex fill operations with+// effects such as bleeding, which simulates a watercolor-like appearance.++ /**+ * Sets the fill color and opacity for subsequent drawing operations.+ * @param {number|p5.Color} a - The red component of the color or grayscale value, or a color object.+ * @param {number} [b] - The green component of the color or grayscale opacity.+ * @param {number} [c] - The blue component of the color.+ * @param {number} [d] - The opacity of the color.+ */function _fill(a,b,c,d) {F.o = (arguments.length < 4) ? ((arguments.length < 3) ? b : 1) : d;F.c = (arguments.length < 3) ? color(a) : color(a,b,c);F.isActive = true;}- function _bleed(_i) {F.b = _i > 0.5 ? 0.5 : _i}- function _noFill() {F.isActive = false}++ /**+ * Sets the bleed level for the fill operation, simulating a watercolor effect.+ * @param {number} _i - The intensity of the bleed effect, capped at 0.5.+ */+ function _bleed(_i) {+ F.b = _i > 0.5 ? 0.5 : _i;+ }++ /**+ * Disables the fill for subsequent drawing operations.+ */+ function _noFill() {+ F.isActive = false;+ }++ /**+ * Object representing the fill state and operations for drawing.+ * @property {boolean} isActive - Indicates if the fill operation is active.+ * @property {number} b - Base value for bleed effect.+ * @property {Array} v - Array of p5.Vector representing vertices of the polygon to fill.+ * @property {Array} m - Array of multipliers for the bleed effect on each vertex.+ * @property {function} fill - Method to fill a polygon with a watercolor effect.+ * @property {function} calcCenter - Method to calculate the centroid of the polygon.+ */const F = {isActive: false,b: 0.07,+ /**+ * Fills the given polygon with a watercolor effect.+ * @param {Object} polygon - The polygon to fill.+ */fill (polygon) {if (this.isActive) {- F.v = []- for (let vert of polygon.a) {F.v.push(createVector(vert[0],vert[1]))}- F.m = [];- let fluid = F.v.length * R.random(0.4)- // Shift elements randomly without changing order- let shift = R.randInt(0,F.v.length);- F.v = F.v.slice(shift,F.v.length).concat(F.v.slice(0,shift));- for (let i = 0; i < F.v.length; i++) {- if (i < fluid) {- F.m.push((constrain(R.random(0.8,1.2) * F.b * 2,0,0.9)))- } else {- F.m.push((R.random(0.8,1.2) * F.b))- }- }- // Generate polygon for watercolor effect- let fill = new fillPol (F.v, F.m, F.calcCenter())- fill.fill(F.c, int(map(F.o,0,255,0,30,true)))+ // Map polygon vertices to p5.Vector objects+ this.v = polygon.a.map(vert => createVector(vert[0], vert[1]));+ // Calculate fluidity once, outside the loop+ const fluid = this.v.length * R.random(0.4);+ // Map vertices to bleed multipliers with more intense effect on 'fluid' vertices+ F.m = this.v.map((_, i) => {+ let multiplier = R.random(0.8, 1.2) * this.b;+ return i < fluid ? constrain(multiplier * 2, 0, 0.9) : multiplier;+ });+ // Shift vertices randomly to create a more natural watercolor edge+ let shift = R.randInt(0, this.v.length);+ this.v = [...this.v.slice(shift), ...this.v.slice(0, shift)];+ // Create and fill the polygon with the calculated bleed effect+ let pol = new fillPol (this.v, this.m, this.calcCenter())+ pol.fill(this.c, int(map(this.o,0,255,0,30,true)))}},+ /**+ * Calculates the center point of the polygon based on the vertices.+ * @returns {p5.Vector} A vector representing the centroid of the polygon.+ */calcCenter () {let midx = 0, midy = 0;for(let i = 0; i < this.v.length; ++i) {@@ -803,84 +1539,164 @@return createVector(midx,midy)}}++ /**+ * The fillPol class is used to create and manage the properties of the polygons that produces+ * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers+ * of color with varying intensity and erase parts to simulate a natural watercolor bleed.+ * The implementation follows Tyler Hobbs' guide to simulating watercolor:+ * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints+ */class fillPol {++ /**+ * The constructor initializes the polygon with a set of vertices, multipliers for the bleed effect, and a center point.+ * @param {p5.Vector[]} _v - An array of p5.Vector objects representing the vertices of the polygon.+ * @param {number[]} _m - An array of numbers representing the multipliers for the bleed effect at each vertex.+ * @param {p5.Vector} _center - A p5.Vector representing the calculated center point of the polygon.+ */constructor (_v,_m,_center) {this.v = _v;this.m = _m;this.midP = _center;this.size = p5.Vector.sub(this.midP,this.v[0]).mag();}- grow (_a,degrow = false) {++ /**+ * Grows the polygon's vertices outwards to simulate the spread of watercolor.+ * Optionally, can also shrink (degrow) the polygon's vertices inward.+ * @param {number} _a - The growth factor.+ * @param {boolean} [degrow=false] - If true, vertices will move inwards.+ * @returns {fillPol} A new `fillPol` object with adjusted vertices.+ */+ grow (growthFactor, degrow = false) {const newVerts = [];const newMods = [];- var vertixlength = this.v.length;- if (_a >= 0.2) {vertixlength = int(_a * this.v.length);}- for (let i = 0; i < vertixlength; i ++) {- const j = (i + 1) % vertixlength;- const v1 = this.v[i];- const v2 = this.v[j];- let mod = (_a == 0.1) ? 0.75 : this.m[i];- if (degrow) mod = -0.5;- const chmod = m => {return m + (randomGaussian(0.5,0.1) - 0.5) * 0.1;}- newVerts.push(v1);- newMods.push(chmod(mod));- const segment = p5.Vector.sub(v2, v1);- const len = segment.mag();- segment.mult(constrain(randomGaussian(0.5,0.2),0.1,0.9));- const v = p5.Vector.add(segment, v1);- segment.rotate(-90 + (randomGaussian(0,0.4)) * 45);- segment.setMag(randomGaussian(0.5,0.2) * R.random(0.6,1.4) * len * mod);- v.add(segment);- newVerts.push(v);- newMods.push(chmod(mod));+ // Determine the length of vertices to process based on growth factor+ let verticesToProcess = growthFactor >= 0.2 ? Math.floor(growthFactor * this.v.length) : this.v.length;+ // Function to change the modifier based on a Gaussian distribution+ const changeModifier = (modifier) => {+ const gaussianVariation = randomGaussian(0.5, 0.1);+ return modifier + (gaussianVariation - 0.5) * 0.1;+ };+ // Pre-calculate rotation factor if angleMode is constant+ const rotationFactor = (angleMode() === "radians") ? Math.PI / 180 : 1;+ // Loop through each vertex to calculate the new position based on growth+ for (let i = 0; i < verticesToProcess; i++) {+ const currentVertex = this.v[i];+ const nextVertex = this.v[(i + 1) % verticesToProcess];+ // Determine the growth modifier+ let mod = (growthFactor === 0.1) ? 0.75 : this.m[i];+ if (degrow) mod *= -0.5;+ // Add the current vertex and its modified value+ newVerts.push(currentVertex);+ newMods.push(changeModifier(mod));+ // Calculate the new vertex position+ let newVertex = p5.Vector.lerp(currentVertex, nextVertex, constrain(randomGaussian(0.5,0.2),0.1,0.9));+ let side = p5.Vector.sub(nextVertex, currentVertex)+ let direction = side.copy().normalize();+ let rotationDegrees = -90 + (randomGaussian(0,0.4)) * 45;+ direction.rotate(rotationDegrees * rotationFactor);+ direction.mult(randomGaussian(0.5, 0.2) * random(0.6, 1.4) * side.mag() * mod);+ newVertex.add(direction);+ // Add the new vertex and its modifier+ newVerts.push(newVertex);+ newMods.push(changeModifier(mod));}return new fillPol (newVerts, newMods, this.midP);}++ /**+ * Fills the polygon with the specified color and intensity.+ * It uses layered growth to simulate watercolor paper absorption and drying patterns.+ * @param {p5.Color|string} color - The fill color.+ * @param {number} intensity - The opacity of the color layers.+ */fill (color, intensity) {- let pol = this.grow()- let pol4 = this.grow(0.6)- let pol2 = pol.grow().grow(0.5);- let pol3 = pol2.grow(0.4);- let numLayers = 18- trans();+ // Precalculate stuff+ const numLayers = 18;+ const intensityThird = intensity / 3;+ const intensityQuarter = intensity / 4;+ const intensityHalf = intensity / 2;++ // Perform initial setup only once+ _trans();Mix.mask.begin();push();noStroke();- strokeWeight(0.5);- translate(matrix[0],matrix[1])+ translate(matrix[0], matrix[1]);++ let pol = this.grow()+ let pol2 = pol.grow().grow(0.5);+ let pol3 = pol2.grow(0.4);+ let pol4 = this.grow(0.6)+for (let i = 0; i < numLayers; i ++) {- if (i == int(numLayers/3) || i == int(2*numLayers/3)) {+ if (i === Math.floor(numLayers / 3) || i === Math.floor(2 * numLayers / 3)) {+ // Grow the polygon objects once per third of the processpol = pol.grow();- pol4 = pol4.grow(0.1)pol2 = pol2.grow(0.1);pol3 = pol3.grow(0.1);+ pol4 = pol4.grow(0.1);}- pol.grow().layer(i, intensity / 2);- pol4.grow(0.1,true).grow().layer(i, intensity / 4,false);- pol2.grow(0.1).layer(i, intensity / 4, false);- pol3.grow(0.1).layer(i, intensity / 3, false);+ // Draw layers+ pol.grow().layer(i, intensityHalf);+ pol4.grow(0.1, true).grow().layer(i, intensityQuarter, false);+ pol2.grow(0.1).layer(i, intensityQuarter, false);+ pol3.grow(0.1).layer(i, intensityThird, false);+ // Erase after each set of layers is drawnpol.erase();}pop();Mix.mask.end();Mix.blend(color)}++ /**+ * Adds a layer of color to the polygon with specified opacity.+ * It also sets a stroke to outline the layer edges.+ * @param {number} _nr - The layer number, affecting the stroke and opacity mapping.+ * @param {number} _alpha - The opacity of the layer.+ * @param {boolean} [bool=true] - If true, adds a stroke to the layer.+ */layer (_nr,_alpha,bool = true) {- push()- fill(255, 0, 0, _alpha)- if (bool) {stroke(255,0,0,10)}+ // Set fill and stroke properties once+ fill(255, 0, 0, _alpha);+ if (bool) {+ stroke(255, 0, 0, R.map(_nr, 0, 18, 3.5, 1));+ strokeWeight(R.map(_nr, 0, 18, 3, 0.5));+ } else {+ noStroke();+ }beginShape();for(let v of this.v) {vertex(v.x, v.y);}endShape(CLOSE);- pop()}++ /**+ * Erases parts of the polygon to create a more natural, uneven watercolor texture.+ * Uses random placement and sizing of circles to simulate texture.+ */erase () {- erase(4)- for(let i = 0; i < R.random(70,100); i++) {circle(this.midP.x + randomGaussian(0,this.size / 2), this.midP.y + randomGaussian(0,this.size / 2), R.random(0.030,0.20) * this.size);}- noErase()+ const numCircles = R.random(70, 100);+ const halfSize = this.size / 2;+ const minSizeFactor = 0.030 * this.size;+ const maxSizeFactor = 0.20 * this.size;+ erase(4);+ for (let i = 0; i < numCircles; i++) {+ const x = this.midP.x + randomGaussian(0, halfSize);+ const y = this.midP.y + randomGaussian(0, halfSize);+ const size = R.random(minSizeFactor, maxSizeFactor);+ circle(x, y, size);+ }+ noErase();}}- // p5 BUG FIX - erase() + noErase() in WEBGL+++ /**+ * Extension of the p5.RendererGL prototype to fix the erase function for the WebGL renderer.+ */p5.RendererGL.prototype.erase = function(opacityFill, opacityStroke) {if (!this._isErasing) {this._cachedBlendMode = this.curBlendMode;@@ -892,6 +1708,9 @@this.curStrokeColor = [1, 1, 1, opacityStroke / 255];}}+ /**+ * Extension of the p5.RendererGL prototype to fix the noErase function for the WebGL renderer.+ */p5.RendererGL.prototype.noErase = function() {if (this._isErasing) {this.curFillColor = this._cachedFillStyle.slice();@@ -904,9 +1723,18 @@}}- //////////////////////////////////////////////////- // STANDARD BRUSHES+// =============================================================================+// Section: Standard Brushes+// =============================================================================+ /**+ * Defines a set of standard brushes with specific characteristics. Each brush is defined+ * with properties such as weight, vibration, definition, quality, opacity, spacing, and+ * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.+ */const standard_brushes = [+ // Define each brush with a name and a set of parameters+ // For example, the "pen" brush has a weight of 0.35, a vibration of 0.12, etc.+ // The "marker2" brush has a custom tip defined by a function that draws rectangles.["pen", { weight: 0.35, vibration: 0.12, definition: 0.5, quality: 8, opacity: 200, spacing: 0.3, pressure: {curve: [0.15,0.2], min_max: [1.3,1]} }],["rotring", { weight: 0.2, vibration: 0.05, definition: 1, quality: 300, opacity: 250, spacing: 0.15, pressure: {curve: [0.05,0.2], min_max: [1.2,0.95]} }],["2B", { weight: 0.4, vibration: 0.45, definition: 0.1, quality: 9, opacity: 160, spacing: 0.2, pressure: {curve: [0.15,0.2], min_max: [1.2,1]} }],@@ -921,280 +1749,85 @@tip: function () { _r.rect(-1.5,-1.5,3,3); _r.rect(1,1,1,1) }, rotate: "natural"}],];+ /**+ * Iterates through the list of standard brushes and adds each one to the brush manager.+ * The brush manager is assumed to be a global object `B` that has an `add` method.+ */for (let s of standard_brushes) {B.add(s[0],s[1])}- function globalScale(_scale) {+ /**+ * Adjusts the global scale of brush parameters based on the provided scale factor.+ * This affects the weight, vibration, and spacing of each standard brush.+ *+ * @param {number} _scale - The scaling factor to apply to the brush parameters.+ */+ function _globalScale(_scale) {for (let s of standard_brushes) {let params = B.list.get(s[0]).paramparams.weight *= _scale, params.vibration *= _scale, params.spacing *= _scale;}}- //////////////////////////////////////////////////- // EXPORTS- // Basic functions- exports.config = _config; // seed RNG generator- exports.load = _load; // load library on selected buffer- exports.preload = _preload; // preload function for custom tips-- // FLOWFIELD- exports.addField = addField; // add new field- exports.field = flowField; // activate / select field- exports.noField = disableField; // disable field- exports.refreshField = refreshField; // refresh field for animations- exports.listFields = listFields; // refresh field for animations-- // BRUSHES- exports.scale = globalScale; // rescales standard brushes- exports.addBrush = B.add; // add new brush- exports.box = brushes; // get array with existing brushes- exports.set = B.set; // set all brush values- exports.pick = B.setBrush; // select brush- exports.clip = B.clip; // clip brushes with rectangle-- // STROKE- exports.stroke = B.setColor;- exports.strokeWeight = B.setWeight;- exports.noStroke = _noStroke;-- // FILL (works with rect, circle, and beginShape)- exports.fill = _fill;- exports.bleed = _bleed;- exports.noFill = _noFill;-- // GEOMETRY- exports.line = B.line;- exports.flowLine = B.flowLine;- exports.rect = _rect;- exports.circle = _circle;- exports.polygon = _polygon;- exports.spline = _spline;- // Equivalent to beginShape- exports.beginShape = _beginShape;- exports.vertex = _vertex;- exports.endShape = _endShape;- // HandStroke- exports.beginStroke = _beginStroke;- exports.move = _move;- exports.endStroke = _endStroke;-- // Hatches- exports.Polygon = Polygon;- exports.hatch = B.hatch;-- // Classes- exports.Plot = Plot;- exports.Pos = Position;--// Shader From Spectral.js: https://github.com/rvanwijnen/spectral.js-// MIT License-//-// Copyright (c) 2023 Ronald van Wijnen-//-// Permission is hereby granted, free of charge, to any person obtaining a-// copy of this software and associated documentation files (the "Software"),-// to deal in the Software without restriction, including without limitation-// the rights to use, copy, modify, merge, publish, distribute, sublicense,-// and/or sell copies of the Software, and to permit persons to whom the-// Software is furnished to do so, subject to the following conditions:-//-// The above copyright notice and this permission notice shall be included in-// all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER-// DEALINGS IN THE SOFTWARE.--function glsl() {- return `-#ifndef SPECTRAL-#define SPECTRAL--const int SPECTRAL_SIZE = 38;-const float SPECTRAL_GAMMA = 2.4;-const float SPECTRAL_EPSILON = 0.0001;--float spectral_uncompand(float x) {- return (x < 0.04045) ? x / 12.92 : pow((x + 0.055) / 1.055, SPECTRAL_GAMMA);-}--float spectral_compand(float x) {- return (x < 0.0031308) ? x * 12.92 : 1.055 * pow(x, 1.0 / SPECTRAL_GAMMA) - 0.055;-}--vec3 spectral_srgb_to_linear(vec3 srgb) {- return vec3(spectral_uncompand(srgb[0]), spectral_uncompand(srgb[1]), spectral_uncompand(srgb[2]));-}+// =============================================================================+// Exports Section: This section lists the public API for the module, providing access+// to the core functionalities such as managing the flow field, brushes, strokes, fills,+// and geometrical shapes drawing.+// =============================================================================-vec3 spectral_linear_to_srgb(vec3 lrgb) {- return clamp(vec3(spectral_compand(lrgb[0]), spectral_compand(lrgb[1]), spectral_compand(lrgb[2])), 0.0, 1.0);-}+// Basic Functions+exports.config = _config; // Configures and seeds the RNG (Random Number Generator).+exports.load = _load; // Loads the library into the selected buffer.+exports.preload = _preload; // Preloads custom tips for the library.-void spectral_upsampling(vec3 lrgb, out float w, out float c, out float m, out float y, out float r, out float g, out float b) {- w = min(lrgb.r, min(lrgb.g, lrgb.b));+// FLOWFIELD Management+exports.addField = _addField; // Adds a new vector field.+exports.field = _field; // Activates or selects a specific vector field.+exports.noField = _disableField; // Disables the current vector field.+exports.refreshField = _refreshField; // Refreshes the vector field, useful for animations.+exports.listFields = _listFields; // Lists all the available fields.- lrgb -= w;+// BRUSH Management+exports.scale = _globalScale; // Rescales all standard brushes.+exports.addBrush = B.add; // Adds a new brush definition.+exports.box = brushes; // Retrieves an array with existing brushes.+exports.set = B.set; // Sets values for all properties of a brush.+exports.pick = B.setBrush; // Selects a brush to use.+exports.clip = B.clip; // Clips brushes with a rectangle.- c = min(lrgb.g, lrgb.b);- m = min(lrgb.r, lrgb.b);- y = min(lrgb.r, lrgb.g);- r = min(max(0., lrgb.r - lrgb.b), max(0., lrgb.r - lrgb.g));- g = min(max(0., lrgb.g - lrgb.b), max(0., lrgb.g - lrgb.r));- b = min(max(0., lrgb.b - lrgb.g), max(0., lrgb.b - lrgb.r));-}+// STROKE Properties+exports.stroke = B.setColor; // Sets the stroke color.+exports.strokeWeight = B.setWeight; // Sets the weight (thickness) of the stroke.+exports.noStroke = _noStroke; // Disables the stroke.-void spectral_linear_to_reflectance(vec3 lrgb, inout float R[SPECTRAL_SIZE]) {- float w, c, m, y, r, g, b;-- spectral_upsampling(lrgb, w, c, m, y, r, g, b);-- R[0] = max(SPECTRAL_EPSILON, w + c * 0.96853629 + m * 0.51567122 + y * 0.02055257 + r * 0.03147571 + g * 0.49108579 + b * 0.97901834);- R[1] = max(SPECTRAL_EPSILON, w + c * 0.96855103 + m * 0.54015520 + y * 0.02059936 + r * 0.03146636 + g * 0.46944057 + b * 0.97901649);- R[2] = max(SPECTRAL_EPSILON, w + c * 0.96859338 + m * 0.62645502 + y * 0.02062723 + r * 0.03140624 + g * 0.40165780 + b * 0.97901118);- R[3] = max(SPECTRAL_EPSILON, w + c * 0.96877345 + m * 0.75595012 + y * 0.02073387 + r * 0.03119611 + g * 0.24490420 + b * 0.97892146);- R[4] = max(SPECTRAL_EPSILON, w + c * 0.96942204 + m * 0.92826996 + y * 0.02114202 + r * 0.03053888 + g * 0.06826880 + b * 0.97858555);- R[5] = max(SPECTRAL_EPSILON, w + c * 0.97143709 + m * 0.97223624 + y * 0.02233154 + r * 0.02856855 + g * 0.02732883 + b * 0.97743705);- R[6] = max(SPECTRAL_EPSILON, w + c * 0.97541862 + m * 0.98616174 + y * 0.02556857 + r * 0.02459485 + g * 0.01360600 + b * 0.97428075);- R[7] = max(SPECTRAL_EPSILON, w + c * 0.98074186 + m * 0.98955255 + y * 0.03330189 + r * 0.01929520 + g * 0.01000187 + b * 0.96663223);- R[8] = max(SPECTRAL_EPSILON, w + c * 0.98580992 + m * 0.98676237 + y * 0.05185294 + r * 0.01423112 + g * 0.01284127 + b * 0.94822893);- R[9] = max(SPECTRAL_EPSILON, w + c * 0.98971194 + m * 0.97312575 + y * 0.10087639 + r * 0.01033111 + g * 0.02636635 + b * 0.89937713);- R[10] = max(SPECTRAL_EPSILON, w + c * 0.99238027 + m * 0.91944277 + y * 0.24000413 + r * 0.00765876 + g * 0.07058713 + b * 0.76070164);- R[11] = max(SPECTRAL_EPSILON, w + c * 0.99409844 + m * 0.32564851 + y * 0.53589066 + r * 0.00593693 + g * 0.70421692 + b * 0.46420440);- R[12] = max(SPECTRAL_EPSILON, w + c * 0.99517200 + m * 0.13820628 + y * 0.79874659 + r * 0.00485616 + g * 0.85473994 + b * 0.20123039);- R[13] = max(SPECTRAL_EPSILON, w + c * 0.99576545 + m * 0.05015143 + y * 0.91186529 + r * 0.00426186 + g * 0.95081565 + b * 0.08808402);- R[14] = max(SPECTRAL_EPSILON, w + c * 0.99593552 + m * 0.02912336 + y * 0.95399623 + r * 0.00409039 + g * 0.97170370 + b * 0.04592894);- R[15] = max(SPECTRAL_EPSILON, w + c * 0.99564041 + m * 0.02421691 + y * 0.97137099 + r * 0.00438375 + g * 0.97651888 + b * 0.02860373);- R[16] = max(SPECTRAL_EPSILON, w + c * 0.99464769 + m * 0.02660696 + y * 0.97939505 + r * 0.00537525 + g * 0.97429245 + b * 0.02060067);- R[17] = max(SPECTRAL_EPSILON, w + c * 0.99229579 + m * 0.03407586 + y * 0.98345207 + r * 0.00772962 + g * 0.97012917 + b * 0.01656701);- R[18] = max(SPECTRAL_EPSILON, w + c * 0.98638762 + m * 0.04835936 + y * 0.98553736 + r * 0.01366120 + g * 0.94258630 + b * 0.01451549);- R[19] = max(SPECTRAL_EPSILON, w + c * 0.96829712 + m * 0.00011720 + y * 0.98648905 + r * 0.03181352 + g * 0.99989207 + b * 0.01357964);- R[20] = max(SPECTRAL_EPSILON, w + c * 0.89228016 + m * 0.00008554 + y * 0.98674535 + r * 0.10791525 + g * 0.99989891 + b * 0.01331243);- R[21] = max(SPECTRAL_EPSILON, w + c * 0.53740239 + m * 0.85267882 + y * 0.98657555 + r * 0.46249516 + g * 0.13823139 + b * 0.01347661);- R[22] = max(SPECTRAL_EPSILON, w + c * 0.15360445 + m * 0.93188793 + y * 0.98611877 + r * 0.84604333 + g * 0.06968113 + b * 0.01387181);- R[23] = max(SPECTRAL_EPSILON, w + c * 0.05705719 + m * 0.94810268 + y * 0.98559942 + r * 0.94275572 + g * 0.05628787 + b * 0.01435472);- R[24] = max(SPECTRAL_EPSILON, w + c * 0.03126539 + m * 0.94200977 + y * 0.98507063 + r * 0.96860996 + g * 0.06111561 + b * 0.01479836);- R[25] = max(SPECTRAL_EPSILON, w + c * 0.02205445 + m * 0.91478045 + y * 0.98460039 + r * 0.97783966 + g * 0.08987709 + b * 0.01515250);- R[26] = max(SPECTRAL_EPSILON, w + c * 0.01802271 + m * 0.87065445 + y * 0.98425301 + r * 0.98187757 + g * 0.13656016 + b * 0.01540513);- R[27] = max(SPECTRAL_EPSILON, w + c * 0.01613460 + m * 0.78827548 + y * 0.98403909 + r * 0.98377315 + g * 0.22169624 + b * 0.01557233);- R[28] = max(SPECTRAL_EPSILON, w + c * 0.01520947 + m * 0.65738359 + y * 0.98388535 + r * 0.98470202 + g * 0.32176956 + b * 0.01565710);- R[29] = max(SPECTRAL_EPSILON, w + c * 0.01475977 + m * 0.59909403 + y * 0.98376116 + r * 0.98515481 + g * 0.36157329 + b * 0.01571025);- R[30] = max(SPECTRAL_EPSILON, w + c * 0.01454263 + m * 0.56817268 + y * 0.98368246 + r * 0.98537114 + g * 0.48361920 + b * 0.01571916);- R[31] = max(SPECTRAL_EPSILON, w + c * 0.01444459 + m * 0.54031997 + y * 0.98365023 + r * 0.98546685 + g * 0.46488579 + b * 0.01572133);- R[32] = max(SPECTRAL_EPSILON, w + c * 0.01439897 + m * 0.52110241 + y * 0.98361309 + r * 0.98550011 + g * 0.47440306 + b * 0.01572502);- R[33] = max(SPECTRAL_EPSILON, w + c * 0.01437620 + m * 0.51041094 + y * 0.98357259 + r * 0.98551031 + g * 0.48576990 + b * 0.01571717);- R[34] = max(SPECTRAL_EPSILON, w + c * 0.01436343 + m * 0.50526577 + y * 0.98353856 + r * 0.98550741 + g * 0.49267971 + b * 0.01571905);- R[35] = max(SPECTRAL_EPSILON, w + c * 0.01435687 + m * 0.50255080 + y * 0.98351247 + r * 0.98551323 + g * 0.49625685 + b * 0.01571059);- R[36] = max(SPECTRAL_EPSILON, w + c * 0.01435370 + m * 0.50126452 + y * 0.98350101 + r * 0.98551563 + g * 0.49807754 + b * 0.01569728);- R[37] = max(SPECTRAL_EPSILON, w + c * 0.01435408 + m * 0.50083021 + y * 0.98350852 + r * 0.98551547 + g * 0.49889859 + b * 0.01570020);-}--vec3 spectral_xyz_to_srgb(vec3 xyz) {- mat3 XYZ_RGB;-- XYZ_RGB[0] = vec3( 3.24306333, -1.53837619, -0.49893282);- XYZ_RGB[1] = vec3(-0.96896309, 1.87542451, 0.04154303);- XYZ_RGB[2] = vec3( 0.05568392, -0.20417438, 1.05799454);-- float r = dot(XYZ_RGB[0], xyz);- float g = dot(XYZ_RGB[1], xyz);- float b = dot(XYZ_RGB[2], xyz);-- return spectral_linear_to_srgb(vec3(r, g, b));-}--vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]) {- vec3 xyz = vec3(0.0);-- xyz += R[0] * vec3(0.00006469, 0.00000184, 0.00030502);- xyz += R[1] * vec3(0.00021941, 0.00000621, 0.00103681);- xyz += R[2] * vec3(0.00112057, 0.00003101, 0.00531314);- xyz += R[3] * vec3(0.00376661, 0.00010475, 0.01795439);- xyz += R[4] * vec3(0.01188055, 0.00035364, 0.05707758);- xyz += R[5] * vec3(0.02328644, 0.00095147, 0.11365162);- xyz += R[6] * vec3(0.03455942, 0.00228226, 0.17335873);- xyz += R[7] * vec3(0.03722379, 0.00420733, 0.19620658);- xyz += R[8] * vec3(0.03241838, 0.00668880, 0.18608237);- xyz += R[9] * vec3(0.02123321, 0.00988840, 0.13995048);- xyz += R[10] * vec3(0.01049099, 0.01524945, 0.08917453);- xyz += R[11] * vec3(0.00329584, 0.02141831, 0.04789621);- xyz += R[12] * vec3(0.00050704, 0.03342293, 0.02814563);- xyz += R[13] * vec3(0.00094867, 0.05131001, 0.01613766);- xyz += R[14] * vec3(0.00627372, 0.07040208, 0.00775910);- xyz += R[15] * vec3(0.01686462, 0.08783871, 0.00429615);- xyz += R[16] * vec3(0.02868965, 0.09424905, 0.00200551);- xyz += R[17] * vec3(0.04267481, 0.09795667, 0.00086147);- xyz += R[18] * vec3(0.05625475, 0.09415219, 0.00036904);- xyz += R[19] * vec3(0.06947040, 0.08678102, 0.00019143);- xyz += R[20] * vec3(0.08305315, 0.07885653, 0.00014956);- xyz += R[21] * vec3(0.08612610, 0.06352670, 0.00009231);- xyz += R[22] * vec3(0.09046614, 0.05374142, 0.00006813);- xyz += R[23] * vec3(0.08500387, 0.04264606, 0.00002883);- xyz += R[24] * vec3(0.07090667, 0.03161735, 0.00001577);- xyz += R[25] * vec3(0.05062889, 0.02088521, 0.00000394);- xyz += R[26] * vec3(0.03547396, 0.01386011, 0.00000158);- xyz += R[27] * vec3(0.02146821, 0.00810264, 0.00000000);- xyz += R[28] * vec3(0.01251646, 0.00463010, 0.00000000);- xyz += R[29] * vec3(0.00680458, 0.00249138, 0.00000000);- xyz += R[30] * vec3(0.00346457, 0.00125930, 0.00000000);- xyz += R[31] * vec3(0.00149761, 0.00054165, 0.00000000);- xyz += R[32] * vec3(0.00076970, 0.00027795, 0.00000000);- xyz += R[33] * vec3(0.00040737, 0.00014711, 0.00000000);- xyz += R[34] * vec3(0.00016901, 0.00006103, 0.00000000);- xyz += R[35] * vec3(0.00009522, 0.00003439, 0.00000000);- xyz += R[36] * vec3(0.00004903, 0.00001771, 0.00000000);- xyz += R[37] * vec3(0.00002000, 0.00000722, 0.00000000);-- return xyz;-}--float spectral_linear_to_concentration(float l1, float l2, float t) {- float t1 = l1 * pow(1.0 - t, 2.0);- float t2 = l2 * pow(t, 2.0);-- return t2 / (t1 + t2);-}--vec3 spectral_mix(vec3 color1, vec3 color2, float t) {- vec3 lrgb1 = spectral_srgb_to_linear(color1);- vec3 lrgb2 = spectral_srgb_to_linear(color2);-- float R1[SPECTRAL_SIZE];- float R2[SPECTRAL_SIZE];-- spectral_linear_to_reflectance(lrgb1, R1);- spectral_linear_to_reflectance(lrgb2, R2);-- float l1 = spectral_reflectance_to_xyz(R1)[1];- float l2 = spectral_reflectance_to_xyz(R2)[1];-- t = spectral_linear_to_concentration(l1, l2, t);-- float R[SPECTRAL_SIZE];-- for (int i = 0; i < SPECTRAL_SIZE; i++) {- float KS = (1.0 - t) * (pow(1.0 - R1[i], 2.0) / (2.0 * R1[i])) + t * (pow(1.0 - R2[i], 2.0) / (2.0 * R2[i]));- float KM = 1.0 + KS - sqrt(pow(KS, 2.0) + 2.0 * KS);-- //Saunderson correction- // let S = ((1.0 - K1) * (1.0 - K2) * KM) / (1.0 - K2 * KM);-- R[i] = KM;- }+// FILL Operations (affects rect, circle, and beginShape)+exports.fill = _fill; // Sets the fill color.+exports.bleed = _bleed; // Sets the bleed property for fills.+exports.noFill = _noFill; // Disables the fill.- return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));-}+// GEOMETRY Drawing Functions+exports.line = B.line; // Draws a line.+exports.flowLine = B.flowLine; // Draws a line that follows the vector field.+exports.flowShape = B.flowShape; // Draws a shape that follows the vector field.+exports.rect = _rect; // Draws a rectangle.+exports.circle = _circle; // Draws a circle.+exports.polygon = _polygon; // Draws a polygon.+exports.spline = _spline; // Draws a spline curve.+// Equivalent to beginShape in p5.js+exports.beginShape = _beginShape; // Begins recording vertices for a custom shape.+exports.vertex = _vertex; // Records a vertex for a custom shape.+exports.endShape = _endShape; // Finishes recording vertices and draws the shape.+// HandStroke - simulates a hand-drawn stroke+exports.beginStroke = _beginStroke; // Begins a hand-drawn stroke.+exports.move = _move; // Moves to a specified point in the hand-drawn stroke.+exports.endStroke = _endStroke; // Ends a hand-drawn stroke.-vec4 spectral_mix(vec4 color1, vec4 color2, float t) {- return vec4(spectral_mix(color1.rgb, color2.rgb, t), mix(color1.a, color2.a, t));-}+// HATCHING Operations+exports.hatch = B.hatch; // Function to create hatched patterns within polygons.-#endif- `;-}+// Classes Exposed+exports.Polygon = Polygon; // The Polygon class, used for creating and manipulating polygons.+exports.Plot = Plot; // The Plot class, for plotting curves.+exports.Pos = Position; // The Position class, for managing positions on the canvas.})));\ No newline at end of filediff --git a/spectral.js b/spectral.jsnew file mode 100644index 0000000..5da9e3e--- /dev/null+++ b/spectral.js@@ -0,0 +1,517 @@+// MIT License+//+// Copyright (c) 2023 Ronald van Wijnen+//+// Permission is hereby granted, free of charge, to any person obtaining a+// copy of this software and associated documentation files (the "Software"),+// to deal in the Software without restriction, including without limitation+// the rights to use, copy, modify, merge, publish, distribute, sublicense,+// and/or sell copies of the Software, and to permit persons to whom the+// Software is furnished to do so, subject to the following conditions:+//+// The above copyright notice and this permission notice shall be included in+// all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+// DEALINGS IN THE SOFTWARE.++(function (global, factory) {+ typeof exports === 'object' && typeof module !== 'undefined'+ ? factory(exports)+ : typeof define === 'function' && define.amd+ ? define(['exports'], factory)+ : ((global = global || self), factory((global.spectral = {})));+})(this, function (exports) {+ ('use strict');++ const RGB = 0;+ const RGBA = 1;+ const HEX = 2;+ const HEXA = 3;++ const SIZE = 38;+ const GAMMA = 2.4;+ const EPSILON = 0.00000001;++ function linear_to_concentration(l1, l2, t) {+ let t1 = l1 * (1 - t) ** 2;+ let t2 = l2 * t ** 2;++ return t2 / (t1 + t2);+ }++ function mix(color1, color2, t, returnFormat) {+ color1 = unpack(color1);+ color2 = unpack(color2);++ let lrgb1 = srgb_to_linear(color1);+ let lrgb2 = srgb_to_linear(color2);++ let R1 = linear_to_reflectance(lrgb1);+ let R2 = linear_to_reflectance(lrgb2);++ let l1 = dotproduct(R1, CIE_CMF_Y);+ let l2 = dotproduct(R2, CIE_CMF_Y);++ t = linear_to_concentration(l1, l2, t);++ const R = new Array(SIZE);++ for (let i = 0; i < SIZE; i++) {+ let KS = (1 - t) * ((1 - R1[i]) ** 2 / (2 * R1[i])) + t * ((1 - R2[i]) ** 2 / (2 * R2[i]));+ let KM = 1 + KS - Math.sqrt(KS ** 2 + 2 * KS);++ //Saunderson correction+ // let S = ((1.0 - K1) * (1.0 - K2) * KM) / (1.0 - K2 * KM);++ R[i] = KM;+ }++ let rgb = xyz_to_srgb(reflectance_to_xyz(R));++ rgb.push(lerp(color1[3], color2[3], t));++ return pack(rgb, returnFormat);+ }++ function palette(color1, color2, size, returnFormat) {+ let g = [];++ for (let i = 0; i < size; i++) {+ g.push(mix(color1, color2, i / (size - 1), returnFormat));+ }++ return g;+ }++ function uncompand(x) {+ return x < 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** GAMMA;+ }++ function compand(x) {+ return x < 0.0031308 ? x * 12.92 : 1.055 * x ** (1.0 / GAMMA) - 0.055;+ }++ function srgb_to_linear(srgb) {+ let r = uncompand(srgb[0] / 255.0);+ let g = uncompand(srgb[1] / 255.0);+ let b = uncompand(srgb[2] / 255.0);++ return [r, g, b];+ }++ function linear_to_srgb(lrgb) {+ let r = compand(lrgb[0]);+ let g = compand(lrgb[1]);+ let b = compand(lrgb[2]);++ return [Math.round(clamp(r, 0, 1) * 255), Math.round(clamp(g, 0, 1) * 255), Math.round(clamp(b, 0, 1) * 255)];+ }++ function xyz_to_srgb(xyz) {+ let r = dotproduct(XYZ_RGB[0], xyz);+ let g = dotproduct(XYZ_RGB[1], xyz);+ let b = dotproduct(XYZ_RGB[2], xyz);++ return linear_to_srgb([r, g, b]);+ }++ function reflectance_to_xyz(R) {+ let x = dotproduct(R, CIE_CMF_X);+ let y = dotproduct(R, CIE_CMF_Y);+ let z = dotproduct(R, CIE_CMF_Z);++ return [x, y, z];+ }++ function spectral_upsampling(lrgb) {+ let w = Math.min(Math.min(lrgb[0], lrgb[1]), lrgb[2]);++ lrgb = [lrgb[0] - w, lrgb[1] - w, lrgb[2] - w];++ let c = Math.min(lrgb[1], lrgb[2]);+ let m = Math.min(lrgb[0], lrgb[2]);+ let y = Math.min(lrgb[0], lrgb[1]);+ let r = Math.max(0, Math.min(lrgb[0] - lrgb[2], lrgb[0] - lrgb[1]));+ let g = Math.max(0, Math.min(lrgb[1] - lrgb[2], lrgb[1] - lrgb[0]));+ let b = Math.max(0, Math.min(lrgb[2] - lrgb[1], lrgb[2] - lrgb[0]));++ return [w, c, m, y, r, g, b];+ }++ function linear_to_reflectance(lrgb) {+ let weights = spectral_upsampling(lrgb);++ const R = new Array(SIZE);++ for (let i = 0; i < SIZE; i++) {+ R[i] = Math.max(+ EPSILON,+ weights[0] + weights[1] * SPD_C[i] + weights[2] * SPD_M[i] + weights[3] * SPD_Y[i] + weights[4] * SPD_R[i] + weights[5] * SPD_G[i] + weights[6] * SPD_B[i]+ );+ }++ return R;+ }++ function lerp(a, b, alpha) {+ return a + alpha * (b - a);+ }++ function clamp(value, min, max) {+ return Math.min(Math.max(value, min), max);+ }++ function dotproduct(a, b) {+ return a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);+ }++ function glsl_color(c) {+ let rgba = unpack(c);++ return [rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3] > 1 ? rgba[3] / 255 : rgba[3]];+ }++ function unpack(color) {+ if (Array.isArray(color)) {+ const [r, g, b, a = 1] = color;++ return [r, g, b, a];+ }++ if (color.startsWith('rgb')) {+ color = color+ .slice(color.indexOf('(') + 1, -1)+ .split(',')+ .map((value) => (value.trim().endsWith('%') ? Math.round(parseFloat(value.trim()) * 2.55) : Number(value.trim())));++ const [r, g, b, a = 1] = color;++ return [r, g, b, a];+ }++ if (color.startsWith('#')) {+ if (color.length === 4 || color.length === 5) {+ color = color+ .split('')+ .slice(1)+ .map((value) => value + value)+ .join('');+ } else {+ color = color.slice(1);+ }++ color = color.match(/.{1,2}/g).map((value) => parseInt(value, 16));++ const [r, g, b, a = 1] = color.length === 3 ? [...color, 1] : color;++ return [r, g, b, a];+ }++ return [0, 0, 0, 1];+ }++ function pack(srgb, returnFormat) {+ let r = srgb[0];+ let g = srgb[1];+ let b = srgb[2];+ let a = srgb[3];++ if (returnFormat === RGB || returnFormat === RGBA) {+ return `rgb${returnFormat === RGBA ? 'a' : ''}(${r}, ${g}, ${b}${returnFormat === RGBA ? ', ' + a : ''})`;+ }++ r = r.toString(16);+ g = g.toString(16);+ b = b.toString(16);+ a = (a > 1 ? a : Math.round(clamp(a, 0, 1) * 255)).toString(16);++ if (r.length == 1) r = '0' + r;+ if (g.length == 1) g = '0' + g;+ if (b.length == 1) b = '0' + b;+ if (a.length == 1) a = '0' + a;++ return `#${r}${g}${b}${returnFormat === HEXA ? a : ''}`;+ }++ // K1 and K2 are used for the Saunderson correction which is used for how the color looks behind a refractive+ // surface like glass+ //+ // 1 is used for a vacuum, no surface+ //+ // Refractive Index+ //+ // https://en.wikipedia.org/wiki/Refractive_index+ // https://en.wikipedia.org/wiki/List_of_refractive_indices+ //+ // Glass = 1.5+ // Vacuum = 1++ const RI = 1.0;+ const K1 = (RI - 1) ** 2 / (RI + 1) ** 2;++ // 0 = neutral, - = lighten, + = darken+ const K2 = 0;++ const SPD_C = [+ 0.96853629, 0.96855103, 0.96859338, 0.96877345, 0.96942204, 0.97143709, 0.97541862, 0.98074186, 0.98580992, 0.98971194, 0.99238027, 0.99409844, 0.995172, 0.99576545,+ 0.99593552, 0.99564041, 0.99464769, 0.99229579, 0.98638762, 0.96829712, 0.89228016, 0.53740239, 0.15360445, 0.05705719, 0.03126539, 0.02205445, 0.01802271, 0.0161346,+ 0.01520947, 0.01475977, 0.01454263, 0.01444459, 0.01439897, 0.0143762, 0.01436343, 0.01435687, 0.0143537, 0.01435408,+ ];++ const SPD_M = [+ 0.51567122, 0.5401552, 0.62645502, 0.75595012, 0.92826996, 0.97223624, 0.98616174, 0.98955255, 0.98676237, 0.97312575, 0.91944277, 0.32564851, 0.13820628, 0.05015143,+ 0.02912336, 0.02421691, 0.02660696, 0.03407586, 0.04835936, 0.0001172, 0.00008554, 0.85267882, 0.93188793, 0.94810268, 0.94200977, 0.91478045, 0.87065445, 0.78827548,+ 0.65738359, 0.59909403, 0.56817268, 0.54031997, 0.52110241, 0.51041094, 0.50526577, 0.5025508, 0.50126452, 0.50083021,+ ];++ const SPD_Y = [+ 0.02055257, 0.02059936, 0.02062723, 0.02073387, 0.02114202, 0.02233154, 0.02556857, 0.03330189, 0.05185294, 0.10087639, 0.24000413, 0.53589066, 0.79874659, 0.91186529,+ 0.95399623, 0.97137099, 0.97939505, 0.98345207, 0.98553736, 0.98648905, 0.98674535, 0.98657555, 0.98611877, 0.98559942, 0.98507063, 0.98460039, 0.98425301, 0.98403909,+ 0.98388535, 0.98376116, 0.98368246, 0.98365023, 0.98361309, 0.98357259, 0.98353856, 0.98351247, 0.98350101, 0.98350852,+ ];++ const SPD_R = [+ 0.03147571, 0.03146636, 0.03140624, 0.03119611, 0.03053888, 0.02856855, 0.02459485, 0.0192952, 0.01423112, 0.01033111, 0.00765876, 0.00593693, 0.00485616, 0.00426186,+ 0.00409039, 0.00438375, 0.00537525, 0.00772962, 0.0136612, 0.03181352, 0.10791525, 0.46249516, 0.84604333, 0.94275572, 0.96860996, 0.97783966, 0.98187757, 0.98377315,+ 0.98470202, 0.98515481, 0.98537114, 0.98546685, 0.98550011, 0.98551031, 0.98550741, 0.98551323, 0.98551563, 0.98551547,+ ];++ const SPD_G = [+ 0.49108579, 0.46944057, 0.4016578, 0.2449042, 0.0682688, 0.02732883, 0.013606, 0.01000187, 0.01284127, 0.02636635, 0.07058713, 0.70421692, 0.85473994, 0.95081565, 0.9717037,+ 0.97651888, 0.97429245, 0.97012917, 0.9425863, 0.99989207, 0.99989891, 0.13823139, 0.06968113, 0.05628787, 0.06111561, 0.08987709, 0.13656016, 0.22169624, 0.32176956,+ 0.36157329, 0.4836192, 0.46488579, 0.47440306, 0.4857699, 0.49267971, 0.49625685, 0.49807754, 0.49889859,+ ];++ const SPD_B = [+ 0.97901834, 0.97901649, 0.97901118, 0.97892146, 0.97858555, 0.97743705, 0.97428075, 0.96663223, 0.94822893, 0.89937713, 0.76070164, 0.4642044, 0.20123039, 0.08808402,+ 0.04592894, 0.02860373, 0.02060067, 0.01656701, 0.01451549, 0.01357964, 0.01331243, 0.01347661, 0.01387181, 0.01435472, 0.01479836, 0.0151525, 0.01540513, 0.01557233,+ 0.0156571, 0.01571025, 0.01571916, 0.01572133, 0.01572502, 0.01571717, 0.01571905, 0.01571059, 0.01569728, 0.0157002,+ ];++ const CIE_CMF_X = [+ 0.00006469, 0.00021941, 0.00112057, 0.00376661, 0.01188055, 0.02328644, 0.03455942, 0.03722379, 0.03241838, 0.02123321, 0.01049099, 0.00329584, 0.00050704, 0.00094867,+ 0.00627372, 0.01686462, 0.02868965, 0.04267481, 0.05625475, 0.0694704, 0.08305315, 0.0861261, 0.09046614, 0.08500387, 0.07090667, 0.05062889, 0.03547396, 0.02146821,+ 0.01251646, 0.00680458, 0.00346457, 0.00149761, 0.0007697, 0.00040737, 0.00016901, 0.00009522, 0.00004903, 0.00002,+ ];++ const CIE_CMF_Y = [+ 0.00000184, 0.00000621, 0.00003101, 0.00010475, 0.00035364, 0.00095147, 0.00228226, 0.00420733, 0.0066888, 0.0098884, 0.01524945, 0.02141831, 0.03342293, 0.05131001,+ 0.07040208, 0.08783871, 0.09424905, 0.09795667, 0.09415219, 0.08678102, 0.07885653, 0.0635267, 0.05374142, 0.04264606, 0.03161735, 0.02088521, 0.01386011, 0.00810264,+ 0.0046301, 0.00249138, 0.0012593, 0.00054165, 0.00027795, 0.00014711, 0.00006103, 0.00003439, 0.00001771, 0.00000722,+ ];++ const CIE_CMF_Z = [+ 0.00030502, 0.00103681, 0.00531314, 0.01795439, 0.05707758, 0.11365162, 0.17335873, 0.19620658, 0.18608237, 0.13995048, 0.08917453, 0.04789621, 0.02814563, 0.01613766,+ 0.0077591, 0.00429615, 0.00200551, 0.00086147, 0.00036904, 0.00019143, 0.00014956, 0.00009231, 0.00006813, 0.00002883, 0.00001577, 0.00000394, 0.00000158, 0.0, 0.0, 0.0, 0.0,+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,+ ];++ const XYZ_RGB = [+ [3.24306333, -1.53837619, -0.49893282],+ [-0.96896309, 1.87542451, 0.04154303],+ [0.05568392, -0.20417438, 1.05799454],+ ];++ function glsl() {+ return `+#ifndef SPECTRAL+#define SPECTRAL++const int SPECTRAL_SIZE = 38;+const float SPECTRAL_GAMMA = 2.4;+const float SPECTRAL_EPSILON = 0.0001;++float spectral_uncompand(float x) {+ return (x < 0.04045) ? x / 12.92 : pow((x + 0.055) / 1.055, SPECTRAL_GAMMA);+}++float spectral_compand(float x) {+ return (x < 0.0031308) ? x * 12.92 : 1.055 * pow(x, 1.0 / SPECTRAL_GAMMA) - 0.055;+}++vec3 spectral_srgb_to_linear(vec3 srgb) {+ return vec3(spectral_uncompand(srgb[0]), spectral_uncompand(srgb[1]), spectral_uncompand(srgb[2]));+}++vec3 spectral_linear_to_srgb(vec3 lrgb) {+ return clamp(vec3(spectral_compand(lrgb[0]), spectral_compand(lrgb[1]), spectral_compand(lrgb[2])), 0.0, 1.0);+}++void spectral_upsampling(vec3 lrgb, out float w, out float c, out float m, out float y, out float r, out float g, out float b) {+ w = min(lrgb.r, min(lrgb.g, lrgb.b));++ lrgb -= w;++ c = min(lrgb.g, lrgb.b);+ m = min(lrgb.r, lrgb.b);+ y = min(lrgb.r, lrgb.g);+ r = min(max(0., lrgb.r - lrgb.b), max(0., lrgb.r - lrgb.g));+ g = min(max(0., lrgb.g - lrgb.b), max(0., lrgb.g - lrgb.r));+ b = min(max(0., lrgb.b - lrgb.g), max(0., lrgb.b - lrgb.r));+}++void spectral_linear_to_reflectance(vec3 lrgb, inout float R[SPECTRAL_SIZE]) {+ float w, c, m, y, r, g, b;++ spectral_upsampling(lrgb, w, c, m, y, r, g, b);++ R[0] = max(SPECTRAL_EPSILON, w + c * 0.96853629 + m * 0.51567122 + y * 0.02055257 + r * 0.03147571 + g * 0.49108579 + b * 0.97901834);+ R[1] = max(SPECTRAL_EPSILON, w + c * 0.96855103 + m * 0.54015520 + y * 0.02059936 + r * 0.03146636 + g * 0.46944057 + b * 0.97901649);+ R[2] = max(SPECTRAL_EPSILON, w + c * 0.96859338 + m * 0.62645502 + y * 0.02062723 + r * 0.03140624 + g * 0.40165780 + b * 0.97901118);+ R[3] = max(SPECTRAL_EPSILON, w + c * 0.96877345 + m * 0.75595012 + y * 0.02073387 + r * 0.03119611 + g * 0.24490420 + b * 0.97892146);+ R[4] = max(SPECTRAL_EPSILON, w + c * 0.96942204 + m * 0.92826996 + y * 0.02114202 + r * 0.03053888 + g * 0.06826880 + b * 0.97858555);+ R[5] = max(SPECTRAL_EPSILON, w + c * 0.97143709 + m * 0.97223624 + y * 0.02233154 + r * 0.02856855 + g * 0.02732883 + b * 0.97743705);+ R[6] = max(SPECTRAL_EPSILON, w + c * 0.97541862 + m * 0.98616174 + y * 0.02556857 + r * 0.02459485 + g * 0.01360600 + b * 0.97428075);+ R[7] = max(SPECTRAL_EPSILON, w + c * 0.98074186 + m * 0.98955255 + y * 0.03330189 + r * 0.01929520 + g * 0.01000187 + b * 0.96663223);+ R[8] = max(SPECTRAL_EPSILON, w + c * 0.98580992 + m * 0.98676237 + y * 0.05185294 + r * 0.01423112 + g * 0.01284127 + b * 0.94822893);+ R[9] = max(SPECTRAL_EPSILON, w + c * 0.98971194 + m * 0.97312575 + y * 0.10087639 + r * 0.01033111 + g * 0.02636635 + b * 0.89937713);+ R[10] = max(SPECTRAL_EPSILON, w + c * 0.99238027 + m * 0.91944277 + y * 0.24000413 + r * 0.00765876 + g * 0.07058713 + b * 0.76070164);+ R[11] = max(SPECTRAL_EPSILON, w + c * 0.99409844 + m * 0.32564851 + y * 0.53589066 + r * 0.00593693 + g * 0.70421692 + b * 0.46420440);+ R[12] = max(SPECTRAL_EPSILON, w + c * 0.99517200 + m * 0.13820628 + y * 0.79874659 + r * 0.00485616 + g * 0.85473994 + b * 0.20123039);+ R[13] = max(SPECTRAL_EPSILON, w + c * 0.99576545 + m * 0.05015143 + y * 0.91186529 + r * 0.00426186 + g * 0.95081565 + b * 0.08808402);+ R[14] = max(SPECTRAL_EPSILON, w + c * 0.99593552 + m * 0.02912336 + y * 0.95399623 + r * 0.00409039 + g * 0.97170370 + b * 0.04592894);+ R[15] = max(SPECTRAL_EPSILON, w + c * 0.99564041 + m * 0.02421691 + y * 0.97137099 + r * 0.00438375 + g * 0.97651888 + b * 0.02860373);+ R[16] = max(SPECTRAL_EPSILON, w + c * 0.99464769 + m * 0.02660696 + y * 0.97939505 + r * 0.00537525 + g * 0.97429245 + b * 0.02060067);+ R[17] = max(SPECTRAL_EPSILON, w + c * 0.99229579 + m * 0.03407586 + y * 0.98345207 + r * 0.00772962 + g * 0.97012917 + b * 0.01656701);+ R[18] = max(SPECTRAL_EPSILON, w + c * 0.98638762 + m * 0.04835936 + y * 0.98553736 + r * 0.01366120 + g * 0.94258630 + b * 0.01451549);+ R[19] = max(SPECTRAL_EPSILON, w + c * 0.96829712 + m * 0.00011720 + y * 0.98648905 + r * 0.03181352 + g * 0.99989207 + b * 0.01357964);+ R[20] = max(SPECTRAL_EPSILON, w + c * 0.89228016 + m * 0.00008554 + y * 0.98674535 + r * 0.10791525 + g * 0.99989891 + b * 0.01331243);+ R[21] = max(SPECTRAL_EPSILON, w + c * 0.53740239 + m * 0.85267882 + y * 0.98657555 + r * 0.46249516 + g * 0.13823139 + b * 0.01347661);+ R[22] = max(SPECTRAL_EPSILON, w + c * 0.15360445 + m * 0.93188793 + y * 0.98611877 + r * 0.84604333 + g * 0.06968113 + b * 0.01387181);+ R[23] = max(SPECTRAL_EPSILON, w + c * 0.05705719 + m * 0.94810268 + y * 0.98559942 + r * 0.94275572 + g * 0.05628787 + b * 0.01435472);+ R[24] = max(SPECTRAL_EPSILON, w + c * 0.03126539 + m * 0.94200977 + y * 0.98507063 + r * 0.96860996 + g * 0.06111561 + b * 0.01479836);+ R[25] = max(SPECTRAL_EPSILON, w + c * 0.02205445 + m * 0.91478045 + y * 0.98460039 + r * 0.97783966 + g * 0.08987709 + b * 0.01515250);+ R[26] = max(SPECTRAL_EPSILON, w + c * 0.01802271 + m * 0.87065445 + y * 0.98425301 + r * 0.98187757 + g * 0.13656016 + b * 0.01540513);+ R[27] = max(SPECTRAL_EPSILON, w + c * 0.01613460 + m * 0.78827548 + y * 0.98403909 + r * 0.98377315 + g * 0.22169624 + b * 0.01557233);+ R[28] = max(SPECTRAL_EPSILON, w + c * 0.01520947 + m * 0.65738359 + y * 0.98388535 + r * 0.98470202 + g * 0.32176956 + b * 0.01565710);+ R[29] = max(SPECTRAL_EPSILON, w + c * 0.01475977 + m * 0.59909403 + y * 0.98376116 + r * 0.98515481 + g * 0.36157329 + b * 0.01571025);+ R[30] = max(SPECTRAL_EPSILON, w + c * 0.01454263 + m * 0.56817268 + y * 0.98368246 + r * 0.98537114 + g * 0.48361920 + b * 0.01571916);+ R[31] = max(SPECTRAL_EPSILON, w + c * 0.01444459 + m * 0.54031997 + y * 0.98365023 + r * 0.98546685 + g * 0.46488579 + b * 0.01572133);+ R[32] = max(SPECTRAL_EPSILON, w + c * 0.01439897 + m * 0.52110241 + y * 0.98361309 + r * 0.98550011 + g * 0.47440306 + b * 0.01572502);+ R[33] = max(SPECTRAL_EPSILON, w + c * 0.01437620 + m * 0.51041094 + y * 0.98357259 + r * 0.98551031 + g * 0.48576990 + b * 0.01571717);+ R[34] = max(SPECTRAL_EPSILON, w + c * 0.01436343 + m * 0.50526577 + y * 0.98353856 + r * 0.98550741 + g * 0.49267971 + b * 0.01571905);+ R[35] = max(SPECTRAL_EPSILON, w + c * 0.01435687 + m * 0.50255080 + y * 0.98351247 + r * 0.98551323 + g * 0.49625685 + b * 0.01571059);+ R[36] = max(SPECTRAL_EPSILON, w + c * 0.01435370 + m * 0.50126452 + y * 0.98350101 + r * 0.98551563 + g * 0.49807754 + b * 0.01569728);+ R[37] = max(SPECTRAL_EPSILON, w + c * 0.01435408 + m * 0.50083021 + y * 0.98350852 + r * 0.98551547 + g * 0.49889859 + b * 0.01570020);+}++vec3 spectral_xyz_to_srgb(vec3 xyz) {+ mat3 XYZ_RGB;++ XYZ_RGB[0] = vec3( 3.24306333, -1.53837619, -0.49893282);+ XYZ_RGB[1] = vec3(-0.96896309, 1.87542451, 0.04154303);+ XYZ_RGB[2] = vec3( 0.05568392, -0.20417438, 1.05799454);++ float r = dot(XYZ_RGB[0], xyz);+ float g = dot(XYZ_RGB[1], xyz);+ float b = dot(XYZ_RGB[2], xyz);++ return spectral_linear_to_srgb(vec3(r, g, b));+}++vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]) {+ vec3 xyz = vec3(0.0);++ xyz += R[0] * vec3(0.00006469, 0.00000184, 0.00030502);+ xyz += R[1] * vec3(0.00021941, 0.00000621, 0.00103681);+ xyz += R[2] * vec3(0.00112057, 0.00003101, 0.00531314);+ xyz += R[3] * vec3(0.00376661, 0.00010475, 0.01795439);+ xyz += R[4] * vec3(0.01188055, 0.00035364, 0.05707758);+ xyz += R[5] * vec3(0.02328644, 0.00095147, 0.11365162);+ xyz += R[6] * vec3(0.03455942, 0.00228226, 0.17335873);+ xyz += R[7] * vec3(0.03722379, 0.00420733, 0.19620658);+ xyz += R[8] * vec3(0.03241838, 0.00668880, 0.18608237);+ xyz += R[9] * vec3(0.02123321, 0.00988840, 0.13995048);+ xyz += R[10] * vec3(0.01049099, 0.01524945, 0.08917453);+ xyz += R[11] * vec3(0.00329584, 0.02141831, 0.04789621);+ xyz += R[12] * vec3(0.00050704, 0.03342293, 0.02814563);+ xyz += R[13] * vec3(0.00094867, 0.05131001, 0.01613766);+ xyz += R[14] * vec3(0.00627372, 0.07040208, 0.00775910);+ xyz += R[15] * vec3(0.01686462, 0.08783871, 0.00429615);+ xyz += R[16] * vec3(0.02868965, 0.09424905, 0.00200551);+ xyz += R[17] * vec3(0.04267481, 0.09795667, 0.00086147);+ xyz += R[18] * vec3(0.05625475, 0.09415219, 0.00036904);+ xyz += R[19] * vec3(0.06947040, 0.08678102, 0.00019143);+ xyz += R[20] * vec3(0.08305315, 0.07885653, 0.00014956);+ xyz += R[21] * vec3(0.08612610, 0.06352670, 0.00009231);+ xyz += R[22] * vec3(0.09046614, 0.05374142, 0.00006813);+ xyz += R[23] * vec3(0.08500387, 0.04264606, 0.00002883);+ xyz += R[24] * vec3(0.07090667, 0.03161735, 0.00001577);+ xyz += R[25] * vec3(0.05062889, 0.02088521, 0.00000394);+ xyz += R[26] * vec3(0.03547396, 0.01386011, 0.00000158);+ xyz += R[27] * vec3(0.02146821, 0.00810264, 0.00000000);+ xyz += R[28] * vec3(0.01251646, 0.00463010, 0.00000000);+ xyz += R[29] * vec3(0.00680458, 0.00249138, 0.00000000);+ xyz += R[30] * vec3(0.00346457, 0.00125930, 0.00000000);+ xyz += R[31] * vec3(0.00149761, 0.00054165, 0.00000000);+ xyz += R[32] * vec3(0.00076970, 0.00027795, 0.00000000);+ xyz += R[33] * vec3(0.00040737, 0.00014711, 0.00000000);+ xyz += R[34] * vec3(0.00016901, 0.00006103, 0.00000000);+ xyz += R[35] * vec3(0.00009522, 0.00003439, 0.00000000);+ xyz += R[36] * vec3(0.00004903, 0.00001771, 0.00000000);+ xyz += R[37] * vec3(0.00002000, 0.00000722, 0.00000000);++ return xyz;+}++float spectral_linear_to_concentration(float l1, float l2, float t) {+ float t1 = l1 * pow(1.0 - t, 2.0);+ float t2 = l2 * pow(t, 2.0);++ return t2 / (t1 + t2);+}++vec3 spectral_mix(vec3 color1, vec3 color2, float t) {+ vec3 lrgb1 = spectral_srgb_to_linear(color1);+ vec3 lrgb2 = spectral_srgb_to_linear(color2);++ float R1[SPECTRAL_SIZE];+ float R2[SPECTRAL_SIZE];++ spectral_linear_to_reflectance(lrgb1, R1);+ spectral_linear_to_reflectance(lrgb2, R2);++ float l1 = spectral_reflectance_to_xyz(R1)[1];+ float l2 = spectral_reflectance_to_xyz(R2)[1];++ t = spectral_linear_to_concentration(l1, l2, t);++ float R[SPECTRAL_SIZE];++ for (int i = 0; i < SPECTRAL_SIZE; i++) {+ float KS = (1.0 - t) * (pow(1.0 - R1[i], 2.0) / (2.0 * R1[i])) + t * (pow(1.0 - R2[i], 2.0) / (2.0 * R2[i]));+ float KM = 1.0 + KS - sqrt(pow(KS, 2.0) + 2.0 * KS);++ //Saunderson correction+ // let S = ((1.0 - K1) * (1.0 - K2) * KM) / (1.0 - K2 * KM);++ R[i] = KM;+ }++ return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));+}++vec4 spectral_mix(vec4 color1, vec4 color2, float t) {+ return vec4(spectral_mix(color1.rgb, color2.rgb, t), mix(color1.a, color2.a, t));+}++#endif+ `;+ }++ exports.RGB = RGB;+ exports.RGBA = RGBA;+ exports.HEX = HEX;+ exports.HEXA = HEXA;++ exports.mix = mix;+ exports.palette = palette;+ exports.glsl_color = glsl_color;+ exports.glsl = glsl;+});