BorgVR Guide

Graphics Script

Automate BorgVR with GSC

GSC scripts control the macOS renderer, import datasets, create reproducible views, and export image sequences. This page documents the language and every BorgVR command.

BorgVR
Edit states and filesThe Data and Edit States guide explains stored files, personal variants and SharePlay, and the differences between exporting, resetting, and deleting. Script commands do not bypass SharePlay or export restrictions.

About Graphics Script

Graphics Script (GSC) is a line-oriented language for reproducible graphics workflows. BorgVR for macOS executes files with the .gsc extension. Open a script from the Script menu or drag it onto the BorgVR start screen.

A dedicated window shows log messages, errors, and long-running import progress while a script executes. BorgVR automatically waits for input dialogs, imports, screenshots, and loading commands before advancing.

Graphical editor The Graphics Script Editor provides syntax support and a graphical environment for creating GSC files.

Run and record scripts

  1. Save the source as a UTF-8 file with the .gsc extension.
  2. Open it in BorgVR for macOS from the Script menu or by dragging it onto the start screen.
  3. Follow execution and errors in the script log. Cancelling an input dialog or encountering an invalid command stops the script.

Use Start recording and Stop and save to capture interactive changes as a GSC file. Consecutive transforms, clipping changes, and transfer-function edits are coalesced. The currently open dataset is saved as the first command.

Paths and output directory Absolute paths are used directly. Relative paths are resolved below the current script output directory selected with setdir. Put names containing spaces in single or double quotes.

Picture configurations and settings

savestate and loadstate save a freely named JSON picture configuration containing all channel TFs, transform, clipping, lighting, background, render mode/isovalue, and projection for the currently open dataset. loadtf and savetf optionally accept a zero-based channel index first. gettransferfunction returns a channel's RGBA bytes as a Base64 string for settransferfunction. settransferfunctionjson instead sets a JSON array of RGBA bytes (0 through 255); compact ramps are linearly interpolated.

getbackground returns the complete background as JSON for setbackgroundstate. screenshot filename false saves an opaque PNG with the configured background; true (default) preserves the transparent render image. savesettings filename true exports all registered settings including credentials; false omits credentials. resetsettings restores defaults and loadsettings restores the archive. Import and reset preserve the running MCP connection.

settransferfunctionjson 0 '[[0,0,0,0],[255,80,0,100],[255,255,255,255]]'
set savedTF gettransferfunction 0
background solid 0 0 0
savestate "picture.json"
screenshot "picture.png" false

loadstate "picture.json"
settransferfunction 0 $savedTF

Control the macOS window

resize width height changes the main window's content size in logical points, not Retina pixels. The extended form also accepts points or pixels and content or frame; frame includes window decoration. The window's minimum and maximum sizes still apply. Detached panels and the script log remain unchanged.

fullscreen true enters native fullscreen; false leaves it. An already matching state is unchanged. Resize exits fullscreen first when necessary. The script waits for AppKit's completion notification before continuing; conflicting transitions and sheets blocking fullscreen are reported as errors. getwindowstate returns point/pixel dimensions, display scale, and fullscreen/transition status as JSON. These commands do not change camera projection.

fullscreen false
resize 1440 900
resize 2880 1800 pixels frame
set window getwindowstate
log $window
fullscreen true

Language basics

boolintint64floatdoublestringrestString
Commands
Each non-empty line contains one command followed by whitespace-separated arguments. Command names are case-sensitive.
Comments
Everything from # to the end of the line is a comment.
Strings
Single and double quotes group text containing spaces. Inside a quoted string, a backslash escapes the next character.
Boolean values
1/0, true/false, on/off, yes/no
Execution batches
A truly empty line ends an execution batch. This lets BorgVR complete a frame or asynchronous operation before the next batch starts. Comment-only lines do not create a batch boundary.

Variables and expressions

VariablesGSC
# A literal value
set steps 72

# Integer expressions support +, -, *, / and normal precedence
set degrees 360 / $steps

# $name and ${name} substitute variables inside any token
log "Rendering $steps frames at ${degrees} degrees"

# $$ produces a literal dollar sign
log "Cost: $$10"

unset degrees

set stores a single value, the result of an integer expression, or the return value of an input function. Integer expressions support +, -, *, and /; multiplication and division take precedence. Parentheses are not supported.

Loops and conditions

Control flowGSC
repeat 4 as index
  if $index == 0
    log "First pass"
  else
    log "Pass $index"
  endif
endrepeat

repeat count repeats the block through endrepeat. Add as name for a zero-based counter. if accepts a Boolean/integer value or a comparison. Numbers support == != < <= > >=; strings support == and !=. Blocks may be nested.

Interactive return values

Use input, fileinput, and dirinput on the right side of set. The interpreter waits for the dialog. Cancelling stops the entire script.

set title input "Dataset description"
set source fileinput "Choose a QVIS, NRRD, or PVM file"
set dicom dirinput "Choose a DICOM directory"

Example programs

Open a dataset and capture a screenshot

single-view.gscReproducible view
# Use the dataset UUID shown in BorgVR's information panel
opendataset "59DBB8EB-1674-4DAE-94D3-369E63D5A418"
waitloaded

rendermode lighting
setrotationquaternion 0 0 0 1
settranslation 0 0
setscale 1.15
clip 0 1 0 1 0 1
setlightdirection -0.4 0.5 0.75
waitframes 2
screenshot "single-view.png"

360-degree image sequence

turntable.gsc72 frames
opendataset "59DBB8EB-1674-4DAE-94D3-369E63D5A418"
waitloaded
setdir "rotation-frames"
resize 1280 720
rendermode tf
resetrotation

repeat 72 as frame
  screenshot "frame_${frame}.png"
  addrotationy 5
  waitframes 1
endrepeat

Import a volume file

import-volume.gscInteractive input
set source fileinput "Choose a QVIS, NRRD, or PVM volume"
set destination input "BorgVR output filename"
set description input "Dataset description"

setimportbricksize 32
setimportoverlap 2
setbordermode 0
importfile "$source" "$destination" "$description"
log "Import completed: $destination"

Compare isovalues

iso-sweep.gscGSC
opendataset "59DBB8EB-1674-4DAE-94D3-369E63D5A418"
waitloaded
setdir "iso-sweep"
rendermode iso

repeat 9 as step
  set value 1 + $step
  isovalueNormalized 0.$value
  waitframes 2
  screenshot "iso-0.${value}.png"
endrepeat

Create an object and a measurement

annotations.gscDeterministic UUIDs
# Sphere: UUID, name, xyz, radius, RGBA, direction flag, direction origin
setspheremarker "A1111111-1111-4111-8111-111111111111" "Target" 0.1 0.2 0.3 0.01 1 0.25 0.1 1 false 0 0 0

# Length measurement: measurement UUID, kind, name, then point UUID/xyz groups
setmeasurement "B2222222-2222-4222-8222-222222222222" length "Reference length" "C3333333-3333-4333-8333-333333333333" 0 0 0 "D4444444-4444-4444-8444-444444444444" 0.1 0 0

Complete command reference

Names in angle brackets are placeholders. Square brackets indicate an optional overload. Coordinates and colors are floating-point values; color components use the range 0 through 1.

Language and execution

SyntaxEffect
set <name> <value|expression|function>Assigns a literal, integer expression, or function return value to a variable.
unset <name>Removes a variable.
repeat <count> [as <name>]
endrepeat
Repeats a block, optionally with a zero-based counter.
if <condition>
else
endif
Runs a conditional block. else is optional.
noop <milliseconds>Waits for the specified time without blocking the app.
input <prompt>Opens a text field and returns the entered text. Use only with set.
fileinput <prompt>Opens a file picker and returns its path. Use only with set.
dirinput <prompt>Opens a directory picker and returns its path. Use only with set.

Logging and application

CommandEffect
log <text...>Writes text to the script log.
logfile <file>Also writes subsequent log output to a file.
clearlogClears the configured log file.
logtimeLogs the current ISO 8601 timestamp.
logGPUInfo [bool]Logs Metal device information; the optional Boolean controls GPU-family output.
setdir <directory>Selects and creates the output directory used for relative paths.
screenshot [file]Saves the next completed rendered frame as a PNG.
resize <width> <height> [points|pixels content|frame]
fullscreen <bool>
getwindowstate
Controls only the main window. Resize defaults to logical points and content size. frame includes decoration. Fullscreen transitions are awaited; getwindowstate returns JSON with actual dimensions.
quitTerminates BorgVR.

Datasets, import, and export

CommandEffect
opendataset <dataset-uuid>Finds the dataset in the local and remote catalog, opens it, and waits for the renderer.
importfile <source> <destination> <description>Imports a QVIS, NRRD/NHDR, or PVM file as a BorgVR dataset.
importdirectory <source> <destination> <description>Imports a DICOM directory.
exportdataset <source.data> <destination.nrrd> <lod>Exports the selected LoD as an uncompressed NRRD; LoD 0 is full resolution.
exportisosurface <destination.obj> [normalized-isovalue]Extracts the current dataset as an OBJ isosurface using the current or supplied normalized isovalue. Script execution waits for completion.
setimportbricksize <int>Overrides the brick edge length for subsequent imports.
setimportoverlap <int>Overrides overlap for subsequent imports.
setbordermode <0|1|2>Sets border handling: 0 = zero fill, 1 = clamp, 2 = repeat.

Volume editing

Dataset and isosurface exports are disabled during SharePlay. Edits and edit-state changes are rejected while an export is running. Starting SharePlay cancels a running export.

These commands edit the currently open dataset locally. The original remains unchanged; edits are saved in the selected state and are shared during SharePlay. Brush centers and radii are physical meters from the volume minimum corner, independent of rotation, zoom, and projection settings. Erase sets the selected channels to 0; restore recovers only their original values. All channels are selected by default.

CommandEffect
logeditstatesLists saved state UUIDs and the active state in the log.
selecteditstate <uuid|original>Switches to the selected state and waits for completion.
neweditstate <name> / duplicateeditstate <name>Creates and activates an empty state or a copy.
renameeditstate <uuid> <name> / deleteeditstate <uuid>Renames a state or deletes an inactive state. State management is disabled during SharePlay.
setvolumebrush <erase|restore> <radius-fraction> <project>Configures the interactive brush and activates mouse/touch editing. Radius: 0.002 to 0.15 of the largest dataset extent. Does not modify voxels yet.
setvolumeeditchannels <channels>Selects channels for the interactive brush and subsequent erase/restore commands: "all" or a string of one-based channel numbers, e.g. "1,3". At least one valid channel is required. Opening resets to all channels; Discard All Edits is independent of this selection.
erasevolume <x> <y> <z> <radius>Erases a sphere at the supplied position; all four values are in meters.
restorevolume <x> <y> <z> <radius>Restores original values inside a sphere; untouched bricks are skipped.
editvolume <erase|restore> <x y z radius...>Processes up to 65536 spheres as one batch, without interpolation between them. All sample values are meters. Execution waits for journaling, not for every background brick job.
waitvolumeedits [timeout-seconds]Waits for pending brick updates. Default: 30 seconds; maximum: 86400. Unavailable remote bricks may cause a timeout.
hasvolumeedits() / volumeeditsbusy()Boolean value functions, e.g. set changed hasvolumeedits and set busy volumeeditsbusy.
preparevolumeeditsRebuilds pending edited bricks with foreground priority and Metal acceleration when available. Waits for persistence; stopping the script preserves recorded edits.
clearvolumeeditsClears the active edit state without another confirmation. During SharePlay, this affects the shared state. Other states and the original remain unchanged.
exportediteddataset <destination.data> [name description]Writes a new dataset from the original plus current edits. Supply name and description together, or inherit both from the original. Preserves source compression; refuses existing destinations. Relative paths use setdir. Waits for completion and displays progress in the script log window. Stopping the script cancels the export.
# Example for a dataset spanning approximately one meter.
erasevolume 0.5 0.5 0.5 0.05
restorevolume 0.5 0.5 0.5 0.02
waitvolumeedits 60
exportediteddataset "edited.data" "Edited volume" "Sphere erased and partly restored"

A brush batch already recorded in the journal survives script cancellation. Export captures a consistent snapshot including preceding batches; waitvolumeedits is not required beforehand. Interactive volume edits are not currently captured by GSC recording; use the explicit commands instead.

Synchronization and performance

CommandEffect
waitframes <count>Waits for the specified number of additional rendered frames.
waitloaded [empty-readbacks]Waits until paging for the active dataset settles. The default is three empty brick readbacks.
waitidle [empty-readbacks]Alias for waitloaded.
resetfpsResets performance statistics.
setfpswindow <seconds>Sets the measurement-window length for FPS statistics.
logfpsWaits for a complete measurement window and logs detailed FPS and paging values.
setDisplaySync <bool>Enables or disables render-output synchronization with the display.

Rendering and background

CommandEffect
resetResets all rendering parameters.
rendermode <tf|lighting|iso>Selects transfer function, illuminated transfer function, or isosurface. Spelled-out aliases are also accepted.
setmethod <0|1|2>Numeric alias: 0 = TF, 1 = TF + lighting, 2 = iso.
showbricks <bool>Enables or disables brick visualization.
showresidentbricks <bool>Shows or hides red, resident bricks.
showemptybricks <bool>Shows or hides green regions skipped as empty.
showmissingbricks <bool>Shows or hides blue regions with missing bricks or coarser substitutes.
setsubbrickskipping <bool>Enables or disables empty subblock skipping.
setopacityadaptivesampling <bool>Enables or disables opacity-adaptive sample spacing for TF and lit TF rendering.
setalphaepsilon <0...1>Sets the TF empty-test alpha threshold. Zero disables the threshold; the transfer function itself and iso rendering remain unchanged.
setfieldofview <10...120>
setparallelprojection <bool>
Vertical field of view in degrees and parallel projection. Both settings stay local and are not synchronized over SharePlay.
showboundingbox <bool>Locally shows or hides the frame around the complete dataset, independently of clipping and object visibility.
background <solid|gradient>Selects the background mode using the stored colors.
background solid <r> <g> <b>Sets an opaque solid background.
background gradient <r1> <g1> <b1> <r2> <g2> <b2>Sets both gradient colors.
setbackground <r> <g> <b> <a>Sets a solid background including alpha.

The three brick type filters also apply to subblocks and affect only diagnostic colors, not traversal or paging. Optimizations and alpha epsilon persist in local settings. GSC recording captures these options and their initial values, followed by changes through menus, Settings, and MCP.

Transform

CommandEffect
resetrotationResets only model rotation.
setrotationquaternion <x> <y> <z> <w>Sets model rotation as a quaternion.
addrotationx <degrees>Adds a rotation around the X axis.
addrotationy <degrees>Adds a rotation around the Y axis.
addrotationz <degrees>Adds a rotation around the Z axis.
settranslation <x> <y>Sets image-plane translation and resets Z to zero.
zoom <scale>
setscale <scale>
Sets a uniform positive model scale.

Clipping and isosurface

CommandEffect
clip <xmin> <xmax> <ymin> <ymax> <zmin> <zmax>Sets normalized clipping bounds in the range 0 through 1.
resetclipResets clipping.
isovalue <dataset-value>Sets the isovalue in dataset scalar units.
isovalueNormalized <0...1>Sets the normalized isovalue.

Transfer function and lighting

CommandEffect
loadtf <file>
settffile <file>
Loads a .tf1d transfer function.
savetf <file>
savetffile <file>
Saves the current transfer function.
settransferfunction <data-channel> <base64>Replaces the complete RGBA transfer function of the zero-based data channel with base64-encoded 8-bit samples. This supports multi-channel datasets and is primarily generated by interaction recording.
resettfResets the transfer function to its default.
setlightdirection <x> <y> <z>Sets and normalizes a non-zero light direction.
setambientlight <r> <g> <b>Sets the ambient-light color.
setdiffuselight <r> <g> <b>Sets the diffuse-light color.
setspecularlight <r> <g> <b>Sets the specular-light color.
resetlightingResets light direction and colors.

Objects, markers, and measurements

Positions use normalized volume coordinates. Colors use RGB or RGBA in the range 0 through 1. Simple add... commands create new UUIDs; deterministic set... commands create or replace the supplied UUID and are suited to recorded scripts.

Visibility and marker files

CommandEffect
hideobjects <bool>Locally hides or shows all objects without deleting data.
hidemeasurements <bool>Locally hides or shows all measurements without deleting data.
loadmarkers <file> [replace]Loads a .marker file. Existing objects are replaced by default; false merges with unique UUIDs.
savemarkers <file>Saves current markers and object instances.
removemarker <uuid|name>Removes the first matching sphere or stroke marker.
clearmarkersRemoves all sphere and stroke markers, but not mesh instances.
removeobject <uuid|name>Removes a marker or placed mesh instance.
clearobjectsRemoves all objects.

Create markers

CommandArguments and effect
addspheremarker <name> <x> <y> <z> <radius> <r> <g> <b>Creates a new sphere marker.
adddirectionalmarker <name> <x> <y> <z> <radius> <r> <g> <b> <ox> <oy> <oz>Creates a sphere marker with a direction ray toward origin o.
addstrokemarker <name> <radius> <r> <g> <b> <x y z...>Creates a stroke from one or more XYZ points; all points receive the same radius.
setspheremarker <uuid> <name> <x y z> <radius> <r g b a> <direction-bool> <ox oy oz>Creates or replaces a sphere marker with a fixed UUID.
setstrokemarker <uuid> <name> <r g b a> <x y z radius...>Creates or replaces a stroke with an individual radius for every point.

Mesh instances and measurements

CommandArguments and effect
setmeshinstance <uuid> <asset-uuid> <name> <tx ty tz> <qx qy qz qw> <sx sy sz> <visible>Creates or replaces an instance of a known mesh asset using translation in meters, quaternion rotation, and scale.
setmeasurement <uuid> <length|area|volume> <name> <point-uuid x y z...>Creates or replaces a measurement. Every point consists of a UUID and XYZ position.
removemeasurement <uuid|name>Removes the first matching measurement.
clearmeasurementsRemoves all measurements.
Mesh dependency setmeshinstance references an asset by UUID. The asset must already be available locally or from a known server source. The command does not embed mesh data in the script.