Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions packages/io/obj-serializer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ const serialize = (options, ...objects) => {
// construct the contents of the OBJ file
let body = '# Wavefront OBJ file generated by JSCAD\n'

// find unique vertices
const vertices = []
// find unique vertices - use Map for O(1) lookup instead of O(n) indexOf
const vertexMap = new Map() // vertex string -> index (1-based)

// convert objects
// TODO: group objects together
Expand All @@ -86,9 +86,10 @@ const serialize = (options, ...objects) => {
polygons.forEach((polygon) => {
polygon.vertices.forEach((vertex) => {
const vertexString = convertVertex(vertex)
if (vertices.indexOf(vertexString) < 0) {
if (!vertexMap.has(vertexString)) {
// add unique vertices
vertices.push(vertexString)
const index = vertexMap.size + 1 // OBJ uses 1-based indexing
vertexMap.set(vertexString, index)
body += `${vertexString}\n`
}
})
Expand All @@ -99,7 +100,7 @@ const serialize = (options, ...objects) => {
polygons.forEach((polygon) => {
// convert vertices to indices
const indices = polygon.vertices
.map((v) => vertices.indexOf(convertVertex(v)) + 1)
.map((v) => vertexMap.get(convertVertex(v)))
// set face color
const color = getColorName(polygon) || objectColor || 'default'
if (color !== previousColor) {
Expand Down