Skip to content

Commit

Permalink
Function to write obj files
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderbates committed Jul 13, 2024
1 parent 80f4372 commit c0cc94a
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions R/vtk.R
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,56 @@ write_mesh3d_to_vtk <- function(mesh, filename) {
system(sprintf("head -n 10 %s", filename))
}

# Write a OBJ file from mesh3d
write_mesh3d_to_obj <- function(mesh, filename) {

This comment has been minimized.

Copy link
@jefferis

jefferis Jul 13, 2024

Member

@alexanderbates does this do something that nat::write.neuron(format='obj') doesn't do?

This comment has been minimized.

Copy link
@alexanderbates

alexanderbates Jul 13, 2024

Author Collaborator

It does not, I had forgotten about nat::write.neuron(format='obj')

if (!inherits(mesh, "mesh3d")) {
stop("Input must be a mesh3d object")
}

# Open the file for writing
con <- file(filename, "w")
on.exit(close(con)) # Ensure the file is closed when the function exits

# Write vertices
vertices <- t(mesh$vb[1:3, ] / mesh$vb[4, ])
write(paste("v", vertices[,1], vertices[,2], vertices[,3]), con, sep = "\n")

# Write texture coordinates if present
if (!is.null(mesh$texcoords)) {
texcoords <- t(mesh$texcoords)
write(paste("vt", texcoords[,1], texcoords[,2]), con, sep = "\n")
}

# Write normals if present
if (!is.null(mesh$normals)) {
normals <- t(mesh$normals[1:3, ] / mesh$normals[4, ])
write(paste("vn", normals[,1], normals[,2], normals[,3]), con, sep = "\n")
}

# Write faces
faces <- t(mesh$it)
if (!is.null(mesh$texcoords) && !is.null(mesh$normals)) {
# Faces with vertex/texture/normal indices
write(paste("f",
paste(faces[,1], faces[,1], faces[,1], sep="/"),
paste(faces[,2], faces[,2], faces[,2], sep="/"),
paste(faces[,3], faces[,3], faces[,3], sep="/")), con, sep = "\n")
} else if (!is.null(mesh$texcoords)) {
# Faces with vertex/texture indices
write(paste("f",
paste(faces[,1], faces[,1], sep="/"),
paste(faces[,2], faces[,2], sep="/"),
paste(faces[,3], faces[,3], sep="/")), con, sep = "\n")
} else if (!is.null(mesh$normals)) {
# Faces with vertex//normal indices
write(paste("f",
paste(faces[,1], "", faces[,1], sep="/"),
paste(faces[,2], "", faces[,2], sep="/"),
paste(faces[,3], "", faces[,3], sep="/")), con, sep = "\n")
} else {
# Faces with only vertex indices
write(paste("f", faces[,1], faces[,2], faces[,3]), con, sep = "\n")
}

cat("OBJ file written successfully:", filename, "\n")
}

0 comments on commit c0cc94a

Please sign in to comment.