### Importing and Starting Basic Components Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_scene_intro.html
Shows how to import the `startBasicComponents` function and initialize the Matterport SDK to run the basic components example.
```javascript
import { startBasicComponents } from './basicComponent';
const mpSdk; // initialized from a successful `connect` call
startBasicComponents(mpSdk);
```
--------------------------------
### Complete SDK Bundle Quick Start Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_quickstart.html
A full HTML example demonstrating how to embed a Matterport model, connect to the SDK, and retrieve model data. Ensure your SDK Key is included in the iframe source URL.
```html
SDK Bundle Quickstart
```
--------------------------------
### Start Development Server
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_setup.html
Start the local development environment using yarn start. This command is used to host the local environment for testing the tutorial.
```bash
> yarn start
```
--------------------------------
### Start Development Server
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent_tutorial.html
Start the development server using the 'dev' script defined in package.json.
```bash
yarn dev
```
```bash
npm run dev
```
--------------------------------
### Start a Tour
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/modules/tour.html
Initiate a tour playback using the `start()` method. An optional index can be provided to start at a specific snapshot. The method returns a promise upon completion.
```javascript
const tourIndex = 1;
mpSdk.Tour.start(tourIndex)
.then(function() {
// Tour start complete.
})
.catch(function(error) {
// Tour start error.
});
```
--------------------------------
### Tour API Usage Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/modules/tour.html
This example demonstrates how to connect to the SDK and use various Tour API methods to control and monitor a tour. It includes event listeners for tour events and sequential calls to start, navigate, and stop the tour.
```APIDOC
## Tour API Methods
### Description
Provides methods to control and query the state of a Matterport tour. This includes starting, stopping, stepping through the tour, and retrieving tour data.
### Methods
* **`Tour.Event.on(Tour.Event.STEPPED, callback)`**
* Description: Subscribes to the event triggered when the tour moves to a new step. The callback receives the index of the new step.
* Parameters:
* `Tour.Event.STEPPED` (string): The event name for step changes.
* `callback` (function): Function to execute when the event is triggered, receiving the new tour index.
* **`Tour.Event.on(Tour.Event.STARTED, callback)`**
* Description: Subscribes to the event triggered when the tour begins playback. The callback is executed upon tour start.
* Parameters:
* `Tour.Event.STARTED` (string): The event name for tour start.
* `callback` (function): Function to execute when the tour starts.
* **`Tour.Event.on(Tour.Event.STOPPED, callback)`**
* Description: Subscribes to the event triggered when the tour stops playback. The callback is executed upon tour stop.
* Parameters:
* `Tour.Event.STOPPED` (string): The event name for tour stop.
* `callback` (function): Function to execute when the tour stops.
* **`Tour.getData()`**
* Description: Retrieves data about the tour, such as the number of stops.
* Returns: A Promise that resolves with an array representing the tour stops.
* **`Tour.start(index)`**
* Description: Starts the tour playback from the specified step index.
* Parameters:
* `index` (number): The index of the step to start the tour from.
* Returns: A Promise that resolves when the tour has started.
* **`Tour.next()`**
* Description: Advances the tour to the next step.
* Returns: A Promise that resolves when the tour has moved to the next step.
* **`Tour.prev()`**
* Description: Moves the tour back to the previous step.
* Returns: A Promise that resolves when the tour has moved to the previous step.
* **`Tour.step(index)`**
* Description: Jumps the tour directly to the specified step index.
* Parameters:
* `index` (number): The index of the step to jump to.
* Returns: A Promise that resolves when the tour has reached the specified step.
* **`Tour.stop()`**
* Description: Stops the tour playback.
* Returns: A Promise that resolves when the tour has stopped.
### Sample Code
```javascript
const connect = function(sdk) {
const mpSdk = sdk;
mpSdk.Tour.Event.on(Tour.Event.STEPPED, function(tourIndex){
console.log('Tour index ' + tourIndex);
});
mpSdk.Tour.Event.on(Tour.Event.STARTED, function(){
console.log('Tour started');
});
mpSdk.Tour.Event.on(Tour.Event.STOPPED, function(){
console.log('Tour stopped');
});
mpSdk.Tour.getData()
.then(function(tour) {
console.log('tour has ' + tour.length + ' stops');
return mpSdk.Tour.start(0);
})
.then(function(){
// console 'Tour started'
// console -> 'Tour index 0'
return mpSdk.Tour.next();
})
.then(function(){
// console -> 'Tour index 1'
return mpSdk.Tour.step(3);
})
.then(function(){
// console -> 'Tour index 3'
return mpSdk.Tour.prev();
})
.then(function(){
// console -> 'Tour index 2'
// console -> 'Tour stopped'
return mpSdk.Tour.stop();
});
}
```
```
--------------------------------
### Create Scene Objects and Nodes
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_scene_intro.html
Demonstrates the basic setup for creating a scene in the Matterport SDK. It shows how to instantiate objects, add nodes to them, and start the scene.
```javascript
const [sceneObject] = await mpSdk.Scene.createObjects(1);
// if we only want one node:
const node = sceneObject.addNode(/* optionally, we can set the node's id here */);
// ... we will be registering and adding components to nodes here in the following sections
// and finally start running the components in our scene
sceneObject.start();
```
--------------------------------
### Install Web Component with NPM
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent.html
Install the @matterport/webcomponent and three.js packages using NPM.
```bash
npm install @matterport/webcomponent three
```
--------------------------------
### Start Tour and Get Snapshots
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_types.html
Defines functions to start a tour and retrieve tour snapshots using the Tour namespace. It demonstrates how to import and use the Tour type and its associated methods.
```typescript
// tourControls.ts
import { Tour } from './mp/sdk'
export function startTour(tour: Tour) {
tour.start();
}
// use the Snapshot type through the Tour type
export function getTourSnapshots(tour: Tour): Promise {
return tour.getData();
}
// index.ts
import { MpSdk } from './mp/sdk';
import { startTour } from './tourControls.ts'
async function useTourControls(mpSdk: MpSdk) {
startTour(mpSdk.Tour);
// use the Snapshot type through the MpSdk type
const tourSnapshots: MpSdk.Tour.Snapshot[] = await getTourSnapshots(mpSdk.Tour);
}
```
--------------------------------
### Complete SDK Integration Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_quickstart.html
A full HTML example demonstrating how to embed the Matterport Showcase Player and connect to it using the SDK. Replace '[YOUR_SDK_KEY_HERE]' with your actual SDK key.
```html
```
--------------------------------
### Embed Web Component with URL Parameters
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent_migration.html
Demonstrates how to use the `` component and pass URL parameters as attributes. This example sets the model and enables quickstart and MLS options.
```html
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_using_oauth.html
Installs the necessary Node.js dependencies for the monorepo and its bundles. Run these commands after downloading the starter project.
```bash
yarn install
yarn install-bundle
```
--------------------------------
### IComponent Implementation Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.icomponent.html
This example demonstrates how to implement a custom component, define its inputs and lifecycle methods, and register it with the SDK.
```APIDOC
## Implementing and Registering a Custom Component
### Description
This example shows how to create a custom component, define its properties and lifecycle methods (`onInit`, `onEvent`, `onInputsUpdated`, `onTick`, `onDestroy`), and register it with the Matterport SDK using `sdk.Scene.register()`.
### Component Implementation (`Box`)
```javascript
function Box() {
this.inputs = {
visible: false,
};
this.onInit = function() {
var THREE = this.context.three;
var geometry = new THREE.BoxGeometry(1, 1, 1);
this.material = new THREE.MeshBasicMaterial();
var mesh = new THREE.Mesh( geometry, this.material );
this.outputs.objectRoot = mesh;
};
this.onEvent = function(type, data) {
// Handle events
};
this.onInputsUpdated = function(previous) {
// Respond to input changes
};
this.onTick = function(tickDelta) {
// Called on every frame update
};
this.onDestroy = function() {
this.material.dispose();
};
}
```
### Component Factory (`BoxFactory`)
```javascript
function BoxFactory() {
return new Box();
}
```
### Registration
```javascript
// Registering the component with the sdk
sdk.Scene.register('box', BoxFactory);
```
### Lifecycle Methods
* **`onInit()`**: Called when the component is initialized. Used for setup, like creating Three.js objects.
* **`onEvent(type, data)`**: Handles custom events emitted by the SDK or other components.
* **`onInputsUpdated(previous)`**: Called when component inputs change. `previous` contains the old input values.
* **`onTick(tickDelta)`**: Executed on each frame render. `tickDelta` is the time elapsed since the last tick.
* **`onDestroy()`**: Called when the component is destroyed. Used for cleanup, like disposing Three.js materials.
### Properties
* **`inputs`**: An object defining the input properties for the component.
* **`outputs`**: An object where you can assign properties that will be exposed as outputs, such as `objectRoot` for the Three.js mesh.
* **`context`**: Provides access to the rendering engine (e.g., `this.context.three`).
* **`material`**: (Example specific) A reference to the Three.js material for cleanup.
```
--------------------------------
### Install Web Component with Yarn
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent.html
Install the @matterport/webcomponent and three.js packages using Yarn.
```bash
yarn add @matterport/webcomponent three
```
--------------------------------
### Start Tour
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/modules/tour.html
Initiates a tour, optionally starting at a specific snapshot.
```APIDOC
## start
`mpSdk.Tour.start(index?: number): Promise`
Starts the tour. If an index is provided, the tour will begin at that specific snapshot.
#### Parameters
* **index** (number) - Optional - The zero-based index of the snapshot to start the tour from. If omitted, the tour starts from the first snapshot.
```javascript
const tourIndex = 1;
mpSdk.Tour.start(tourIndex)
.then(function() {
console.log('Tour start complete.');
})
.catch(function(error) {
console.error('Tour start error: ', error);
});
```
```
--------------------------------
### Tour Started Event
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/index.html
This event fires when the guided tour within the showcase begins.
```APIDOC
## mpSdk.on(mpSdk.Tour.Event.STARTED, callback)
### Description
This event fires when the tour has started.
### Parameters
* **event**: `mpSdk.Tour.Event.STARTED` - The event to listen for.
* **callback**: `function(): void` - The function to execute when the event fires.
### Example
```javascript
mpSdk.on(mpSdk.Tour.Event.STARTED,
function() {
console.log('Tour started!');
}
);
```
### Returns
`[Emitter](interfaces/emitter.html)`
```
--------------------------------
### Install Three.js
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent_tutorial.html
Install the Three.js library. Note that only the version specified in package.json's peerDependencies is officially supported.
```bash
yarn add three@0.151
```
```bash
npm install three@0.151
```
--------------------------------
### Custom Tour Logic with SDK
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/modules/tour.html
Demonstrates how to use the Matterport SDK's Tour API to control and respond to tour events. This example logs tour events, retrieves tour data, starts the tour, navigates through steps, and stops the tour.
```javascript
const connect = function(sdk) {
const mpSdk = sdk;
mpSdk.Tour.Event.on(Tour.Event.STEPPED, function(tourIndex){
console.log('Tour index ' + tourIndex);
});
mpSdk.Tour.Event.on(Tour.Event.STARTED, function(){
console.log('Tour started');
});
mpSdk.Tour.Event.on(Tour.Event.STOPPED, function(){
console.log('Tour stopped');
});
mpSdk.Tour.getData()
.then(function(tour) {
console.log('tour has ' + tour.length + ' stops');
return mpSdk.Tour.start(0);
})
.then(function(){
// console 'Tour started'
// console -> 'Tour index 0'
return mpSdk.Tour.next();
})
.then(function(){
// console -> 'Tour index 1'
return mpSdk.Tour.step(3);
})
.then(function(){
// console -> 'Tour index 3'
return mpSdk.Tour.prev();
})
.then(function(){
// console -> 'Tour index 2'
// console -> 'Tour stopped'
return mpSdk.Tour.stop();
});
}
```
--------------------------------
### Install Matterport SDK
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_tutorials_package.html
Install the Matterport SDK package using either npm or yarn.
```bash
npm install @matterport/sdk
```
```bash
yarn add @matterport/sdk
```
--------------------------------
### Install Webpack Dependencies
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_tutorials_package.html
Install Webpack and essential plugins for building your project. Use either NPM or Yarn.
```bash
# npm
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
# yarn
yarn add --dev webpack webpack-cli webpack-dev-server html-webpack-plugin
```
--------------------------------
### Import and Start Bound Components
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_connecting_components.html
Provides instructions on how to import and initialize the `startBoundComponents` function with an initialized `mpSdk` instance.
```javascript
import { startBoundComponents } from './basicComponent';
const mpSdk; // initialized from a successful `connect` call
startBoundComponents(mpSdk);
```
--------------------------------
### Install Webpack and Plugins
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent_tutorial.html
Install Webpack, Webpack CLI, Webpack Dev Server, and HTML Webpack Plugin as development dependencies.
```bash
yarn add --dev webpack webpack-cli webpack-dev-server html-webpack-plugin
```
```bash
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
```
--------------------------------
### start
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.iobject.html
Starts all nodes that are referenced by this scene object. This action typically initializes and activates the components and logic within the associated nodes.
```APIDOC
## start
### Description
Starts all nodes referenced by this scene object. This method is used to initiate the execution of all associated nodes and their components.
### Method
`start(): void`
### Returns
- **void** - This method does not return any value.
### Example
```javascript
// Assuming sceneObject is an instance of Scene.IObject
sceneObject.start();
```
```
--------------------------------
### Install Static Assets with NPM
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent.html
Install static assets for the web component using NPM. Replace YOUR_STATIC_ASSETS_DIR with your actual directory path.
```bash
npx matterport-assets YOUR_STATIC_ASSETS_DIR
```
--------------------------------
### Start Scene Object Nodes
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.iobject.html
The `start` method initiates all nodes associated with a scene object. This is a simple void function with no parameters.
```typescript
sceneObject.start();
```
--------------------------------
### start
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.inode.html
Transitions the scene node to the Operating state if it is currently Initializing. This method has no effect if the node is already Operating.
```APIDOC
## start(): void
### Description
Transitions the node to Operating if it is in the Initializing state. Calling this function has no effect if the node is already Operating.
### Method Signature
`start(): void`
### Returns
void
```
--------------------------------
### Integrate with Showcase SDK
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/oauth_private_model_embed.html
Provides an example of how to connect the Showcase SDK using an obtained access token.
```javascript
const mpSdk = await connect(iframe, {
auth: token
});
```
--------------------------------
### Start the OAuth Client Application
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_using_oauth.html
Starts the OAuth client application (webpack-dev-server). This command is run in a separate terminal tab to serve the frontend.
```bash
yarn start-app [--port ]
```
--------------------------------
### Start the OAuth Server
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_using_oauth.html
Starts the OAuth server application. This command is run in one terminal tab to serve the backend functionality.
```bash
yarn start-server [--port ]
```
--------------------------------
### Component Outputs Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.icomponent.html
This example demonstrates how to set the `objectRoot` and `collider` outputs within a component's `onInit` function. `objectRoot` is added to the scene graph, and `collider` is included in raycast detection.
```javascript
function Box() {
this.onInit = function() {
var THREE = this.context.three;
var geometry = new THREE.BoxGeometry(1, 1, 1);
this.material = new THREE.MeshBasicMaterial();
var mesh = new THREE.Mesh( geometry, this.material );
this.outputs.objectRoot = mesh; // gets added to the scene node
this.outputs.collider = mesh; // will now be part of raycast testing
}
}
```
--------------------------------
### Setup SDK in index.js
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_tutorials_package.html
Import the `setupSdk` function and initialize the SDK with your SDK key within an async function. Includes basic error handling.
```javascript
import { setupSdk } from '@matterport/sdk'
const main = async () => {
// Initialize SDK here
const mpSdk = await setupSdk('yourSdkKey')
}
main().catch(err => console.error('Error:', err))
```
--------------------------------
### Listen for Tour Started Event
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/index.html
Subscribe to the event that fires when the guided tour begins. This event does not pass any arguments to the callback function.
```javascript
mpSdk.on(mpSdk.Tour.Event.STARTED,
function() {
console.log('Tour started!');
}
);
```
--------------------------------
### Create and Attach a Hello World Sandbox
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_tutorials_htmlsandbox.html
Demonstrates how to create a new tag, register a static sandbox with custom HTML and CSS, and then attach the sandbox to the created tag.
```javascript
// create a tag
const [tagId] = await mpSdk.Tag.add({
label: 'Test Tag',
anchorPosition: { x: 0, y: 0, z: 0 },
stemVector: { x: 0, y: 0.3, z: 0 },
});
// register a static sandbox
const [sandboxId] = await mpSdk.Tag.registerSandbox(`
Hello, Sandbox!
`);
// associate (attach) the sandbox to the tag
mpSdk.Tag.attach(tagId, sandboxId);
```
--------------------------------
### Get Model Dimensions
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/modelapi_snippets.html
Query the Model API to retrieve dimensions and other geometric properties for a specific model. This example uses a GraphQL query with variables.
```graphql
query getDimensions($modelId: ID!) {
model(id: $modelId) {
name
description
dimensions {
...dimensions
}
floors {
label
dimensions(units: imperial) {
...dimensions
}
}
rooms {
id
label
tags
dimensions {
...dimensions
}
}
}
}
fragment dimensions on Dimension {
areaCeiling
areaFloor
areaFloorIndoor
areaWall
volume
depth
height
width
units
}
```
```json
{
"modelId": "FE1FLGnch5h"
}
```
--------------------------------
### Initialize NPM or Yarn Project
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_tutorials_package.html
Initialize a new project using either NPM or Yarn. Accept the default values for all prompts.
```bash
mkdir mp-sdk
cd mp-sdk
# npm
npm init
# yarn
yarn init
```
--------------------------------
### Serialize and Deserialize Scene Objects
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_using_scene_objects.html
This example shows how to serialize a scene object to a JSON string and then deserialize it back. This is useful for saving and restoring the state of scene objects, including their nodes, components, bindings, and paths. Ensure the scene object is started before serialization and after deserialization.
```typescript
// Starting from the previous example, serialize the scene object to a json string
// after having started it. All nodes, components, bindings and paths are preserved.
const serializedString = await sdk.Scene.serialize(sceneObject);
// To restore the scene object, deserialize and start it.
const deserializedSceneObject = await mpSdk.Scene.deserialize(serializedString);
deserializedSceneObject.start();
```
--------------------------------
### Creating and Managing Scene Nodes and Components
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_architecture.html
Demonstrates how to create scene objects, add nodes, attach components with initial inputs, start the node, and stop it.
```javascript
// Create a scene object. `createObjects` can create multiple objects and returns an array with that number of objects
const [sceneObject] = await sdk.Scene.createObjects(1)
// Create a scene node with an optional unique id
const node = sceneObject.addNode('my-node')
// Adding a component to 'my-node' with optional initialInputs and option id
const initialInputs = {
url: 'https://cdn.jsdelivr.net/gh/mrdoob/three.js@dev/examples/models/fbx/stanford-bunny.fbx',
}
const component = node.addComponent('mp.fbxLoader', initialInputs, "my-component")
// Start 'my-node'
node.start()
// Destroying a scene node
node.stop()
```
--------------------------------
### Install Three.js Types (TypeScript)
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent_tutorial.html
If using TypeScript, install the corresponding Three.js types.
```bash
yarn add --dev @types/three
```
```bash
npm install --save-dev @types/three
```
--------------------------------
### Clone Showcase SDK Tutorial Repository (HTTPS)
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_setup.html
Clone the Matterport Showcase SDK tutorial repository using HTTPS and install dependencies.
```bash
> git clone https://github.com/matterport/showcase-sdk-tutorial.git
> cd showcase-sdk-tutorial
> yarn install
```
--------------------------------
### Create Scene Objects and Add Lights
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_models.html
Sets up the scene by creating a scene object and adding a lighting component. Ensure lights are added, otherwise models will appear black.
```javascript
const [ sceneObject ] = await sdk.Scene.createObjects(1);
const lights = sceneObject.addNode();
lights.addComponent('mp.lights');
lights.start();
```
--------------------------------
### Clone Showcase SDK Tutorial Repository (SSH)
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_tutorials_setup.html
Clone the Matterport Showcase SDK tutorial repository using SSH and install dependencies.
```bash
> git clone git@github.com:matterport/showcase-sdk-tutorial.git
> cd showcase-sdk-tutorial
> yarn install
```
--------------------------------
### Configure SDK with Multiple Options
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent_advanced.html
Set multiple application-level configuration properties like 'exampleOne' and 'exampleTwo' using 'config-' prefixed attributes.
```html
```
--------------------------------
### Remove Model Share Access (Example)
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/accountapi_changelog.html
Example mutation to remove a user's access to a specific model.
```graphql
mutation {
removeModelShareAccess(userId:"r6wRPLhXvjz", modelId:"pcJ2TYcQPDo")
}
```
--------------------------------
### Import and Connect to Showcase SDK
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_types.html
Demonstrates how to import the ShowcaseBundleWindow type, get the iframe content window, and connect to the MP_SDK using an SDK key. This is the initial step to interact with the SDK.
```typescript
import { ShowcaseBundleWindow } from './bundle/sdk';
const showcaseIframe = document.getElementById('showcase') as HTMLIFrameElement;
const showcaseWindow = showcaseElement.contentWindow as ShowcaseBundleWindow;
// connect the sdk and get the sdk object
const mpSdk = await showcaseWindow.MP_SDK.connect(showcaseIframe, '{YOUR SDK KEY}');
```
--------------------------------
### Mode Change Start Event
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/index.html
This event fires when the camera is starting to transition to a new mode. It provides the old and new modes.
```APIDOC
## mpSdk.on(mpSdk.Mode.Event.CHANGE_START, callback)
### Description
This event fires when the camera is starting to transition to a mode.
### Parameters
* **event**: `mpSdk.Mode.Event.CHANGE_START` - The event to listen for.
* **callback**: `function(oldMode: string, newMode: string): void` - The function to execute when the event fires.
* **oldMode**: `string` - The mode the camera is leaving.
* **newMode**: `string` - The mode the camera is entering.
### Example
```javascript
mpSdk.on(mpSdk.Mode.Event.CHANGE_START,
function(oldMode, newMode){
console.log('Mode changing from ' + oldMode);
console.log('Mode changing to ' + newMode);
}
);
```
### Returns
`[Emitter](interfaces/emitter.html)`
```
--------------------------------
### Initialize and Connect to SDK
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_concepts.html
Connect to the SDK within an iframe and handle potential errors. This is the initial step to interact with the Showcase SDK.
```javascript
try {
const mpSdk = await connect(iframe);
console.log('Hello SDK', mpSdk);
}
catch (e) {
console.error('Error', e);
}
```
--------------------------------
### Complete Import Workflow with Python
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/importapi_code_examples.html
This example demonstrates a complete import workflow using Python and the requests library. It supports multipart upload for large files, automatically splitting the upload into parts based on API constraints.
```Python
import os
import math
import base64
import requests
# ------------------------------------------------------------
# CONFIGURATION
# ------------------------------------------------------------
# Replace these with your ID and secret.
# You can find this in Settings -> Developer Tools -> API Token Management.
TOKEN_ID = ""
TOKEN_SECRET = ""
# Replace this with your org ID.
# You can find it in the settings as "Account ID".
ORG_ID = ""
# Replace this with the path to your E57 file locally.
FILE_PATH = ""
# ------------------------------------------------------------
# END OF CONFIGURATION - DO NOT EDIT BELOW THIS LINE
# ------------------------------------------------------------
ENDPOINT = "https://api.matterport.com/api/import/graph"
MAX_PART_SIZE = 5 * 1024 * 1024 * 1024 # 5 GB
def get_auth_header(token_id, token_secret):
credentials = f"{token_id}:{token_secret}"
base64_credentials = base64.b64encode(credentials.encode()).decode()
return {"Authorization": f"Basic {base64_credentials}"}
def run_query(query, variables=None):
headers = get_auth_header(TOKEN_ID, TOKEN_SECRET)
headers["Content-Type"] = "application/json"
payload = {"query": query, "variables": variables or {}}
response = requests.post(ENDPOINT, headers=headers, json=payload)
if response.status_code != 200:
raise Exception(f"Request failed: {response.status_code} - {response.text}")
result = response.json()
if "errors" in result:
raise Exception(f"GraphQL error: {result['errors']}")
return result["data"]
ADD_IMPORT_SESSION = """
mutation AddImportSession($organizationId: ID, $processType: ProcessType!, $name: String) {
addImportSession(organizationId: $organizationId, processType: $processType, name: $name) {
id
}
}
"""
ADD_E57_OBJECT = """
mutation AddE57Object($importSessionId: ID!, $e57: E57ObjectInput!) {
addE57Object(importSessionId: $importSessionId, e57: $e57) {
id
clientId
files {
id
name
clientId
size
}
}
}
"""
BEGIN_UPLOAD = """
mutation beginUpload($importSessionId: ID!, $importFileId: ID!) {
beginUpload(importSessionId: $importSessionId, importFileId: $importFileId) {
id
}
}
"""
REQUEST_PART_UPLOAD = """
mutation requestPartUpload($importSessionId: ID!, $importFileId: ID!, $part: Int!, $size: Long!) {
requestPartUpload(importSessionId: $importSessionId, importFileId: $importFileId, part: $part, size: $size) {
url
minSize
maxSize
headers {
key
value
}
method
completed
}
}
"""
```
--------------------------------
### Install Static Assets with Yarn
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdkbundle_webcomponent.html
Install static assets for the web component using Yarn. Replace YOUR_STATIC_ASSETS_DIR with your actual directory path.
```bash
yarn matterport-assets YOUR_STATIC_ASSETS_DIR
```
--------------------------------
### Patch Job Variables Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/capture_services_queries.html
Example variables for the patchJob mutation. Note that 'specialRequests' can be provided multiple times, with the last one taking precedence.
```json
{
"id": "agr36qzk217huz5qdqkd076ib",
"input": {
"specialRequests": "Hello Testing",
"contactName": "Mr. Point of Contact",
"contactEmail": "poc@mycompany.com",
"contactPhone": "888-736-8360",
"specialRequests": "Wear a red shirt",
"contactWillBeOnsite": false,
"scheduledStartTime": "2022-01-11T23:00:00Z"
}
}
```
--------------------------------
### Access Token Response Example
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/oauth_model_api.html
This is an example of the JSON response received after successfully requesting access tokens. It includes the access token, token type, expiration time, and refresh token.
```json
{
"access_token": "3mwbyppm4u0gz1z14ktqtiteb",
"token_type": "Bearer",
"expires_in": 3599,
"refresh_token": "ichxdbm59z74m6tkcbqi092rc:"
}
```
--------------------------------
### Add or Update Model Share Access (Example)
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/accountapi_changelog.html
Example mutation to add or update model share access for a user, specifying user ID, model ID, and role ID.
```graphql
mutation {
addOrUpdateModelShareAccess(userId:"r6wRPLhXvjz", modelId:"pcJ2TYcQPDo", roleId:"00000000002") {
user {
email
}
modelId
modelShareAccessLevel {
name
}
}
}
```
--------------------------------
### Implementing a Basic Box Component
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.icomponent.html
This example demonstrates how to implement a simple 'Box' component using the IComponent interface. It initializes a Three.js box geometry and material, and registers the component with the SDK under the name 'box'.
```javascript
function Box() {
this.inputs = {
visible: false,
};
this.onInit = function() {
var THREE = this.context.three;
var geometry = new THREE.BoxGeometry(1, 1, 1);
this.material = new THREE.MeshBasicMaterial();
var mesh = new THREE.Mesh( geometry, this.material );
this.outputs.objectRoot = mesh;
};
this.onEvent = function(type, data) {
}
this.onInputsUpdated = function(previous) {
};
this.onTick = function(tickDelta) {
}
this.onDestroy = function() {
this.material.dispose();
};
}
function BoxFactory() {
return new Box();
}
// Registering the component with the sdk
sdk.Scene.register('box', BoxFactory);
```
--------------------------------
### Example Phase Times Object
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/modules/app.html
Provides an example of the phaseTimes object within the State type. It shows epoch timestamps for various application phases, with 0 indicating a phase that has not yet occurred.
```typescript
{
phaseTimes: {
[Phase.UNINITIALIZED]: 1570084156590,
[Phase.WAITING]: 0,
[Phase.LOADING]: 0,
[Phase.STARTING]: 0,
[Phase.PLAYING]: 0,
[Phase.ERROR]: 0,
}
}
```
--------------------------------
### Handle Access Token Refreshing with SDK
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/oauth_private_model_embed.html
Demonstrates how to set up a token refresher using the SDK to seamlessly provide new access tokens to Showcase when the current one expires.
```javascript
const tokenEndpoint = 'https://yourdomain.com/yourapp/refresh';
const fetcher = {
async fetch() {
console.log('Refreshing Showcase Access Token');
try {
const response = await fetch(tokenEndpoint);
}
catch(e) {
console.log('Could not refresh access token', e);
}
const token = await response.json();
return token;
},
};
const initial_access_token_payload = await fetcher.fetch();
mpSdk.OAuth.createTokenRefresher(initial_access_token_payload, fetcher);
```
--------------------------------
### Initialize and Add Component to Scene Node
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/interfaces/scene.inode.html
Demonstrates creating a scene node, adding a glTF loader component, setting its position, and starting the node. Components must be added during the Initializing state.
```javascript
const [sceneObject] = await sdk.Scene.createObjects(1);
const node = sceneObject.addNode();
node.addComponent('mp.gltfLoader', {
url: 'http://www.someModelSite.com/rabbit.gltf'
});
node.position.set(0, 1, 0);
node.start();
```
--------------------------------
### Get Folder by ID
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/modelapi_changelog.html
This query retrieves a Folder object by its unique ID.
```graphql
query {
folder(id: ID!): Folder
}
```
--------------------------------
### Complete index.js with Interactions
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/sdk_tutorials_package.html
The full `index.js` file including SDK initialization, waiting for the app to load, and camera rotation.
```javascript
import { setupSdk } from '@matterport/sdk'
const main = async () => {
// Initialize SDK here
const mpSdk = await setupSdk('yourSdkKey')
await mpSdk.App.state.waitUntil(state => state.phase === mpSdk.App.Phase.PLAYING)
mpSdk.Camera.rotate(35, 0)
}
main().catch(err => console.error('Error:', err))
```
--------------------------------
### getLoadTimes
Source: https://github.com/matterport/showcase-sdk/blob/gh-pages/docs/reference/current/modules/app.html
Deprecated method. Use the `state` observable to get load times.
```APIDOC
## getLoadTimes
### Description
Deprecated. Use `App.state` observable to get load times.
### Method
`getLoadTimes()`
### Returns
`Promise