ProGen3d_js - Visual Grammar Editor

ProGen3d_js

Author: Ms Pamela G Hauff

Grammar Input

Ready.

        

        
        

        
        
      

Scene Viewer

Your browser does not support the canvas element.

Tokens & Scene

Tutorial: Visual Grammar 101 — Step 0/9 (initialising)
R R name ( min max ) — define a variable range (e.g., R len ( 0.15 0.3 )).
T T ( x y z ) — translate position in 3D space.
S S ( sx sy sz ) — scale (uniform or per-axis).
A A ( degrees axis ) — rotate by degrees around axis (0=X, 1=Y, 2=Z).
D D ( sx sy sz ) — scale cube dimensions in x/y/z.
DS DS ( sx sy sz ) — dynamic scale based on iteration variables.
I I ( Cube | CubeX | CubeY | Sphere | Cylinder … texture scale ) — instantiate primitive with texture and scale.
Rules RuleName repeat vars… -> body. Use R* for random variables. Transform stack: [ push, ] pop, | separator.
Loops R* varName ( min max ) creates iteration variable. Reference in expressions like 360/N*k.
Spacing Tokens are space-delimited. Put spaces around parentheses and brackets:
S ( 1 2 3 ) · [ Y ] / ❌ S(1 2 3) · [Y]
Examples Start 1 -> [ T ( 0 1 0 ) I ( Cube metal 0.5 ) ]
Radial -> R* N ( 8 12 ) RadialInit
RadialInit 1 N -> R* k ( 0 N/2 ) RadialCore
Textures Available: metal, wood, glass, stone, plastic, concrete, marble, and 50+ more presets.

Grammar Reader WebGLr2
Complete Class and Function Reference

Summary Statistics

Architecture Overview

The application follows a modular architecture:

  1. Lexing & Parsing Layer: GrammarLexer, Grammar, MathParser, MathTokenizer
  2. Analysis Layer: AnalysisEngine, Token, Rule, Variable
  3. Execution Layer: Context, Scope, Scene, Solution
  4. Rendering Layer: WebGLSceneRenderer, RendererManager
  5. UI Layer: EditorApplication, ConsoleManager, TutorialManager
  6. Math Layer: Mat4, Vec3, Axis, MathExpressionEvaluator
  7. Error Handling: ParseError, RuntimeGrammarError, SolutionError

Key Constants

Core Classes

WebGLSceneRenderer

Purpose: WebGL rendering engine
Key Methods:
  • constructor(canvasOrSelector, opts={}) - Initializes renderer
  • setScene(scene) - Sets scene to render
  • invalidate() - Invalidates render
  • render() - Renders scene
  • resize() - Resizes canvas
  • createAllPresetTextures() - Creates textures
  • getTexture(name) - Gets texture
  • setWireframe(on=true) - Sets wireframe mode
  • setLineColor(r=0, g=0, b=0, a=0.3) - Sets line color

Scene

Purpose: Manages 3D scene objects
Key Methods:
  • constructor() - Initializes scene
  • add(type, transform1, transform2, transform3, texIndex, arg, val, axisName = "z") - Adds object
  • clear() - Clears scene
  • getAll() - Gets all objects

Grammar

Purpose: Parses and processes grammar definitions
Key Methods:
  • constructor(fileText) - Parses grammar from text
  • MathS(input) - Processes math expressions
  • ReadTokens(rule, rule_str, sec) - Reads tokens from rule
  • Recurse(rule) - Recursively processes rule
  • findRule(name) - Finds rule by name
  • expectOp(S, op, ctx = "syntax") - Expects operator
  • isNumStr(s) - Checks if string is number

GrammarLexer

Purpose: Lexical analysis of grammar text
Key Methods:
  • constructor(text) - Initializes lexer
  • _lex() - Performs lexical analysis
  • _matchArrow(i) - Matches arrow operator
  • _matchMath(start) - Matches math expression
  • _readIdentifier(s, i, end) - Reads identifier
  • _readNumber(s, i, end) - Reads number

AnalysisEngine

Purpose: Analyzes grammar text, tokenizes, and provides diagnostics
Key Methods:
  • analyze(text, caretPos = 0) - Analyzes grammar text at caret position
  • tokenize(text) - Tokenizes grammar text
  • runDiagnostics(text, tokens) - Runs diagnostics on grammar
  • collectSymbols(text) - Collects symbols from grammar text
  • buildRuleIndex(text, tokens, ruleNames) - Builds index of grammar rules

Math & Transformation Classes

Mat4

Purpose: 4x4 transformation matrix operations
Key Methods:
  • constructor(elements = null) - Creates matrix
  • identity() - Sets to identity
  • translate(x, y, z) - Translates matrix
  • scale(x, y, z) - Scales matrix
  • rotateX(angle) - Rotates around X
  • rotateY(angle) - Rotates around Y
  • rotateZ(angle) - Rotates around Z
  • multiply(other) - Multiplies matrices
  • invert() - Inverts matrix
  • transformPoint(point) - Transforms point
  • transformDirection(direction) - Transforms direction
  • getNormalMatrix() - Gets normal matrix
  • toFloat32Array() - Converts to Float32

Vec3

Purpose: 3D vector operations
Key Methods:
  • constructor(x = 0, y = 0, z = 0) - Creates vector
  • add(other) - Adds vectors
  • sub(other) - Subtracts
  • mul(other) - Multiplies
  • div(other) - Divides
  • dot(other) - Dot product
  • cross(other) - Cross product
  • magnitude() - Gets magnitude
  • normalize() - Normalizes
  • scale(x = 1, y = 1, z = 1) - Scales
  • distanceTo(other) - Distance to
  • lerp(other, t) - Linear interpolation

Axis

Purpose: Represents a 3D axis with transformations
Key Methods:
  • constructor(kind = "z") - Creates axis (x, y, or z)
  • applyTransform(M) - Applies transformation matrix
  • toFlat32() - Converts to Float32Array

Scope

Purpose: Manages transformation scope
Key Methods:
  • constructor(other = null) - Creates scope
  • T(v) - Translate
  • S(v) - Scale
  • Rx(angleDeg) - Rotate X
  • Ry(angleDeg) - Rotate Y
  • Rz(angleDeg) - Rotate Z
  • DS(v) - Dynamic scale
  • DT(v) - Dynamic translate
  • apply(M) - Applies matrix
  • getTransform() - Gets transform
  • getTransform2() - Gets secondary transform
  • getTransform3() - Gets tertiary transform

MathExpressionEvaluator

Purpose: Evaluates mathematical expressions
Key Methods:
  • constructor(variables={}, functions={}) - Initializes evaluator

Execution & UI Classes

Context

Purpose: Manages execution context and scope stack
Key Methods:
  • constructor() - Initializes context
  • current() - Gets current context
  • push() - Pushes context
  • pop() - Pops context
  • pushScope() - Pushes new scope
  • popScope() - Pops scope
  • getCurrentScope() - Gets current scope
  • newScope() - Creates new scope

Token

Purpose: Represents a grammar token
Key Methods:
  • constructor(name, instCount=0) - Creates token
  • addArgument(v) - Adds argument
  • addInstanceType(s) - Adds instance type
  • setVarName(s) - Sets variable name
  • isRule() - Checks if rule
  • performAction(context, scene, deps = {}) - Performs action
  • print() - Prints token

Rule

Purpose: Represents a grammar rule
Key Methods:
  • constructor(name, repeat) - Creates rule
  • addToken(tok, sec) - Adds token to rule
  • print() - Prints rule

Variable

Purpose: Represents a grammar variable
Key Methods:
  • constructor(name, min, max, i) - Creates variable
  • getRandom() - Gets random value

EditorApplication

Purpose: Main editor application controller
Key Methods:
  • constructor() - Initializes application
  • initialize() - Initializes application
  • initializeUI() - Initializes UI
  • runGrammar() - Runs grammar
  • render() - Renders editor
  • setupEventListeners() - Sets up listeners
  • toggleOrbit() - Toggles orbit

ConsoleManager

Purpose: Manages console output and logging
Key Methods:
  • constructor(outputElement) - Initializes console manager
  • info(t) - Logs info message
  • warn(t) - Logs warning message
  • error(t) - Logs error message
  • renderLine(type, text) - Renders console line

Standalone Functions & Error Handling

Key Standalone Functions

Error Handling Classes

ParseError (extends Error)

Purpose: Custom error for parsing failures
Key Methods:
  • constructor(message, line = 0, col = 0, snippet = "") - Creates parse error

RuntimeGrammarError (extends Error)

Purpose: Runtime grammar execution errors
Key Methods:
  • constructor(message) - Creates runtime error

SolutionError (extends Error)

Purpose: Solution processing errors
Key Methods:
  • constructor(message, idx = -1, expr = "") - Creates solution error

Additional Classes

RendererManager

Purpose: Manages WebGL rendering
Key Methods:
  • constructor(consoleManager) - Initializes renderer
  • initialize() - Initializes renderer
  • runGrammarPipeline(text, statusCallback) - Runs grammar pipeline
  • toggleOrbit() - Toggles orbit mode
  • clear() - Clears scene

TutorialManager

Purpose: Manages tutorial system
Key Methods:
  • constructor(consoleManager) - Initializes tutorial
  • initialize(sourceElement) - Initializes tutorial
  • createDemoGrammar() - Creates demo
  • createTutorialButton() - Creates button
  • updateHeader(stepIndex, total, title, completed = false) - Updates header

Versatile Structure Archetypes

Here are versatile structure archetypes you can generate and combine, each with tunable variables and axis alignment (0 = X, 1 = Y, 2 = Z). These map well to procedural grammars like the ones we’ve been building.

Foundational Motifs

Spokes (Radial arrays)

Description: Instances radiate around a central axis at equal angular intervals.
Good for: Hubs, starbursts, antennas, petals.
Key vars: N (count), R (radius), axis, element scale.

Ring (Toroidal loop)

Description: A closed loop of instances arranged around an axis.
Good for: Wheels, collars, stadium tiers.
Key vars: N (segments), R (major radius), scale, axis.

Band (Linear sequence)

Description: A line of instances distributed along a span.
Good for: Facades, ribs, tracks.
Key vars: N (segments), span length, deformation mod, axis.

Stack (Vertical column)

Description: Repeating instances ascending along an axis.
Good for: Towers, pagodas, pillars.
Key vars: H (levels), step height, taper profile, axis.

Grid (2D lattice)

Description: N×N arrays on a plane.
Good for: Floors, facades, shelving.
Key vars: G (grid size), cell spacing, layering depth, axis orientation.

Derived / Compound Motifs

RingStack (Concentric rings)

Description: Multiple rings stacked along an axis.
Good for: Amphitheaters, turbine cages.
Key vars: rings (count), per-ring N, vertical step, scale ramp.

Spiral (Helical band)

Description: A band that winds around an axis with pitch.
Good for: Stairs, DNA-like towers, ramps.
Key vars: turns, pitch, radius ramp, axis.

Fork (Branching)

Description: Splits a band/stack into multiple offspring.
Good for: Trees, branching frames.
Key vars: depth, branching factor, divergence angle.

RadialGrid (Polar lattice)

Description: Concentric rings × radial spokes.
Good for: Plazas, solar farms.
Key vars: ring count, spokes count, ring spacing.

Ribbon (Curved band)

Description: Band sampled along a spline.
Good for: Bridges, ornament, aerodynamic skins.
Key vars: curve function, thickness, twist, tessellation.

Architectural / System Motifs

TerracedStack (Stepped setbacks)

Description: Stack with shrink factor per level.
Good for: Ziggurats, skyscrapers.
Key vars: floors, shrinkFactor, floorHeight.

FaçadeBandGrid

Description: Band/grid combo forming window rows/columns.
Good for: Buildings, wall systems.
Key vars: band N, grid G, window spacing, mullion thickness.

VaultedRing/Grid

Description: Grid with arched/ring elements.
Good for: Halls, canopies.
Key vars: span, arch height, axis.

RadialCanopy

Description: Spokes + ring stack with upward bending.
Good for: Pavilions, umbrellas.
Key vars: spokes N, rings, curvature, axis.

Fractal / Recursive Motifs

RecursiveRing

Description: Ring where each element emits a smaller ring.
Good for: Filigree, fractal frames.
Key vars: recursion depth, child scale, angle jitter.

L-system Hybrid

Description: L-system lines mapped to instances.
Good for: Trees, vines.
Key vars: axiom/rules, iterations, segment scale, axis mapping.

Symmetry & Alignment Controls

Suggested Variable Schema

Global: axis, scaleMin/max, spanMin/max, stepMin/max, randomSeed.

Example Compositions

Implementation Notes

Use the format Structure{n}{Type}{Axis}. Align axes with rotations and normalized iterators. Extend the generator with Spiral, RingStack, and RadialGrid for richer outputs.