Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

10.2 KB
Raw Blame
#!/usr/bin/env node
/**
 * forma-3d CLI — cross-platform pure-WASM headless 3D polyhedral modeling engine.
 * Supports: eval, render, draw, spec, mcp, version, --help
 */

import { readFileSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { extname } from "node:path";
import { loadForma } from "../lib/index.mjs";
import { writeBlendFromGlbBytes } from "./blend-bridge.mjs";

const VERSION = JSON.parse(
  readFileSync(new URL("../package.json", import.meta.url), "utf-8")
).version;

function printHelp() {
  process.stdout.write(
    `forma ${VERSION} (WASM) — pure-Rust headless 3D polyhedral modeling engine for AI agents\n\n` +
      `USAGE:\n` +
      `  forma-3d eval [--scene] [--out FILE] [--render PNG] [--view VIEW] [--size 512] [--draw SVG] [--unit UNIT] [--strict|--no-strict] [--critique] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n` +
      `  forma-3d lint [--unit UNIT] [--strict|--no-strict] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n` +
      `  forma-3d render [--scene] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n` +
      `  forma-3d draw [--scene] --out blueprint.svg [file|-]\n` +
      `  forma-3d spec [--dialect pipe|compact] [--topic deform|curves|uv|remesh|scene] [--gbnf]\n` +
      `  forma-3d mcp\n` +
      `  forma-3d version | --version | -V\n\n` +
      `KEY OPTIONS:\n` +
      `  --scene               Export/render/draw ALL named parts together\n` +
      `                        (default without --scene exports ONLY the last-modified part)\n` +
      `  --out, -o FILE        Export mesh (.glb, .obj, .stl, .3mf, .step, .blend)\n` +
      `  --render PNG          Render studio preview PNG (combine with --scene for full assembly)\n` +
      `  --view VIEW           Preview angle: quad|front|back|right|left|top|iso (default: quad)\n` +
      `  --size PX             Preview PNG size in pixels (default: 512)\n` +
      `  --draw SVG            Emit 3-view orthographic blueprint SVG (combine with --scene for full assembly)\n` +
      `  --unit, -u UNIT       Model unit: m|cm|mm|um|in|ft (default: m)\n` +
      `  --strict/--no-strict  Enforce watertight manifold geometry (default: --strict)\n` +
      `  --critique            Run deterministic craftsmanship lint & assembly contact checks\n` +
      `  --json                Emit machine-readable JSON observation to stdout\n\n` +
      `EXAMPLES:\n` +
      `  forma-3d eval --scene --out scene.glb --render preview.png scene.forma\n` +
      `  forma-3d spec --topic deform   # also: curves, uv, remesh, scene\n\n` +
      `EXIT CODES:\n` +
      `  0  Success\n` +
      `  1  Script, I/O, or export error\n` +
      `  2  Invalid CLI usage or flag\n` +
      `  3  Strict manifold/invariant check failed\n`
  );
}

function usageErr(msg) {
  process.stderr.write(`ERR: ${msg}\n`);
  process.exit(2);
}

function requireVal(args, i, flag, hint) {
  if (i + 1 >= args.length) {
    usageErr(`${flag} requires ${hint}`);
  }
  return args[i + 1];
}

async function readStdin() {
  const chunks = [];
  for await (const chunk of process.stdin) {
    chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  }
  return Buffer.concat(chunks).toString("utf-8");
}

async function main() {
  const args = process.argv.slice(2);
  if (args.length === 0 || args[0] === "-h" || args[0] === "--help" || args[0] === "help") {
    printHelp();
    return;
  }

  const cmd = args[0];
  if (cmd === "version" || cmd === "--version" || cmd === "-V") {
    process.stdout.write(`forma ${VERSION}\n`);
    return;
  }

  if (cmd === "mcp") {
    await import("./forma-mcp.mjs");
    return;
  }

  const engine = await loadForma();

  if (cmd === "spec") {
    let dialect = "pipe";
    let gbnf = false;
    let topic = null;
    for (let i = 1; i < args.length; i++) {
      const a = args[i];
      if (a === "--dialect" || a === "-d") {
        dialect = requireVal(args, i++, a, "value (pipe|compact)");
      } else if (a === "--topic" || a === "-t") {
        topic = requireVal(args, i++, a, "value (deform|curves|uv|remesh|scene)");
      } else if (a === "--gbnf") {
        gbnf = true;
      } else if (a.startsWith("-")) {
        usageErr(`unknown flag '${a}' for 'forma-3d spec'. Run 'forma-3d --help'.`);
      } else if (topic === null) {
        topic = a;
      } else {
        usageErr(`unexpected argument '${a}' for 'forma-3d spec'. Run 'forma-3d --help'.`);
      }
    }
    try {
      const out = topic !== null ? engine.specTopic(topic) : engine.spec({ dialect, gbnf });
      process.stdout.write(out + "\n");
      return;
    } catch (err) {
      usageErr(err instanceof Error ? err.message : String(err));
    }
  }

  if (cmd !== "eval" && cmd !== "lint" && cmd !== "render" && cmd !== "draw") {
    usageErr(`unknown subcommand '${cmd}'. Run 'forma-3d --help'.`);
  }

  const isLintCmd = cmd === "lint";
  let dialect = "pipe";
  let unit = null;
  let strict = true;
  let critique = isLintCmd;
  let includeRawBox = false;
  let asJson = false;
  let exportScene = false;
  let outPath = null;
  let renderPath = null;
  let drawPath = null;
  let renderSize = 512;
  let renderView = "quad";
  let inFile = null;

  for (let i = 1; i < args.length; i++) {
    const a = args[i];
    if (a === "--dialect" || a === "-d") {
      dialect = requireVal(args, i++, a, "value (pipe|compact)");
    } else if (a === "--unit" || a === "-u") {
      unit = requireVal(args, i++, a, "value (m|cm|mm|um|in|ft)");
    } else if (a === "--out" || a === "-o") {
      const p = requireVal(args, i++, a, "output path");
      if (cmd === "render") renderPath = p;
      else if (cmd === "draw") drawPath = p;
      else outPath = p;
    } else if (a === "--render") {
      renderPath = requireVal(args, i++, a, "PNG path");
    } else if (a === "--draw") {
      drawPath = requireVal(args, i++, a, "SVG path");
    } else if (a === "--size") {
      const raw = requireVal(args, i++, a, "positive pixel integer");
      const parsed = Number.parseInt(raw, 10);
      if (!Number.isFinite(parsed) || parsed <= 0 || String(parsed) !== raw.trim()) {
        usageErr(`invalid --size '${raw}': expected positive integer`);
      }
      renderSize = parsed;
    } else if (a === "--view") {
      renderView = requireVal(args, i++, a, "value (quad|front|back|right|left|top|iso)");
    } else if (a === "--strict") {
      strict = true;
    } else if (a === "--no-strict") {
      strict = false;
    } else if (a === "--critique") {
      critique = true;
    } else if (a === "--raw-box") {
      includeRawBox = true;
    } else if (a === "--json") {
      asJson = true;
    } else if (a === "--scene") {
      exportScene = true;
    } else if (a.startsWith("-") && a !== "-") {
      usageErr(`unknown flag '${a}'. Run 'forma-3d --help'.`);
    } else if (inFile !== null) {
      usageErr(`unexpected extra input file '${a}' (only one script file is accepted)`);
    } else {
      inFile = a;
    }
  }

  if (cmd === "render" && !renderPath) {
    usageErr("'forma-3d render' requires '--out preview.png'");
  }
  if (cmd === "draw" && !drawPath) {
    usageErr("'forma-3d draw' requires '--out blueprint.svg'");
  }

  const src = !inFile || inFile === "-" ? await readStdin() : await readFile(inFile, "utf-8");
  const session = engine.createSession();
  try {
    if (unit !== null) {
      try {
        session.setUnit(unit);
      } catch (err) {
        usageErr(err instanceof Error ? err.message : String(err));
      }
    }
    const obs = session.eval(src, { dialect, strict });

    const partCount = Object.keys(obs.parts ?? {}).length;
    const instMatch = /\binsts=(\d+)/.exec(obs.text ?? "");
    const totalObjs = partCount + (instMatch ? Number.parseInt(instMatch[1], 10) : 0);
    const wroteAny = Boolean(outPath || renderPath || drawPath);
    if (!exportScene && wroteAny && totalObjs > 1) {
      process.stderr.write(
        `NOTE: scene has ${totalObjs} objects, but exported/rendered only the last part because --scene was not set. Pass --scene to export/render all ${totalObjs} objects together.\n`
      );
    }

    if (outPath) {
      const ext = extname(outPath).replace(/^\./, "").toLowerCase();
      if (exportScene) {
        if (ext === "blend") {
          await writeBlendFromGlbBytes(session.exportSceneBytes("glb"), outPath);
        } else {
          await writeFile(outPath, session.exportSceneBytes(ext));
        }
      } else if (ext === "blend") {
        await writeBlendFromGlbBytes(session.exportBytes("glb"), outPath);
      } else {
        await writeFile(outPath, session.exportBytes(ext));
      }
    }
    if (renderPath) {
      const pngBytes = exportScene
        ? session.exportScenePngBytes(renderSize, renderView)
        : session.exportBytes("png", { size: renderSize, view: renderView });
      await writeFile(renderPath, pngBytes);
    }
    if (drawPath) {
      const svgData = exportScene ? session.exportSceneSvg() : session.exportBytes("svg");
      await writeFile(drawPath, svgData);
    }

    const lintRep = critique ? session.lint({ includeRawBox }) : null;
    if (isLintCmd) {
      if (asJson) {
        process.stdout.write(JSON.stringify(lintRep) + "\n");
      } else {
        process.stdout.write((lintRep.text ?? "") + "\n");
      }
    } else if (asJson) {
      const payload = lintRep ? { ...obs, lint: lintRep } : obs;
      process.stdout.write(JSON.stringify(payload) + "\n");
    } else {
      process.stdout.write(obs.text + "\n");
      if (lintRep && lintRep.critique_text) {
        process.stdout.write(lintRep.critique_text + "\n");
      } else if (lintRep && lintRep.issues?.length > 0 && lintRep.text) {
        process.stdout.write(lintRep.text + "\n");
      }
    }
    if (strict && !obs.ok) {
      process.exit(3);
    }
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    if (asJson) {
      process.stdout.write(JSON.stringify({ ok: false, error: msg }) + "\n");
    } else {
      process.stderr.write(`ERR: ${msg}\n`);
    }
    if (strict && msg.includes("invariant violation on '")) {
      process.exit(3);
    }
    process.exit(1);
  } finally {
    session.free();
  }
}

main().catch((err) => {
  process.stderr.write(`ERR: ${err instanceof Error ? err.message : String(err)}\n`);
  process.exit(1);
});