mcneel / rhino-developer-samples

Rhino and Grasshopper developer sample code
http://developer.rhino3d.com
Other
631 stars 332 forks source link

Converting OBJ to 3DM: Validity Issues in Generated Files #94

Open hassanteymoori opened 7 months ago

hassanteymoori commented 7 months ago

I’m attempting to load and convert an OBJ file to 3DM format using the rhino3dmlibrary. Here’s the relevant code snippet:

import rhino3dm from 'rhino3dm';
import * as fs from 'fs';
import * as THREE from 'three';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';

const rhino = await rhino3dm();
console.log('Loaded rhino3dm.');

const fileContent = fs.readFileSync('public/models/test.obj').toString();

const loader = new OBJLoader();
const obj = loader.parse(fileContent);

let exportGeometry = null;
if (obj.children) {
    obj.children.forEach((mesh) => {
        if (!exportGeometry) {
            console.log('here');
            exportGeometry = mesh.geometry;
        } else {
            exportGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries([exportGeometry, mesh.geometry], false);
        }
    });
}
const rhinoMesh = rhino.Mesh.createFromThreejsJSON({data: exportGeometry})

const doc = new rhino.File3dm()
doc.objects().add(rhinoMesh, null)

let opts = new rhino.File3dmWriteOptions()
opts.version = 6;
let buffer = doc.toByteArrayOptions(opts);
fs.writeFileSync('public/models/test.3dm', buffer);
console.log('3DM file saved successfully.');

The code successfully generates a 3DM file, but unfortunately, the resulting file is not valid. When re-uploaded to a 3D viewer, it fails to load properly. I’ve followed the example from the repository, but I’m encountering this issue.

Any insights on why the generated 3DM file isn’t valid, and how I can address this problem?

GitHubDragonFly commented 7 months ago

@hassanteymoori this is just an attempt to help you a little bit with this issue.

You can always check the code in my custom 3DM Exporter for a reference.

If your obj is just a mesh that doesn't have any children then your if (obj.children) will always be skipped.

You should instead try to traverse the obj and create a rhino mesh out of any mesh you encounter and then add it to the rhino document (or file).

Take your time and inspect the function parse_objects() in my custom exporter.