HomeGuidesAPI ReferenceChangelogDiscussions
Hire a ReactVision Expert 🛠️Launch Studio 🖥️Sponsor on GitHub ❤️Log In
Guides

ViroARScene

The ViroARScene component allows developers to logically group their experiences and components and switch between them using the ViroARSceneNavigator.

This component also hosts various properties that enable developers to control and interact with the AR subsystem. Like displayPointCloud which configures the renderer to draw the AR point cloud. The onAnchorFound|Updated|Removed functions work in conjunction with ViroARPlane's manual anchoring mode to enable developers to fully control their experience.

Example use:
<ViroARScene onTrackingUpdated={this._trackingUpdated}>
  <ViroARPlane>
    <ViroBox position={[0, .5, 0]} />
  </ViroARPlane>
</ViroARScene>

Content at the root of the scene stays put (3.2.1+)

Viro anchors each direct child of ViroARScene (a ViroNode, Viro3DObject, ViroBox and so on) to a native AR anchor, so it stays in place as ARKit or ARCore refines its map of the room. Before 3.2.1 this happened only on Android.

  • iOS (3.2.1+): each direct child is anchored with an ARKit anchor once tracking is NORMAL. Its position, animations, drag and physics keep working in scene coordinates; only ARKit's corrections to the anchor move it. Anchors, markers (ViroARImageMarker, ViroARObjectMarker), planes and ViroVPSAnchor place themselves and are left alone.
  • Android (3.2.1+): Viro waits for the scene's tracking to be NORMAL before it anchors a node, however long that takes. Before, it tried once a second up to three times, so when tracking took more than about three seconds to start (a dim room, a covered camera, fast motion) the node stayed unanchored for the session and drifted. A position set while the node waits is now the one it anchors at.
  • Meta Quest: nodes keep their plain position; only ARCore makes these anchors.

To keep content placed from a hit test in place, render it as a direct child of ViroARScene at the hit position. Do not rely on createAnchoredNode, which returns an anchor nothing can be attached to.

📘

Android, 3.2.1+: a call to a hidden scene answers instead of crashing. A tab switch or a screen pushed on top tears the AR scene down without unmounting it. A navigator call still queued then, such as a getCameraGeospatialPose poll, used to crash the app (SIGSEGV). It now fails with the error AR scene not available; call it again once the scene is showing.

Props

anchorDetectionTypes

TypeDescription
string | string[]Determines what types of anchors the scene should return.

Currently supports the following values:
"None" | "PlanesHorizontal" | "PlanesVertical"

v2.53.0: The default now detects both horizontal and vertical planes (["PlanesHorizontal", "PlanesVertical"]).

Web, 3.2.3+: anchorDetectionTypes filters planes on web. Plane detection itself is on by default on the navigator (set arOptions.detectPlanes to false to turn it off).

displayPointCloud

interface PointCloudOptions {
  //  image used to represent each point
  imageSource: ImageSourcePropType;
  // scale of the image used for each point, the default is [.01,.01,.01]
  imageScale: [number, number, number];
  // the max number of points drawn each frame
  maxPoints: number;
}
TypeDescription
boolean | pointCloudOptionsSetting this property to true draws the point cloud using a default configuration.

Setting this property to false disables the drawing of the point cloud.

This property can also take a dictionary of properties which enable point cloud drawing with the given pointCloudOptions.

Web, 3.3.0+: draws the web tracker's feature points as particles, with imageSource, imageScale and maxPoints. Needs @reactvision/viro-web-renderer 1.4.0; on 1.3.0 it warns once and does nothing.

Example:

<ViroARScene 
  displayPointCloud={{
    imageSource: require("./res/pointCloudPoint.png"),
    imageScale: [.02,.02,.02],
    maxPoints: 100 
  }} />

dragPlane

TypeDescription
ViroDragPlaneWhen a drag type of "FixedToPlane" is given, dragging is limited to a user defined plane. The dragging behavior is then configured by this property (specified by a point on the plane and its normal vector). You can also limit the maximum distance the dragged object is allowed to travel away from the camera/controller (useful for situations where the user can drag an object towards infinity).

dragType

TypeDescription
"FixedDistance" | "FixedToWorld" | "FixedDistanceOrigin" | "FixedToPlane"Determines the behavior of drag if onDrag is specified. The default value is "FixedDistance".

FixedDistance: Dragging is limited to a fixed radius around the user, dragged from the point at which the user has grabbed the geometry containing this draggable node

FixedDistanceOrigin: Dragging is limited to a fixed radius around the user, dragged from the point of this node's position in world space.

FixedToWorld: Dragging is based on intersection with real world objects. Available only in AR

FixedToPlane: Dragging is limited to a fixed plane around the user. The configuration of this plane is defined by the dragPlane property.

ignoreEventHandling

TypeDescription
booleanWhen set to true, this control will ignore events and not prevent controls behind it from receiving event callbacks.

The default value is false.

onAmbientLightUpdate

TypeDescription
(intensity, colorTempurature) => voidFunction that provides an estimate of the light intensity and color temperature.

intensity: a number representing the estimated intensity of the ambient light as detected by the camera

colorTemperature: a number representing the estimated colorTemperature of the ambient light as detected by the camera

Web, 3.2.2+: onAmbientLightUpdate works on web, estimated from the camera feed about four times a second and smoothed. It reports { intensity, color }: an intensity of 1000 is a neutrally lit room, as on ARKit and ARCore, and color is a hex string. Editor scenes use it to scale their light rig. See Web Setup Guide.

onAnchorFound

TypeDescription
(anchor) => voidCalled when the AR system finds an Anchor.

See Anchor.

onAnchorUpdated

TypeDescription
(anchor) => voidCalled when the AR system detects changed properties of a previously found Anchor.

See Anchor.

Android, 3.2.1+: a cloud anchor resolved with the reactvision provider is an ARCore anchor, and onAnchorUpdated reports it under the resolve result's anchor.anchorId as ARCore refines its pose. See Cloud Anchors.

onAnchorRemoved

TypeDescription
() => voidCalled when the AR system detects that a previously found Anchor no longer exists

See Anchor.

onARPointCloudUpdate

{  
  "pointCloud": {
    "points" : [ 
      [x, y, z, confidence], 
      ... 
     ],
    "identifiers": [ 
      identifier1, 
      identifier2, 
      ... 
    ] 
  }
}
TypeDescription
(pointCloud) => voidThis callback will invoke whenever the point cloud is updated. pointCloud is a Javascript object containing the point cloud in the format above:

where: x, y, z - represents the x,y,z coordinates of the point in world space.

confidence - is a float value from 0 -> 1 that represents the confidence that the underlying system has for this point (Android only).

identifier - is a number that is unique to the corresponding point in the points array that allow the user to track points between point cloud updates (iOS only)

Web, 3.3.0+: works, from the web tracker's feature points, once its scale is in metres. confidence is always 1, because the web tracker has none, and identifiers are stable between updates. Needs @reactvision/viro-web-renderer 1.4.0; on 1.3.0 it warns once and does nothing.

onCameraARHitTest

Web, 3.2.3+: fires on web, including on a virtual camera's planes. Results use the same ViroARHitTestResult shape as the other hit tests (planes only; 3.3.0+: also FeaturePoint while a point cloud prop is set).

{    
  "hitTestResults": [ 
    [ARHitTestResult1], [ARHitTestResult2], ...
  ],
  "cameraOrientation": {
    position: [x, y, z],
    rotation:[x, y, z],
    forward:[x, y, z],
    up[x, y, z]
  }
}
TypeDescription
If defined, a callback is invoked returning the camera position and orientation along with a set of hit results in an array consisting of ARHitTestResult objects. The hit test results correspond to the AR points found by the AR system defined by the ray shooting from the camera direction and position. This can be used to show a tracking plane placed in the world while the user moves or to inform the user of the confidence of the area being looked at.

If defined, this callback is invoked as often as possible in order to keep with the frame rate.

The above object structure is returned.

ARHitTestResult format found here.

cameraOrientation consists of position, the rotation of the camera in degrees, and the current forward and up vectors of the camera.

onCameraTransformUpdate

{
  cameraTransform: {    
    position : [posX, posY, posZ],
    rotation : [rotX, rotY, rotZ],
    forward : [forwardX, forwardY, forwardZ],    
    up : [upX, upY, upZ],  
  }
}
TypeDescription
(updateObj) => voidA callback invoked when the camera changes (at most, once per frame).

Returns the value as an object:

pos - position (in world coordinates) of the camera

rot - rotation (in world coordinates) of the camera in Euler angles (degrees).
forward - the forward vector of the camera (in world coordinates
up - the up vector of the camera (in world coordinates)

Web, 3.2.2+: onCameraTransformUpdate works on web, once per frame the camera has moved. It carries position, rotation (Euler degrees), forward and up, also under the cameraTransform key. It reads the AR session's camera, the virtualCamera, or the 3D navigators' default camera. In 3.2.2, with a ViroCamera or ViroOrbitCamera as the point of view the pose is not known and it warns; 3.2.3 adds reads under a perspective camera component in a 3D scene, and 3.3.0 adds them while that camera is the point of view in live AR. Reads under an orthographic projection in a 3D scene are a known web limitation.

onClick

See ViroNode onClick.

Web, 3.2.3+: scene-level onClick, onClickState, onHover, onPinch, onRotate and onFuse fire when the event is not captured on a node. A tap on empty space reports position [], as native does. onTransformUpdate and ignoreEventHandling also work.

onClickState

See ViroNode onClickState.

onCollision

See ViroNode onCollision.

onDrag

See ViroNode onDrag.

Android, 3.4.0+: scene-level onDrag, onPinch and onRotate, with dragType and dragPlane, fire on Android as on iOS.

onFuse

See ViroNode onFuse.

onHover

See ViroNode onHover.

onPinch

See ViroNode onPinch.

onPlatformUpdate

const handlePlatformUpdate = (platformInfo) => {
  const platform = platformInfo.vrPlatform;
  const headset = platformInfo.headset;
  const controller = platformInfo.controller;
}
TypeDescription
Callback method set to be notified of platform specific information like headset type or controller type.

Example Code:

Supported platforms: gvr, ovr-mobile
Supported Headsets: cardboard, daydream, gearvr
Supported Controllers: cardboard, daydream, gearvr

onRotate

See ViroNode onRotate.

onScroll

See ViroNode onScroll.

onSwipe

See ViroNode onSwipe.

onTouch

See ViroNode onTouch.

onTrackingInitialized (deprecated)

TypeDescription
WARN: This function will be deprecated in the upcoming release, in favor of onTrackingUpdated.

Function called when the AR system has properly initialized. The platform maintains a right-handed coordinate system, where the origin of the system is the user's location at the time AR tracking was initialized. The camera's forward vector is [0, 0, -1] and up vector is [0,1,0].

onTrackingUpdated

TypeDescription
FunctionInvoked when the tracking state of the device changes. The tracking state indicates how well the device is able to track its position within the real world. Tracking state is subject to lighting conditions, the speed at which the device is moving, and other environmental factors.

Tracking states include:

TRACKING_UNAVAILABLE (1): Tracking is unavailable: the camera's position in the world is not known.

TRACKING_LIMITED (2): Tracking is available, but the camera's position in the world may be inaccurate and should not be used with confidence.

TRACKING_NORMAL (3): Camera position tracking is providing optimal results.

For iOS, a possible diagnosis for limited tracking quality is provided in the second parameter: "reason". These states include:

TRACKING_REASON_NONE (1): The current tracking state is not limited.

TRACKING_REASON_EXCESSIVE_MOTION (2): The device is moving too fast for accurate position tracking.

TRACKING_REASON_INSUFFICIENT_FEATURES (3) The scene visible to the camera does not contain enough distinguishable features for optimal position tracking.

TRACKING_REASON_INSUFFICIENT_LIGHT (4) (Android 3.1.0+, web 3.2.3+): There is too little light for tracking. iOS does not report it.

Web, 3.3.0+ (viro-web-renderer 1.4.0): a frame the tracker still tracks but flags with a reason (excessive motion, too few features or too little light) is reported as TRACKING_LIMITED with that reason, as ARKit does, and content keeps drawing. With renderer 1.3.0 those frames were reported as TRACKING_NORMAL.

Sample code: (Note that we use ViroConstants to properly compare different tracked states):

const handleTrackingUpdated = (state, reason) => {
  if (state == ViroConstants.TRACKING_NORMAL) {
    // Show my AR Scene experience    
  } else if (state == ViroConstants.TRACKING_NONE) {
    // Prompt user to move phone around    
  }  
}

Android, 3.2.1+: UNAVAILABLE reaches onTrackingUpdated about 200 ms after tracking drops, not on the first frame without it, and NORMAL is still reported at once. Together with a camera config capped at 1920×1080 at 30 fps and paused planes being kept, this stops tracking alternating between UNAVAILABLE and NORMAL on phones that could not sustain Viro's camera config, such as the Galaxy A56 (#568).

postProcessEffects

TypeDescription
string[]Specifies which post-process effects to enable. Refer to Post-Process Effects for more information.

Web, 3.2.3+: postProcessEffects works on ViroARScene and ViroScene. Unknown names are skipped with a warning. Needs @reactvision/viro-web-renderer 1.3.0.

physicsWorld

interface PhysicsWorld {
  // required
  gravity: number[],
  drawBounds: boolean
}
TypeDescription
PhysicsWorld (see above)Contains and processes the physics bodies of all viro controls that have been physics enabled in this scene. Environmental physics properties are also applied, like gravity.

gravity - A constant gravitational acceleration that is applied to all physics body objects in this scene. It is a vector in the terms of meters per second. Defaults to [0, -9.81, 0].

drawBounds - If true, renders the mesh representing the shape of all physics bodies in this scene.

soundRoom

Code Example:

soundRoom={{
  size: {[2,2,2]},
  wallMaterial: "acoustic_ceiling_tiles",
  ceilingMaterial: "glass_thin",
  floorMaterial: "concrete_block_coarse"
}}
TypeDescription
Describes the acoustic properties of the room around the user by allowing the developer to describe the room based on its dimensions and its surface properties. Note: This is not supported in Cardboard iOS.

List of soundRoom properties:

size - The 3D dimensions of the room.
wallMaterial - Sound Material for the four walls.
ceilingMaterial - Sound Material for the ceiling
floorMaterial - Sound Material for the floor

List of Supported Sound Materials:
acoustic_ceiling_tiles Acoustic ceiling tiles, absorbs most frequencies.
brick_bare - Bare brick, relatively reflective.
brick_painted - Painted brick
concrete_block_coarse - Coarse surface concrete block.
concrete_block_painted - Painted concrete block.
curtain_heavy - Heavy curtains.
fiber_glass_insulation - Fiber glass insulation.
glass_thin - Thin glass.
glass_thick - Thick glass.
grass - Grass.
linoleum_on_concrete - Linoleum on concrete.
marble - Marble.
metal - Galvanized sheet metal.
parquet_on_concrete - Wooden parquet on concrete.
plaster_rough - Rough plaster surface.
plaster_smooth - Smooth plaster surface.
plywood_panel - Plywood panel
polished_concrete_or_tile - Polished concrete or tile surface.
sheet_rock - Sheet rock
transparent - Acoustically transparent material, reflects no sound.
water_or_ice_surface - Surface of water or ice.
wood_ceiling - Wooden ceiling.
wood_panel - Wood paneling.

rotation

TypeDescription
[number, number, number]The rotation of the component around it's local axis specified as Euler angles [x, y, z]. Units for each angle are specified in degrees.

style

TypeDescription
StylesstylePropType

transformBehaviors

TypeDescription
PropTypes.arrayOf(PropTypes.string)Put the PropType Description here.

Methods

async findCollisionsWithRayAsync(from: number[], to: number[], closest: boolean, viroTag: string)

This function is used to find collisions between physics bodies and a line emanating from the given from position to the to position. Collided components have their onCollision callbacks invoked.

Parameters

from: the origin position of the line||to|the end position of the line
closest: if true, only the first object intersected by the line (determined by closest distance to the origin) receives the onCollision callback
viroTag: the string tag passed to collided components' onCollision callbacks

Returns

returns true/false whether or not a collision was detected

async findCollisionsWithShapeAsync(from: number[], to: number[], shapeString: string, shapeParam: object, viroTag: string)

This function is used to find collisions between physics bodies and the given shape moving from the given from position to the to position. Collided components have their onCollision callbacks invoked.

If the from and to positions are the same, then this function invokes the onCollision callbacks of all components within the given shape.

Parameters

from: the origin position of the line
to: the end position of the line
shapeString: the name of the shape to use in this test
shapeParam: the configuration of the shape used in this collision test
viroTag: the string tag passed to collided components' onCollision callbacks

Returns

true/false whether or not a collision was detected|

async getCameraOrientationAsync()

This function is used to fetch the current Camera's orientation.

Web, 3.2.2+: works on web, with getCameraPositionAsync(), which resolves to the camera's position. Both reject before an AR session has started, because there is no camera pose yet. In 3.2.3, both also work under a perspective ViroCamera or ViroOrbitCamera in a 3D scene. 3.3.0+: they also work while such a camera is the point of view in live AR, and report the drawn camera: the camera node's position with the device's rotation, as native does. Reads under an orthographic projection in a 3D scene are a known web limitation.

Returns

an object that contains the camera's position, rotation, forward vector and up vector as number arrays

async performARHitTestWithRay(ray: number[])

On Meta Quest (3.0.2+), AR hit tests from JS are supported (WithRay / WithWorldPoints).

This function performs a AR system-backed hit test with the given ray from the camera's position outward.

Web, 3.2.2+: the four performARHitTest... methods work on web and return ViroARHitTestResults. The web tracker finds planes only, so a hit is ExistingPlaneUsingExtent inside a plane's detected rectangle and ExistingPlane on its extension, with hasDepthData false.

Web, 3.3.0+: with onARPointCloudUpdate or displayPointCloud set, a hit can also be FeaturePoint: the tracker's feature point nearest the ray, with no anchor. Under a scene ViroCamera or ViroOrbitCamera in live AR, performARHitTestWithRay and performARHitTestWithPosition start from the drawn camera (the camera node's position with the device's rotation), as on native; performARHitTestWithPoint tests from the device's view, as ARKit and ARCore do.

returns

returns an array of ARHitTestResult corresponding to the AR points found by the AR system along the ray.

async performARHitTestWithPosition(position: number[])

This function performs an AR system-backed hit test with the ray from the camera to the given position.

Returns

returns an array of ARHitTestResult corresponding to the AR points found by the AR system along the ray.

async performARHitTestWithPoint(x: number, y: number)

This function performs an AR system-backed hit test with the given 2D screen coordinates in pixels. You may need to scale the x and y position by the pixel ratio to get the correct result:

For example:

performARHitTestWithPoint(evt.nativeEvent.locationX * PixelRatio.get(), evt.nativeEvent.locationX * PixelRatio.get()) 

Returns

returns an array of ARHitTestResult corresponding to the AR points found by the AR system along the ray.

async performARHitTestWithWorldPoints(points: number[][]) (Quest / 3.0.2+)

Web, 3.2.2+: takes two arguments, (origin, destination), and tests the segment between them.

Performs an AR system-backed hit test against the given world-space points. Available on Meta Quest from 3.0.2 alongside performARHitTestWithRay (Quest hit tests no longer crash or return black results).

Returns

An array of ARHitTestResult.

async createAnchoredNode(hitResult: ViroARHitTestResult)

Creates a native AR anchor at the location of a hit test result from one of the performARHitTest... methods, and returns its reference: nodeId, reactTag, anchorId and transform (position, rotation, scale). Hit test results are only valid for 30 seconds, so call it soon after the hit test. It throws if the result has no ID (it did not come from a performARHitTest... method).

⚠️

Nothing can be attached to this anchor: no component takes the returned reference, and its transform is the one at creation and is not updated. To keep placed content in place, render it as a direct child of ViroARScene at the hit position; Viro anchors each direct child once tracking is normal. See Content at the root of the scene stays put.

Returns

A promise that resolves to the anchor's reference, or null if it failed.

ARHitTestResult

These are the individual objects in the array of ARHitTestResults returned by the two performARHitTest... functions.

interface ArHitTestResult {
  type: "ExistingPlaneUsingExtent" | "ExistingPlane" | "EstimatedHorizontalPlane" | "FeaturePoint" | "DepthPoint",
  transform: {
    position: number[],
    rotation: number[],
    scale: number[]
  }
}
KeyTypeDescription
type"ExistingPlaneUsingExtent" | "ExistingPlane" | "EstimatedHorizontalPlane" | "FeaturePoint" | "DepthPoint"The type of point returned. DepthPoint is new in v2.53.0 and returned when depthEnabled is set on ViroARSceneNavigator.
transformobjectThe transform of the point. Contains the following keys: position, rotation, scale as arrays of numbers.

Anchor

This is the object given to the developer through the onAnchorFound, onAnchorUpdated and onAnchorRemoved callback functions.

KeyValue
anchorIdstringId of the anchor
typestringtype of the anchor
positionarrayOf(number)Position of the anchor in world coordinates.
rotationarrayOf(number)Rotation of the rotation of the anchor in degrees.
center (ViroARPlane only)arrayOf(number)Center of the plane relative to the plane's position.
alignment (ViroARPlane only)stringThe plane alignment, one of the following values:"horizontal" - iOS only"HorizontalDownwards" - Android only"HorizontalUpwards" - Android only"NonHorizontal" - Android only
width (ViroARPlane only)numberCurrent width of the attached plane
height (ViroARPlane only)numberCurrent height of the attached plane
verticesarrayOf(arrayOf(number))An array of 3D points representing the vertices along the boundary of a polygonal plane for thisViroARPlane. Although the contents of this property consist of 3D points, the represented polygonal plane is always two-dimensional, and is always positioned in only the x and z axis. This points are always placed relative to the ViroARPlane's center transform.
trackingMethod (ViroARImageMarker & Android only)Android only**String**The current tracking method used to keep track of the Image Marker Anchor. It can be one of the following values:"notTracking" - image marker hasn't yet been found"tracking" - image marker is actively being tracked"lastKnownPose" - image marker isn't currently being tracked but instead rendered based on its last known pose

Post-Process Effects

EffectDescription
grayscaleAn effect where the resulting image is in black and white.
sepiaAn effect where the resulting image has a dark reddish-brown pigment color effect on it.
sincityA sin-city like effect where the resulting image is in black and white, except for places where there is saturated red colors.
baralleldistortionA fish-eye-like effect where the fish eye lens distortion becomes more pronounce towards the center of the image.
pincushiondistortionA cushioning effect where the resulting image is "pinched" into the center.
thermalvisionA coloring effect where the resulting image gives of a "radiant heat" look from a thermal sensor.
crosshatchAn effect where the resulting image is made up of tiny crossed lines that recreates the scene.
pixelatedAn effect where the resulting image is pixelized.