Visualize point cloud intensity with a colormap.

Parameters
100% © IGN
index.js
import colormap from 'colormap';

import * as FunctionCurveEditor from 'function-curve-editor';

import { MathUtils, Vector3, Color } from 'three';
import { MapControls } from 'three/examples/jsm/controls/MapControls.js';
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';

import Instance from '@giro3d/giro3d/core/Instance.js';
import Tiles3D from '@giro3d/giro3d/entities/Tiles3D.js';
import PointCloudMaterial, { MODE } from '@giro3d/giro3d/renderer/PointCloudMaterial.js';
import Tiles3DSource from '@giro3d/giro3d/sources/Tiles3DSource.js';
import Inspector from '@giro3d/giro3d/gui/Inspector.js';

/**
 * Binds a toggle switch or checkbox.
 * @param {string} id The id of the <input> element.
 * @param {(v: boolean) => void} onChange The callback when the dropdown value changes.
 * @returns {(v: boolean) => void} The function to update the value from outside.
 */
function bindToggle(id, onChange) {
    /** @type {HTMLInputElement} */
    const toggle = document.getElementById(id);

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

    return v => {
        toggle.checked = v;
        onChange(toggle.checked);
    };
}

/**
 * Binds a text-value dropdown.
 * @param {string} id The id of the <input> element.
 * @param {(v: string) => void} onChange The callback when the dropdown value changes.
 * @returns {(v: string) => void} The function to update the value from outside.
 */
function bindDropDown(id, onChange) {
    /** @type {HTMLInputElement} */
    const mode = document.getElementById(id);
    mode.onchange = () => {
        onChange(mode.value);
    };

    return v => {
        mode.value = v;
        onChange(mode.value);
    };
}

/**
 * Binds a button.
 * @param {string} id The id of the <button> element.
 * @param {() => void} onClick The click handler.
 */
function bindButton(id, onClick) {
    document.getElementById(id).onclick = () => {
        onClick();
    };
}

/**
 * Create an array of {@link Color}s from the specified colormap preset.
 * @param {string} preset The name of the colormap preset.
 * @param {boolean} [discrete=false] If `true`, the color array will have 10 steps, otherwise 256.
 * @param {boolean} [invert=false] If `true`, the color array will be reversed.
 * @returns {Color[]} The color array.
 */
function makeColorRamp(preset, discrete = false, invert = false, mirror = false) {
    let nshades = discrete ? 10 : 256;

    // eslint-disable-next-line no-undef
    const values = colormap({ colormap: preset, nshades });
    // eslint-disable-next-line no-undef
    const colors = values.map(v => new Color(v));

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

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

    return colors;
}

Instance.registerCRS(
    'EPSG:3946',
    '+proj=lcc +lat_1=45.25 +lat_2=46.75 +lat_0=46 +lon_0=3 +x_0=1700000 ' +
        '+y_0=5200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs',
);

const viewerDiv = document.getElementById('viewerDiv');

const instance = new Instance(viewerDiv, {
    crs: 'EPSG:3946',
    renderer: {
        clearColor: false, // To make canvas transparent
    },
});

// Enable point cloud post processing effects
instance.renderingOptions.enableEDL = true;
// But not inpainting and occlusion because it would hinder the opacity filtering
instance.renderingOptions.enableInpainting = false;
instance.renderingOptions.enablePointCloudOcclusion = false;

// Create a custom material for our point cloud.
const material = new PointCloudMaterial({ mode: MODE.INTENSITY });

material.colorMap.min = 0;
material.colorMap.max = 30;
material.colorMap.colors = makeColorRamp('greys');

let parameters = {
    ramp: 'greys',
    discrete: false,
    invert: false,
    colors: makeColorRamp('greys', false, false),
    opacity: new Array(256).fill(1),
    min: 0,
    max: 30,
};

const url = 'https://3d.oslandia.com/giro3d/3d-tiles/lidarhd_intensity/tileset.json';

// Create the 3D tiles entity
const pointcloud = new Tiles3D('pointcloud', new Tiles3DSource(url), {
    material,
});

function placeCamera(position, lookAt) {
    instance.camera.camera3D.position.set(position.x, position.y, position.z);
    instance.camera.camera3D.lookAt(lookAt);
    // create controls
    const controls = new MapControls(instance.camera.camera3D, instance.domElement);
    controls.target.copy(lookAt);
    controls.enableDamping = true;
    controls.dampingFactor = 0.25;

    instance.useTHREEControls(controls);

    instance.notifyChange(instance.camera.camera3D);
}

const tmpVec3 = new Vector3();

// add pointcloud to scene
function initializeCamera() {
    const bbox = pointcloud.root.bbox
        ? pointcloud.root.bbox
        : pointcloud.root.boundingVolume.box.clone().applyMatrix4(pointcloud.root.matrixWorld);

    instance.camera.camera3D.far = 2.0 * bbox.getSize(tmpVec3).length();

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

    placeCamera(new Vector3(221965, 6873398, 1951), lookAt);

}

instance.add(pointcloud).then(initializeCamera);

Inspector.attach(document.getElementById('panelDiv'), instance);

function updatePreview(colors) {
    const canvas = document.getElementById('gradient');
    const ctx = canvas.getContext('2d');

    canvas.width = colors.length;
    canvas.height = 32;

    for (let i = 0; i < colors.length; i++) {
        const color = colors[i];
        ctx.fillStyle = `#${color.getHexString()}`;
        ctx.fillRect(i, 0, 1, canvas.height);
    }
}

updatePreview(parameters.colors);

function updateColorRamp() {
    parameters.colors = makeColorRamp(parameters.ramp, parameters.discrete, parameters.invert);
    material.colorMap.colors = parameters.colors;
    material.colorMap.min = parameters.min;
    material.colorMap.max = parameters.max;
    material.colorMap.mode = parameters.mode;

    updateTransparency();

    updatePreview(parameters.colors);

    instance.notifyChange(pointcloud);
}

const setDiscrete = bindToggle('discrete', v => {
    parameters.discrete = v;
    updateColorRamp();
});
const setInvert = bindToggle('invert', v => {
    parameters.invert = v;
    updateColorRamp();
});
const setRamp = bindDropDown('ramp', v => {
    parameters.ramp = v;
    updateColorRamp();
    instance.notifyChange(pointcloud);
});
const updateBounds = bindColorMapBounds((min, max) => {
    material.colorMap.min = min;
    material.colorMap.max = max;
    instance.notifyChange(pointcloud);
});

function bindColorMapBounds(callback) {
    /** @type {HTMLInputElement} */
    const lower = document.getElementById('lower');

    /** @type {HTMLInputElement} */
    const upper = document.getElementById('upper');

    callback(lower.valueAsNumber, upper.valueAsNumber);

    function updateLabels() {
        document.getElementById('minLabel').innerText = `Lower bound: ${lower.valueAsNumber}`;
        document.getElementById('maxLabel').innerText = `Upper bound: ${upper.valueAsNumber}`;
    }

    lower.oninput = function oninput() {
        const rawValue = lower.valueAsNumber;
        const clampedValue = MathUtils.clamp(rawValue, lower.min, upper.valueAsNumber - 1);
        lower.valueAsNumber = clampedValue;
        callback(lower.valueAsNumber, upper.valueAsNumber);
        instance.notifyChange(pointcloud);
        updateLabels();
    };

    upper.oninput = function oninput() {
        const rawValue = upper.valueAsNumber;
        const clampedValue = MathUtils.clamp(rawValue, lower.valueAsNumber + 1, upper.max);
        upper.valueAsNumber = clampedValue;
        callback(lower.valueAsNumber, upper.valueAsNumber);
        instance.notifyChange(pointcloud);
        updateLabels();
    };

    return (min, max) => {
        lower.min = min;
        lower.max = max;
        upper.min = min;
        upper.max = max;
        lower.valueAsNumber = min;
        upper.valueAsNumber = max;
        updateLabels();
    };
}

const canvas = document.getElementById('curve');
const widget = new FunctionCurveEditor.Widget(canvas);

function updateTransparency() {
    const length = parameters.colors.length;
    const f = widget.getFunction();
    const opacities = new Array(length);
    for (let i = 0; i < length; i++) {
        const t = i / length;
        opacities[i] = f(t);
    }
    parameters.opacity = opacities;
    material.colorMap.opacity = opacities;
}

function setupCurveEditor() {
    // Curve editor
    const initialKnots = [
        { x: 0, y: 1 },
        { x: 1, y: 1 },
    ];

    widget.setEditorState({
        knots: initialKnots,
        xMin: -0.2,
        xMax: 1.2,
        yMin: -0.2,
        yMax: 1.2,
        interpolationMethod: 'linear',
        extendedDomain: true,
        relevantXMin: 0,
        relevantXMax: 1,
        gridEnabled: true,
    });

    widget.addEventListener('change', () => {
        updateColorRamp();
    });
}

setupCurveEditor();

function resetToDefaults() {
    setupCurveEditor();

    setRamp('greys');
    setDiscrete(false);
    setInvert(false);
    updateBounds(0, 30);

    parameters = {
        ramp: 'greys',
        discrete: false,
        invert: false,
        colors: makeColorRamp('greys', false, false),
        opacity: new Array(256).fill(1),
        min: 0,
        max: 30,
    };

    material.colorMap.active = true;

    updateColorRamp();

    instance.notifyChange(pointcloud);
}

bindButton('reset', resetToDefaults);

const labelElement = document.createElement('div');
labelElement.classList = 'badge rounded-pill text-bg-light';
labelElement.style.marginTop = '2rem';

const intensityValue = document.createElement('span');
intensityValue.style.marginLeft = '0.5rem';

const intensityColor = document.createElement('span');
intensityColor.classList = 'badge rounded-pill';
intensityColor.style.color = 'white';
intensityColor.style.background = 'red';
intensityColor.style.width = '1rem';
intensityColor.innerText = ' ';

labelElement.appendChild(intensityColor);
labelElement.appendChild(intensityValue);

const label = new CSS2DObject(labelElement);

instance.add(label);

// Let's query the intensity of the picked point and display it in the label.
function updateLabel(mouseEvent) {
    const results = instance.pickObjectsAt(mouseEvent, { radius: 6 });

    // Reset label visibility
    label.visible = false;

    if (results && results.length > 0) {
        for (const result of results) {
            const { object, point, index } = result;

            if (object.isPointCloud) {
                const intensity = object.getIntensity(index);

                if (intensity) {
                    const color = material.colorMap.sample(intensity);
                    const opacity = material.colorMap.sampleOpacity(intensity);

                    if (opacity > 0.5) {
                        const hex = color.getHexString();
                        intensityColor.style.background = `#${hex}`;

                        intensityValue.innerText = `${intensity.toFixed(2)}`;

                        label.visible = true;
                        label.position.copy(point);
                        label.updateMatrixWorld(true);

                        break;
                    }
                }
            }
        }
    }

    instance.notifyChange();
}

instance.domElement.addEventListener('mousemove', updateLabel);

// For some reason we have to wait a bit in order to the curve editor to display properly on Firefox.
setTimeout(resetToDefaults, 100);
index.html
<!doctype html>
<html lang="en">
    <head>
        <title>Point cloud intensity</title>
        <meta charset="UTF-8" />
        <meta name="name" content="point_cloud_intensity" />
        <meta name="description" content="Visualize point cloud intensity with a colormap." />
        <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/next/css/example.css"
        />

        <style>
        #viewerDiv 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="viewerDiv" class="m-0 p-0 w-100 h-100"></div>
        <div id="panelDiv" class="position-absolute top-0 start-0 mh-100 overflow-auto"></div>

        <div class="side-pane-with-status-bar" style="width: 20rem">
            <!--Parameters -->
            <div class="card">
                <div class="card-header">
                    Parameters
                    <button type="button" id="reset" class="btn btn-sm btn-primary rounded float-end">
                        reset
                    </button>
                </div>

                <div class="card-body" id="top-options">
                    <!-- Reverse color map -->
                    <div class="form-check form-switch mb-1">
                        <input
                            class="form-check-input"
                            type="checkbox"
                            role="switch"
                            id="invert"
                            autocomplete="off"
                        />
                        <label class="form-check-label" for="invert">Invert color map</label>
                    </div>

                    <!-- Discrete color map -->
                    <div class="form-check form-switch mb-3">
                        <input
                            class="form-check-input"
                            type="checkbox"
                            role="switch"
                            id="discrete"
                            autocomplete="off"
                        />
                        <label class="form-check-label" for="discrete">Discrete color map</label>
                    </div>

                    <!-- Color ramp selector -->
                    <div class="input-group mb-3">
                        <label class="input-group-text" for="ramp">Colors</label>
                        <select class="form-select" id="ramp" autocomplete="off">
                            <option value="greys" selected>Greys</option>
                            <option value="viridis">Viridis</option>
                            <option value="jet">Jet</option>
                            <option value="blackbody">Blackbody</option>
                            <option value="earth">Earth</option>
                            <option value="bathymetry">Bathymetry</option>
                            <option value="magma">Magma</option>
                            <option value="par">Par</option>
                            <option value="rdbu">RdBu</option>
                        </select>
                    </div>

                    <!-- Gradient preview -->
                    <div class="mb-3 w-100">
                        <canvas
                            id="gradient"
                            height="32"
                            class="w-100 border rounded"
                            style="height: 32px; image-rendering: pixelated"
                        ></canvas>
                    </div>

                    <!-- Opacity curve -->
                    <div class="mb-3 w-100">
                        <label for="curve" class="mb-2">Opacity curve</label>
                        <canvas id="curve" height="128" class="w-100" style="height: 128px"></canvas>
                    </div>

                    <!-- Bound sliders -->
                    <div class="input-group border rounded p-2">
                        <label for="lower" id="minLabel" class="form-label">Lower bound</label>
                        <div class="input-group">
                            <input
                                type="range"
                                min="0"
                                max="30"
                                value="0"
                                class="form-range"
                                id="lower"
                                autocomplete="off"
                            />
                        </div>

                        <label for="upper" id="maxLabel" class="form-label">Upper bound</label>
                        <div class="input-group">
                            <input
                                type="range"
                                min="0"
                                max="30"
                                value="30"
                                class="form-range"
                                id="upper"
                                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_intensity",
    "dependencies": {
        "colormap": "^2.3.2",
        "function-curve-editor": "^1.0.16",
        "@giro3d/giro3d": "git+https://gitlab.com/giro3d/giro3d.git"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}