### Function Definition Example (Lambda) Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Short lambda-style function definition. ```javascript myFunction = (arg1) => arg1 * 2 ``` -------------------------------- ### Function Definition Example (Standard) Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Standard function definition using the `function` keyword. ```javascript function myFunction(arg1) {return arg1 * 2} ``` -------------------------------- ### Calculate Array Reductions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Examples of using arrayReduce to perform common operations like summation, finding maximums, counting instances, and finding the index of the closest value. ```Pixelblaze arrayReduce(a, (acc, v) => acc + v, 0) ``` ```Pixelblaze arrayReduce(a, (acc, v) => max(acc,v), a[0]) ``` ```Pixelblaze key = 5; arrayReduce(a, (acc, v) => acc + (v == key), 0) ``` ```Pixelblaze target = 5; arrayReduce(a, (acc, v, i, a) => abs(target - v) < abs(target - a[acc]) ? i : acc , 0) ``` -------------------------------- ### Create a Toggle Switch Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `toggle` followed by a name to create a toggle switch. It receives `true` when on and `false` when off. ```javascript export function toggleEnableAwesomeness(isEnabled) {...} ``` -------------------------------- ### Array Replacement Source: https://context7.com/simap/pixelblaze/llms.txt Demonstrates replacing array contents starting at a specific index using `replace()` or `replaceAt()`. ```javascript // Replace array contents var buffer = array(5) buffer.replace(1, 2, 3, 4, 5) // Replace starting at index 0 buffer.replaceAt(2, 99, 88) // Replace starting at index 2 ``` -------------------------------- ### Create an HSV Color Picker Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `hsvPicker` followed by a name to create an HSV color picker. Values are between 0.0 and 1.0. ```javascript export function hsvPickerPrimaryColor(h, s, v) {...} ``` -------------------------------- ### Create an RGB Color Picker Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `rgbPicker` followed by a name to create an RGB color picker. Values are between 0.0 and 1.0. ```javascript export function rgbPickerPrimaryColor(r, g, b) {...} ``` -------------------------------- ### Display a Gauge Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `gauge` followed by a name to display a gauge. The returned number should be between 0.0 and 1.0, representing a percentage. ```javascript export function gaugeLightLevel() {return ...} ``` -------------------------------- ### Render Function with UI Controls Source: https://context7.com/simap/pixelblaze/llms.txt Example render function that utilizes UI controls like toggles, color pickers, and number inputs to modify its output. ```javascript export function render(index) { if (enableEffect) { hsv(pickedHue + index / pixelCount * scale, pickedSat, pickedVal) } } ``` -------------------------------- ### Create a Number Input Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `inputNumber` followed by a name to create a number input field. It is called with the new value when entered. ```javascript export function inputNumberScale(v) {...} ``` -------------------------------- ### Create a Trigger Button Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `trigger` followed by a name to create a trigger button. This function is called when the button is pressed and has no parameters. ```javascript export function triggerFireLasers() {...} ``` -------------------------------- ### Generate 2D Pixel Map with JavaScript Source: https://github.com/simap/pixelblaze/blob/master/README.mapper.md Use a JavaScript function to dynamically generate a pixel map based on pixel count. This example creates a zigzag matrix layout. ```javascript function (pixelCount) { width = 8 var map = [] for (i = 0; i < pixelCount; i++) { y = Math.floor(i / width) x = i % width x = y % 2 == 1 ? width - 1 - x : x //zigzag map.push([x, y]) } return map } ``` -------------------------------- ### Display a Number Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function starting with `showNumber` followed by a name to display a number. The returned number is displayed with 4 decimal places and the function is called frequently. ```javascript export function showNumberEnergyAverage() {return ...} ``` -------------------------------- ### Check Map Dimensions Source: https://context7.com/simap/pixelblaze/llms.txt Check the dimensionality of the installed pixel map (2D or 3D) using helper functions. ```javascript // Check map dimensions export function beforeRender(delta) { var dims = pixelMapDimensions() // Returns 0, 2, or 3 if (has2DMap()) { /* 2D map installed */ } if (has3DMap()) { /* 3D map installed */ } } ``` -------------------------------- ### Get Current Time with Clock Functions Source: https://context7.com/simap/pixelblaze/llms.txt Retrieve current time and date information when Pixelblaze is connected to the internet. Useful for time-based effects or logic. ```javascript // Clock functions (requires internet connection) export function render(index) { var hour = clockHour() // 0-23 (24-hour format) var minute = clockMinute() // 0-59 var second = clockSecond() // 0-59 var day = clockDay() // 1-31 var month = clockMonth() // 1-12 var year = clockYear() // e.g., 2024 var weekday = clockWeekday() // 1=Sunday, 2=Monday, etc. // Night mode: dim after 10pm var brightness = (hour >= 22 || hour < 6) ? 0.2 : 1 hsv(index / pixelCount, 1, brightness) } ``` -------------------------------- ### Configure and Use GPIO Pins Source: https://context7.com/simap/pixelblaze/llms.txt Configure pins as inputs or outputs, read digital and analog values, and use capacitive touch sensing. Ensure correct pin modes are set before use. ```javascript // Configure pin modes pinMode(4, INPUT) // Digital input pinMode(5, INPUT_PULLUP) // Input with pull-up resistor pinMode(6, OUTPUT) // Digital output pinMode(7, ANALOG) // Analog input // Digital I/O digitalWrite(6, HIGH) // Set pin HIGH digitalWrite(6, LOW) // Set pin LOW var state = digitalRead(4) // Returns 1.0 or 0.0 // Analog input (0.0 to 1.0) var voltage = analogRead(7) // Capacitive touch sensing (0.0 to 1.0) var touch = touchRead(T0) // Use touch pin constants T0, T2, T4, T6, T7 export function render(index) { var proximity = touchRead(T0) hsv(index / pixelCount, 1, proximity) } ``` -------------------------------- ### Implement Basic Render Functions Source: https://context7.com/simap/pixelblaze/llms.txt Use beforeRender for timing-based calculations and render functions for 1D, 2D, or 3D pixel mapping. ```javascript // Basic 1D animation - rainbow wave moving along the strip var t1 export function beforeRender(delta) { t1 = time(0.1) // Slow sawtooth wave (~6.5 seconds per cycle) } export function render(index) { // Calculate hue based on position and time var hue = index / pixelCount + t1 hsv(hue, 1, 1) } // 2D pattern - expanding rings from center export function render2D(index, x, y) { // x, y are in "world units" (0.0 to 1.0) var distance = hypot(x - 0.5, y - 0.5) var hue = distance + t1 hsv(hue, 1, 1 - distance) } // 3D volumetric pattern - color cube export function render3D(index, x, y, z) { hsv(x, y, z) // Hue=x, Saturation=y, Value=z } ``` -------------------------------- ### Array Initialization and Transformation Source: https://context7.com/simap/pixelblaze/llms.txt Demonstrates creating arrays using `array(n)` or literals, and initializing with `forEach`. Transforms array elements using `mapTo`. ```javascript // Create and initialize arrays var colors = array(pixelCount) var positions = [0.1, 0.3, 0.5, 0.7, 0.9] // Initialize with forEach colors.forEach((v, i, arr) => { arr[i] = random(1) // Random initial colors }) // Transform array with mapTo (src -> dest) var doubled = array(5) positions.mapTo(doubled, (v, i) => v * 2) ``` -------------------------------- ### Audio Reactive Frequency Spectrum Visualizer Source: https://context7.com/simap/pixelblaze/llms.txt Visualize audio frequency spectrum data. Maps frequency bins to LED colors and brightness. ```javascript // Audio reactive - frequency spectrum visualizer var freqBin = floor(index / pixelCount * 32) var magnitude = frequencyData[freqBin] hsv(index / pixelCount, 1, magnitude) ``` -------------------------------- ### Control Pattern Playback with Sequencer Functions Source: https://context7.com/simap/pixelblaze/llms.txt Programmatically control pattern transitions using sequencer functions. Advance patterns, check the current mode, or jump to specific playlist positions. ```javascript // Advance to next pattern (like button press) export function triggerNextPattern() { sequencerNext() } // Check sequencer mode var mode = sequencerGetMode() // SEQ_OFF = 0 // SEQ_SHUFFLE_ALL = 1 // SEQ_PLAYLIST = 2 // SEQ_SYNCHRONIZED = 3 (sync group follower) // Playlist control var currentPos = playlistGetPosition() // 0-based index var totalItems = playlistGetLength() // Jump to specific playlist item export function inputNumberGoToItem(position) { if (position >= 0 && position < playlistGetLength()) { playlistSetPosition(position) } } // Previous pattern export function triggerPrevious() { var pos = playlistGetPosition() var newPos = pos > 0 ? pos - 1 : playlistGetLength() - 1 playlistSetPosition(newPos) } // Sync group node identification var myNode = nodeId() // Returns configured node ID export function render(index) { // Different behavior per node in sync group var hueOffset = myNode * 0.1 hsv(index / pixelCount + hueOffset, 1, 1) } ``` -------------------------------- ### Generate Waveforms and Transitions Source: https://context7.com/simap/pixelblaze/llms.txt Utilize time, wave, triangle, and square functions to create oscillating values, and smoothstep for easing transitions. ```javascript var t1, t2, t3 export function beforeRender(delta) { t1 = time(0.1) // Sawtooth, ~6.5 second cycle t2 = time(0.05) // Faster, ~3.3 second cycle t3 = time(0.02) // Even faster, ~1.3 second cycle } export function render(index) { var position = index / pixelCount // Smooth sine wave (0 to 1) var sineValue = wave(t1 + position) // Triangle wave (0 to 1, linear ramp up/down) var triValue = triangle(t2 + position) // Square wave with 30% duty cycle var sqValue = square(t3 + position, 0.3) // Linear interpolation between colors var blended = mix(0, 1, sineValue) // mix(low, high, weight) hsv(position, 1, sineValue) } // Smooth transitions with smoothstep export function render(index) { var x = index / pixelCount // Smooth transition from 0 to 1 as x crosses 0.3 to 0.7 var v = smoothstep(0.3, 0.7, x) hsv(0, 0, v) // White gradient with smooth edges } ``` -------------------------------- ### Implement Lookup Table for Mode Selection Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Use an array of functions as a lookup table to bypass the lack of switch-case statements. ```javascript modes[0] = () => {/* do mode 0 */}; modes[1] = () => {/* do mode 1 */}; // ... modes[currentMode](); ``` -------------------------------- ### Manage Colors and Palettes Source: https://context7.com/simap/pixelblaze/llms.txt Set pixel colors using HSV or RGB functions, or apply custom gradients using setPalette and paint. ```javascript // HSV color - hue wraps automatically (0.0 to 1.0) export function render(index) { var hue = index / pixelCount var saturation = 1 var value = 0.8 // 80% brightness hsv(hue, saturation, value) } // RGB color - values from 0.0 to 1.0 export function render(index) { var red = 1, green = 0.5, blue = 0 rgb(red, green, blue) // Orange color } // Custom palette - gradient from black to magenta to cyan var gradient = [ 0, 0, 0, 0, // position 0%, rgb(0,0,0) black 0.5, 1, 0, 1, // position 50%, rgb(1,0,1) magenta 1, 0, 1, 1 // position 100%, rgb(0,1,1) cyan ] setPalette(gradient) export function render(index) { var position = index / pixelCount var brightness = 0.8 paint(position, brightness) // Color from palette at position } ``` -------------------------------- ### Fractal Brownian Motion (Perlin FBM) Source: https://context7.com/simap/pixelblaze/llms.txt Creates layered detail using Fractal Brownian Motion. Adjust lacunarity, gain, and octaves for different effects. ```javascript // Fractal Brownian Motion - layered detail export function render2D(index, x, y) { var scale = 3 var lacunarity = 2 // Distance between octaves var gain = 0.5 // Strength falloff per octave var octaves = 4 // Number of noise layers var n = perlinFbm(x * scale, y * scale, t1 * 5, lacunarity, gain, octaves) hsv(n + t1, 1, abs(n)) } ``` -------------------------------- ### Seamlessly Wrapping Perlin Noise Source: https://context7.com/simap/pixelblaze/llms.txt Creates seamlessly tiling Perlin noise textures by setting wrap dimensions. Useful for backgrounds and repeating patterns. ```javascript // Seamlessly wrapping noise texture setPerlinWrap(8, 8, 256) // Wrap at 8x8 in x,y export function render2D(index, x, y) { var n = perlin(x * 8, y * 8, t1 * 10, 0) hsv(n + 0.5, 1, 0.8) } ``` -------------------------------- ### Declare Sensor Variables Source: https://context7.com/simap/pixelblaze/llms.txt Declare variables to access sensor data. These are initialized if the sensor expansion board is connected. ```javascript // Declare sensor variables (initialized if board connected) export var frequencyData // 32-element frequency array (12.5Hz-10kHz) export var energyAverage // Overall audio volume export var maxFrequency // Dominant frequency export var maxFrequencyMagnitude export var accelerometer // [x, y, z] array, -16G to +16G export var light // Ambient light level export var analogInputs // [A0, A1, A2, A3, A4] array ``` -------------------------------- ### Export Sensor Expansion Board Variables Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Declare exported variables to access data from the sensor expansion board, such as audio frequency data and accelerometer values. ```javascript export var frequencyData export var energyAverage export var maxFrequencyMagnitude export var maxFrequency export var accelerometer export var light export var analogInputs ``` -------------------------------- ### Input / Output Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for reading and writing to hardware pins. ```APIDOC ## analogRead(pin) Reads the value from the pin as a number between 0.0 and 1.0. ## pinMode(pin, mode) Set the pin mode as an INPUT, INPUT_PULLUP, INPUT_PULLDOWN, OUTPUT, OUTPUT_OPEN_DRAIN, or ANALOG. ## digitalWrite(pin, state) Set a pin HIGH or LOW. Any non-zero value will set the pin HIGH. ## digitalRead(pin) Read a pin state, returns 1.0 if the pin is HIGH, 0.0 for LOW otherwise. ## touchRead(pin) Detect touch and proximity on a pin using capacitive sensing. Returns a value between 0.0 and 1.0. ``` -------------------------------- ### Sequencer / Playlist Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions to control pattern sequencing and playlist navigation. ```APIDOC ## sequencerNext() Advance to next pattern. ## sequencerGetMode() Returns the current sequencer mode (SEQ_OFF, SEQ_SHUFFLE_ALL, SEQ_PLAYLIST, SEQ_SYNCHRONIZED). ## playlistGetPosition() Returns the current index of the playlist. ## playlistSetPosition(position) Switch to the specified playlist item. ## playlistGetLength() Returns the number of items in the playlist. ``` -------------------------------- ### Array Mutation and Reduction Source: https://context7.com/simap/pixelblaze/llms.txt Shows how to modify array elements in place with `mutate` and aggregate values using `reduce` or `arraySum`. ```javascript // Modify in place with mutate colors.mutate((v, i) => v + 0.01) // Shift all hues // Reduce to single value var total = colors.reduce((acc, v) => acc + v, 0) var average = total / colors.length // Or use arraySum shortcut var sum = arraySum(colors) var avg = sum / arrayLength(colors) ``` -------------------------------- ### Volume-Based Brightness Control Source: https://context7.com/simap/pixelblaze/llms.txt Control LED brightness based on overall audio volume. Higher volume results in brighter LEDs. ```javascript // Volume-based brightness var hue = index / pixelCount hsv(hue, 1, energyAverage) ``` -------------------------------- ### Sensor Expansion Board Data Access Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Accessing hardware sensor data via exported variables in Pixelblaze patterns. ```APIDOC ## Sensor Expansion Board Data ### Description Access data from the Pixelblaze sensor expansion board by exporting specific variables. These variables provide real-time data from audio, motion, and light sensors. ### Exported Variables - **frequencyData** (array) - 32 element array with frequency magnitude data (12.5-10khz) - **energyAverage** (number) - Total audio volume - **maxFrequency** (number) - Strongest tone detected (39Hz resolution) - **maxFrequencyMagnitude** (number) - Magnitude of the strongest tone - **accelerometer** (array) - 3 element array [x, y, z] for 3-axis 16G accelerometer - **light** (number) - Ambient light sensor value - **analogInputs** (array) - 5 element array for analog values A0-A4 ### Usage Example ```javascript export var frequencyData export var energyAverage export var accelerometer export var light ``` ``` -------------------------------- ### 2D Rendering with Pixel Map Coordinates Source: https://github.com/simap/pixelblaze/blob/master/README.mapper.md Use the `render2D` function to create patterns that respond to the X and Y coordinates of each pixel. Coordinates are provided in 'world units' between 0.0 and 1.0. ```javascript export function render2D(index, x, y) { hsv(x, 1, y) } ``` -------------------------------- ### Accelerometer-Based Color Mapping Source: https://context7.com/simap/pixelblaze/llms.txt Map accelerometer data to LED colors and brightness. Uses X-axis for hue and Y-axis for brightness. ```javascript // Accelerometer-based color var tilt = (accelerometer[0] + 1) / 2 // Normalize X to 0-1 var shake = abs(accelerometer[1]) hsv(tilt, 1, shake) ``` -------------------------------- ### Analog Input Control Source: https://context7.com/simap/pixelblaze/llms.txt Control LED color using analog input values. Maps the first analog input (A0) to hue. ```javascript // Analog input control var pot = analogInputs[0] // Potentiometer on A0 hsv(pot, 1, 1) ``` -------------------------------- ### Array Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for creating, iterating, and manipulating arrays. ```APIDOC ## Array Functions ### Description Functions to manage array data structures, including iteration, sorting, and reduction. ### Functions - **array(n)**: Creates a new array with n elements. - **arrayForEach(a, fn)**: Iterates over array a calling fn(value, index, array). - **arrayLength(a)**: Returns the size of the array. - **arrayMapTo(src, dest, fn)**: Maps src to dest using fn. - **arrayMutate(a, fn)**: Modifies array a in place using fn. - **arrayReduce(a, fn, initialValue)**: Reduces array to a single value. - **arrayReplace(a, ...)**: Replaces elements starting at index 0. - **arrayReplaceAt(a, offset, ...)**: Replaces elements starting at offset. - **arraySort(a)**: Sorts numbers in ascending order. - **arraySortBy(a, fn)**: Sorts using a custom comparison function. - **arraySum(a)**: Returns the sum of all elements. ``` -------------------------------- ### UI Output: Gauge Source: https://context7.com/simap/pixelblaze/llms.txt Displays a gauge control representing a value between 0.0 and 1.0, shown as a percentage. ```javascript // Output: gauge (0.0 to 1.0, shown as percentage) export function gaugeIntensity() { return currentIntensity } ``` -------------------------------- ### Array Sorting Source: https://context7.com/simap/pixelblaze/llms.txt Illustrates sorting arrays in ascending order with `sort()` and descending order using a custom comparator with `sortBy()`. ```javascript // Sort array var data = [3, 1, 4, 1, 5, 9] data.sort() // Ascending: [1, 1, 3, 4, 5, 9] // Custom sort with comparator data.sortBy((a, b) => b - a) // Descending ``` -------------------------------- ### Auto-Dimming Based on Ambient Light Source: https://context7.com/simap/pixelblaze/llms.txt Automatically adjust LED brightness based on ambient light levels. LEDs dim in brighter environments. ```javascript // Auto-dim based on ambient light var brightness = clamp(1 - light, 0.1, 1) // Dimmer in bright rooms hsv(index / pixelCount, 1, brightness) ``` -------------------------------- ### Basic Perlin Noise Generation Source: https://context7.com/simap/pixelblaze/llms.txt Generates basic Perlin noise for smooth, organic movement. Animates through the Z dimension. ```javascript var t1 export function beforeRender(delta) { t1 = time(0.05) } // Basic Perlin noise - smooth organic movement export function render2D(index, x, y) { var scale = 4 // Noise density var z = t1 * 10 // Animate through Z dimension var n = perlin(x * scale, y * scale, z, 0) // Returns -0.5 to 0.5 n = n + 0.5 // Shift to 0 to 1 hsv(n, 1, n) } ``` -------------------------------- ### UI Color Picker (RGB) Source: https://context7.com/simap/pixelblaze/llms.txt Integrates an RGB color picker. The exported function name determines the control and its associated variables. ```javascript // Color picker - RGB variant var colorR = 1, colorG = 0, colorB = 0 export function rgbPickerAccent(r, g, b) { colorR = r colorG = g colorB = b } ``` -------------------------------- ### Math Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Built-in mathematical functions available for pattern calculations. ```APIDOC ## Math Functions ### Description Pixelblaze provides a standard set of math functions for trigonometry, rounding, and logarithmic operations. ### Functions - **abs(v)**: Returns absolute value. - **acos(x)**: Returns arccosine in radians. - **asin(x)**: Returns arcsine in radians. - **atan(x)**: Returns arctangent in radians. - **atan2(y, x)**: Returns angle in radians between positive x-axis and point (x, y). - **ceil(v)**: Rounds up to next integer. - **clamp(value, low, hi)**: Constrains value between low and high. - **cos(angleRads)**: Returns cosine. - **exp(x)**: Returns e^x. - **floor(v)**: Rounds down to next integer. - **frac(v)**: Returns fractional component. - **hypot(x, y)**: Square root of sum of squares of x and y. - **hypot3(x, y, z)**: Square root of sum of squares of x, y, and z. - **log(v)**: Natural logarithm. - **log2(v)**: Base 2 logarithm. - **max(v1, v2)**: Returns larger of two numbers. - **min(v1, v2)**: Returns smaller of two numbers. - **mod(x, y)**: Floored remainder of x/y. - **pow(base, exponent)**: Returns base to the exponent power. ``` -------------------------------- ### UI Output: Show Number Source: https://context7.com/simap/pixelblaze/llms.txt Displays a calculated number in the UI. The exported function should return the value to be displayed. ```javascript // Output: display a number export function showNumberFPS() { return 1000 / delta // Calculated FPS } ``` -------------------------------- ### Clock / Time Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for retrieving current time information when connected to the internet. ```APIDOC ## Clock Functions - **clockYear()** - Returns the current year. - **clockMonth()** - Returns the current month. - **clockDay()** - Returns the current day. - **clockHour()** - Returns the hour in 24-hour format. - **clockMinute()** - Returns the current minute. - **clockSecond()** - Returns the current second. - **clockWeekday()** - Returns the weekday (Sunday = 1, Monday = 2, etc.). ``` -------------------------------- ### UI Color Picker (HSV) Source: https://context7.com/simap/pixelblaze/llms.txt Integrates a color picker that returns HSV values. The exported function name defines the control. ```javascript // Color picker - HSV variant var pickedHue = 0, pickedSat = 1, pickedVal = 1 export function hsvPickerColor(h, s, v) { pickedHue = h pickedSat = s pickedVal = v } ``` -------------------------------- ### Perform Mathematical Calculations Source: https://context7.com/simap/pixelblaze/llms.txt Utilize a comprehensive set of math functions, including trigonometry, rounding, clamping, and random number generation. All calculations use 16.16 fixed-point format. ```javascript // Trigonometry (angles in radians) var angle = PI / 4 // 45 degrees var s = sin(angle) var c = cos(angle) var t = tan(angle) // Inverse trig var aAngle = asin(0.5) var bAngle = acos(0.5) var cAngle = atan(1) var dAngle = atan2(y, x) // Angle to point (x,y) // Distance calculations var dist2D = hypot(x, y) // sqrt(x² + y²) var dist3D = hypot3(x, y, z) // sqrt(x² + y² + z²) // Rounding var a = floor(5.9) // 5 var b = ceil(5.1) // 6 var c = round(5.5) // 6 var d = trunc(-5.7) // -5 (toward zero) var e = frac(5.7) // 0.7 (fractional part) // Clamping and range var v = clamp(value, 0, 1) // Limit to 0-1 var small = min(a, b) var large = max(a, b) // Modulo with consistent sign var wrapped = mod(-3.5, 3) // 2.5 (same sign as divisor) // vs: -3.5 % 3 == -0.5 // Exponentials and logarithms var powered = pow(2, 10) // 1024 var rooted = sqrt(16) // 4 var natural = exp(1) // e ≈ 2.718 var ln = log(E) // 1 var log2Val = log2(256) // 8 // Random numbers var rand = random(100) // True random 0 to 99.999... prngSeed(42) // Set deterministic seed var pseudo = prng(100) // Pseudorandom, reproducible sequence // Available constants // E, PI, PI2 (2π), PI3_4 (3π/4), PISQ (π²) // LN2, LN10, LOG2E, LOG10E, SQRT1_2, SQRT2 ``` -------------------------------- ### 3D Rendering with Pixel Map Coordinates Source: https://github.com/simap/pixelblaze/blob/master/README.mapper.md Utilize the `render3D` function for patterns that require X, Y, and Z coordinates. This allows for volumetric effects, with coordinates also in 'world units' (0.0 to 1.0). ```javascript export function render3D(index, x, y, z) { hsv(x, y, z) } ``` -------------------------------- ### Pixel / Color Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions to set pixel colors using HSV or RGB color spaces and manage color palettes. ```APIDOC ## hsv(hue, saturation, value) ### Description Sets the current pixel using HSV color space with high dynamic range support. ## hsv24(hue, saturation, value) ### Description Sets the current pixel using 24-bit HSV color space. ## rgb(red, green, blue) ### Description Sets the current pixel to the RGB value provided (0.0 to 1.0). ## setPalette(array) ### Description Sets the palette to a gradient based on an array of positions and RGB values. ## paint(value, [brightness]) ### Description Sets the current pixel to a color based on the value's position in the current palette. ``` -------------------------------- ### JavaScript Pixel Map - LED Ring Source: https://context7.com/simap/pixelblaze/llms.txt Generates a 2D pixel map using a JavaScript function, arranging pixels in a circular layout for an LED ring. ```javascript // LED ring map - circular layout function (pixelCount) { var map = [] for (var i = 0; i < pixelCount; i++) { var angle = (i / pixelCount) * Math.PI * 2 var x = Math.cos(angle) var y = Math.sin(angle) map.push([x, y]) } return map } ``` -------------------------------- ### Mathematical Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for random number generation, rounding, and trigonometry. ```APIDOC ## Mathematical Functions ### Description Provides utilities for pseudorandom numbers, rounding, and basic trigonometry. ### Functions - **prng(max)**: Returns a pseudorandom number between 0.0 and max (exclusive). - **prngSeed(seed)**: Sets the seed for prng(). Returns the old seed. - **random(max)**: Returns a true random number between 0.0 and max (exclusive). - **round(v)**: Rounds a number to the nearest integer. - **sin(angleRads)**: Returns the sine of an angle in radians. - **sqrt(v)**: Returns the square root of a number. - **tan(angleRads)**: Returns the tangent of an angle in radians. - **trunc(v)**: Returns the integer component of a number. ``` -------------------------------- ### Perlin Noise Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for generating various types of 3D Perlin noise and configuring wrapping behavior. ```APIDOC ## perlin(x, y, z, seed) ### Description Generate 3D Perlin noise. Every integer value produces a different random result, with smooth transitions between them. ## perlinFbm(x, y, z, lacunarity, gain, octaves) ### Description Generate 3D fractal Perlin noise (fractal Brownian Motion). ## perlinRidge(x, y, z, lacunarity, gain, offset, octaves) ### Description Generate 3D fractal ridged Perlin noise. ## perlinTurbulence(x, y, z, lacunarity, gain, octaves) ### Description Generate 3D fractal turbulent Perlin noise. ## setPerlinWrap(x, y, z) ### Description Causes perlin functions to wrap at the given integer intervals between 2 and 256. ``` -------------------------------- ### Pixel Mapping Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for iterating over pixels and applying coordinate transformations. ```APIDOC ## mapPixels(fn) ### Description Walk through the pixels with pixel map coordinates. The given `fn` is invoked with 4 arguments: (index, x, y, z). ### Parameters - **fn** (function) - Required - Callback function receiving (index, x, y, z). ``` -------------------------------- ### Pixel Map Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions to query the properties of the current pixel map. ```APIDOC ## pixelMapDimensions() ### Description Return the number of dimensions in the pixel map. ## has2DMap() ### Description Returns true if there is a 2D pixel map. ## has3DMap() ### Description Returns true if there is a 3D pixel map. ``` -------------------------------- ### Iterate Pixels with mapPixels Source: https://context7.com/simap/pixelblaze/llms.txt Iterate over all pixels using the `mapPixels` function, allowing processing of each pixel's coordinates after transformations are applied. ```javascript // Walk all pixels with mapPixels export function beforeRender(delta) { mapPixels((index, x, y, z) => { // Process each pixel's coordinates // Transforms are applied before this function }) } ``` -------------------------------- ### Set Palette Gradient Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Defines a color gradient using an array of positions and RGB values, then applies it to the current palette. ```javascript var rgbGradient = [ 0, 0, 0, 0, //position start, rgb(0,0,0) 0.75, 1, 0, 1, //position 75%, rgb(1,0,1) 1, 0, 1, 1 // position end, rgb(0,1,1) ] setPalette(rgbGradient) ``` -------------------------------- ### Exported Render Function for Pixelblaze Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md The `render(index)` function is called for each pixel. Use `hsv` or `rgb` to set the pixel color. This is the primary function for defining pixel colors. ```javascript export function render(index) { hsv(index / pixelCount, 1, 1) } ``` -------------------------------- ### Before Render Animation Function in Pixelblaze Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md The `beforeRender(delta)` function is called before each frame. Use the `delta` argument (milliseconds elapsed) to create frame-rate independent animations. ```javascript export function beforeRender(delta) { // Animation logic here } ``` -------------------------------- ### Ridged Perlin Noise Source: https://context7.com/simap/pixelblaze/llms.txt Generates mountain-like ridges using the Perlin ridge function. Parameters control the ridged appearance. ```javascript // Ridged noise - mountain-like ridges export function render2D(index, x, y) { var n = perlinRidge(x * 4, y * 4, t1 * 3, 2, 0.5, 1, 4) hsv(0.6, 1, n) } ``` -------------------------------- ### Alternative Render Functions in Pixelblaze Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Use `render2D` or `render3D` when a 2D or 3D pixel map is available. Pixelblaze automatically selects the appropriate function based on the map. ```javascript export function render2D(index, x, y) { hsv(x / width, 1, 1) } ``` ```javascript export function render3D(index, x, y, z) { hsv(z / depth, 1, 1) } ``` -------------------------------- ### Define 2D Pixel Map with JSON Array Source: https://github.com/simap/pixelblaze/blob/master/README.mapper.md Use a JSON array to define the 2D coordinates for each pixel in a map. Each inner array represents a pixel's [x, y] coordinates. ```json [ [0,0], [100,0], [100,100], [0,100], ] ``` -------------------------------- ### Calculate Array Average Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Calculate the average of an array by dividing the sum of its elements by its length. ```Pixelblaze average = arraySum(a) / arrayLength(a) ``` -------------------------------- ### JavaScript Pixel Map - Zigzag Matrix Source: https://context7.com/simap/pixelblaze/llms.txt Generates a 2D pixel map using a JavaScript function, creating an 8-wide zigzag matrix layout. ```javascript // JavaScript pixel map function - 8-wide zigzag matrix function (pixelCount) { var width = 8 var map = [] for (var i = 0; i < pixelCount; i++) { var y = Math.floor(i / width) var x = i % width x = y % 2 == 1 ? width - 1 - x : x // Zigzag alternating rows map.push([x, y]) } return map } ``` -------------------------------- ### Exporting Variables for Watching in Pixelblaze Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export global variables to monitor their values in the Var Watcher. For arrays, each element is shown with its index. Data is sampled at the end of rendering. ```javascript var myExportedVar export function render(index) { myExportedVar = index } ``` ```javascript var myExportedVar export function render(index) { if (index == 42) { myExportedVar = "Specific Pixel Data" } } ``` -------------------------------- ### Creating a Range Slider Control in Pixelblaze Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Export a function prefixed with `slider` to create a UI range slider. The function receives values between 0.0 and 1.0. Store the value to use it in your pattern. ```javascript var mySetting = 0.5 export function sliderMySetting(v) { mySetting = v } ``` -------------------------------- ### Waveform Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions for generating and manipulating waveforms. ```APIDOC ## Waveform Functions ### Description Utilities for generating sawtooth, sine, square, and triangle waves, as well as interpolation functions. ### Functions - **time(interval)**: Returns a sawtooth waveform between 0.0 and 1.0. - **wave(v)**: Converts sawtooth v to a sinusoidal waveform. - **square(v, duty)**: Converts sawtooth v to a square wave. - **triangle(v)**: Converts sawtooth v to a triangle waveform. - **mix(low, high, weight)**: Linear interpolation between low and high. - **smoothstep(low, high, v)**: Hermite interpolation between 0.0 and 1.0. - **bezierQuadratic(t, p0, p1, p2)**: Quadratic bezier curve calculation. - **bezierCubic(t, p0, p1, p2)**: Cubic bezier curve calculation. ``` -------------------------------- ### 2D Coordinate Transformations Source: https://context7.com/simap/pixelblaze/llms.txt Applies 2D transformations like translate, rotate, and scale to pixel map coordinates before rendering. Transformations are reset each frame. ```javascript var t1 export function beforeRender(delta) { t1 = time(0.1) // Reset and apply new transforms each frame resetTransform() // Center the origin, rotate, then scale translate(-0.5, -0.5) // Move center to origin rotate(t1 * PI2) // Rotate around center scale(1 + wave(t1), 1 + wave(t1)) // Pulsing scale translate(0.5, 0.5) // Move back } export function render2D(index, x, y) { // x, y are now transformed coordinates hsv(x, 1, y) } ``` -------------------------------- ### UI Number Input Source: https://context7.com/simap/pixelblaze/llms.txt Provides a number input field for arbitrary values. The exported function receives the input value. ```javascript // Number input (any value) var scale = 1 export function inputNumberScale(v) { scale = v } ``` -------------------------------- ### 3D Coordinate Transformations Source: https://context7.com/simap/pixelblaze/llms.txt Applies 3D transformations including translation, rotation around axes, and scaling. Transformations are reset each frame. ```javascript // 3D transformations export function beforeRender(delta) { resetTransform() translate3D(-0.5, -0.5, -0.5) // Center origin rotateX(t1 * PI2) // Spin around X axis rotateY(t1 * PI2 * 0.7) // Spin around Y axis rotateZ(t1 * PI2 * 0.3) // Spin around Z axis scale3D(2, 2, 2) // Double scale translate3D(0.5, 0.5, 0.5) // Restore position } ``` -------------------------------- ### JavaScript Pixel Map - 3D Helix Source: https://context7.com/simap/pixelblaze/llms.txt Generates a 3D pixel map using a JavaScript function, creating a helix or spiral layout. ```javascript // 3D helix/spiral map function (pixelCount) { var map = [] var turns = 5 for (var i = 0; i < pixelCount; i++) { var t = i / pixelCount var angle = t * turns * Math.PI * 2 var x = Math.cos(angle) var y = Math.sin(angle) var z = t // Height increases linearly map.push([x, y, z]) } return map } ``` -------------------------------- ### UI Toggle Switch Source: https://context7.com/simap/pixelblaze/llms.txt Implements a toggle switch control that returns a boolean value. Use the exported function name to link it to a variable. ```javascript // Toggle switch (true/false) var enableEffect = true export function toggleEnableEffect(isEnabled) { enableEffect = isEnabled } ``` -------------------------------- ### UI Trigger Button Source: https://context7.com/simap/pixelblaze/llms.txt Adds a button control that fires an event when pressed. The exported function is called on press. ```javascript // Trigger button (called on press) var triggered = false export function triggerFlash() { triggered = true } ``` -------------------------------- ### Coordinate Transformation Functions Source: https://github.com/simap/pixelblaze/blob/master/README.expressions.md Functions to manipulate pixel map coordinates via translation, scaling, and rotation. ```APIDOC ## resetTransform() ### Description Resets coordinate transforms to the default. ## translate(x, y) / translate3D(x, y, z) ### Description Move in 2D or 3D space. ## scale(x, y) / scale3D(x, y, z) ### Description Scale in 2D or 3D space. ## rotate(angleRads) / rotateX(angleRads) / rotateY(angleRads) / rotateZ(angleRads) ### Description Rotate space by an angle in radians. ``` -------------------------------- ### JSON Pixel Map - Square Layout Source: https://context7.com/simap/pixelblaze/llms.txt Defines a 2D pixel map as a JSON array of coordinates, representing the four corners of a square. ```json // JSON pixel map - 4 corners of a square // Save this in the Mapper tab [ [0, 0], // Pixel 0: top-left [100, 0], // Pixel 1: top-right [100, 100], // Pixel 2: bottom-right [0, 100] // Pixel 3: bottom-left ] ``` -------------------------------- ### UI Slider Control Source: https://context7.com/simap/pixelblaze/llms.txt Implements a UI slider that provides a 0.0 to 1.0 value. The exported function name determines the control type and name. ```javascript // Slider control (0.0 to 1.0) var speed = 0.5 export function sliderSpeed(v) { speed = v } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.