InstanceDefinition Serialization

Is there anyway that can directly serialize an InstanceDefinition object?

What I’m trying to do is to store a block to a binary file that can be reused afterwards. It seems that the InstanceDefinition is not marked as Serializable.

//  InstanceDefinition obj = ... ...
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
    bf.Serialize(ms, obj);
    var bytes = ms.ToArray();

It throws:
Type 'Rhino.DocObjects.InstanceDefinition' in Assembly 'RhinoCommon, Version=6.24.20079.23341, Culture=neutral, PublicKeyToken=552281e97c755530' is not marked as serializable. (line: 0)

What I could do now is that I could explode the InstanceDefinition first, and store the geometry separately, with some additional markups saying “hey these are things within a block named xxxxxx”, so that when I came back later on to read them (probably from a database or a single file, haven’t decided yet), I have an idea these ones belongs to one block thus assemble them correctly… but is it the correct way of doing it?

Hi @bwkair,

Trying to serialize an InstanceDefiniton object isn’t enough. An InstanceDefinition reference a bunch of instance definition geometry. And that geometry has properties such as layers, materials, etc. What I’m saying is that this is really hard to get right.

Honestly the best thing to do in this case is to just script the BlockManager command and it’s Export option. something like this:

public class TestExportBlockCommand : Command
  public override string EnglishName => "TestExportBlock";

  protected override Result RunCommand(RhinoDoc doc, RunMode mode)
    var block_name = "Widget";
    var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    var filename = Path.Combine(path, block_name + ".3dm");
    var script = string.Format("_-BlockManager _Export \"{0}\" \"{1}\" _Enter", block_name, filename);
    RhinoApp.RunScript(script, true);
    return Result.Success;

– Dale

Thanks @dale.

Before actually read your reply, I had tried some code and realized the problem you had mentioned. The block is not only dealing with the geometry alone. The materials are really the main problem.

I’ve noticed the new RhinoDoc.ExportSelected() API come up with Rhino7 which is a really attractive option for me to do some tricks with it, but it may not be available for everyone yet. So I’ll try the BlockManager and see how it goes on Monday.