### Initialize Simulation System Source: https://context7.com/juniorrojas/algovivo/llms.txt Demonstrates how to load the WebAssembly backend and initialize the System class with vertex, triangle, and muscle data. It also shows how to configure core physics parameters like gravity and time steps. ```javascript import algovivo from "https://cdn.jsdelivr.net/gh/juniorrojas/algovivo@ae28f9c/build/algovivo.min.mjs"; async function loadWasm() { const response = await fetch("https://cdn.jsdelivr.net/gh/juniorrojas/algovivo@ae28f9c/build/algovivo.wasm"); const wasm = await WebAssembly.instantiateStreaming(response); return wasm.instance; } const system = new algovivo.System({ wasmInstance: await loadWasm() }); system.set({ pos: [[0, 0], [2, 0], [1, 1]], triangles: [[0, 1, 2]], muscles: [[0, 2], [1, 2]] }); system.h = 0.033; system.g = 9.8; system.k = 90; system.friction.k = 300; system.collision.k = 14000; ``` -------------------------------- ### Initialize Neural Controller in JavaScript Source: https://github.com/juniorrojas/algovivo/blob/main/README.md Demonstrates how to load mesh and policy data, initialize the Algovivo system with WASM, and run a simulation loop for a neural controller. ```html ``` -------------------------------- ### Build Project from Source Source: https://github.com/juniorrojas/algovivo/blob/main/README.md Commands to build the JavaScript library and the WebAssembly backend using Docker. ```bash npm ci npm run build ``` ```bash python codegen/codegen_csrc.py && \ docker run \ --user $(id -u):$(id -g) \ -v $(pwd):/workspace \ -w /workspace \ ghcr.io/juniorrojas/algovivo/llvm18-enzyme:latest \ ./build.sh ``` -------------------------------- ### Initialize and Run Algovivo Simulation Source: https://github.com/juniorrojas/algovivo/blob/main/README.md This snippet demonstrates how to load the Algovivo WebAssembly module, initialize the simulation system with custom geometry and muscle configurations, and run a periodic animation loop. ```html ``` -------------------------------- ### Initialize Algovivo 2D Renderer and Scene Source: https://github.com/juniorrojas/algovivo/blob/main/test/render/mm2d/browser/public/lineShader.html This snippet initializes the Algovivo renderer, sets up a camera, and creates a mesh with a custom line shader to render colored edges. It maps world coordinates to screen pixels using the camera's scale inference. ```css body { margin: 0; padding: 0; box-sizing: border-box; } ``` ```javascript import algovivo from "./algovivo.mjs"; const mm2d = algovivo.mm2d; const renderer = new mm2d.Renderer(); renderer.setSize({ width: 200, height: 200 }); document.body.appendChild(renderer.domElement); const scene = new mm2d.Scene(); const camera = new mm2d.Camera(); const mesh = scene.addMesh(); mesh.pos = [[0, 0], [1, 0], [0.5, 1]]; mesh.lines = [[0, 1], [1, 2], [2, 0]]; mesh.lineShader = { renderLine(args) { const { ctx, camera, id, a, b } = args; const scale = camera.inferScale(); const worldLineWidth = 0.02; const screenLineWidth = worldLineWidth * scale; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.strokeStyle = ["red", "green", "blue"][id]; ctx.lineWidth = screenLineWidth; ctx.stroke(); } }; camera.center({ worldCenter: [0.5, 0.5], worldWidth: 2, viewportWidth: renderer.width, viewportHeight: renderer.height }); renderer.render(scene, camera); window.mm2dReady = true; ``` -------------------------------- ### Run Algovivo Simulation with Neural Control in HTML Source: https://context7.com/juniorrojas/algovivo/llms.txt This HTML code sets up a complete simulation environment using algovivo. It loads the WebAssembly module, fetches mesh and policy data, creates a physics system and a neural controller, initializes a viewport for rendering, and runs a simulation loop that updates the policy, physics, and renders the scene at 30 FPS. It also logs the creature's horizontal position periodically. ```html

algovivo - Soft Body Locomotion

``` -------------------------------- ### Initialize and Render 2D Scene with Algovivo Source: https://github.com/juniorrojas/algovivo/blob/main/test/render/mm2d/browser/public/minimalSceneCameraRenderer.html This snippet initializes the Algovivo renderer, sets up a scene, creates a triangular mesh, and renders it to the document body. It requires the algovivo.mjs module and assumes a browser environment. ```javascript import algovivo from "./algovivo.mjs"; const mm2d = algovivo.mm2d; const renderer = new mm2d.Renderer(); renderer.setSize({ width: 200, height: 200 }); document.body.appendChild(renderer.domElement); const scene = new mm2d.Scene(); const camera = new mm2d.Camera(); const mesh = scene.addMesh(); mesh.pos = [[0, 0], [1, 0.3], [0.5, 1.0]]; mesh.triangles = [[0, 1, 2]]; camera.center({ worldCenter: mesh.computeCenter(), worldWidth: 2, viewportWidth: renderer.width, viewportHeight: renderer.height }); renderer.render(scene, camera); window.mm2dReady = true; ``` ```css body { margin: 0; padding: 0; box-sizing: border-box; } ``` -------------------------------- ### Initialize and Render 2D Scene with Algovivo Source: https://github.com/juniorrojas/algovivo/blob/main/test/render/mm2d/browser/public/pointShader.html This snippet initializes the algovivo 2D renderer, sets its size, appends it to the document body, and sets up a basic scene with a camera and a mesh. It also defines a custom point shader for rendering mesh vertices and configures the camera's view before rendering the scene. ```javascript import algovivo from "./algovivo.mjs"; const mm2d = algovivo.mm2d; const renderer = new mm2d.Renderer(); renderer.setSize({ width: 200, height: 200 }); document.body.appendChild(renderer.domElement); const scene = new mm2d.Scene(); const camera = new mm2d.Camera(); const mesh = scene.addMesh(); mesh.pos = [ [0, 0], [1, 0], [0.5, 1] ]; // a point mesh.pointShader = { renderPoint(args) { const { ctx, camera, id, p } = args; const scale = camera.inferScale(); const worldRadius = 0.05; const screenRadius = worldRadius * scale; ctx.beginPath(); ctx.arc(p[0], p[1], screenRadius, 0, 2 * Math.PI); ctx.fillStyle = ["red", "green", "blue"][id]; ctx.fill(); } }; camera.center({ worldCenter: [0.5, 0.5], worldWidth: 2, viewportWidth: renderer.width, viewportHeight: renderer.height }); renderer.render(scene, camera); window.mm2dReady = true; ``` -------------------------------- ### Execute Simulation Step Source: https://context7.com/juniorrojas/algovivo/llms.txt Shows how to advance the physics simulation using the step() method within a loop. This updates vertex positions and velocities based on the configured energy functions. ```javascript let simulationTime = 0; const dt = system.h; function simulate() { system.step(); simulationTime += dt; const newPositions = system.pos.toArray(); console.log(`Time: ${simulationTime.toFixed(3)}s`); } setInterval(simulate, 1000 / 30); ``` -------------------------------- ### Configure Muscles in Algovivo Source: https://context7.com/juniorrojas/algovivo/llms.txt Demonstrates how to define muscle connections between vertices, set rest lengths, adjust stiffness, and manage activation levels within the system. ```javascript const muscles = system.muscles; system.setMuscles({ indices: [[0, 2], [1, 2], [0, 1]], l0: [0.5, 0.5, 2.0], k: 100 }); console.log(`Number of muscles: ${muscles.numMuscles}`); system.k = 120; system.a.set([0.5, 0.8, 1.0]); system.a.fill_(0.7); ``` -------------------------------- ### SystemViewport: WebGL Visualization Source: https://context7.com/juniorrojas/algovivo/llms.txt Initializes and renders a WebGL-based simulation viewport with interactive features. It allows customization of visual styles, camera control, and programmatic manipulation of simulation elements. Dependencies include the algovivo library and a system object. ```javascript const viewport = new algovivo.SystemViewport({ system: system, width: 600, height: 400, fillColor: "white", borderColor: "black", backgroundColor: "#f0f0f0", activeMuscleColor: [255, 0, 0], inactiveMuscleColor: [250, 190, 190], gridColor: "#acadad", draggable: true, renderVertexIds: false, sortedVertexIds: meshData.sorted_vertex_ids, vertexDepths: meshData.depth }); document.body.appendChild(viewport.domElement); function renderLoop() { viewport.render(); requestAnimationFrame(renderLoop); } renderLoop(); viewport.setVertexPos(0, [1.5, 0.5]); viewport.fixVertex(2); viewport.freeVertex(); viewport.setSize({ width: 800, height: 600 }); const camera = viewport.camera; ``` -------------------------------- ### Define Mesh Elements with Triangles Source: https://context7.com/juniorrojas/algovivo/llms.txt Shows how to initialize triangular mesh elements for soft body structures and access material parameters like shear modulus and Lamé's parameters. ```javascript const triangles = system.triangles; system.setTriangles({ indices: [[0, 1, 2], [1, 3, 2]] }); console.log(`Number of triangles: ${triangles.numTriangles}`); const mu = triangles.mu.toArray(); const lambda = triangles.lambda.toArray(); ``` -------------------------------- ### Perform Tensor Operations and Neural Networks Source: https://context7.com/juniorrojas/algovivo/llms.txt Illustrates the use of the mmgrten module for tensor manipulation, including creation, element-wise operations, and building neural network layers. ```javascript const ten = system.ten; const a = ten.tensor([[1, 2], [3, 4]]); a.fill_(5); a.clamp_({ min: 0, max: 1 }); const nn = ten.nn; const model = nn.Sequential(nn.Linear(8, 32), nn.ReLU(), nn.Linear(32, 4), nn.Tanh()); const output = model.forward(ten.tensor([1, 2, 3, 4, 5, 6, 7, 8])); a.dispose(); model.dispose(); ``` -------------------------------- ### Global CSS Reset and Styling Source: https://github.com/juniorrojas/algovivo/blob/main/demo/public/index.html Defines the base styles for the application, including margin resets, box-sizing, and typography. It also provides specific classes for code block styling with distinct color themes. ```css * { margin: 0; padding: 0; box-sizing: border-box; font-family: "Palanquin"; font-size: 18px; } html, body { width: 100%; } p { margin-bottom: 10px; margin-top: 10px; } .code { border: 1px solid rgb(176, 176, 176); background-color: rgb(42 42 42); border-radius: 5px; padding: 3px; font-family: monospace; white-space: nowrap; } .code2 { border: 1px solid rgb(176, 176, 176); background-color: rgb(237 237 237); border-radius: 5px; padding: 3px; font-family: monospace; white-space: nowrap; } ``` -------------------------------- ### MLPPolicy: Neural Network Controller Source: https://context7.com/juniorrojas/algovivo/llms.txt Implements a multi-layer perceptron policy for autonomous locomotion using proprioceptive inputs to output muscle control signals. It requires loading mesh and policy data, initializing a simulation system, and then stepping through the policy and system updates. Dependencies include fetch API, Wasm loading, and the algovivo library. ```javascript const meshData = await (await fetch("mesh.json")).json(); const policyData = await (await fetch("policy.json")).json(); const system = new algovivo.System({ wasmInstance: await loadWasm() }); system.set(meshData); const policy = new algovivo.nn.MLPPolicy({ system: system, active: true, stochastic: false, stdDev: 0.05 }); policy.loadData(policyData); setInterval(() => { policy.step(); system.step(); viewport.render(); }, 1000 / 30); const policyDataFormat = { fc1: { weight: [[...], [...]], bias: [...] }, fc2: { weight: [[...], [...]], bias: [...] }, min_a: 0.25, max_abs_da: 0.3, center_vertex_id: 27, forward_vertex_id: 11 }; ``` -------------------------------- ### POST /system/muscles Source: https://context7.com/juniorrojas/algovivo/llms.txt Configures muscle connections between vertices, allowing for the definition of rest lengths, stiffness, and activation states. ```APIDOC ## POST /system/muscles ### Description Configures muscle connections between vertices in the physics system. ### Method POST ### Endpoint /system/setMuscles ### Parameters #### Request Body - **indices** (Array>) - Required - List of vertex pairs representing muscle connections. - **l0** (Array) - Optional - Rest lengths for each muscle. - **k** (number) - Optional - Global stiffness coefficient for muscles. ### Request Example { "indices": [[0, 2], [1, 2]], "l0": [0.5, 0.5], "k": 100 } ### Response #### Success Response (200) - **status** (string) - Confirmation of muscle configuration update. ``` -------------------------------- ### Control Muscle Activation Source: https://context7.com/juniorrojas/algovivo/llms.txt Explains how to manipulate muscle contraction levels using the system.a tensor. Values range from 0 to 1, allowing for dynamic locomotion behaviors. ```javascript system.a.set([0.3, 1.0]); let t = 0; setInterval(() => { const activation1 = 0.2 + 0.8 * (Math.cos(t * 0.1) * 0.5 + 0.5); const activation2 = 0.2 + 0.8 * (Math.sin(t * 0.1) * 0.5 + 0.5); system.a.set([activation1, activation2]); t++; system.step(); }, 1000 / 30); ``` -------------------------------- ### Dynamic Module Script Loader Source: https://github.com/juniorrojas/algovivo/blob/main/demo/public/index.html An IIFE that dynamically injects the main application module into the DOM. It appends a timestamp query parameter to the script source to prevent browser caching. ```javascript (function() { const script = document.createElement("script"); const now = new Date(); const nstr = now.getTime().toString(); script.type = "module"; script.src = `main.build.js?t=${nstr}`; document.body.appendChild(script); })(); ``` -------------------------------- ### POST /system/tensor/nn Source: https://context7.com/juniorrojas/algovivo/llms.txt Performs neural network operations using the underlying WebAssembly-backed tensor engine. ```APIDOC ## POST /system/tensor/nn ### Description Executes a forward pass through a defined neural network model. ### Method POST ### Endpoint /system/ten/nn/forward ### Parameters #### Request Body - **input** (Array) - Required - Input tensor data for the model. ### Request Example { "input": [1, 2, 3, 4, 5, 6, 7, 8] } ### Response #### Success Response (200) - **output** (Array) - The resulting tensor output from the model forward pass. ``` -------------------------------- ### Vertices: Vertex Management Source: https://context7.com/juniorrojas/algovivo/llms.txt Manages vertex positions, velocities, and constraints within the simulation system. Provides methods to access, set, add, and manipulate individual vertex states, including fixing vertices in place. It interacts with the `System` object's vertices property. ```javascript const vertices = system.vertices; console.log(`Number of vertices: ${vertices.numVertices}`); const pos = vertices.pos.toArray(); const vel = vertices.vel.toArray(); vertices.setVertexPos(0, [1.0, 2.0]); const v0pos = vertices.getVertexPos(0); vertices.addVertex({ pos: [3.0, 1.0], vel: [0.0, 0.0] }); vertices.fixVertex(0); console.log(`Fixed vertex ID: ${vertices.fixedVertexId}`); vertices.freeVertex(); console.log(`Fixed vertex ID: ${vertices.fixedVertexId}`); system.vertices.vertexMass = 6.0; ``` -------------------------------- ### POST /system/triangles Source: https://context7.com/juniorrojas/algovivo/llms.txt Defines the triangular mesh elements for the soft body, utilizing neo-Hookean elasticity parameters. ```APIDOC ## POST /system/triangles ### Description Sets the triangular mesh structure for the soft body simulation. ### Method POST ### Endpoint /system/setTriangles ### Parameters #### Request Body - **indices** (Array>) - Required - List of vertex triplets forming triangles. ### Request Example { "indices": [[0, 1, 2], [1, 3, 2]] } ### Response #### Success Response (200) - **status** (string) - Confirmation of mesh element update. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.