Skip to main content

Overview

The Particle Simulator uses a powerful formula evaluation engine that supports mathematical expressions with variables, functions, and constants. Formulas can be used to define forces in dynamics mode or position functions in kinematics mode.

Available Variables

Your formulas have access to four key variables that represent the particle’s state:
VariableDescriptionType
tElapsed time in secondsNumber
xCurrent X-axis position of the particleNumber
yCurrent Y-axis position of the particleNumber
zCurrent Z-axis position of the particleNumber
In Kinematics mode, formulas represent position components as functions of time: f(t).In Dynamics mode, formulas represent force components that can depend on time, position, or both: F(t, x, y, z).

Mathematical Functions

All functions from JavaScript’s Math object are available in your formulas:

Trigonometric Functions

FunctionDescriptionExample
sin(n)Sine of n (radians)10 * sin(t)
cos(n)Cosine of n (radians)5 * cos(2*t)
tan(n)Tangent of n (radians)tan(t/3)
atan2(y, x)Arctangent of y/x (in radians)atan2(y, x)

Hyperbolic Functions

FunctionDescriptionExample
sinh(n)Hyperbolic sinesinh(t)
cosh(n)Hyperbolic cosinecosh(t)
tanh(n)Hyperbolic tangent20 * tanh(sin(t))

Power and Logarithmic Functions

FunctionDescriptionExample
sqrt(n)Square rootsqrt(x^2 + y^2 + z^2)
log(n)Natural logarithm (base e)log(t + 1)
log10(n)Base-10 logarithmlog10(abs(x))

Utility Functions

FunctionDescriptionExample
abs(n)Absolute valueabs(x)
floor(n)Round down to nearest integerfloor(t)
ceil(n)Round up to nearest integerceil(t)
round(n)Round to nearest integerround(t)
sign(n)Sign of number (-1, 0, or 1)sign(x)

Advanced Functions

FunctionDescriptionExample
min(a, b)Minimum of two valuesmin(x, y)
max(a, b)Maximum of two valuesmax(x, 0)
random()Random number between 0 and 1random() * 10

Mathematical Constants

These mathematical constants are available directly in your formulas:
ConstantDescriptionValue (Approx)
PIRatio of circle circumference to diameter3.14159
EBase of natural logarithms (Euler’s number)2.71828
SQRT2Square root of 21.41421

Operators

Supported mathematical operators:
OperatorDescriptionExample
+Additionx + 5
-Subtraction10 - t
*Multiplication2 * x
/Divisionx / 2
^ or **Exponentiationx^2 or x**2
Both ^ and ** work for exponentiation. The engine automatically converts ^ to ** internally.

Formula Caching Mechanism

The simulator implements an advanced caching system for optimal performance:
Movimiento.ts
const formulaCache: Record<string, Function> = {};

export const evaluarFormula = (
  formula: string,
  t: number,
  x: number = 0,
  y: number = 0,
  z: number = 0
): number => {
  try {
    if (!formula || formula.trim() === "" || formula === "0") return 0;

    const cacheKey = formula.toLowerCase().trim();
    let fn = formulaCache[cacheKey];

    if (!fn) {
      // Replace ^ with ** for exponentiation
      const cleanedFormula = cacheKey.replace(/\^/g, "**");
      
      // Create function injecting t, x, y, z AND all Math functions
      fn = new Function(
        "t", "x", "y", "z", ...mathKeys,
        `return (function() { 
          try { 
            return ${cleanedFormula}; 
          } catch(e) { return 0; } 
        })()`
      );
      formulaCache[cacheKey] = fn;
    }

    // Execute with variables and Math values
    const resultado = fn(t, x, y, z, ...mathValues);

    return typeof resultado === "number" && !isNaN(resultado) ? resultado : 0;
  } catch (e) {
    return 0;
  }
};

How It Works

  1. First Evaluation: When a formula is first encountered, it’s converted to a JavaScript function and cached
  2. Function Injection: All Math object functions and constants are automatically injected into the formula scope
  3. Subsequent Evaluations: Cached functions are reused, avoiding expensive re-parsing
  4. Case Insensitive: Formulas are normalized to lowercase for cache lookup
  5. Error Handling: Invalid formulas return 0 instead of throwing errors
This caching mechanism allows the simulator to maintain high performance even with 100+ particles running complex formulas in real-time.

Examples of Valid Formulas

Kinematics Mode Examples

In kinematics mode, define position as a function of time:
fx(t): 10 * sin(t)
fy(t): 0
fz(t): 10 * cos(t)

Dynamics Mode Examples

In dynamics mode, define forces that can depend on position and time:
Fx: -10 * x
Fy: -10 * y
Fz: -10 * z
Be careful with division by zero! Use safeguards like sqrt(x^2 + y^2 + z^2 + 0.001) to avoid singularities.

Best Practices

Performance Tips

  1. Keep formulas simple: Complex nested functions may impact performance with many particles
  2. Avoid random(): Using random() in force formulas prevents caching benefits
  3. Reuse similar formulas: The cache works best when multiple particles use identical formulas

Common Pitfalls

Always add a small epsilon when dividing by position-dependent values:
Bad
Fx: -x / sqrt(x^2 + y^2 + z^2)
Good
Fx: -x / sqrt(x^2 + y^2 + z^2 + 0.001)
Be explicit with operator precedence:
Ambiguous
Fx: 2 * x + y / z
Clear
Fx: (2 * x) + (y / z)
All trigonometric functions expect radians:
Wrong (treating as degrees)
Fx: sin(90)
Correct (convert to radians)
Fx: sin(90 * PI / 180)

Testing Your Formulas

To verify your formulas work correctly:
  1. Start with a single particle
  2. Set deltaT to a small value (0.001 - 0.01)
  3. Enable Force: INDIVIDUAL mode to visualize force vectors
  4. Enable the Trail to see the particle’s path
  5. Check the Info Panel for position and velocity values
Use the INFO panel to monitor real-time values of position (x, y, z) and velocity while testing your formulas.

Particle Editor

Learn how to add and edit forces in the editor interface

Events System

Trigger actions based on formula-driven conditions

Build docs developers (and LLMs) love