Create a complete, highly interactive p5.js simulation demonstrating: Create an interactive P5.js simulation that demonstrates: Create an interactive simulation showing light refraction through different media with adjustable angle of incidence, wavelength, and material density. Include real-time Snell's Law calculations and visual bending of light rays at the interface.. Include user controls, real-time feedback, clear visual indicators, and educational annotations that help users understand the underlying concepts.
CRITICAL REQUIREMENTS:
ACCURACY: The simulation must be scientifically/mathematically accurate for Create an interactive P5.js simulation that demonstrates: Create an interactive simulation showing light refraction through different media with adjustable angle of incidence, wavelength, and material density. Include real-time Snell's Law calculations and visual bending of light rays at the interface.. Include user controls, real-time feedback, clear visual indicators, and educational annotations that help users understand the underlying concepts.
FUNCTIONAL INTERACTIVITY: All sliders and buttons MUST actually control and modify the simulation behavior in real-time
EDUCATIONAL: Users should learn about Create an interactive P5.js simulation that demonstrates: Create an interactive simulation showing light refraction through different media with adjustable angle of incidence, wavelength, and material density. Include real-time Snell's Law calculations and visual bending of light rays at the interface.. Include user controls, real-time feedback, clear visual indicators, and educational annotations that help users understand the underlying concepts. through experimentation and parameter manipulation
VISUAL PRECISION: Animations should be smooth, realistic, and visually accurate to real-world physics
MANDATORY INTERACTIVE ELEMENTS THAT MUST WORK:
At least 4-6 sliders controlling key parameters with realistic ranges - these MUST change simulation behavior
At least 3-4 buttons for actions (reset, pause/play, presets, etc.) - these MUST perform actual functions
Real-time parameter display showing current values that update as sliders move
Visual feedback that responds immediately and visibly to control changes
Mouse interactions where physically meaningful
CRITICAL: CONTROLS MUST BE FUNCTIONAL, NOT DECORATIVE
Every slider must control a variable that actively affects the simulation
Every button must perform a meaningful action that changes the simulation state
Parameter changes must be immediately visible in the simulation output
Use the actual slider values in mathematical calculations and physics equations
ANIMATION AND TIMING REQUIREMENTS:
Use realistic time scaling - avoid animations that are too fast or unrealistic
Assistant
Implement proper frame rate control using deltaTime or fixed timesteps
Use realistic physical constants and scaling factors
Ensure smooth, stable animations at 60fps
Avoid conflicting visual elements or overlapping controls
Make animations visually appealing and scientifically accurate
CONTROL IMPLEMENTATION REQUIREMENTS:
Sliders: Use createSlider(min, max, default, step) with appropriate ranges that make physical sense
Buttons: Use createButton('Label') with meaningful functions that actually execute
Position controls below canvas using .parent(controlsDiv) and CSS for layout. ABSOLUTELY DO NOT use .position(x, y) for any p5.js elements (sliders, buttons, canvas) as this will break layout.
Show parameter values with text() in the main canvas that update in real-time
Use function declarations for event handlers: function resetSim() {}
ALWAYS use slider.value() in your calculations - never ignore slider inputs
CODE FORMAT REQUIREMENTS:
Use GLOBAL MODE p5.js (NOT instance mode)
Define setup() and draw() as regular functions
All variables should be global (use let/var at top level)
Use standard p5.js function names: createCanvas, background, fill, etc.
NO sketch wrapper function - write direct p5.js code
SIMULATION ACCURACY FOR CREATE AN INTERACTIVE P5.JS SIMULATION THAT DEMONSTRATES: CREATE AN INTERACTIVE SIMULATION SHOWING LIGHT REFRACTION THROUGH DIFFERENT MEDIA WITH ADJUSTABLE ANGLE OF INCIDENCE, WAVELENGTH, AND MATERIAL DENSITY. INCLUDE REAL-TIME SNELL'S LAW CALCULATIONS AND VISUAL BENDING OF LIGHT RAYS AT THE INTERFACE.. INCLUDE USER CONTROLS, REAL-TIME FEEDBACK, CLEAR VISUAL INDICATORS, AND EDUCATIONAL ANNOTATIONS THAT HELP USERS UNDERSTAND THE UNDERLYING CONCEPTS.:
Use correct physics equations, mathematical relationships, or algorithmic principles
Realistic parameter ranges and default values that make physical sense
Smooth, continuous animations with proper time scaling
Proper scaling and units where applicable
Include scientific constants or realistic coefficients
ENSURE every parameter controlled by sliders affects the simulation visibly
Use appropriate time steps and scaling factors to avoid too-fast animations
TEXT AND DISPLAY REQUIREMENTS:
Show ONLY the simulation title at the top
Display ONLY key physics parameters (velocity, acceleration, force, etc.) - no instructions or explanations
Keep text minimal and clean - maximum 4-5 parameter displays
NO instruction text like "Click to...", "Drag to...", etc.
Use concise parameter labels like "Velocity: 5.2 m/s" not "Current velocity value is 5.2"
Position parameter text neatly in corners or edges, not cluttering the center
VISUAL REQUIREMENTS:
Clear, educational visualization of the concept with a MODERN, SLEEK aesthetic.
Use a vibrant, harmonious color palette. Consider gradients or subtle shadows for depth.
Multiple visual elements (trails, vectors, measurements, etc.) that don't conflict.
Color coding to distinguish different aspects.
Grid lines, axes, or reference markers where helpful, styled subtly.
Immediate and obvious visual response to parameter changes.
Smooth, realistic motion that matches real-world physics.
Proper visual hierarchy - important elements should stand out.
Clean, uncluttered display with minimal text.
All text (labels, values, titles) within the canvas should be clearly readable, using a modern font (if possible within p5.js limitations) and contrasting colors.
EXAMPLE OF FUNCTIONAL CONTROLS WITH PROPER TIMING:
javascript
// Global variables that ACTUALLY affect simulation
let gravitySlider, dampingSlider;
let gravity = 0.5; // This gets updated by slider
let damping = 0.99; // This gets updated by slider
let resetBtn, pauseBtn;
let isPaused = false;
let timeScale = 0.02; // Control animation speed
function setup() {
createCanvas(400, 400);
// Create a div to hold all controls
let controlsDiv = createDiv('');
controlsDiv.id('p5-controls'); // Assign an ID for easier styling/selection
controlsDiv.style('display', 'flex');
controlsDiv.style('flex-wrap', 'wrap');
controlsDiv.style('gap', '10px'); // Spacing between controls
controlsDiv.style('margin-top', '10px'); // Space below canvas
controlsDiv.style('justify-content', 'center'); // Center controls
// Create sliders that CONTROL the simulation with realistic ranges
gravitySlider = createSlider(0.1, 1.0, 0.4, 0.05);
gravitySlider.parent(controlsDiv); // Attach to the div
gravitySlider.style('width', '150px'); // Example width
dampingSlider = createSlider(0.9, 1.0, 0.995, 0.001);
dampingSlider.parent(controlsDiv); // Attach to the div
dampingSlider.style('width', '150px'); // Example width
// Create buttons that DO something
resetBtn = createButton('Reset Simulation');
resetBtn.parent(controlsDiv); // Attach to the div
resetBtn.style('background-color', '#4CAF50'); // Green background
resetBtn.style('color', 'white'); // White text
resetBtn.style('border', 'none');
resetBtn.style('padding', '8px 16px');
resetBtn.style('border-radius', '5px');
resetBtn.style('cursor', 'pointer');
resetBtn.style('font-size', '14px');
resetBtn.style('transition', 'background-color 0.3s ease');
resetBtn.mouseOver(() => resetBtn.style('background-color', '#45a049'));
resetBtn.mouseOut(() => resetBtn.style('background-color', '#4CAF50'));
pauseBtn = createButton('Pause/Play');
pauseBtn.parent(controlsDiv); // Attach to the div
pauseBtn.style('background-color', '#008CBA'); // Blue background
pauseBtn.style('color', 'white'); // White text
pauseBtn.style('border', 'none');
pauseBtn.style('padding', '8px 16px');
pauseBtn.style('border-radius', '5px');
pauseBtn.style('cursor', 'pointer');
pauseBtn.style('font-size', '14px');
pauseBtn.style('transition', 'background-color 0.3s ease');
pauseBtn.mouseOver(() => pauseBtn.style('background-color', '#007B9A'));
pauseBtn.mouseOut(() => pauseBtn.style('background-color', '#008CBA'));
// IMPORTANT: Ensure the canvas is also parented correctly if needed, or its container is styled.
// p5.js canvas is usually appended to the element where new p5.js(sketch, node) is called.
// The controlsDiv will be a sibling to the canvas within that parent node.
}
function draw() {
background(20, 20, 30); // Dark background for modern look
// ACTUALLY USE the slider values - this is critical!
gravity = gravitySlider.value();
damping = dampingSlider.value();
if (!isPaused) {
// Use gravity and damping in actual physics calculations with proper time scaling
velocity += gravity * timeScale;
velocity *= damping;
position += velocity;
}
// Show ONLY title and key parameters - keep it minimal
fill(255); // White text for contrast
textAlign(CENTER);
textSize(24); // Larger title
textStyle(BOLD);
text('Create An Interactive P5.Js Simulation That Demonstrates: Create An Interactive Simulation Showing Light Refraction Through Different Media With Adjustable Angle Of Incidence, Wavelength, And Material Density. Include Real-Time Snell'S Law Calculations And Visual Bending Of Light Rays At The Interface.. Include User Controls, Real-Time Feedback, Clear Visual Indicators, And Educational Annotations That Help Users Understand The Underlying Concepts. Simulation', width/2, 40);
fill(200, 200, 255); // Light blue text for parameters
textAlign(LEFT);
textSize(16);
textStyle(NORMAL);
text('Gravity: ' + gravity.toFixed(2), 20, 80);
text('Damping: ' + damping.toFixed(3), 20, 100);
text('Velocity: ' + velocity.toFixed(2), 20, 120);
text('Position: ' + position.toFixed(2), 20, 140);
// Draw simulation that responds to parameters with realistic motion
fill(255, 100, 100); // Vibrant red for the ellipse
noStroke();
ellipse(position, height/2, 30, 30);
}
// Functions that actually work
function resetSimulation() {
position = width/2;
velocity = 0;
}
function togglePause() {
isPaused = !isPaused;
}
IMPORTANT:
Focus on the specific physics, mathematics, or principles of Create an interactive P5.js simulation that demonstrates: Create an interactive simulation showing light refraction through different media with adjustable angle of incidence, wavelength, and material density. Include real-time Snell's Law calculations and visual bending of light rays at the interface.. Include user controls, real-time feedback, clear visual indicators, and educational annotations that help users understand the underlying concepts.
Make controls that ACTUALLY matter for understanding the concept
Every slider must control a variable used in the simulation
Every button must perform a visible action
Ensure the simulation behaves realistically and responds to all controls
Use proper time scaling to avoid unrealistically fast animations
Position controls carefully to avoid visual conflicts
Make animations smooth and scientifically accurate
Keep text displays MINIMAL - only title and key parameters
NO instruction text or explanations in the simulation
Only output JavaScript code, no explanations
Use global mode p5.js format (no sketch wrapper)
Position controls below the 400x400 canvas with proper spacing
Ensure all interactive elements (sliders, buttons) have clear labels and contrasting colors for visibility and a modern look.
Generate an accurate, interactive simulation of: Create an interactive P5.js simulation that demonstrates: Create an interactive simulation showing light refraction through different media with adjustable angle of incidence, wavelength, and material density. Include real-time Snell's Law calculations and visual bending of light rays at the interface.. Include user controls, real-time feedback, clear visual indicators, and educational annotations that help users understand the underlying concepts. with WORKING controls, REALISTIC timing, and MINIMAL text displays
javascript
// Global variables for simulation parameters and controls
let angleIncSlider, wavelengthSlider, density1Slider, density2Slider, intensitySlider, speedScaleSlider;
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
let canvasWidth = 600;
let canvasHeight = 400;
let interfaceY = canvasHeight / 2; // Horizontal interface line between two media
// Physical constants and variables
// Speed of light in vacuum (m/s)
const c = 299792458;
// Variables updated from sliders
let angleIncDeg = 30; // degrees
let wavelength = 550; // nm (green light default)
let density1 = 1.0; // relative density (e.g. air ~1.0)
let density2 = 1.33; // relative density (e.g. water ~1.33)
let intensity = 1.0; // relative intensity (0.1 to 1)
let speedScale = 1.0; // animation speed scaling
// Computed variables
let n1, n2; // refractive indices from densities (simplified model)
let angleIncRad; // angle of incidence in radians
let angleRefrRad; // angle of refraction in radians
let sinRefr; // sin of refracted angle (for total internal reflection check)
let isTIR = false; // flag for total internal reflection
// Ray animation variables
let rayLength = 250;
let rayProgress = 0; // progress of ray animation (0 to 1)
let raySpeed = 0.5; // base speed (will be scaled by speedScale)
let rayPaused = false;
// Colors
const colorMedium1 = [30, 144, 255]; // DodgerBlue (medium 1)
const colorMedium2 = [255, 140, 0]; // DarkOrange (medium 2)
const colorRayInc = [255, 255, 100]; // Yellowish for incident ray
const colorRayRefr = [100, 255, 255]; // Cyan for refracted ray
const colorRayReflec = [255, 100, 100];// Red for reflected ray (if TIR)
const colorInterface = [200, 200, 200]; // Light gray for interface line
const colorGrid = [80, 80, 80]; // Dark gray for grid lines
// Fonts and styles
let modernFont;
function preload() {
// Load a modern font if possible (fallback to default)
// Using default for compatibility
}
function setup() {
createCanvas(canvasWidth, canvasHeight);
frameRate(60);
textFont('Helvetica, Arial, sans-serif');
// Controls container div
let controlsDiv = createDiv('');
controlsDiv.id('p5-controls');
controlsDiv.style('display', 'flex');
controlsDiv.style('flex-wrap', 'wrap');
controlsDiv.style('gap', '12px');
controlsDiv.style('margin-top', '12px');
controlsDiv.style('justify-content', 'center');
controlsDiv.style('max-width', canvasWidth + 'px');
controlsDiv.style('user-select', 'none');
// Angle of Incidence Slider (0° to 89°)
angleIncSlider = createSlider(0, 89, 30, 1);
angleIncSlider.parent(controlsDiv);
angleIncSlider.style('width', '140px');
angleIncSlider.attribute('title', 'Angle of Incidence (degrees)');
// Wavelength Slider (380 nm to 750 nm)
wavelengthSlider = createSlider(380, 750, 550, 1);
wavelengthSlider.parent(controlsDiv);
wavelengthSlider.style('width', '140px');
wavelengthSlider.attribute('title', 'Wavelength (nm)');
// Density Medium 1 Slider (0.5 to 3.0)
density1Slider = createSlider(0.5, 3.0, 1.0, 0.01);
density1Slider.parent(controlsDiv);
density1Slider.style('width', '140px');
density1Slider.attribute('title', 'Material Density Medium 1');
// Density Medium 2 Slider (0.5 to 3.0)
density2Slider = createSlider(0.5, 3.0, 1.33, 0.01);
density2Slider.parent(controlsDiv);
density2Slider.style('width', '140px');
density2Slider.attribute('title', 'Material Density Medium 2');
// Intensity Slider (0.1 to 1.0)
intensitySlider = createSlider(0.1, 1.0, 1.0, 0.01);
intensitySlider.parent(controlsDiv);
intensitySlider.style('width', '140px');
intensitySlider.attribute('title', 'Light Intensity');
// Speed Scale Slider (0.1 to 3.0)
speedScaleSlider = createSlider(0.1, 3.0, 1.0, 0.01);
speedScaleSlider.parent(controlsDiv);
speedScaleSlider.style('width', '140px');
speedScaleSlider.attribute('title', 'Animation Speed Scale');
// Buttons container div for better layout
let buttonsDiv = createDiv('');
buttonsDiv.parent(controlsDiv);
buttonsDiv.style('display', 'flex');
buttonsDiv.style('gap', '12px');
buttonsDiv.style('margin-top', '6px');
buttonsDiv.style('width', '100%');
buttonsDiv.style('justify-content', 'center');
// Reset Button
resetBtn = createButton('Reset');
resetBtn.parent(buttonsDiv);
styleButton(resetBtn, '#4CAF50');
resetBtn.mousePressed(resetSim);
// Pause/Play Button
pauseBtn = createButton('Pause');
pauseBtn.parent(buttonsDiv);
styleButton(pauseBtn, '#008CBA');
pauseBtn.mousePressed(togglePause);
// Preset 1 Button (Air to Water)
presetBtn1 = createButton('Air → Water');
presetBtn1.parent(buttonsDiv);
styleButton(presetBtn1, '#FF9800');
presetBtn1.mousePressed(() => {
angleIncSlider.value(30);
wavelengthSlider.value(550);
density1Slider.value(1.0);
density2Slider.value(1.33);
intensitySlider.value(1.0);
speedScaleSlider.value(1.0);
resetSim();
});
// Preset 2 Button (Water to Glass)
presetBtn2 = createButton('Water → Glass');
presetBtn2.parent(buttonsDiv);
styleButton(presetBtn2, '#9C27B0');
presetBtn2.mousePressed(() => {
angleIncSlider.value(45);
wavelengthSlider.value(650);
density1Slider.value(1.33);
density2Slider.value(1.52);
intensitySlider.value(0.8);
speedScaleSlider.value(1.2);
resetSim();
});
resetSim();
}
function styleButton(btn, bgColor) {
btn.style('background-color', bgColor);
btn.style('color', 'white');
btn.style('border', 'none');
btn.style('padding', '8px 18px');
btn.style('border-radius', '5px');
btn.style('cursor', 'pointer');
btn.style('font-size', '14px');
btn.style('transition', 'background-color 0.3s ease');
btn.mouseOver(() => btn.style('background-color', shadeColor(bgColor, -15)));
btn.mouseOut(() => btn.style('background-color', bgColor));
}
// Utility to darken/lighten colors for hover effect
function shadeColor(color, percent) {
let f=parseInt(color.slice(1),16),t=percent<0?0:255,p=percent<0?percent*-1:percent;
let R=f>>16,G=f>>8&0x00FF,B=f&0x0000FF;
let r=Math.round((t-R)*p)+R;
let g=Math.round((t-G)*p)+G;
let b=Math.round((t-B)*p)+B;
return "#" + (0x1000000 + (r<<16) + (g<<8) + b).toString(16).slice(1);
}
function draw() {
background(18, 18, 30);
// Update parameters from sliders
angleIncDeg = angleIncSlider.value();
wavelength = wavelengthSlider.value();
density1 = density1Slider.value();
density2 = density2Slider.value();
intensity = intensitySlider.value();
speedScale = speedScaleSlider.value();
// Calculate refractive indices from densities (simplified model)
// n ~ sqrt(density), approximate for demonstration
n1 = sqrt(density1);
n2 = sqrt(density2);
// Convert angle of incidence to radians
angleIncRad = radians(angleIncDeg);
// Snell's Law: n1 * sin(theta1) = n2 * sin(theta2)
let sinRefrRaw = (n1 / n2) * sin(angleIncRad);
// Check for total internal reflection (TIR)
if (abs(sinRefrRaw) > 1) {
isTIR = true;
angleRefrRad = NaN;
} else {
isTIR = false;
angleRefrRad = asin(sinRefrRaw);
}
// Update ray animation progress
if (!isPaused) {
rayProgress += raySpeed * speedScale * (deltaTime / 1000);
if (rayProgress > 1) rayProgress = 0;
}
drawGrid();
drawMedia();
drawInterface();
drawRays();
drawTextInfo();
}
// Draw subtle grid lines for reference
function drawGrid() {
stroke(colorGrid[0], colorGrid[1], colorGrid[2], 50);
strokeWeight(1);
let gridSpacing = 40;
for (let x = 0; x <= width; x += gridSpacing) {
line(x, 0, x, height);
}
for (let y = 0; y <= height; y += gridSpacing) {
line(0, y, width, y);
}
}
// Draw the two media with gradient backgrounds
function drawMedia() {
noStroke();
// Medium 1 (top)
setGradient(0, 0, width, interfaceY,
color(colorMedium1[0], colorMedium1[1], colorMedium1[2], 180),
color(colorMedium1[0], colorMedium1[1], colorMedium1[2], 40), 'Y');
// Medium 2 (bottom)
setGradient(0, interfaceY, width, height - interfaceY,
color(colorMedium2[0], colorMedium2[1], colorMedium2[2], 180),
color(colorMedium2[0], colorMedium2[1], colorMedium2[2], 40), 'Y');
}
// Draw horizontal interface line
function drawInterface() {
stroke(colorInterface[0], colorInterface[1], colorInterface[2], 200);
strokeWeight(3);
line(0, interfaceY, width, interfaceY);
// Draw refractive index labels near interface edges
noStroke();
fill(colorMedium1);
textSize(14);
textAlign(LEFT, BOTTOM);
text('n₁ = ' + n1.toFixed(2), 10, interfaceY - 6);
fill(colorMedium2);
textAlign(RIGHT, TOP);
text('n₂ = ' + n2.toFixed(2), width - 10, interfaceY + 6);
}
// Draw incident, refracted, and reflected rays with animation
function drawRays() {
push();
translate(width / 2, interfaceY);
// Incident ray start point (far left)
let incLength = rayLength;
let incAngle = -angleIncRad; // measured from normal (vertical line)
// Incident ray vector
let incVec = p5.Vector.fromAngle(incAngle - HALF_PI).mult(-incLength);
// Draw incident ray trail (fading tail)
stroke(colorRayInc[0], colorRayInc[1], colorRayInc[2], 120 * intensity);
strokeWeight(3);
line(incVec.x, incVec.y, 0, 0);
// Animate incident ray tip
let incTip = p5.Vector.lerp(incVec, createVector(0, 0), rayProgress);
stroke(colorRayInc[0], colorRayInc[1], colorRayInc[2], 255 * intensity);
strokeWeight(6);
point(incTip.x, incTip.y);
// Normal line (vertical)
stroke(255, 255, 255, 100);
strokeWeight(1);
line(0, -rayLength / 1.5, 0, rayLength / 1.5);
// If total internal reflection, draw reflected ray
if (isTIR) {
// Reflected angle = incident angle (same side)
let reflAngle = incAngle;
let reflVec = p5.Vector.fromAngle(HALF_PI - reflAngle).mult(rayLength);
// Reflected ray trail
stroke(colorRayReflec[0], colorRayReflec[1], colorRayReflec[2], 120 * intensity);
strokeWeight(3);
line(0, 0, reflVec.x, reflVec.y);
// Animate reflected ray tip
let reflTip = p5.Vector.lerp(createVector(0, 0), reflVec, rayProgress);
stroke(colorRayReflec[0], colorRayReflec[1], colorRayReflec[2], 255 * intensity);
strokeWeight(6);
point(reflTip.x, reflTip.y);
// Annotation for TIR
noStroke();
fill(255, 100, 100, 180);
textSize(16);
textAlign(CENTER, BOTTOM);
text('Total Internal Reflection', 0, rayLength / 1.8);
} else {
// Refracted ray
let refrAngle = angleRefrRad;
// Refracted ray vector (downwards, below interface)
let refrVec = p5.Vector.fromAngle(HALF_PI - refrAngle).mult(rayLength);
// Refracted ray trail
stroke(colorRayRefr[0], colorRayRefr[1], colorRayRefr[2], 120 * intensity);
strokeWeight(3);
line(0, 0, refrVec.x, refrVec.y);
// Animate refracted ray tip
let refrTip = p5.Vector.lerp(createVector(0, 0), refrVec, rayProgress);
stroke(colorRayRefr[0], colorRayRefr[1], colorRayRefr[2], 255 * intensity);
strokeWeight(6);
point(refrTip.x, refrTip.y);
}
pop();
}
// Draw minimal text info: title and key parameters
function drawTextInfo() {
noStroke();
fill(255);
textAlign(CENTER, TOP);
textSize(22);
textStyle(BOLD);
text('Light Refraction Simulation', width / 2, 10);
textSize(14);
textStyle(NORMAL);
fill(200, 220, 255);
// Top-left corner parameters
textAlign(LEFT, TOP);
let leftX = 12;
let topY = 50;
text(`Angle Incidence: ${angleIncDeg.toFixed(1)}°`, leftX, topY);
text(`Wavelength: ${wavelength} nm`, leftX, topY + 20);
text(`Density n₁: ${density1.toFixed(2)}`, leftX, topY + 40);
// Top-right corner parameters
textAlign(RIGHT, TOP);
let rightX = width - 12;
text(`Density n₂: ${density2.toFixed(2)}`, rightX, topY);
text(`Intensity: ${intensity.toFixed(2)}`, rightX, topY + 20);
text(`Speed Scale: ${speedScale.toFixed(2)}`, rightX, topY + 40);
// Bottom-left: Snell's Law calculation results
textAlign(LEFT, BOTTOM);
let bottomY = height - 12;
if (isTIR) {
fill(255, 100, 100);
text('Total Internal Reflection', leftX, bottomY);
} else {
fill(200, 220, 255);
text(`Angle Refraction: ${degrees(angleRefrRad).toFixed(2)}°`, leftX, bottomY);
}
}
// Reset simulation state
function resetSim() {
rayProgress = 0;
isPaused = false;
pauseBtn.html('Pause');
}
// Pause/play toggle
function togglePause() {
isPaused = !isPaused;
pauseBtn.html(isPaused ? 'Play' : 'Pause');
}
// Gradient fill helper (vertical or horizontal)
function setGradient(x, y, w, h, c1, c2, axis) {
noFill();
if (axis === 'Y') {
for (let i = y; i <= y + h; i++) {
let inter = map(i, y, y + h, 0, 1);
let c = lerpColor(c1, c2, inter);
stroke(c);
line(x, i, x + w, i);
}
} else if (axis === 'X') {
for (let i = x; i <= x + w; i++) {
let inter = map(i, x, x + w, 0, 1);
let c = lerpColor(c1, c2, inter);
stroke(c);
line(i, y, i, y + h);
}
}
}