Repository

js/Mobilizing/renderer/3D/three/shape/3D/parser/XYZ.js

import Mesh from "../../Mesh";
import { Vector3 } from "../../../types/Vector3";
import Color from '../../../types/Color';

/**
* XYZ file parser
*/
export default class XYZ {
    /**
    * parse
    * @static
    * @param {String} data
    * @param {String} dataOrder
    */
    static parse({
        data = undefined,
        separator = " ",
        useColors = true,
    } = {}) {
        //TODO: manage order
        //@TODO for further use, implement dataorder
        //const dataOrder = getOrDefault(params, "dataOrder", "xyzrgbsn");

        this.data = data;
        this.separator = separator;
        this.useColors = useColors;

        const vertices = [];
        const colors = [];
        const normals = [];
        const scales = [];

        const lines = this.data.toString().split("\n");
        //console.log("XYZ lines = " + lines);

        lines.forEach((line) => {

            const words = line.split(this.separator);
            const wordsLength = words.length;

            //we have at least points
            if (wordsLength > 1) {
                const vertex = new Vector3(words[0], words[1], words[2]);
                vertices.push(vertex);

                //we may have rgb
                if (wordsLength > 3) {
                    const color = new Color(words[3], words[4], words[5]);
                    colors.push(color);
                }
                //we may have scale factor
                if (wordsLength > 4) {
                    const scale = words[6];
                    scales.push(scale);
                }
                //we may have rgb
                if (wordsLength > 5) {
                    const normal = new Vector3(words[7], words[8], words[9]);
                    normals.push(normal);
                }
            }
            //console.log("WORDS:"+words);
        });

        const datas = {};
        datas.vertices = vertices;

        if (colors.length > 0) {
            datas.colors = colors;
        }
        if (scales.length > 0) {
            datas.scales = scales;
        }
        if (normals.length > 0) {
            datas.normals = normals;
        }

        console.log(datas);
        return XYZ.createMesh(datas, this.useColors);
    }

    static createMesh(datas, useColors) {
        const points = new Mesh({ primitive: "point", material: "points" });
        points.erase(); //we must start with a clean geometry

        /* datas.vertices.forEach( function(vertex) {
            points.pushVertex(vertex);
        }); */
        if (datas.vertices) {
            points.setVertices(datas.vertices);
        }

        if (datas.colors && useColors) {
            points.setVertexColors(datas.colors);
        }

        return points;
    }
}