Demonstrates the Intersecting Volumes feature for point clouds

Loading metadata...
100% Autzen stadium dataset provided by United States Geological Survey and Hobu, Inc.
index.js
import {
  Color,
  Matrix4,
  OrthographicCamera,
  PerspectiveCamera,
  Vector3,
} from "three";

import ColorMap from "@giro3d/giro3d/core/ColorMap.js";
import CoordinateSystem from "@giro3d/giro3d/core/geographic/CoordinateSystem.js";
import Instance from "@giro3d/giro3d/core/Instance.js";
import PointCloud from "@giro3d/giro3d/entities/PointCloud.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";
import COPCSource from "@giro3d/giro3d/sources/COPCSource.js";
import { setLazPerfPath } from "@giro3d/giro3d/sources/las/config.js";

function bindProgress(id) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLDivElement)) {
    throw new Error(
      "invalid binding element: expected HTMLDivElement, got: " +
        element.constructor.name,
    );
  }

  const setProgress = (normalized, text) => {
    element.style.width = `${Math.round(normalized * 100)}%`;
    if (text) {
      element.innerText = text;
    }
  };

  return [setProgress, element.parentElement];
}

function bindSlider(id, onChange) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLInputElement, got: " +
        element.constructor.name,
    );
  }

  element.oninput = function oninput() {
    onChange(element.valueAsNumber);
  };

  const setValue = (v, min, max, step) => {
    if (min != null && max != null) {
      element.min = min.toString();
      element.max = max.toString();

      if (step != null) {
        element.step = step;
      }
    }
    element.valueAsNumber = v;
    onChange(element.valueAsNumber);
  };

  const initialValue = element.valueAsNumber;

  return [setValue, initialValue, element];
}

function bindToggle(id, onChange) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLButtonElement, got: " +
        element.constructor.name,
    );
  }

  element.oninput = function oninput() {
    onChange(element.checked);
  };

  const callback = (v) => {
    element.checked = v;
    onChange(element.checked);
  };

  return [callback, element.checked, element];
}

function formatPointCount(count, numberFormat = undefined) {
  let displayedPointCount = count;
  let suffix = "";

  if (count > 1_000_000) {
    displayedPointCount /= 1_000_000;
    suffix = "M";
  } else if (count > 1_000_000_000) {
    displayedPointCount /= 1_000_000_000;
    suffix = "B";
  }

  if (numberFormat == null) {
    numberFormat = new Intl.NumberFormat(undefined, {
      maximumFractionDigits: 2,
    });
  }

  return numberFormat.format(displayedPointCount) + suffix;
}

function makeColorRamp(
  preset,
  discrete = false,
  invert = false,
  mirror = false,
) {
  let nshades = discrete ? 10 : 256;

  const values = colormap({ colormap: preset, nshades });

  const colors = values.map((v) => new Color(v));

  if (invert) {
    colors.reverse();
  }

  if (mirror) {
    const mirrored = [...colors, ...colors.reverse()];
    return mirrored;
  }

  return colors;
}

function placeCameraOnTop(volume, instance) {
  if (!instance) {
    return;
  }

  const center = volume.getCenter(new Vector3());
  const size = volume.getSize(new Vector3());

  const camera = instance.view.camera;
  const top = volume.max.z;
  const fov = camera.fov;
  const aspect = camera.aspect;

  const hFov = MathUtils.degToRad(fov) / 2;
  const altitude = (Math.max(size.x / aspect, size.y) / Math.tan(hFov)) * 0.5;

  instance.view.camera.position.set(center.x, center.y - 1, altitude + top);
  instance.view.camera.lookAt(center);

  const controls = new MapControls(instance.view.camera, instance.domElement);
  controls.target.copy(center);
  controls.enableDamping = true;
  controls.dampingFactor = 0.25;

  instance.view.setControls(controls);
  instance.notifyChange(instance.view.camera);
}

// LAS processing requires the WebAssembly laz-perf library
// This path is specific to your project, and must be set accordingly.
setLazPerfPath("/assets/wasm");

// We use this CRS when the point cloud does not have a CRS defined.
// It is technically the WebMercator CRS, but we label it 'unknown' to make
// it very explicit that it is not correct.
// See https://gitlab.com/giro3d/giro3d/-/issues/514
CoordinateSystem.register(
  "unknown",
  "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs",
);

let instance;

const options = {
  mode: "attribute",
  attribute: "position",
  colorRamp: "bathymetry",
  min: 0,
  max: 100,
};

let entity;

// Create the color map. The color ramp and bounds will be set later.
const colorMap = new ColorMap({ colors: [], min: 0, max: 1 });

const [setProgress, progressElement] = bindProgress("progress");

bindToggle("edl", (v) => {
  instance.renderingOptions.enableEDL = v;
  instance.notifyChange();
});

bindToggle("inpainting", (v) => {
  instance.renderingOptions.enableInpainting = v;
  instance.renderingOptions.enablePointCloudOcclusion = v;
  instance.notifyChange();
});

bindSlider("point-size", (size) => {
  if (entity) {
    entity.pointSize = size;
    document.getElementById("point-size-label").innerHTML =
      `Point size: <b>${size === 0 ? "auto" : size.toFixed(0)}</b>`;
  }
});

function updateColorMap() {
  if (entity && instance) {
    colorMap.colors = makeColorRamp(options.colorRamp);
    instance.notifyChange();
  }
}

async function fetchCrsDefinitionFromEpsg(code) {
  async function fetchText(url) {
    const res = await fetch(url, { mode: "cors" });
    const def = await res.text();
    return def;
  }

  return await fetchText(`https://epsg.io/${code}.proj4?download=1`);
}

const numberFormat = new Intl.NumberFormat(undefined, {
  maximumFractionDigits: 2,
});

function updateDisplayedPointCounts(count, displayed) {
  const pointCountElement = document.getElementById("point-count");
  pointCountElement.innerHTML = formatPointCount(count, numberFormat);
  pointCountElement.title = numberFormat.format(count);

  const activePointCountElement = document.getElementById(
    "displayed-point-count",
  );
  activePointCountElement.innerHTML = formatPointCount(displayed, numberFormat);
  activePointCountElement.title = numberFormat.format(displayed);
}

function buildViewProjectionMatrix(camera) {
  camera.updateMatrixWorld();
  camera.updateProjectionMatrix();
  return new Matrix4().multiplyMatrices(
    camera.projectionMatrix,
    camera.matrixWorldInverse,
  );
}

function buildIntersectingVolumes() {
  const result = [];

  const fakePerspCamera = new PerspectiveCamera(90, 1, 200, 1000);
  fakePerspCamera.position.set(638690, 851602, 542);
  fakePerspCamera.lookAt(
    fakePerspCamera.position
      .clone()
      .add(
        new Vector3(
          -0.63259536468089,
          0.7725958632603044,
          -0.054025333477148996,
        ),
      ),
  );
  result.push({
    worldToBoxNdc: buildViewProjectionMatrix(fakePerspCamera),
    color: new Color(0xff0000),
  });

  const fakeOrthoCamera = new OrthographicCamera(-600, 600, 600, -600, 50, 400);
  fakeOrthoCamera.position.set(637173, 850000, 454);
  fakeOrthoCamera.lookAt(
    fakeOrthoCamera.position
      .clone()
      .add(
        new Vector3(
          0.04810697763524398,
          0.998397464675122,
          0.02980304066854412,
        ),
      ),
  );
  result.push({
    worldToBoxNdc: buildViewProjectionMatrix(fakeOrthoCamera),
    color: new Color(0x00ff00),
  });

  return result;
}

const intersectingVolumes = buildIntersectingVolumes();

function updateIntersectingVolumes() {
  entity.intersectingVolumes.length = 0;

  const input = document.getElementById("intersecting-volumes");
  if (input.checked) {
    entity.intersectingVolumes.push(...intersectingVolumes);
  }
}

window.addEventListener("keydown", (event) => {
  if (event.key === "g") {
    const camera = instance.view.camera;
    console.log("position", camera.getWorldPosition(new Vector3()).toArray());
    console.log("direction", camera.getWorldDirection(new Vector3()).toArray());
  }
});

function populateGUI() {
  document.getElementById("accordion").style.display = "block";

  const tableElement = document.getElementById("table");
  tableElement.style.display = "block";

  const projectionElement = document.getElementById("projection");
  const epsgCode = instance.coordinateSystem.srid?.tryGetEpsgCode();
  if (typeof epsgCode === "number") {
    projectionElement.href = `https://epsg.io/${epsgCode}`;
    projectionElement.innerHTML = instance.coordinateSystem.id;
  } else {
    projectionElement.parentElement.remove();
  }

  progressElement.style.display = "none";
}

// Loads the point cloud from the url parameter
async function load(url) {
  progressElement.style.display = "block";

  // Let's create the source
  const source = new COPCSource({ url });

  source.addEventListener("progress", () => setProgress(source.progress));

  try {
    // Initialize the source in advance, so that we can
    // access the metadata of the remote LAS file.
    await source.initialize();
  } catch (err) {
    if (err instanceof Error) {
      const messageElement = document.getElementById("message");
      messageElement.innerText = err.message;
      messageElement.style.display = "block";
    }
    progressElement.style.display = "none";
    console.error(err);
    return;
  }

  const metadata = await source.getMetadata();

  instance = new Instance({
    target: "view",
    crs: metadata.crs,
    backgroundColor: null,
  });

  options.attribute = metadata.attributes[0].name;

  // Let's enable Eye Dome Lighting to make the point cloud more readable.
  instance.renderingOptions.enableEDL = true;
  instance.renderingOptions.EDLRadius = 0.6;
  instance.renderingOptions.EDLStrength = 5;

  // Let's create our point cloud with the COPC source.
  entity = new PointCloud({ source });

  await instance.add(entity);

  instance.addEventListener("update-end", () =>
    updateDisplayedPointCounts(entity.pointCount, entity.displayedPointCount),
  );

  // Let's get the volume of the point cloud for various operations.
  const volume = entity.getBoundingBox();

  for (const attribute of metadata.attributes) {
    entity.setAttributeColorMap(attribute.name, colorMap);
  }

  updateIntersectingVolumes();
  bindToggle("intersecting-volumes", () => {
    updateIntersectingVolumes();
    instance.notifyChange();
  });

  updateColorMap();

  // If the source provides a coordinate system, we can load a map
  // to display as a geographic context and be able to check that the
  // point cloud is properly positioned.
  const epsgCode = metadata.crs.srid?.tryGetEpsgCode();
  if (typeof epsgCode === "number") {
    try {
      const definitionFromEpsg = await fetchCrsDefinitionFromEpsg(epsgCode);
      CoordinateSystem.register(metadata.crs.id, definitionFromEpsg);
      document.getElementById("basemap-group").style.display = "block";
    } catch (e) {
      console.warn("could not load map: " + e);
    }
  }

  populateGUI();

  Inspector.attach("inspector", instance);

  if (instance.coordinateSystem.srid) {
  }

  placeCameraOnTop(volume, instance);

  instance.notifyChange();
}

const defaultUrl =
  "https://3d.oslandia.com/giro3d/pointclouds/autzen-classified.copc.laz";

// Extract dataset URL from URL
const url = new URL(document.URL);
let datasetUrl = url.searchParams.get("dataset");
if (!datasetUrl) {
  datasetUrl = defaultUrl;
  url.searchParams.append("dataset", datasetUrl);
  window.history.replaceState({}, null, url.toString());
}

const fragments = new URL(datasetUrl).pathname.split("/");
document.getElementById("filename").innerText = fragments[fragments.length - 1];

// GUI controls for classification handling

load(datasetUrl).catch(console.error);
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>Pointcloud Intersecting Volumes</title>
    <meta charset="UTF-8" />
    <meta name="name" content="point-cloud-intersecting-volumes" />
    <meta
      name="description"
      content="Demonstrates the Intersecting Volumes feature for point clouds"
    />
    <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"
    />

    <style>
      #view canvas {
        background: rgb(132, 170, 182);
        background: radial-gradient(
          circle,
          rgba(132, 170, 182, 1) 0%,
          rgba(37, 44, 48, 1) 100%
        );
      }
    </style>
  </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="side-pane-with-status-bar" style="width: 20rem">
      <div class="progress" role="progressbar">
        <div
          class="progress-bar bg-info progress-bar-striped progress-bar-animated text-dark"
          id="progress"
          style="width: 0%"
        >
          Loading metadata...
        </div>
      </div>

      <!-- Error message -->
      <div
        class="alert alert-danger mt-0 mb-0"
        id="message"
        style="display: none"
        role="alert"
      >
        A simple primary alert—check it out!
      </div>

      <!--Parameters -->
      <div class="card-body">
        <!-- Accordion -->
        <div class="accordion" style="display: none" id="accordion">
          <!-- Section: info -->
          <div class="accordion-item">
            <h2 class="accordion-header">
              <button
                class="accordion-button collapsed"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#section-info"
                aria-controls="section-info"
              >
                Info
              </button>
            </h2>
            <div
              id="section-info"
              class="accordion-collapse collapse"
              data-bs-parent="#accordion"
            >
              <ul
                class="list-group list-group-flush"
                id="table"
                style="display: none; font-size: 0.875rem"
              >
                <li class="list-group-item">
                  Filename
                  <b
                    id="filename"
                    class="d-float float-end text-truncate"
                    style="max-width: 70%"
                  ></b>
                </li>
                <li
                  class="list-group-item"
                  title="The total number of points in the dataset"
                >
                  Total points
                  <b id="point-count" class="d-float float-end"></b>
                </li>
                <li
                  class="list-group-item"
                  title="The number of points currently displayed"
                >
                  Displayed points
                  <b id="displayed-point-count" class="d-float float-end"></b>
                </li>
                <li
                  class="list-group-item"
                  title="The coordinate reference system of this dataset"
                >
                  CRS
                  <a
                    target="_blank"
                    id="projection"
                    class="d-float float-end"
                  ></a>
                </li>
              </ul>
            </div>
          </div>

          <!-- Section: options -->
          <div class="accordion-item">
            <h2 class="accordion-header">
              <button
                class="accordion-button"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#section-options"
                aria-expanded="false"
                aria-controls="section-options"
              >
                Options
              </button>
            </h2>

            <div
              id="section-options"
              class="accordion-collapse collapse show p-2"
              data-bs-parent="#accordion"
            >
              <!-- Eye Dome Lighting -->
              <div class="form-check form-switch">
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  checked
                  id="edl"
                  autocomplete="off"
                />
                <label
                  title="Toggles Eye Dome Lighting post-processing effect"
                  class="form-check-label"
                  for="edl"
                  >Eye Dome Lighting</label
                >
              </div>

              <!-- Inpainting -->
              <div class="form-check form-switch">
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="inpainting"
                  autocomplete="off"
                />
                <label
                  title="Toggles inpainting"
                  class="form-check-label"
                  for="inpainting"
                  >Inpainting</label
                >
              </div>

              <!-- Intersecting volumes -->
              <div class="form-check form-switch">
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="intersecting-volumes"
                  autocomplete="off"
                  checked
                />
                <label
                  title="Toggles intersecting volumes"
                  class="form-check-label"
                  for="intersecting-volumes"
                  >Intersecting volumes</label
                >
              </div>

              <!-- Point size slider -->
              <label
                for="point-size"
                class="form-label mt-2"
                id="point-size-label"
                >Point size: <b>auto</b></label
              >
              <input
                type="range"
                min="0"
                max="50"
                step="1"
                value="0"
                title="The point size, in pixels"
                class="form-range"
                id="point-size"
                autocomplete="off"
              />
            </div>
          </div>
        </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": "point-cloud-intersecting-volumes",
    "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',
    },
  },
})