Display any 3D Tiles from a url.

Element informations
Name Value
Click on the scene to inspect object properties
100%
index.js
import { Toast } from "bootstrap";
import {
  AmbientLight,
  Color,
  DirectionalLight,
  GridHelper,
  MathUtils,
  Mesh,
  Vector3,
} from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";

import CoordinateSystem from "@giro3d/giro3d/core/geographic/CoordinateSystem.js";
import Instance from "@giro3d/giro3d/core/Instance.js";
import Tiles3D from "@giro3d/giro3d/entities/Tiles3D.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";

const TILESET_URL_INPUT_ID = "tileset_url";
const DEFAULT_URL =
  "https://3d.oslandia.com/3dtiles/19_rue_Marc_Antoine_Petit_ifc/tileset.json";
const input = document.getElementById(TILESET_URL_INPUT_ID);

input.placeholder = DEFAULT_URL;

const tmpVec3 = new Vector3();

function replace_window_url(enteredUrl) {
  const url = new URL(document.URL);
  url.searchParams.delete(TILESET_URL_INPUT_ID);

  url.searchParams.append(TILESET_URL_INPUT_ID, enteredUrl);

  window.history.replaceState({}, null, url.toString());
}

// init instance
const instance = new Instance({
  target: "view", // The id of the <div> to attach the instance
  crs: CoordinateSystem.epsg3857,
  backgroundColor: 0xcccccc,
});

// Add a sunlight
const sun = new DirectionalLight("#ffffff", 1.4);
sun.position.set(1, 0, 1).normalize();
sun.updateMatrixWorld(true);
instance.scene.add(sun);

// We can look below the floor, so let's light also a bit there
const sun2 = new DirectionalLight("#ffffff", 0.5);
sun2.position.set(0, -1, 1);
sun2.updateMatrixWorld();
instance.scene.add(sun2);

// Add ambient light
const ambientLight = new AmbientLight(0xffffff, 1);
instance.scene.add(ambientLight);
instance.view.minNearPlane = 0.5;

// create controls
const controls = new MapControls(instance.view.camera, instance.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
instance.view.setControls(controls);

// declare the tileset
let tileset = null;

// setup the error displaying
const toastLiveExample = document.getElementById("liveToast");
const toastBootstrap = Toast.getOrCreateInstance(toastLiveExample);
function displayError(evt) {
  document.getElementById("error").innerText = evt.error.message;
  toastBootstrap.show();
}

function run(url) {
  if (tileset != null) {
    instance.remove(tileset);
  }
  tileset = new Tiles3D({ url: url.toString() });

  // If the tileset comes from an ifc converted with py3dtiles, hide some elements that don't bring visual value
  tileset.addEventListener("object-created", (evt) => {
    const scene = evt.obj;
    scene.traverse((obj) => {
      if (obj.userData?.class === "IfcSpace") {
        obj.visible = false;
        instance.notifyChange();
      }
    });
  });

  instance.add(tileset).then(initializeCamera, displayError).catch(console.log);
}

function placeCamera(position, lookAt) {
  instance.view.camera.position.set(position.x, position.y, position.z);
  instance.view.camera.lookAt(lookAt);
  controls.target.copy(lookAt);
  StatusBar.updateUrl();
  instance.notifyChange(instance.view.camera);
}

// add pointcloud to scene
function initializeCamera() {
  const bbox = tileset.getBoundingBox();

  const ratio = bbox.getSize(tmpVec3).x / bbox.getSize(tmpVec3).z;

  const position = bbox
    .getCenter(new Vector3())
    .clone()
    .add(bbox.getSize(tmpVec3).multiply(new Vector3(-2, -2, ratio)));

  const lookAt = bbox.getCenter(tmpVec3);
  lookAt.z = bbox.min.z;

  placeCamera(position, lookAt);

  const grid = new GridHelper(60, 10);
  grid.rotateX(MathUtils.degToRad(90));

  grid.position.copy(lookAt);

  instance.add(grid);
  grid.updateMatrixWorld(true);
}

// url parsing and initialization
let tileset_url = new URL(document.URL).searchParams.get(TILESET_URL_INPUT_ID);

if (tileset_url == null) {
  tileset_url = DEFAULT_URL;
}

replace_window_url(tileset_url);

input.value = tileset_url;
run(tileset_url);

document.getElementById("start").onclick = () => {
  const enteredUrl = input.value;

  if (enteredUrl != null) {
    replace_window_url(enteredUrl);
    run(enteredUrl);
  }
};

// picking and highlighting logic
const resultsTable = document.getElementById("results-body");

let highlighted;
let highlightColor = new Color(0xff7171);

let canPick = true;

function highlight(evt) {
  if (!canPick) {
    return;
  }

  const picked = instance.pickObjectsAt(evt, {
    radius: 5,
    limit: 10,
    where: [tileset],
    filter: (pick) => pick.object.visible, // Ignore invisible objects, such as IfcSpace elements
  });

  if (highlighted && highlighted.material.color != null) {
    // reset style
    const material = highlighted.material;
    material.color.copy(material.userData.oldColor);

    instance.notifyChange(highlighted);
  }

  if (picked.length === 0) {
    const row = document.createElement("tr");
    const count = document.createElement("th");
    count.setAttribute("scope", "row");
    count.innerText = "-";
    const coordinates = document.createElement("td");
    coordinates.innerText = "-";
    const distanceToCamera = document.createElement("td");
    distanceToCamera.innerText = "-";
    row.append(count, coordinates, distanceToCamera);
    resultsTable.replaceChildren(row);
  } else {
    const obj = picked[0].object;
    if (obj instanceof Mesh) {
      const material = obj.material;

      // keep the old color to reset it later
      if (material.color != null) {
        if (!material.userData.oldColor) {
          material.userData.oldColor = material.color.clone();
        }

        material.color.copy(highlightColor);
      }

      instance.notifyChange(obj);
      highlighted = obj;
    }

    const rows = [];

    for (const [name, value] of Object.entries(obj.userData)) {
      if (name !== "oldColor" && name !== "parentEntity") {
        const row = document.createElement("tr");
        const nameCell = document.createElement("td");
        nameCell.innerHTML = `<code>${name}</code>`;
        const valueCell = document.createElement("td");
        valueCell.innerText = value;
        row.append(nameCell, valueCell);
        rows.push(row);
      }
    }

    resultsTable.replaceChildren(...rows);
  }
}

// Prevent picking if user is dragging mouse
instance.domElement.addEventListener("mousedown", () => (canPick = true));
instance.domElement.addEventListener("mousemove", () => (canPick = false));
instance.domElement.addEventListener("mouseup", highlight);

Inspector.attach("inspector", instance);
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>3D Tiles Simple Viewer</title>
    <meta charset="UTF-8" />
    <meta name="name" content="3d-tiles-simple-viewer" />
    <meta name="description" content="Display any 3D Tiles from a url." />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="icon" href="https://giro3d.org/images/favicon.svg" />
    <link
      href="https://giro3d.org/assets/bootstrap-custom.css"
      rel="stylesheet"
    />
    <script src="https://giro3d.org/assets/bootstrap.bundle.min.js"></script>
    <link
      rel="stylesheet"
      type="text/css"
      href="https://giro3d.org/latest/examples/css/example.css"
    />
  </head>

  <body>
    <div id="view" class="m-0 p-0 w-100 h-100"></div>
    <div
      id="inspector"
      class="position-absolute top-0 start-0 mh-100 overflow-auto"
    ></div>

    <div class="toast-container position-fixed top-0 end-0 p-3">
      <div
        id="liveToast"
        class="toast"
        role="alert"
        aria-live="assertive"
        aria-atomic="true"
      >
        <div class="toast-header">
          <strong class="me-auto">Error loading tileset</strong>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="toast"
            aria-label="Close"
          ></button>
        </div>
        <div class="toast-body">
          Tileset loading failed: <span id="error"></span>
        </div>
      </div>
    </div>

    <div class="side-pane-with-status-bar">
      <div class="input-group">
        <input
          type="text"
          class="form-control"
          id="tileset_url"
          placeholder="http://domain.tld/path/tileset.json"
        />
        <button class="btn btn-primary" id="start">Reload</button>
      </div>
      <div class="card">
        <h5 class="card-header">Element informations</h5>
        <div class="card-body" style="max-width: 30vw">
          <!-- Result table -->
          <table class="table table-sm table-striped">
            <thead>
              <tr>
                <th scope="col">Name</th>
                <th scope="col">Value</th>
              </tr>
            </thead>
            <tbody id="results-body">
              <tr>
                <th scope="row" colspan="4">
                  Click on the scene to inspect object properties
                </th>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <script type="module" src="index.js"></script>
    <script>
      /* activate popovers */
      const popoverTriggerList = [].slice.call(
        document.querySelectorAll('[data-bs-toggle="popover"]'),
      );
      popoverTriggerList.map(
        // bootstrap is used as script in the template, disable warning about undef
        // eslint-disable-next-line no-undef
        (popoverTriggerEl) =>
          new bootstrap.Popover(popoverTriggerEl, {
            trigger: "hover",
            placement: "left",
            content: document.getElementById(
              popoverTriggerEl.getAttribute("data-bs-content"),
            ).innerHTML,
            html: true,
          }),
      );
    </script>
  </body>
</html>
package.json
{
    "name": "3d-tiles-simple-viewer",
    "dependencies": {
        "@giro3d/giro3d": "1.0.0"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}
vite.config.js
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    target: 'esnext',
  },
  optimizeDeps: {
    esbuildOptions: {
      target: 'esnext',
    },
  },
})