All files / app/codeCharta/services/3DExports serialize3mf.service.ts

100% Statements 95/95
100% Branches 25/25
100% Functions 10/10
100% Lines 91/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 2565x 5x                     5x 5x 5x                     5x 2x 2x 2x 2x 2x   2x                       2x       2x 2x               3x 3x 3x 3x 3x 3x   3x 7x     3x                         12x 1x     11x 2x 2x 1x   2x     11x 11x   11x 11x   11x   11x   11x 11x         15x 15x 2x 78x   78x 72x   6x     13x 11x   11x 5x 6x 6x 6x   1350x 11x   15x                     14x   14x 1428x         1428x   1428x 88x     1428x   1428x 268x 268x 268x   1160x       14x                 14x 6x 448x     448x     8x 8x 128x 128x 128x   128x 52x       52x                             19x 16x   19x 19x 19x               19x         96x               96x   288x             5x                  
import { strToU8, zipSync } from "fflate"
import {
    BufferAttribute,
    BufferGeometry,
    Float32BufferAttribute,
    Material,
    Matrix4,
    Mesh,
    MeshBasicMaterial,
    ShaderMaterial,
    Vector3
} from "three"
import { getXMLrelationships, getXMLcontentType } from "./generateXML/build3mfStatics"
import { getXMLmodelConfig } from "./generateXML/build3mfModelConfig"
import { getXMLmodel } from "./generateXML/build3mfModel"
 
export interface Volume {
    id: number
    name: string
    color: string
    extruder: number
    firstTriangleId: number
    lastTriangleId: number
}
 
export async function serialize3mf(mesh: Mesh): Promise<string> {
    const { vertices, triangles, volumes } = extractMeshData(mesh)
    const model = getXMLmodel(vertices, triangles)
    const modelConfig = getXMLmodelConfig(volumes)
    const contentType = getXMLcontentType()
    const relationships = getXMLrelationships()
 
    const data = {
        "3D": {
            "3dmodel.model": strToU8(model)
        },
        _rels: {
            ".rels": strToU8(relationships)
        },
        Metadata: {
            "Slic3r_PE_model.config": strToU8(modelConfig)
        },
        "[Content_Types].xml": strToU8(contentType)
    }
    const options = {
        comment: "created by CodeCharta"
    }
 
    const compressed3mf = zipSync(data, options).buffer
    return compressed3mf as unknown as string
}
 
function extractMeshData(mesh: Mesh): {
    vertices: string[]
    triangles: string[]
    volumes: Volume[]
} {
    const vertices: string[] = []
    const triangles: string[] = []
    const volumes: Volume[] = []
    const vertexToNewVertexIndex: Map<string, number> = new Map()
    const colorToExtruder: Map<string, number> = new Map()
    const volumeCount = 1
 
    for (const child of mesh.children as Mesh[]) {
        extractChildMeshData(child, vertices, triangles, vertexToNewVertexIndex, volumeCount, colorToExtruder, volumes)
    }
 
    return { vertices, triangles, volumes }
}
 
function extractChildMeshData(
    mesh: Mesh,
    vertices: string[],
    triangles: string[],
    vertexToNewVertexIndex: Map<string, number>,
    volumeCount: number,
    colorToExtruder: Map<string, number>,
    volumes: Volume[],
    parentMatrix: Matrix4 = undefined
): void {
    if (!mesh.visible) {
        return
    }
 
    for (const child of mesh.children as Mesh[]) {
        let newParentMatrix = mesh.matrix
        if (parentMatrix) {
            newParentMatrix = parentMatrix.clone().multiply(mesh.matrix)
        }
        extractChildMeshData(child, vertices, triangles, vertexToNewVertexIndex, volumeCount, colorToExtruder, volumes, newParentMatrix)
    }
 
    const colorToVertexIndices = groupMeshVerticesByColor(mesh)
    const vertexIndexToNewVertexIndex: Map<number, number> = new Map()
 
    for (const [color, vertexIndexes] of colorToVertexIndices.entries()) {
        const firstTriangleId = triangles.length
 
        constructVertices(vertices, vertexToNewVertexIndex, vertexIndexToNewVertexIndex, vertexIndexes, mesh, parentMatrix)
 
        constructTriangles(mesh.geometry, triangles, vertexIndexToNewVertexIndex, vertexIndexes)
 
        constructVolume(mesh, color, firstTriangleId, triangles.length - 1, volumes, volumeCount, colorToExtruder)
        volumeCount++
    }
}
 
function groupMeshVerticesByColor(mesh: Mesh): Map<string, number[]> {
    const colorToVertexIndices: Map<string, number[]> = new Map()
    if (mesh.geometry.attributes.color) {
        for (let index = 0; index < mesh.geometry.attributes.color.count; index++) {
            const hexColorString = convertColorArrayToHexString(mesh.geometry.attributes.color as Float32BufferAttribute, index)
 
            if (colorToVertexIndices.has(hexColorString)) {
                colorToVertexIndices.get(hexColorString).push(index)
            } else {
                colorToVertexIndices.set(hexColorString, [index])
            }
        }
    } else if (mesh.geometry.attributes.position) {
        const material = mesh.material as Material
        let hexColorString: string
        if ((material as MeshBasicMaterial).color) {
            hexColorString = (material as MeshBasicMaterial).color.getHexString()
        } else if ((material as ShaderMaterial).isShaderMaterial) {
            const colorArray = (material as ShaderMaterial).defaultAttributeValues.color
            hexColorString = convertColorArrayToHexString(colorArray, 0)
        }
        const indexArray = Array.from({ length: mesh.geometry.attributes.position.count }, (_, index) => index)
        colorToVertexIndices.set(hexColorString, indexArray)
    }
    return colorToVertexIndices
}
 
function constructVertices(
    vertices: string[],
    vertexToNewVertexIndex: Map<string, number>,
    vertexIndexToNewVertexIndex: Map<number, number>,
    vertexIndexes: number[],
    mesh: Mesh,
    parentMatrix: Matrix4
) {
    const positionAttribute = mesh.geometry.attributes.position
 
    for (const vertexIndex of vertexIndexes) {
        const vertex = new Vector3(
            positionAttribute.getX(vertexIndex),
            positionAttribute.getY(vertexIndex),
            positionAttribute.getZ(vertexIndex)
        )
        vertex.applyMatrix4(mesh.matrix)
 
        if (parentMatrix) {
            vertex.applyMatrix4(parentMatrix)
        }
 
        const vertexString = `<vertex x="${vertex.x}" y="${vertex.y}" z="${vertex.z}"/>`
 
        if (!vertexToNewVertexIndex.has(vertexString)) {
            vertices.push(vertexString)
            vertexToNewVertexIndex.set(vertexString, vertices.length - 1)
            vertexIndexToNewVertexIndex.set(vertexIndex, vertices.length - 1)
        } else {
            vertexIndexToNewVertexIndex.set(vertexIndex, vertexToNewVertexIndex.get(vertexString))
        }
    }
 
    return
}
 
function constructTriangles(
    geometry: BufferGeometry,
    triangles: string[],
    vertexIndexToNewVertexIndex: Map<number, number>,
    vertexIndexes: number[]
): void {
    if (!geometry.index) {
        for (let index = 0; index < vertexIndexToNewVertexIndex.size; index += 3) {
            const triangle = `<triangle v1="${vertexIndexToNewVertexIndex.get(index)}" v2="${vertexIndexToNewVertexIndex.get(
                index + 1
            )}" v3="${vertexIndexToNewVertexIndex.get(index + 2)}" />`
            triangles.push(triangle)
        }
    } else {
        const vertexIndices = geometry.index
        for (let index = 0; index < vertexIndices.count; index += 3) {
            const vertexIndex1 = vertexIndices.getX(index)
            const vertexIndex2 = vertexIndices.getY(index)
            const vertexIndex3 = vertexIndices.getZ(index)
 
            if (vertexIndexes.includes(vertexIndex1) && vertexIndexes.includes(vertexIndex2) && vertexIndexes.includes(vertexIndex3)) {
                const triangle = `<triangle v1="${vertexIndexToNewVertexIndex.get(vertexIndex1)}" v2="${vertexIndexToNewVertexIndex.get(
                    vertexIndex2
                )}" v3="${vertexIndexToNewVertexIndex.get(vertexIndex3)}" />`
 
                triangles.push(triangle)
            }
        }
    }
}
 
function constructVolume(
    child: Mesh,
    color: string,
    firstTriangleId: number,
    lastTriangleId: number,
    volumes: Volume[],
    volumeCount: number,
    colorToExtruder: Map<string, number>
): void {
    if (!colorToExtruder.has(color)) {
        colorToExtruder.set(color, colorToExtruder.size + 1)
    }
    const extruder = colorToExtruder.get(color)
    const volumeName = child.name === "Map" ? `${child.name} 0x${color}` : child.name
    const volume: Volume = {
        id: volumeCount,
        name: volumeName,
        color,
        extruder,
        firstTriangleId,
        lastTriangleId
    }
    volumes.push(volume)
}
 
function convertColorArrayToHexString(color: Float32BufferAttribute | number[], index: number): string {
    const colorsArray: number[] =
        color instanceof BufferAttribute
            ? [
                  (color as Float32BufferAttribute).getX(index),
                  (color as Float32BufferAttribute).getY(index),
                  (color as Float32BufferAttribute).getZ(index)
              ]
            : [color[index], color[index + 1], color[index + 2]]
 
    return colorsArray
        .map(c =>
            Math.round(c * 255)
                .toString(16)
                .padStart(2, "0")
        )
        .join("")
}
 
export const exportedForTesting = {
    extractMeshData,
    extractChildMeshData,
    groupMeshVerticesByColor,
    constructVertices,
    constructTriangles,
    constructVolume,
    convertColorArrayToHexString
}