PointCloudLoader.js 2.09 KB
import { FileLoader, Loader, Vector3 } from 'three';

class PointCloudLoader extends Loader {
    constructor(manager) {
        super(manager);
    }

    load(url, onLoad, onProgress, onError) {
        const loader = new FileLoader(this.manager);
        loader.setPath(this.path);
        loader.setResponseType('arraybuffer');
        loader.setRequestHeader(this.requestHeader);
        loader.setWithCredentials(this.withCredentials);

        loader.load(
            url,
            function (data) {
                try {
                    onLoad(parsePointCloudData(data));
                } catch (e) {
                    handleLoadError(e, url, onError);
                }
            },
            onProgress,
            function (error) {
                handleLoadError(error, url, onError);
            }
        );
    }

    parse(data) {
        function ensureString(buffer) {
            return typeof buffer !== 'string' ? new TextDecoder().decode(buffer) : buffer;
        }
        const textData = ensureString(data);
        let pointCloudData = textData.split(/\s/);
        let index = 0;
        const vertices = [];
        pointCloudData = pointCloudData.filter((el) => el.length > 0);
        while (index < pointCloudData.length) {
            if (pointCloudData[index] && pointCloudData[index + 1] && pointCloudData[index + 2]) {
                vertices.push(
                    new Vector3(
                        Number(pointCloudData[index]),
                        Number(pointCloudData[index + 1]),
                        Number(pointCloudData[index + 2])
                    )
                );
            }
            index += 3; // Assuming each point has 4 units of data
        }

        return {
            type: 'PtsModel',
            vertices
        };
    }
}

function parsePointCloudData(data) {
    return new PointCloudLoader().parse(data);
}

function handleLoadError(error, url, onError) {
    if (onError) {
        onError(error);
    } else {
        console.error(error);
    }

    new PointCloudLoader().manager.itemError(url);
}

export { PointCloudLoader };