Parse obj files

Hello,

I’m using a c++ library in a grasshopper plugin that ouputs the result as an OBJ ASCII string. It only returns vertices and faces, no textures or normals. I have seen that there is a Rhinocommon method for importing obj files programatically but it seems to be geared for Rhino. I could use a third partly OBJ parser but I was wondering if there is a native rhinocommon solution.

Best,

private void RunScript(string file, ref object A)
{
  var doc = RhinoDoc.CreateHeadless("");
  var options = new FileReadOptions()
    {
      BatchMode = true,
      ImportMode = true,
      ImportReferenceMode = false,
      InsertMode = false,
      NewMode = false,
      OpenMode = false,
      ScaleGeometry = false,
      UseScaleGeometry = true
      };
  var objOptions = new FileObjReadOptions(options)
    {
      MapYtoZ = true,
      IgnoreTextures = true,
      UseObjGroupsAs = FileObjReadOptions.UseObjGsAs.IgnoreObjGroups
      };
  FileObj.Read(file, doc, objOptions);
  var meshes = new List<Mesh>();
  foreach (var rhinoObject in doc.Objects.GetObjectList(ObjectType.Mesh))
  {
    var meshObject = rhinoObject as MeshObject;
    if (meshObject == null) continue;
    var mesh = meshObject.Geometry as Mesh;
    if (mesh == null) continue;
    meshes.Add(mesh.DuplicateMesh());
  }
  doc.Dispose();
  A = meshes;
}

ObjMeshes.gh (1.8 KB)
untitled1.obj (62.7 KB) (source)

2 Likes

Thank you @Mahdiyar! I wasn’t aware you could create a headless doc, which sorts some of the issues I had with using FileRead. However, this implies that I have to collect the stdout string save it to a tmp file and then feed it to FileObj.Read. I have two concerns, perhaps unfunded, with this approach when the plugin is distributed: performance and permissions. Can a plugin write to disk? Or maybe the question should be where does it have permissions to write to disk. The performance issue is a rabit hole…maybe leave it for another day.