VirtualMachine

VirtualMachine

Handles connections between blocks, stage, and extensions.

Constructor

new VirtualMachine()

Members

_dragTarget :Target

The currently dragging target, for redirecting IO data.

Type:

editingTarget :Target

The "currently editing"/selected target ID for the VM. Block events from any Blockly workspace are routed to this target.

Type:

renderer

(non-null) runtime :Runtime

VM runtime, to store blocks, I/O devices, sprites/targets, etc.

Type:

Methods

_addSprite2(sprite, zipnullable) → {Promise}

Add a single sprite from the "Sprite2" (i.e., SB2 sprite) format.

Parameters:
Name Type Attributes Description
sprite object

Object representing 2.0 sprite to be added.

zip ArrayBuffer <nullable>

Optional zip of assets being referenced by json

Returns:

Promise that resolves after the sprite is added

Type
Promise

_addSprite3(sprite, zipnullable) → {Promise}

Add a single sb3 sprite.

Parameters:
Name Type Attributes Description
sprite object

Object rperesenting 3.0 sprite to be added.

zip ArrayBuffer <nullable>

Optional zip of assets being referenced by target json

Returns:

Promise that resolves after the sprite is added

Type
Promise

addBackdrop(md5ext, backdropObjectnon-null) → (nullable) {Promise}

Properties:
Name Type Attributes Description
skinId int

the ID of the backdrop's render skin, once installed.

rotationCenterX number

the X component of the backdrop's origin.

rotationCenterY number

the Y component of the backdrop's origin.

bitmapResolution number <optional>

the resolution scale for a bitmap backdrop.

Add a backdrop to the stage.

Parameters:
Name Type Description
md5ext string

the MD5 and extension of the backdrop to be loaded.

backdropObject object

Object representing the backdrop.

Returns:
  • a promise that resolves when the backdrop has been added
Type
Promise

addCostume(md5ext, costumeObjectnon-null, optTargetId, optVersion) → (nullable) {Promise}

Properties:
Name Type Attributes Description
skinId int

the ID of the costume's render skin, once installed.

rotationCenterX number

the X component of the costume's origin.

rotationCenterY number

the Y component of the costume's origin.

bitmapResolution number <optional>

the resolution scale for a bitmap costume.

Add a costume to the current editing target.

Parameters:
Name Type Description
md5ext string

the MD5 and extension of the costume to be loaded.

costumeObject object

Object representing the costume.

optTargetId string

the id of the target to add to, if not the editing target.

optVersion string

if this is 2, load costume as sb2, otherwise load costume as sb3.

Returns:
  • a promise that resolves when the costume has been added
Type
Promise

addCostumeFromLibrary(md5ext, costumeObjectnon-null) → (nullable) {Promise}

Properties:
Name Type Attributes Description
skinId int

the ID of the costume's render skin, once installed.

rotationCenterX number

the X component of the costume's origin.

rotationCenterY number

the Y component of the costume's origin.

bitmapResolution number <optional>

the resolution scale for a bitmap costume.

Add a costume loaded from the library to the current editing target.

Parameters:
Name Type Description
md5ext string

the MD5 and extension of the costume to be loaded.

costumeObject object

Object representing the costume.

Returns:
  • a promise that resolves when the costume has been added
Type
Promise

addSound(soundObjectnon-null, optTargetId) → (nullable) {Promise}

Add a sound to the current editing target.

Parameters:
Name Type Description
soundObject object

Object representing the costume.

optTargetId string

the id of the target to add to, if not the editing target.

Returns:
  • a promise that resolves when the sound has been decoded and added
Type
Promise

addSprite(input) → (non-null) {Promise}

Add a sprite, this could be .sprite2 or .sprite3. Unpack and validate such a file first.

Parameters:
Name Type Description
input string | object

A json string, object, or ArrayBuffer representing the project to load.

Returns:

Promise that resolves after targets are installed.

Type
Promise

attachAudioEngine(audioEnginenon-null)

Set the audio engine for the VM/runtime

Parameters:
Name Type Description
audioEngine AudioEngine

The audio engine to attach

attachRenderer(renderernon-null)

Set the renderer for the VM/runtime

Parameters:
Name Type Description
renderer RenderWebGL

The renderer to attach

attachStorage(storagenon-null)

Set the storage module for the VM/runtime

Parameters:
Name Type Description
storage ScratchStorage

The storage module to attach

attachV2BitmapAdapter(bitmapAdapternon-null)

Set the bitmap adapter for the VM/runtime, which converts scratch 2 bitmaps to scratch 3 bitmaps. (Scratch 3 bitmaps are all bitmap resolution 2)

Parameters:
Name Type Description
bitmapAdapter function

The adapter to attach

attachV2SVGAdapter(svgAdapternon-null)

Set the svg adapter for the VM/runtime, which converts scratch 2 svgs to scratch 3 svgs

Parameters:
Name Type Description
svgAdapter SvgRenderer

The adapter to attach

blockListener(enon-null)

Handle a Blockly event for the current editing target.

Parameters:
Name Type Description
e Blockly.Event

Any Blockly event.

clear()

Clear out current running project data.

configureScratchLinkSocketFactory(factory)

Allow VM consumer to configure the ScratchLink socket creator.

Parameters:
Name Type Description
factory function

The custom ScratchLink socket factory.

connectPeripheral(extensionId, peripheralId)

Connect to the extension's specified peripheral.

Parameters:
Name Type Description
extensionId string

the id of the extension.

peripheralId number

the id of the peripheral.

deleteCostume(costumeIndex) → (nullable) {function}

Delete a costume from the current editing target.

Parameters:
Name Type Description
costumeIndex int

the index of the costume to be removed.

Returns:

A function to restore the deleted costume, or null, if no costume was deleted.

Type
function

deleteSound(soundIndex) → (nullable) {function}

Delete a sound from the current editing target.

Parameters:
Name Type Description
soundIndex int

the index of the sound to be removed.

Returns:

A function to restore the sound that was deleted, or null, if no sound was deleted.

Type
function

deleteSprite(targetId) → {function}

Delete a sprite and all its clones.

Parameters:
Name Type Description
targetId string

ID of a target whose sprite to delete.

Returns:

Returns a function to restore the sprite that was deleted

Type
function

deserializeProject(projectJSON, zipnullable) → {Promise}

Load a project from a Scratch JSON representation.

Parameters:
Name Type Attributes Description
projectJSON string

JSON string representing a project.

zip JSZip <nullable>

Optional zipped project containing assets to be loaded.

Returns:

Promise that resolves after the project has loaded

Type
Promise

disconnectPeripheral(extensionId)

Disconnect from the extension's connected peripheral.

Parameters:
Name Type Description
extensionId string

the id of the extension.

downloadProjectId(id)

Load a project from the Scratch web site, by ID.

Parameters:
Name Type Description
id string

the ID of the project to download, as a string.

duplicateCostume(costumeIndexnon-null) → (nullable) {Promise}

Duplicate the costume at the given index. Add it at that index + 1.

Parameters:
Name Type Description
costumeIndex int

Index of costume to duplicate

Returns:
  • a promise that resolves when the costume has been decoded and added
Type
Promise

duplicateSound(soundIndexnon-null) → (nullable) {Promise}

Duplicate the sound at the given index. Add it at that index + 1.

Parameters:
Name Type Description
soundIndex int

Index of sound to duplicate

Returns:
  • a promise that resolves when the sound has been decoded and added
Type
Promise

duplicateSprite(targetId) → {Promise}

Duplicate a sprite.

Parameters:
Name Type Description
targetId string

ID of a target whose sprite to duplicate.

Returns:

Promise that resolves when duplicated target has been added to the runtime.

Type
Promise

emitTargetsUpdate(triggerProjectChange)

Emit metadata about available targets. An editor UI could use this to display a list of targets and show the currently editing one.

Parameters:
Name Type Description
triggerProjectChange bool

If true, also emit a project changed event. Disabled selectively by updates that don't affect project serialization. Defaults to true.

emitWorkspaceUpdate()

Emit an Blockly/scratch-blocks compatible XML representation of the current editing target's blocks.

exportSprite(targetId, optZipTypeopt) → {object}

Exports a sprite in the sprite3 format.

Parameters:
Name Type Attributes Description
targetId string

ID of the target to export

optZipType string <optional>

Optional type that the resulting zip should be outputted in. Options are: base64, binarystring, array, uint8array, arraybuffer, blob, or nodebuffer. Defaults to blob if argument not provided. See https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html#type-option for more information about these options.

Returns:

A generated zip of the sprite and its assets in the format specified by optZipType or blob by default.

Type
object

flyoutBlockListener(enon-null)

Handle a Blockly event for the flyout.

Parameters:
Name Type Description
e Blockly.Event

Any Blockly event.

fromJSON(json) → {Promise}

Load a project from a Scratch JSON representation.

Parameters:
Name Type Description
json string

JSON string representing a project.

Returns:

Promise that resolves after the project has loaded

Type
Promise

getCostume(costumeIndex) → {string}

Get a string representation of the image from storage.

Parameters:
Name Type Description
costumeIndex int

the index of the costume to be got.

Returns:

the costume's SVG string if it's SVG, a dataURI if it's a PNG or JPG, or null if it couldn't be found or decoded.

Type
string

getLocale() → {string}

get the current locale for the VM

Returns:

the current locale in the VM

Type
string

getPeripheralIsConnected(extensionId) → {boolean}

Returns whether the extension has a currently connected peripheral.

Parameters:
Name Type Description
extensionId string

the id of the extension.

Returns:
  • whether the extension has a connected peripheral.
Type
boolean

getPlaygroundData()

Get data for playground. Data comes back in an emitted event.

getSoundBuffer(soundIndex) → {AudioBuffer}

Get a sound buffer from the audio engine.

Parameters:
Name Type Description
soundIndex int

the index of the sound to be got.

Returns:

the sound's audio buffer.

Type
AudioBuffer

getTargetIdForDrawableId(drawableId) → (nullable) {string}

Get a target id for a drawable id. Useful for interacting with the renderer

Parameters:
Name Type Description
drawableId int

The drawable id to request the target id for

Returns:

The target id, if found. Will also be null if the target found is the stage.

Type
string

getVariableValue(targetIdnon-null, variableIdnon-null) → (nullable) {*}

Get a target's variable's value. Return null if the target or variable does not exist.

Parameters:
Name Type Description
targetId string

ID of the target which owns the variable.

variableId string

ID of the variable to set.

Returns:

The value of the variable, or null if it could not be looked up.

Type
*

greenFlag()

"Green flag" handler - start all threads starting with a green flag.

installTargets(targets, extensions, wholeProject) → {Promise}

Install deserialize results: zero or more targets after the extensions (if any) used by those targets.

Parameters:
Name Type Description
targets Array.<Target>

the targets to be installed

extensions ImportedExtensionsInfo

metadata about extensions used by these targets

wholeProject boolean

set to true if installing a whole project, as opposed to a single sprite.

Returns:

resolved once targets have been installed

Type
Promise

loadProject(input) → (non-null) {Promise}

Load a Scratch project from a .sb, .sb2, .sb3 or json string.

Parameters:
Name Type Description
input string | object

A json string, object, or ArrayBuffer representing the project to load.

Returns:

Promise that resolves after targets are installed.

Type
Promise

monitorBlockListener(enon-null)

Handle a Blockly event for the flyout to be passed to the monitor container.

Parameters:
Name Type Description
e Blockly.Event

Any Blockly event.

postIOData(devicenullable, data)

Post I/O data to the virtual devices.

Parameters:
Name Type Attributes Description
device string <nullable>

Name of virtual I/O device.

data object

Any data object to post to the I/O device.

postSpriteInfo(data)

Post/edit sprite info for the current editing target or the drag target.

Parameters:
Name Type Description
data object

An object with sprite info data to set.

refreshWorkspace()

Repopulate the workspace with the blocks of the current editingTarget. This allows us to get around bugs like gui#413.

renameCostume(costumeIndex, newName)

Rename a costume on the current editing target.

Parameters:
Name Type Description
costumeIndex int

the index of the costume to be renamed.

newName string

the desired new name of the costume (will be modified if already in use).

renameSound(soundIndex, newName)

Rename a sound on the current editing target.

Parameters:
Name Type Description
soundIndex int

the index of the sound to be renamed.

newName string

the desired new name of the sound (will be modified if already in use).

renameSprite(targetId, newName)

Rename a sprite.

Parameters:
Name Type Description
targetId string

ID of a target whose sprite to rename.

newName string

New name of the sprite.

reorderCostume(targetIdnon-null, costumeIndexnon-null, newIndexnon-null) → {boolean}

Reorder the costumes of a target if it exists. Return whether it succeeded.

Parameters:
Name Type Description
targetId string

ID of the target which owns the costumes.

costumeIndex number

index of the costume to move.

newIndex number

index that the costume should be moved to.

Returns:

Whether a costume was reordered.

Type
boolean

reorderSound(targetIdnon-null, soundIndexnon-null, newIndexnon-null) → {boolean}

Reorder the sounds of a target if it exists. Return whether it occured.

Parameters:
Name Type Description
targetId string

ID of the target which owns the sounds.

soundIndex number

index of the sound to move.

newIndex number

index that the sound should be moved to.

Returns:

Whether a sound was reordered.

Type
boolean

reorderTarget(targetIndexnon-null, newIndexnon-null) → {boolean}

Reorder target by index. Return whether a change was made.

Parameters:
Name Type Description
targetIndex string

Index of the target.

newIndex number

index that the target should be moved to.

Returns:

Whether a target was reordered.

Type
boolean

saveProjectSb3() → {string}

Returns:

Project in a Scratch 3.0 JSON representation.

Type
string

scanForPeripheral(extensionId)

Tell the specified extension to scan for a peripheral.

Parameters:
Name Type Description
extensionId string

the id of the extension.

setCompatibilityMode(compatibilityModeOn)

Set whether the VM is in 2.0 "compatibility mode." When true, ticks go at 2.0 speed (30 TPS).

Parameters:
Name Type Description
compatibilityModeOn boolean

Whether compatibility mode is set.

setEditingTarget(targetId)

Set an editing target. An editor UI can use this function to switch between editing different targets, sprites, etc. After switching the editing target, the VM may emit updates to the list of targets and any attached workspace blocks (see emitTargetsUpdate and emitWorkspaceUpdate).

Parameters:
Name Type Description
targetId string

Id of target to set as editing.

setLocale(localenon-null, messagesnon-null) → {Promise}

set the current locale and builtin messages for the VM

Parameters:
Name Type Description
locale string

current locale

messages object

builtin messages map for current locale

Returns:

Promise that resolves when all the blocks have been updated for a new locale (or empty if locale hasn't changed.)

Type
Promise

setTurboMode(turboModeOn)

Set whether the VM is in "turbo mode." When true, loops don't yield to redraw.

Parameters:
Name Type Description
turboModeOn boolean

Whether turbo mode should be set.

setVariableValue(targetIdnon-null, variableIdnon-null, valuenon-null) → {boolean}

Set a target's variable's value. Return whether it succeeded.

Parameters:
Name Type Description
targetId string

ID of the target which owns the variable.

variableId string

ID of the variable to set.

value *

The new value of that variable.

Returns:

whether the target and variable were found and updated.

Type
boolean

shareBlocksToTarget(blocksnon-null, targetIdnon-null, optFromTargetIdnullable) → (non-null) {Promise}

Called when blocks are dragged from one sprite to another. Adds the blocks to the workspace of the given target.

Parameters:
Name Type Attributes Description
blocks Array.<object>

Blocks to add.

targetId string

Id of target to add blocks to.

optFromTargetId string <nullable>

Optional target id indicating that blocks are being shared from that target. This is needed for resolving any potential variable conflicts.

Returns:

Promise that resolves when the extensions and blocks have been added.

Type
Promise

shareCostumeToTarget(costumeIndexnon-null, targetIdnon-null) → {Promise}

Called when costumes are dragged from editing target to another target. Sets the newly added costume as the current costume.

Parameters:
Name Type Description
costumeIndex number

Index of the costume of the editing target to share.

targetId string

Id of target to add the costume.

Returns:

Promise that resolves when the new costume has been loaded.

Type
Promise

shareSoundToTarget(soundIndexnon-null, targetIdnon-null) → {Promise}

Called when sounds are dragged from editing target to another target.

Parameters:
Name Type Description
soundIndex number

Index of the sound of the editing target to share.

targetId string

Id of target to add the sound.

Returns:

Promise that resolves when the new sound has been loaded.

Type
Promise

start()

Start running the VM - do this before anything else.

startDrag(targetId)

Put a target into a "drag" state, during which its X/Y positions will be unaffected by blocks.

Parameters:
Name Type Description
targetId string

The id for the target to put into a drag state

stopAll()

Stop all threads and running activities.

stopDrag(targetId)

Remove a target from a drag state, so blocks may begin affecting X/Y position again

Parameters:
Name Type Description
targetId string

The id for the target to remove from the drag state

toJSON() → {string}

Export project as a Scratch 3.0 JSON representation.

Returns:

Serialized state of the runtime.

Type
string

updateBitmap(costumeIndexnon-null, bitmapnon-null, rotationCenterXnon-null, rotationCenterYnon-null, bitmapResolutionnon-null)

Update a costume with the given bitmap

Parameters:
Name Type Description
costumeIndex int

the index of the costume to be updated.

bitmap ImageData

new bitmap for the renderer.

rotationCenterX number

x of point about which the costume rotates, relative to its upper left corner

rotationCenterY number

y of point about which the costume rotates, relative to its upper left corner

bitmapResolution number

1 for bitmaps that have 1 pixel per unit of stage, 2 for double-resolution bitmaps

updateSoundBuffer(soundIndex, newBuffer, soundEncoding)

Update a sound buffer.

Parameters:
Name Type Description
soundIndex int

the index of the sound to be updated.

newBuffer AudioBuffer

new audio buffer for the audio engine.

soundEncoding ArrayBuffer

the new (wav) encoded sound to be stored

updateSvg(costumeIndex, svg, rotationCenterX, rotationCenterY)

Update a costume with the given SVG

Parameters:
Name Type Description
costumeIndex int

the index of the costume to be updated.

svg string

new SVG for the renderer.

rotationCenterX number

x of point about which the costume rotates, relative to its upper left corner

rotationCenterY number

y of point about which the costume rotates, relative to its upper left corner

variableListener(enon-null)

Handle a Blockly event for the variable map.

Parameters:
Name Type Description
e Blockly.Event

Any Blockly event.