### Engine Initialization and Setup Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/engine.html Demonstrates how to initialize the Kiri:Moto engine, load a model from a URL, and configure device settings. ```APIDOC ## Kiri:Moto Engine API ### Description This section covers the core functionalities of the Kiri:Moto Javascript Engine, including loading models, setting engine modes, and configuring device parameters. ### Load Model #### Endpoint `load(url)` #### Description Loads a 3D model (e.g., STL) from a given URL. #### Parameters - **url** (string) - Required - The URL pointing to the 3D model file. ### Parse Model #### Endpoint `parse(data)` #### Description Parses 3D model data directly from a string or binary buffer. #### Parameters - **data** (string | ArrayBuffer) - Required - The 3D model data. ### Set Engine Mode #### Endpoint `setMode(mode)` #### Description Sets the operational mode of the engine (e.g., FDM, CAM, LASER). #### Parameters - **mode** (string) - Required - The desired engine mode. Supported modes: 'FDM', 'CAM', 'LASER', 'SLA' (untested). ### Set Device Configuration #### Endpoint `setDevice(options)` #### Description Configures device-specific parameters for G-code generation. #### Parameters - **options** (object) - Required - An object containing device settings. - **mode** (string) - Optional - The device mode (e.g., 'LASER'). - **internal** (number) - Optional - Internal device parameter. - **bedHeight** (number) - Optional - Height of the build bed. - **bedWidth** (number) - Optional - Width of the build bed. - **bedDepth** (number) - Optional - Depth of the build bed. - **maxHeight** (number) - Optional - Maximum build height. - **gcodePre** (array) - Optional - G-code commands to execute before printing. - **gcodePost** (array) - Optional - G-code commands to execute after printing. - **gcodeFExt** (string) - Optional - File extension for G-code output. - **gcodeSpace** (boolean) - Optional - Whether to use spaces in G-code. - **gcodeLaserOn** (array) - Optional - G-code commands for laser ON. - **gcodeLaserOff** (array) - Optional - G-code commands for laser OFF. - **new** (boolean) - Optional - Flag for new device configuration. - **deviceName** (string) - Optional - Name of the device. - **imageURL** (string) - Optional - URL of a device image. - **laserMaxPower** (number) - Optional - Maximum laser power. - **bedBelt** (boolean) - Optional - Whether the bed uses a belt system. - **bedRound** (boolean) - Optional - Whether the bed is round. - **originCenter** (boolean) - Optional - Whether the origin is at the center. - **fwRetract** (boolean) - Optional - Firmware retraction setting. ### Set Process Configuration #### Endpoint `setProcess(options)` #### Description Configures process-specific parameters for slicing and path generation. #### Parameters - **options** (object) - Required - An object containing process settings. ### Set Stock Dimensions #### Endpoint `setStock(options)` #### Description Sets the stock dimensions, particularly relevant for CAM mode. #### Parameters - **options** (object) - Required - An object containing stock dimensions. ### Set Available Tools #### Endpoint `setTools(tools)` #### Description Defines the available tools for CAM operations. #### Parameters - **tools** (array) - Required - An array of tool configurations. ### Move Object Origin #### Endpoint `moveTo(x, y, z)` #### Description Sets the absolute origin of the loaded object in 3D space. #### Parameters - **x** (number) - Required - The X-coordinate for the new origin. - **y** (number) - Required - The Y-coordinate for the new origin. - **z** (number) - Required - The Z-coordinate for the new origin. ### Relative Move Origin #### Endpoint `move(x, y, z)` #### Description Applies a relative move to the origin of the loaded object. #### Parameters - **x** (number) - Required - The relative X-axis movement. - **y** (number) - Required - The relative Y-axis movement. - **z** (number) - Required - The relative Z-axis movement. ### Scale Object Axes #### Endpoint `scale(x, y, z)` #### Description Scales the loaded object along the X, Y, and Z axes. #### Parameters - **x** (number) - Required - The scaling factor for the X-axis. - **y** (number) - Required - The scaling factor for the Y-axis. - **z** (number) - Required - The scaling factor for the Z-axis. ### Rotate Object Axes #### Endpoint `rotate(x, y, z)` #### Description Rotates the loaded object around the X, Y, and Z axes (in radians). #### Parameters - **x** (number) - Required - The rotation angle in radians for the X-axis. - **y** (number) - Required - The rotation angle in radians for the Y-axis. - **z** (number) - Required - The rotation angle in radians for the Z-axis. ### Slice Model #### Endpoint `slice()` #### Description Asynchronously slices the loaded 3D model into layers. ### Prepare Sliced Data #### Endpoint `prepare()` #### Description Asynchronously routes the paths for the sliced data, preparing it for G-code generation. ### Generate G-code #### Endpoint `export()` #### Description Asynchronously generates G-code from the prepared sliced data. ### Set Progress Listener #### Endpoint `setListener(fn)` #### Description Sets a callback function to receive progress messages from the engine. #### Parameters - **fn** (function) - Required - The callback function to handle progress updates. ``` -------------------------------- ### Run Grid Apps Documentation Locally (NPM) Source: https://github.com/gridspace/grid-apps/blob/master/contributing.md Instructions for running the Grid Apps documentation locally using Node.js and npm. Requires Node.js installation and cloning the repository. ```bash npm run setup npm run docs-dev ``` -------------------------------- ### Test Locally with Docker Compose Source: https://github.com/gridspace/grid-apps/blob/master/readme.md Steps to clone the repository, set up Node.js dependencies, and start the application using Docker Compose. This method is suitable for Linux/Mac developers. ```shell git clone git@github.com:GridSpace/grid-apps.git cd grid-apps npm run setup docker-compose -f src/dock/compose.yml up ``` -------------------------------- ### Run Linux x86 Desktop Binary Source: https://github.com/gridspace/grid-apps/blob/master/readme.md Commands to install Fuse, make the AppImage executable, and run the KiriMoto desktop application on Linux x86. Requires root privileges for Fuse installation. ```shell sudo apt -y install fuse chmod 755 KiriMoto-linux-x86_64.AppImage ./KiriMoto-linux-x86_64.AppImage --no-sandbox ``` -------------------------------- ### Test Locally with NodeJS Source: https://github.com/gridspace/grid-apps/blob/master/readme.md Commands for developers to clone the repository, install Node.js dependencies, and run the application in development mode using npm. ```shell git clone git@github.com:GridSpace/grid-apps.git cd grid-apps npm run setup npm run dev ``` -------------------------------- ### Build and Run Docusaurus Docs Locally Source: https://github.com/gridspace/grid-apps/blob/master/readme.md Instructions for cloning the repository, setting up dependencies, and running the Docusaurus documentation development server locally. Assumes Node.js and npm are installed. ```shell git clone git@github.com:GridSpace/grid-apps.git cd grid-apps npm run setup npm run docs-dev ``` -------------------------------- ### Run Grid Apps Locally (NPM) Source: https://github.com/gridspace/grid-apps/blob/master/contributing.md Instructions for running the Grid Apps project locally using Node.js and npm. Requires Node.js installation and cloning the repository. ```bash npm run setup npm run dev ``` -------------------------------- ### Create and Localize Language File (JavaScript) Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/localization.md Demonstrates the process of creating a new language file by copying the English default and replacing its content with localized values. This is the primary step for adding a new language to Kiri:Moto. ```javascript function createAndLocalizeLanguageFile() { // 1. Copy the default English language file (e.g., web/kiri/lang/en.js) // 2. Rename the copied file to your new language code (e.g., web/kiri/lang/fr.js) // 3. Replace all string values in the new file with the localized content for the target language. // Example of a structure within the file: // { // "app": { // "title": "Kiri:Moto" // }, // "menu": { // "file": "File", // "edit": "Edit" // } // } } ``` -------------------------------- ### Kiri:Moto Engine Initialization and Laser Setup Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/engine.html Initializes the Kiri:Moto engine, configures it for LASER mode with specific device parameters like bed dimensions, laser power, and G-code extensions, and then proceeds to slice, prepare, and export the model. ```javascript onload = async () => { const eng = await KiriEngine.init({ workerPath: "/gridspace/grid-apps/", onLog: console.log, onProgress: console.log, onStatus: console.log, onWarn: console.warn, onError: console.error, onUpdate: console.log, setReady: () => {}, outShaper: false }); eng.setDevice({ mode: "LASER", internal: 0, bedHeight: 2.5, bedWidth: 600, bedDepth: 308, maxHeight: 150, gcodePre: [], gcodePost: [], gcodeFExt: "svg", gcodeSpace: true, gcodeLaserOn: [], gcodeLaserOff: [], new: false, deviceName: "Xtool.P2", imageURL: "", laserMaxPower: 255, bedBelt: false, bedRound: false, originCenter: false, fwRetract: false }).then(eng => eng.slice()) .then(eng => eng.prepare()) .then(eng => eng.export()) .then(display_gcode); } ``` -------------------------------- ### Test Localized Language (URL Parameter) Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/localization.md Shows how to test a newly added language by appending a specific query parameter to the application's URL. This allows developers to preview their localization changes before submitting them. ```url http://localhost:8080/app?ln:XX // Replace 'XX' with the two-letter or compound language-country code (e.g., 'fr' or 'en-us') without the .js extension. ``` -------------------------------- ### Initialize and Configure Kiri:Moto Engine for Laser Cutting Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/engine.html Shows the initialization and configuration of the Kiri:Moto engine for laser cutting. This example includes loading a model, setting the operation mode to LASER, defining stock dimensions, and specifying process parameters relevant to laser operations such as kerf, power, and speed. ```javascript new Engine() .setListener(display_message) .load("/obj/cube.stl") // should to call widget.setTopZ here ideally .then(eng => eng.setMode("LASER")) .then(eng => eng.setStock({ x: 25, y: 25, z: 24.999998092651367, center: { x: 0, y: 0, z: 12.499999046325684 } })) .then(eng => eng.setProcess({ processName: "default", ctSliceKerf: 0.1, ctSliceHeight: 0.5, ctSliceHeightMin: 0, ctSliceSingle: false, ctOutTileSpacing: 1, ctOutPower: 100, ctOutSpeed: 1000, ctOutGroup: true, ctOutZColor: false, ctOutLayer: false, ctOutMark: false, ctOutStack: false, ctOutMerged: false, ctOriginCenter: false, ctOriginBounds: false, outputInvertX: false, outputInvertY: false, ctOutKnifeDepth: 1, ctOutKnifePasses: 1, ctOutKnifeTip: 2, ctOutInches: false, ct ``` -------------------------------- ### Initialize and Configure Kiri:Moto Engine for FDM Printing Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/engine.html Demonstrates the basic setup for Kiri:Moto's FDM (Fused Deposition Modeling) engine. It includes loading an STL file, setting processing parameters, defining device-specific G-code commands (pre and post), and initiating the slicing process. ```javascript new Engine() .setListener(display_message) .load("/obj/cube.stl") .then(eng => eng.setProcess({ // empty })) .then(eng => eng.setDevice({ gcodePre: [ "M82", "M104 S220" ], gcodePost: [ "M107" ] })) .then(eng => eng.slice()) .then(eng => eng.prepare()) .then(eng => eng.export()) .then(display_gcode); ``` -------------------------------- ### Browser-Side Module Execution Log Source: https://github.com/gridspace/grid-apps/blob/master/sample/readme.md This snippet displays the console log messages that appear in Kiri:Moto when a newly loaded server-side module injects its code into the browser. It shows the start and completion of the main and worker modules. ```javascript --- kiri main module start --- --- kiri main module started --- {server_said: 'received 39 bytes'} --- kiri worker module start --- --- kiri worker module started --- ``` -------------------------------- ### Managing Slicing Controller with Engine API Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/engine-apis.md Illustrates setting the slicing controller, which manages the worker pool for slicing operations. This method enables starting or stopping the processing pipeline as needed. ```javascript const engine = new Engine(); const controllerSettings = { poolSize: 4 }; // Set slicing controller engine.setController(controllerSettings); ``` -------------------------------- ### Get Kiri Settings Key Source: https://github.com/gridspace/grid-apps/wiki/Profile-Persistence Pressing the uppercase 'U' key in Kiri generates a unique settings key, updating the browser's URL to reflect this key. This key can be used to restore the settings later. ```User Action Press 'U' (uppercase) ``` -------------------------------- ### Rewriting Comments to Parentheses in GCode Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/gcode-macros.md Enables the conversion of standard GCode comments (starting with ';') into a parenthesis format, useful for compatibility or specific processing needs. Introduced in v3.8. ```gcode ;; COMMENT_REWRITE_PARENS ``` -------------------------------- ### JavaScript Timer Class for Performance Measurement Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/gyroid-test.html The Timer class records elapsed time for different operations. It can 'start' a timer, 'mark' specific points with labels, and provide a string representation of the recorded times. This is useful for profiling JavaScript code. ```javascript class Timer { constructor() { this.time = 0; this.times = {}; this.order = []; this.start(); } start() { this.time = Date.now(); } mark(label) { let newtime = Date.now(); let oldval = this.times[label] || 0; if (oldval === 0) { this.order.push(label); } this.times[label] = oldval + (newtime - this.time); this.time = newtime; } toString() { return this.order.map(l => `${l}:${this.times[l]}`); } } ``` -------------------------------- ### Chain Sparse Points into Polygons (JavaScript) Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/gyroid-test.html Joins sparse points into polygons by iteratively finding the closest unclaimed point to the end of the current chain. This process is guided by a prevailing direction to improve chaining efficiency and handles cases with no peers. ```javascript let polys = []; let chain; let added; let cleared = 0; do { for (let i=0; i maxdist) { break; } sparse[cl_idx] = null; cleared++; chain.push(cl_elm); added = true; } } while (added); } while (cleared < sparse.length); timer.mark('chain'); ``` -------------------------------- ### Kiri:Moto CLI Help and Options Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/apis.md Displays the help information and available options for the Kiri:Moto command-line interface. It outlines parameters for logging, file paths, model loading, source files, device/process/controller definitions, output, and transformations. ```bash node src/kiri-run/cli --help cli --verbose | enable verbose logging --dir=[dir] | root directory for file paths (default: '.') --model=[file] | model file to load (or last parameter) --source=[file] | source file list (defaults to kiri engine) --device=[file] | device definition file (json) --process=[file] | process definition file (json) --controller=[file] | controller definition file (json) --output=[file] | gcode output to file or '-' for stdout --position=x,y,z | move loaded model to position x,y,z --rotate=x,y,z | rotate loaded model x,y,z radians --scale=x,y,z | scale loaded model in x,y,z --move=x,y,z | move loaded model x,y,z millimeters ``` -------------------------------- ### Test Locally with Electron Source: https://github.com/gridspace/grid-apps/blob/master/readme.md Instructions for developers to clone the repository, set up Node.js dependencies, and launch the application using Electron for local testing. ```shell git clone git@github.com:GridSpace/grid-apps.git cd grid-apps npm run setup npm run start ``` -------------------------------- ### Executing Slicing and Preparation with Engine API Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/engine-apis.md Shows how to initiate the slicing process and then prepare the generated toolpaths for export. Both operations return Promises that resolve when their respective stages are complete. ```javascript const engine = new Engine(); // Assume model is loaded and configured // Start slicing process engine.slice().then(engine => { console.log('Slicing complete.'); // Prepare toolpaths after slicing return engine.prepare(); }).then(engine => { console.log('Toolpath preparation complete.'); }); ``` -------------------------------- ### Deploy Kiri:Moto on TrueNAS via YAML Source: https://github.com/gridspace/grid-apps/blob/master/readme.md A YAML configuration snippet for deploying Kiri:Moto as a service on TrueNAS. It specifies the build context from a Git repository and maps a port for access. ```yaml services: kirimoto: build: context: https://github.com/GridSpace/grid-apps.git#refs/tags/latest dockerfile: ./src/dock/Dockerfile ports: - "8080:8080" ``` -------------------------------- ### Server-Side Module Loading Log Source: https://github.com/gridspace/grid-apps/blob/master/sample/readme.md This snippet shows the expected log output from the gs-app-server when a server-side module is loaded. It indicates the path to the module's initialization file and a confirmation message. ```log 220128.120432 '[head]' { module: './mod/sample/init.js' } 220128.120432 '[head]' '--- sample server-side module loaded ---' ``` -------------------------------- ### JavaScript Map Class for Typed Array Data Storage Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/gyroid-test.html The Map class provides a way to store 2D data using typed arrays (Float32Array, Int32Array, Uint8Array). It allows getting and putting values at specific (x, y) coordinates and handles the conversion to a flat array index. ```javascript class Map { constructor(x,y,type) { this.x = x; this.y = y; switch (type) { case 'f': this.map = new Float32Array(x*y); break; case 'i': this.map = new Int32Array(x*y); break; case 'c': this.map = new Uint8Array(x*y); break; default: throw `invalid type: ${type}`; } } pos(x,y) { return x+y*this.x; } get(x,y) { return this.map[x+y*this.x]; } put(x,y,v) { this.map[x+y*this.x] = v; } } ``` -------------------------------- ### JavaScript Grid Class for Spatial Data Management Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/gyroid-test.html The Grid class manages a 2D array of data, dividing a larger area into smaller cells based on a given size and divisor. It provides methods to get cell data, access internal grid elements, and find neighboring cells. ```javascript class Grid { constructor(size,div) { this.size = (size/div)|0; this.div = div; this.grid = new Array(div * div); } get(x,y) { x = (x/this.div)|0; y = (y/this.div)|0; let pos = x + y * this.size; let rec = this.grid[pos]; if (rec) return rec; return this.grid[pos] = []; } _get(x,y) { if (x < 0 || y < 0 || x > this.size || y > this.size) { return undefined; } return this.grid[x + y * this.size]; } peers(x,y) { let grid = this.grid; let r = this.x; // console.log('peers',x,y) x = (x/this.div)|0; y = (y/this.div)|0; let peers = [], p; p = this._get(x,y); if (p) peers.push(p); p = this._get(x-1,y); if (p) peers.push(p); p = this._get(x+1,y); if (p) peers.push(p); p = this._get(x,y-1); if (p) peers.push(p); p = this._get(x,y+1); if (p) peers.push(p); p = this._get(x+1,y+1); if (p) peers.push(p); p = this._get(x-1,y+1); if (p) peers.push(p); p = this._get(x+1,y-1); if (p) peers.push(p); p = this._get(x-1,y-1); if (p) peers.push(p); // console.log('---',x,y,peers,this.x,this.y) return peers; } density() { let size = this.size; for (let y=0; y v ? (v.length).toString().padStart(2,'0') : '..').join(' ')); } } } ``` -------------------------------- ### Load Shared Settings via URL Hash Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/shared-profiles.md Demonstrates how to load Kiri:Moto settings by appending a unique settings key to the application's URL. This allows users to share or load a specific configuration directly. ```URL https://grid.space/kiri/#setting/ver ``` -------------------------------- ### Command Line API Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/apis.md Utilize the Kiri:Moto slicer engine as a command-line utility for automated or batch processing of models. ```APIDOC ## Command Line API ### Description The Kiri:Moto slicer engine can be operated directly from the command line. This allows for flexible integration into scripting and automated workflows. ### Method `node src/kiri-run/cli ` ### Parameters #### Path Parameters - **file** (string) - Required - The model file to load, or the last parameter if not specified with `--model`. #### Query Parameters - **--verbose** - Enable verbose logging. - **--dir=[dir]** (string) - Set the root directory for file paths. Defaults to the current directory (`.`). - **--model=[file]** (string) - Specify the model file to load. - **--source=[file]** (string) - Specify source files, defaults to the Kiri engine. - **--device=[file]** (string) - Path to a JSON file defining device settings. - **--process=[file]** (string) - Path to a JSON file defining process settings. - **--controller=[file]** (string) - Path to a JSON file defining controller settings. - **--output=[file]** (string) - Specify the output file for G-code. Use `'-'` for stdout. - **--position=x,y,z** (string) - Move the loaded model to the specified X,Y,Z coordinates. - **--rotate=x,y,z** (string) - Rotate the loaded model by X,Y,Z radians. - **--scale=x,y,z** (string) - Scale the loaded model along the X,Y,Z axes. - **--move=x,y,z** (string) - Move the loaded model by X,Y,Z millimeters. ### Request Example ```bash node src/kiri-run/cli --device=kiri-fdm-device.json --process=kiri-fdm-process.json my_model.stl --output=output.gcode ``` ### Further Information - Example [Device](https://github.com/GridSpace/grid-apps/blob/master/src/cli/kiri-fdm-device.json) and [Process](https://github.com/GridSpace/grid-apps/blob/master/src/cli/kiri-fdm-process.json) settings. - JSON dictionaries for reference are available in the [CLI package](https://github.com/GridSpace/grid-apps/tree/master/src/cli). ``` -------------------------------- ### File Drop and Data Loading (JavaScript) Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/cxdlp.html Handles file drop events, reads the dropped file as an array buffer, and initializes a CXDLP object with the file data. It sets up UI elements like sliders based on the loaded data and triggers initial rendering and metadata display. ```javascript function onload() { document.addEventListener("drop", (ev) => { document.body.classList.remove("over"); let files = ev.dataTransfer.files; let reader = new FileReader(); reader.onloadend = (e) => { let cxdlp = window.cxdlp = new CXDLP(); cxdlp.read(new DataView(e.target.result), 0); slider.max = layers.value = cxdlp.layers.length - 1; render(slider.value = layer.value = 0); meta(cxdlp); }; reader.readAsArrayBuffer(files[0]); ev.stopPropagation(); ev.preventDefault(); }, false); document.addEventListener("dragover", (ev) => { ev.stopPropagation(); ev.preventDefault(); document.body.classList.add("over"); }, false); document.addEventListener("dragleave", (ev) => { ev.stopPropagation(); ev.preventDefault(); document.body.classList.remove("over"); }, false); slider.oninput = slider.onchange = () => { render(layer.value = slider.value); }; layer.onchange = () => { render(slider.value = layer.value); }; } window.addEventListener("DOMContentLoaded", onload); ``` -------------------------------- ### Kiri:Moto Frame Message API Initialization and Event Handling Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/frame.html Initializes the Kiri:Moto frame, sets up an Ace editor for code input, loads default or saved code, and defines a message handler to display received messages. This snippet demonstrates setting up the API's core components and message reception. ```javascript let defc = [ "let api = kiri.frame;", "api.setMode('FDM');", "api.clear();", "api.load('/obj/cube.stl');", "api.on('loaded', () => {", " api.slice();", "});", "api.on('slice.done', () => {", " api.prepare();", "});", "api.on('prepare.done', () => {", " api.export();", "});" ].join('\n'); let msgs = []; let edit; function $(id) { return document.getElementById(id) } function onload() { let fnstr = demo.toString().split("\n"); edit = ace.edit($("mbody"), { mode: "ace/mode/javascript", theme: "ace/theme/chrome", selectionStyle: "text" }); edit.session.setTabSize(4); edit.session.setUseSoftTabs(true); edit.session.setValue(localStorage.kiri_frame_code || defc); kiri.frame.setFrame('fbody'); kiri.frame.onmessage = receive_message; } function receive_message(data, msg) { msgs.push(JSON.stringify(data)); $('rbody').innerText = msgs.join("\n-----\n"); $('rbody').scrollTop = 1000000; } ``` -------------------------------- ### JavaScript Initialization and Event Handling for Gyroid Visualization Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/gyroid-test.html This JavaScript code initializes the gyroid visualization application. It parses URL parameters for configuration, sets up event listeners for UI controls like checkboxes and input fields, and initiates the rendering process. ```javascript let PI2 = Math.PI * 2; let rez = 300; let inc = PI2 / rez; let zcache = {}; let timer = new Timer(); let maxdist = rez * 0.01; let fast = true; let tip = 0.2; function $(id) { return document.getElementById(id); } function init() { let opt = document.location.search.substring(1).split('&').map(v => { return v.split('=').map(v => decodeURIComponent(v)); }).reduce( (m,v) => { m[v[0]] = v[1]; return m; }, {}); function reload() { opt.speed = $('fast').checked ? 'fast' : 'slow'; opt.caps = $('caps').checked ? 1 : 0; opt.raw = $('raw').checked ? 1 : 0; let search = []; Object.entries(opt).forEach((k,v) => { search.push(encodeURIComponent(k[0]) + '=' + encodeURIComponent(k[1])); }); document.location.search = search.join('&'); }; $('offset').onkeypress = (ev) => { if (ev.key === 'Enter') { opt.offset = $('offset').value; reload(); } }; $('offset').focus(); if (opt.offset) tip = $('offset').value = (parseFloat(opt.offset) || 0); if (opt.raw) $('raw').checked = opt.raw === 1; if (opt.caps) $('caps').checked = opt.caps === 1; $('fast').checked = fast = opt.speed !== 'slow'; $('fast').onchange = reload; $('raw').onchange = update; $('caps').onchange = update; $('zval').max = rez; let mark = Date.now(); for (let z=0, zi=0; z= tip) || (v0 >= tip && v1 <= tip) || (v0 <= -tip && v1 >= -tip) || (v0 >= -tip && v1 <= -tip) ) { edge.put(x,y,1); points++; points_lr++; } } } timer.mark('gen_red'); // top-down threshold search ``` -------------------------------- ### Initialize and Configure Kiri:Moto Engine for CAM Operations Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/engine.html Illustrates the configuration of Kiri:Moto's CAM (Computer-Aided Manufacturing) engine. This involves loading an STL, setting CAM-specific parameters, defining stock material, tools, machining operations, and device configurations for CNC machines. ```javascript new Engine() .setListener(display_message) .load("/obj/cube.stl") // should to call widget.setTopZ here ideally .then(eng => eng.setMode("CAM")) .then(eng => eng.setStock({ "x": 25, "y": 25, "z": 25, "center": { "x": 0, "y": 0, "z": 12.5 } })) .then(eng => eng.moveTo(50, 0, 0)) .then(eng=> eng.setTools([{ id: 1000, number: 1, type: "endmill", name: "end 1/4", metric: false, shaft_diam: 0.25, shaft_len: 1, flute_diam: 0.25, flute_len: 2, taper_tip: 0, order: 5 }])) .then(eng => eng.setProcess({ camEaseAngle:10, camEaseDown:true, camZAnchor: "bottom", camDepthFirst : false, camZThru: 1.524, camZBottom:-25, // temp hack to get around setTopZ bug camToolInit: true, ops: [{ type: "outline", tool: 1000, spindle: 13000, step: 0.4, steps: 1, down: 5.08, rate: 635, plunge: 51, dogbones: false, omitvoid: false, omitthru: false, outside: false, inside: false, wide: false, top: false, ov_topz: 0, ov_botz: 0, ov_conv: true }] })) .then(eng => eng.setDevice({ mode: "CAM", internal: 0, bedHeight: 2.5, bedWidth: 678.18, bedDepth: 1524, maxHeight: 150, originCenter: false, spindleMax: 24000, gcodePre: [ "G20 ; set units to inches (required)", "G90 ; absolute position mode (required)" ], gcodePost: [ "M05 ; spindle off", "M30 ; program end" ], gcodeDwell: [ "G4 P{time} ; dwell for {time}ms" ], gcodeSpindle: [ "M3 S{speed} ; spindle on at {spindle} rpm" ], gcodeChange: [ "M05 ; spindle off", "M6 T{tool} ; change tool to '{tool_name}'", "G37; get tool offset with ETS" ], gcodeFExt: "nc", gcodeSpace: true, gcodeStrip: false, deviceName: "Tormach.24R", useLaser: false })) .then(eng => eng.slice()) .then(eng => eng.prepare()) .then(eng => eng.export()) .then(display_gcode); ``` -------------------------------- ### Setting Custom Device Profiles with Engine API Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/engine-apis.md Demonstrates merging a custom device profile into the current engine settings. This allows for tailored configurations specific to different printing hardware. ```javascript const engine = new Engine(); const customDeviceProfile = { ... }; // Your device profile object // Merge custom device profile engine.setDevice(customDeviceProfile); ``` -------------------------------- ### Retrieve Device Configuration (JavaScript) Source: https://github.com/gridspace/grid-apps/blob/master/contributing.md JavaScript code snippet to retrieve the current device configuration using the Kiri API. This is typically run in the browser's developer console. ```javascript kiri.api.conf.get().device ``` -------------------------------- ### G-code Download Functionality Source: https://github.com/gridspace/grid-apps/blob/master/web/kiri/engine.html Creates a Blob from the saved G-code data, generates a temporary URL for it, prompts the user for a filename, and then simulates a click on a hidden anchor tag to trigger the download. ```javascript function download() { let blob = new Blob([saveit], {type: "octet/stream"}); let url = window.URL.createObjectURL(blob); let filename = window.prompt("Enter filename", "sample.gcode"); $('download').innerHTML = ``; $('xo').click(); } ``` -------------------------------- ### Defining Tools for Slicing with Engine API Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/engine-apis.md Demonstrates setting tool definitions, such as cutters or extruders, for the slicing process. This ensures the engine uses the correct parameters for different manufacturing tools. ```javascript const engine = new Engine(); const toolDefinitions = [ { type: 'extruder', diameter: 0.4, speed: 50 }, { type: 'cutter', diameter: 3.0 } ]; // Set tool definitions engine.setTools(toolDefinitions); ``` -------------------------------- ### Restore Kiri Settings Source: https://github.com/gridspace/grid-apps/wiki/Profile-Persistence Pressing the lowercase 'u' key in Kiri prompts for a settings key, which is then used to restore the application's configuration. ```User Action Press 'u' (lowercase) ``` -------------------------------- ### Javascript Slicer Engine API Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/apis.md Access the latest slicing engine code live from the grid.space CDN and interact with it using the defined Engine APIs. ```APIDOC ## Javascript Slicer Engine ### Description The Kiri:Moto Javascript Slicer Engine provides a live-served slicing engine that can be embedded into your web pages. Interaction with the engine is done through a set of defined API calls. ### Endpoint `https://grid.space/code/engine.js` ### Usage Include the script in your HTML page and then use the provided API functions. Refer to the [Engine APIs](engine-apis) page for a complete list of available functions. ``` -------------------------------- ### Engine API Methods Source: https://github.com/gridspace/grid-apps/blob/master/docs/kiri-moto/engine-apis.md This section details the methods available on the Engine class for interacting with the Kiri 3D slicing engine. ```APIDOC ## Engine Class Methods ### Description Provides methods for loading, parsing, manipulating, and slicing 3D models using the Kiri engine. ### Methods - **`load(url)`** - **Description**: Loads an STL file from a given URL and centers the model. - **Returns**: `Promise` - **`clear()`** - **Description**: Clears all objects from the workspace. - **Returns**: `void` - **`parse(data)`** - **Description**: Parses raw STL data and loads it as a centered widget. - **Returns**: `Promise` - **`setListener(listener)`** - **Description**: Sets an event listener function to receive engine progress updates. - **Returns**: `Engine` - **`setRender(bool)`** - **Description**: Enables or disables rendering. - **Returns**: `Engine` - **`setMode(mode)`** - **Description**: Sets the slicing mode. Supported modes are "CAM", "FDM", "LASER", "SLA". - **Parameters**: - **mode** (string) - The slicing mode to set. - **Returns**: `Engine` - **`setDevice(device)`** - **Description**: Merges a custom device profile into the current settings. - **Returns**: `Engine` - **`setProcess(process)`** - **Description**: Merges custom slicing process parameters. - **Returns**: `Engine` - **`setController(controller)`** - **Description**: Sets the slicing controller settings and starts/stops the worker pool accordingly. - **Returns**: `Engine` - **`setTools(tools)`** - **Description**: Sets the tool definitions (e.g. cutters, extruders). - **Returns**: `Engine` - **`setStock(stock)`** - **Description**: Sets the stock material dimensions. - **Returns**: `Engine` - **`setOrigin(x, y, z)`** - **Description**: Defines the origin point for the part. - **Parameters**: - **x** (number) - The x-coordinate of the origin. - **y** (number) - The y-coordinate of the origin. - **z** (number) - The z-coordinate of the origin. - **Returns**: `Engine` - **`moveTo(x, y, z)`** - **Description**: Moves the widget to the specified absolute coordinates. - **Parameters**: - **x** (number) - The target x-coordinate. - **y** (number) - The target y-coordinate. - **z** (number) - The target z-coordinate. - **Returns**: `Engine` - **`move(x, y, z)`** - **Description**: Moves the widget by the specified delta values. - **Parameters**: - **x** (number) - The delta x value. - **y** (number) - The delta y value. - **z** (number) - The delta z value. - **Returns**: `Engine` - **`scale(x, y, z)`** - **Description**: Scales the widget along each axis. - **Parameters**: - **x** (number) - The scaling factor for the x-axis. - **y** (number) - The scaling factor for the y-axis. - **z** (number) - The scaling factor for the z-axis. - **Returns**: `Engine` - **`rotate(x, y, z)`** - **Description**: Rotates the widget in degrees along each axis. - **Parameters**: - **x** (number) - The rotation in degrees around the x-axis. - **y** (number) - The rotation in degrees around the y-axis. - **z** (number) - The rotation in degrees around the z-axis. - **Returns**: `Engine` - **`slice()`** - **Description**: Starts the slicing process and returns once complete. - **Returns**: `Promise` - **`prepare()`** - **Description**: Prepares the sliced toolpaths for export (e.g. G-code generation). - **Returns**: `Promise` - **`export()`** - **Description**: Exports the toolpaths as a string (e.g. G-code). - **Returns**: `Promise` ```