コード例 #1
0
        public static GH_Archive ArchiveFromBase64String(string blob)
        {
            if (string.IsNullOrWhiteSpace(blob))
            {
                return(null);
            }

            byte[] byteArray = Convert.FromBase64String(blob);
            try
            {
                var byteArchive = new GH_Archive();
                if (byteArchive.Deserialize_Binary(byteArray))
                {
                    return(byteArchive);
                }
            }
            catch (Exception) { }

            var grasshopperXml = StripBom(System.Text.Encoding.UTF8.GetString(byteArray));
            var xmlArchive     = new GH_Archive();

            if (xmlArchive.Deserialize_Xml(grasshopperXml))
            {
                return(xmlArchive);
            }

            return(null);
        }
コード例 #2
0
        public static Result ReadFromFile(string filePath, out GH_Document definition)
        {
            definition = null;

            var CurrentCulture = Thread.CurrentThread.CurrentCulture;

            try
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                var archive = new GH_Archive();
                if (!archive.ReadFromFile(filePath))
                {
                    return(Result.Failed);
                }

                definition = new GH_Document();
                if (archive.ExtractObject(definition, "Definition"))
                {
                    return(Result.Succeeded);
                }

                definition?.Dispose();
                definition = null;
                return(Result.Failed);
            }
            catch (Exception)
            {
                return(Result.Failed);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = CurrentCulture;
            }
        }
コード例 #3
0
        public static MenuBarManager.CallbackStatus ReadFromFile(string filePath, out GH_Document definition)
        {
            definition = null;

            try
            {
                var archive = new GH_Archive();
                if (!archive.ReadFromFile(filePath))
                {
                    return(MenuBarManager.CallbackStatus.Error);
                }

                definition = new GH_Document();
                if (archive.ExtractObject(definition, "Definition"))
                {
                    return(MenuBarManager.CallbackStatus.Continue);
                }

                definition?.Dispose();
                definition = null;
                return(MenuBarManager.CallbackStatus.Error);
            }
            catch (Exception)
            {
                return(MenuBarManager.CallbackStatus.Error);
            }
        }
コード例 #4
0
ファイル: MedinaMotif.cs プロジェクト: rch-dev/medina.api
        public MedinaMotif(string name, string ghxText)
        {
            Name = name;

            GhArchive = new GH_Archive();
            GhArchive.Deserialize_Xml(ghxText);
            GhDoc = new GH_Document();
            GhArchive.ExtractObject(GhDoc, "Definition");
        }
コード例 #5
0
        private static GrasshopperDefinition Construct(GH_Archive archive)
        {
            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception("Unable to extract definition from archive");
            }

            // raise DocumentServer.DocumentAdded event (used by some plug-ins)
            Grasshopper.Instances.DocumentServer.AddDocument(definition);

            GrasshopperDefinition rc = new GrasshopperDefinition(definition);

            foreach (var obj in definition.Objects)
            {
                IGH_ContextualParameter contextualParam = obj as IGH_ContextualParameter;
                if (contextualParam != null)
                {
                    IGH_Param param = obj as IGH_Param;
                    if (param != null)
                    {
                        rc._input[param.NickName] = new InputGroup(param);
                    }
                    continue;
                }

                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                string nickname     = group.NickName;
                var    groupObjects = group.Objects();
                if (nickname.Contains("RH_IN") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._input[nickname] = new InputGroup(param);
                    }
                }

                if (nickname.Contains("RH_OUT") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._output[nickname] = param;
                    }
                }
            }
            return(rc);
        }
コード例 #6
0
 private void RecallGraph(IGH_Graph g)
 {
     if (g != null && m_graph_history.ContainsKey(g.GraphTypeID))
     {
         GH_Archive gH_Archive = new GH_Archive();
         if (gH_Archive.Deserialize_Xml(m_graph_history[g.GraphTypeID]))
         {
             gH_Archive.ExtractObject((GH_ISerializable)g, "graph");
         }
     }
 }
コード例 #7
0
        public MedinaMotifBuilder FromGhx(string path)
        {
            var ghxText = System.IO.File.ReadAllText(path);

            GhArchive = new GH_Archive();
            GhArchive.Deserialize_Xml(ghxText);
            GhDoc = new GH_Document();
            GhArchive.ExtractObject(GhDoc, "Definition");

            return(this);
        }
コード例 #8
0
 private static GH_Archive ReadFromFile(string filePath)
 {
     try
     {
         var archive = new GH_Archive();
         archive.ReadFromFile(filePath);
         return(archive);
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #9
0
        public static GH_Archive ArchiveFromUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return(null);
            }

            if (File.Exists(url))
            {
                // local file
                var archive = new GH_Archive();
                if (archive.ReadFromFile(url))
                {
                    RegisterFileWatcher(url);
                    return(archive);
                }
                return(null);
            }

            byte[]         byteArray = null;
            HttpWebRequest request   = (HttpWebRequest)WebRequest.Create(url);

            request.AutomaticDecompression = DecompressionMethods.GZip;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (var stream = response.GetResponseStream())
                    using (var memStream = new MemoryStream())
                    {
                        stream.CopyTo(memStream);
                        byteArray = memStream.ToArray();
                    }

            try
            {
                var byteArchive = new GH_Archive();
                if (byteArchive.Deserialize_Binary(byteArray))
                {
                    return(byteArchive);
                }
            }
            catch (Exception) { }

            var grasshopperXml = StripBom(System.Text.Encoding.UTF8.GetString(byteArray));
            var xmlArchive     = new GH_Archive();

            if (xmlArchive.Deserialize_Xml(grasshopperXml))
            {
                return(xmlArchive);
            }

            return(null);
        }
コード例 #10
0
        // Currently need a separate RunHelper function so the .NET runtime won't attempt to load the
        // Grasshopper assembly until after RhinoCore has been created. This should be "fixable" in a
        // future version of the RhinoInside nuget package
        static void RunHelper()
        {
            // Extract definition to sample location as executable
            var    assembly       = typeof(Program).Assembly;
            string dir            = System.IO.Path.GetDirectoryName(assembly.Location);
            string definitionPath = System.IO.Path.Combine(dir, "simple_def.gh");

            using (var resStream = assembly.GetManifestResourceStream("RunGrasshopper.simple_def.gh"))
                using (var outStream = new System.IO.FileStream(definitionPath, System.IO.FileMode.Create))
                {
                    resStream.CopyTo(outStream);
                }


            // Start grasshopper in "headless" mode
            var pluginObject = Rhino.RhinoApp.GetPlugInObject("Grasshopper") as Grasshopper.Plugin.GH_RhinoScriptInterface;

            pluginObject.RunHeadless();

            var archive = new GH_Archive();

            archive.ReadFromFile(definitionPath);

            using (var definition = new Grasshopper.Kernel.GH_Document())
            {
                archive.ExtractObject(definition, "Definition");
                foreach (var obj in definition.Objects)
                {
                    if (obj is Grasshopper.Kernel.IGH_Param param)
                    {
                        if (obj.NickName == "CollectMe")
                        {
                            param.CollectData();
                            param.ComputeData();
                            foreach (var item in param.VolatileData.AllData(true))
                            {
                                Line computedLine = Line.Unset;
                                if (item.CastTo(out computedLine))
                                {
                                    Console.WriteLine($"Got a line ... {computedLine}");
                                }
                            }
                        }
                    }
                }
            }
            Console.WriteLine("Done... press and key to exit");
            Console.ReadKey();
        }
コード例 #11
0
        private static void DisplayObjectStatistics(GH_Archive archive)
        {
            var root       = archive.GetRootNode;
            var definition = root.FindChunk("Definition");
            var objects    = definition.FindChunk("DefinitionObjects");

            var count   = objects.GetInt32("ObjectCount");
            var missing = 0;

            var guids     = new List <Guid>(count);
            var plurality = new List <int>(count);
            var names     = new List <string>(count);

            for (int i = 0; i < count; i++)
            {
                var chunk = objects.FindChunk("Object", i);
                if (chunk is null)
                {
                    missing++;
                }
                else
                {
                    ParseObjectChunk(chunk, guids, plurality, names);
                }
            }

            var descriptors = new string[guids.Count];

            for (int i = 0; i < guids.Count; i++)
            {
                var prefix = $"{plurality[i]} × {names[i]} ";
                if (prefix.Length < 30)
                {
                    prefix += new string(' ', 30 - prefix.Length);
                }
                descriptors[i] = $"{prefix}({guids[i]})";
            }
            Array.Sort(plurality.ToArray(), descriptors);
            Array.Reverse(descriptors);

            Console.Write("Object Count:   "); WriteLine(ConsoleColor.DarkCyan, count.ToString());
            Console.Write("Missing Chunks: "); WriteLine(ConsoleColor.DarkRed, missing.ToString());

            for (int i = 0; i < descriptors.Length; i++)
            {
                WriteLine(ConsoleColor.Magenta, descriptors[i]);
            }
        }
コード例 #12
0
        private static GH_Archive ReadFile(string path)
        {
            var archive = new GH_Archive();

            try
            {
                if (archive.ReadFromFile(path))
                {
                    if (archive.MessageCount() > 0)
                    {
                        foreach (var msg in archive.Messages)
                        {
                            switch (msg.Type)
                            {
                            case GH_Message_Type.warning:
                                WriteLine(ConsoleColor.DarkYellow, "  " + msg.Message);
                                break;

                            case GH_Message_Type.error:
                                WriteLine(ConsoleColor.Red, "  " + msg.Message);
                                break;
                            }
                        }
                    }

                    if (archive.GetRootNode is null)
                    {
                        WriteLine(ConsoleColor.Red, "An error occured while reading that file:");
                        WriteLine(ConsoleColor.Red, "  The archive does not contain a root node.");
                        Console.ReadKey(true);
                        return(null);
                    }
                    return(archive);
                }

                Console.ReadKey(true);
                return(null);
            }
            catch (Exception ex)
            {
                WriteLine(ConsoleColor.Red, "An error occured while reading that file:");
                WriteLine(ConsoleColor.Red, "  " + ex.Message);
                Console.ReadKey(true);
                return(null);
            }
        }
コード例 #13
0
        public static GH_Archive GetCachedArchive(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return(null);
            }
            GH_Archive archive = System.Runtime.Caching.MemoryCache.Default.Get(key) as GH_Archive;

            if (archive == null)
            {
                archive = ResthopperEndpointsModule.ArchiveFromUrl(key);
                if (archive != null)
                {
                    System.Runtime.Caching.MemoryCache.Default.Add(key, archive, CachePolicy);
                }
            }
            return(archive);
        }
コード例 #14
0
ファイル: Parser.cs プロジェクト: mjkkirschner/VVD
        //Actual constructor for use in the program
        public static CommonGraph CommonGraphFromGHFile(string file)
        {
            CommonGraph cg = new CommonGraph();

            //construct GH Archive object for XML Traversal
            GH_Archive archive = new GH_Archive();
            archive.ReadFromFile(file);

            //traverse GH file tree
            var rootNode = archive.GetRootNode;
            var definition = rootNode.FindChunk("Definition");
            var defObjects = definition.FindChunk("DefinitionObjects");
            int objCount = defObjects.GetInt32("ObjectCount");

            //for every object in the definition object list:
            for (int i = 0; i < objCount; i++)
            {
                var singleObjectChunk = defObjects.Chunks[i] as GH_Chunk;

                Guid typeGuid = singleObjectChunk.GetGuid("GUID");

                var container = singleObjectChunk.FindChunk("Container");
                Guid instanceGuid = container.GetGuid("InstanceGuid");
                string name = singleObjectChunk.GetString("Name");

                //Test if the object has sources (and is therefore an object of interest.)
                //TODO: improve this method
                bool isActiveObject = container.ItemExists("SourceCount");

                bool hasInputs = container.Chunks.Where(C => C.Name == "param_input").Count() > 0;
                bool hasOutputs = container.Chunks.Where(C => C.Name == "param_output").Count() > 0;
                bool isComponent = hasInputs || hasOutputs;

                Console.WriteLine(isComponent.ToString());
                Node node = new Node();
                node.Type = typeGuid.ToString();
                node.InstanceGuid = instanceGuid;

                cg.Nodes.Add(node);
            }

            return cg;
        }
コード例 #15
0
        private static void DisplayDocumentStatistics(GH_Archive archive)
        {
            var root = archive.GetRootNode;

            var definition = root.FindChunk("Definition");
            var header     = definition.FindChunk("DocumentHeader");
            var properties = definition.FindChunk("DefinitionProperties");

            var archiveVersion = root.GetVersion("ArchiveVersion");
            var pluginVersion  = definition.GetVersion("plugin_version");
            var documentId     = header.GetGuid("DocumentID");
            var documentDate   = properties.GetDate("Date");
            var documentName   = properties.GetString("Name");

            Console.Write("Archive Version: "); WriteLine(ConsoleColor.DarkCyan, archiveVersion.ToString());
            Console.Write("Plug-In Version: "); WriteLine(ConsoleColor.DarkCyan, pluginVersion.ToString());
            Console.Write("Document ID:     "); WriteLine(ConsoleColor.DarkCyan, $"{{{documentId}}}");
            Console.Write("Document Date:   "); WriteLine(ConsoleColor.DarkCyan, documentDate.ToLongDateString() + " " + documentDate.ToLongTimeString());
            Console.Write("Document Name:   "); WriteLine(ConsoleColor.DarkCyan, $"'{documentName}'");
        }
コード例 #16
0
ファイル: Medina.cs プロジェクト: rch-dev/medina.api
        public static List <MedinaMotif> LoadMotifs(string path)
        {
            var archive = new GH_Archive();

            var ghxText = System.IO.File.ReadAllText(path);

            try
            {
                archive.Deserialize_Xml(ghxText);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            var definition = new GH_Document();

            archive.ExtractObject(definition, "Definition");

            Console.WriteLine($"{definition.ObjectCount.ToString()} objects in loaded definition.");

            foreach (var obj in definition.Objects)
            {
                var param = obj as IGH_Param;
                if (param == null)
                {
                    continue;
                }

                if (param.Sources.Count == 0 && param.Recipients.Count != 0 && param.NickName.Length > 1)
                {
                    Console.WriteLine($"Primary input named {param.NickName} discovered!");
                }
                else if (param.NickName != null || param.NickName.Length > 1)
                {
                    //Console.WriteLine($"Param {param.NickName} skipped. ({param.SourceCount.ToString()} sources / {param.Recipients.Count} recipients)");
                }
            }

            return(null);
        }
コード例 #17
0
        private static GrasshopperDefinition Construct(GH_Archive archive)
        {
            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception("Unable to extract definition from archive");
            }

            GrasshopperDefinition rc = new GrasshopperDefinition(definition);

            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                string nickname     = group.NickName;
                var    groupObjects = group.Objects();
                if (nickname.Contains("RH_IN") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._input[nickname] = new InputGroup(param);
                    }
                }

                if (nickname.Contains("RH_OUT") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._output[nickname] = param;
                    }
                }
            }
            return(rc);
        }
コード例 #18
0
        private void RememberGraph(IGH_Graph g)
        {
            if (g == null)
            {
                return;
            }
            Guid graphTypeID = g.GraphTypeID;

            if (m_graph_history.ContainsKey(graphTypeID))
            {
                m_graph_history.Remove(graphTypeID);
            }
            GH_Archive gH_Archive = new GH_Archive();

            if (gH_Archive.AppendObject((GH_ISerializable)g, "graph"))
            {
                string value = gH_Archive.Serialize_Xml();
                if (!string.IsNullOrEmpty(value))
                {
                    m_graph_history.Add(graphTypeID, value);
                }
            }
        }
コード例 #19
0
        private static void DisplayAuthorStatistics(GH_Archive archive)
        {
            var root       = archive.GetRootNode;
            var definition = root.FindChunk("Definition");
            var author     = definition.FindChunk("Author");

            if (author is null)
            {
                WriteLine(ConsoleColor.Red, "File does not contain any author data.");
                WriteLine(ConsoleColor.Red, "This is not indicative of a problem as it is optional.");
                return;
            }

            string name      = "<unspecified>";
            string email     = "<unspecified>";
            string phone     = "<unspecified>";
            string address   = "<unspecified>";
            string website   = "<unspecified>";
            string company   = "<unspecified>";
            string copyright = "<unspecified>";

            author.TryGetString("Name", ref name);
            author.TryGetString("EMail", ref email);
            author.TryGetString("Phone", ref phone);
            author.TryGetString("Address", ref address);
            author.TryGetString("Website", ref website);
            author.TryGetString("Company", ref company);
            author.TryGetString("Copyright", ref copyright);

            Console.Write("Name:      "); WriteLine(ConsoleColor.DarkCyan, name);
            Console.Write("Company:   "); WriteLine(ConsoleColor.DarkCyan, company);
            Console.Write("Copyright: "); WriteLine(ConsoleColor.DarkCyan, copyright);
            Console.Write("E-mail:    "); WriteLine(ConsoleColor.DarkCyan, email);
            Console.Write("Phone:     "); WriteLine(ConsoleColor.DarkCyan, phone);
            Console.Write("Website:   "); WriteLine(ConsoleColor.DarkCyan, website);
            Console.Write("Address:   "); WriteLine(ConsoleColor.DarkCyan, address.Replace(Environment.NewLine, ", "));
        }
コード例 #20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool enabled = false;

            if (DA.GetData <bool>(0, ref enabled))
            {
                GH_Document document = this.OnPingDocument();
                if (document == null)
                {
                    base.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Document");
                    return;
                }
                string filePath = document.FilePath;
                if (string.IsNullOrEmpty(filePath))
                {
                    base.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Document not saved yet!");
                    return;
                }
                string        directory     = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
                DirectoryInfo directoryInfo = Directory.CreateDirectory(directory);
                if (directoryInfo == null)
                {
                    directoryInfo = new DirectoryInfo(directory);
                }
                foreach (FileInfo file in directoryInfo.GetFiles())
                {
                    file.Delete();                     // Should ignore git files
                }
                foreach (GH_Component component in Grasshopper.Instances.ActiveCanvas.Document.Objects.OfType <GH_Component>())
                {
                    GH_Archive archieve = new GH_Archive();
                    archieve.AppendObject(component, "Component");
                    archieve.WriteToFile(Path.Combine(directory, component.InstanceGuid.ToString("N") + ".ghx"), true, false);
                }
            }
        }
コード例 #21
0
        private static void DisplayPluginStatistics(GH_Archive archive)
        {
            var root       = archive.GetRootNode;
            var definition = root.FindChunk("Definition");
            var libraries  = definition.FindChunk("GHALibraries");

            if (libraries is null)
            {
                WriteLine(ConsoleColor.DarkRed, "Grasshopper file contains no plug-in library data...");
                return;
            }

            var count = libraries.GetInt32("Count");

            WriteLine(ConsoleColor.DarkCyan, $"Grasshopper file contains components from {count} non-standard plug-ins.");

            for (int i = 0; i < count; i++)
            {
                WriteLine(ConsoleColor.DarkCyan, $"Plugin {i + 1}:");
                var chunk = libraries.FindChunk("Library", i);
                DisplayPluginStatistics(chunk);
                Console.WriteLine();
            }
        }
コード例 #22
0
        public Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            // Load Grasshopper
            PlugIn.LoadPlugIn(new Guid(0xB45A29B1, 0x4343, 0x4035, 0x98, 0x9E, 0x04, 0x4E, 0x85, 0x80, 0xD9, 0xCF));

            string filePath;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter           = "Grasshopper Binary (*.gh)|*.gh|Grasshopper Xml (*.ghx)|*.ghx";
                openFileDialog.FilterIndex      = 1;
                openFileDialog.RestoreDirectory = true;

                switch (openFileDialog.ShowDialog())
                {
                case DialogResult.OK:     filePath = openFileDialog.FileName; break;

                case DialogResult.Cancel: return(Result.Cancelled);

                default:                  return(Result.Failed);
                }
            }

            var archive = new GH_Archive();

            if (!archive.ReadFromFile(filePath))
            {
                return(Result.Failed);
            }

            var outputs = new List <KeyValuePair <string, List <GeometryBase> > >();

            using (var definition = new GH_Document())
            {
                if (!archive.ExtractObject(definition, "Definition"))
                {
                    return(Result.Failed);
                }

                foreach (var obj in definition.Objects)
                {
                    var param = obj as IGH_Param;
                    if (param == null)
                    {
                        continue;
                    }

                    if (param.Sources.Count == 0 || param.Recipients.Count != 0)
                    {
                        continue;
                    }

                    try
                    {
                        param.CollectData();
                        param.ComputeData();
                    }
                    catch (Exception e)
                    {
                        Debug.Fail(e.Source, e.Message);
                        param.Phase = GH_SolutionPhase.Failed;
                    }

                    if (param.Phase == GH_SolutionPhase.Failed)
                    {
                        return(Result.Failed);
                    }

                    var output       = new List <GeometryBase>();
                    var volatileData = param.VolatileData;
                    for (int p = 0; p < volatileData.PathCount; ++p)
                    {
                        foreach (var goo in volatileData.get_Branch(p))
                        {
                            switch (goo)
                            {
                            case GH_Point point: output.Add(new Rhino.Geometry.Point(point.Value)); break;

                            case GH_Curve curve: output.Add(curve.Value); break;

                            case GH_Brep brep:   output.Add(brep.Value); break;

                            case GH_Mesh mesh:   output.Add(mesh.Value); break;
                            }
                        }
                    }

                    if (output.Count > 0)
                    {
                        outputs.Add(new KeyValuePair <string, List <GeometryBase> >(param.Name, output));
                    }
                }
            }

            if (outputs.Count > 0)
            {
                var uiApp = data.Application;
                var doc   = uiApp.ActiveUIDocument.Document;

                using (var trans = new Transaction(doc))
                {
                    if (trans.Start(MethodBase.GetCurrentMethod().DeclaringType.Name) == TransactionStatus.Started)
                    {
                        var categoryId = new ElementId(BuiltInCategory.OST_GenericModel);

                        foreach (var output in outputs)
                        {
                            var ds = DirectShape.CreateElement(doc, categoryId);
                            ds.Name = output.Key;

                            foreach (var geometries in output.Value.ToHost())
                            {
                                if (geometries != null)
                                {
                                    ds.AppendShape(geometries);
                                }
                            }
                        }

                        trans.Commit();
                    }
                }
            }

            return(Result.Succeeded);
        }
コード例 #23
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            myMatrix      = constructMatrixFromSliders((GH_Component)Component);
            INSTANCECOUNT = myMatrix.Count;
            if (INSTANCECOUNT > 4242)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "There are " + INSTANCECOUNT + " instances. That's quite a lot. Try reducing the parameter space!\nSpeckle WILL work but you might have a long wait ahead.");
            }
            this.Message = "# Instances:\n" + myMatrix.Count;

            if (!SOLVE)
            {
                // part of some obscure ritual code
                geometries = new List <List <System.Object> >();
                kvpairs    = new List <SuperKVP>();

                myProperties = new List <SuperProperty>();

                foreach (IGH_Param param in Component.Params.Input[1].Sources)
                {
                    SuperProperty myProperty = new SuperProperty(getPanelName(param));
                    myProperties.Add(myProperty);
                }

                EMERGENCY_BREAK = false;


                List <System.Object> inputObjects = new List <System.Object>();

                this.Message = "# Instances:\n" + myMatrix.Count;

                // critical - if not set we don't know where to sthap
                INSTANCECOUNT = myMatrix.Count;
            }
            else
            {
                // sanity checks
                if (EMERGENCY_BREAK)
                {
                    return;
                }

                // running through the iterations - so store and save

                List <System.Object> geoms = new List <System.Object>();
                List <string>        guids = new List <string>();

                foreach (IGH_Param param in Component.Params.Input[2].Sources)
                {
                    foreach (Object myObj in param.VolatileData.AllData(true))
                    {
                        geoms.Add(myObj);                         // these are the object geometries
                        guids.Add(param.InstanceGuid.ToString()); // these are the guids of the parent componenets
                    }
                }

                string path = Path.Combine(FOLDERLOCATION, currentInstanceName + ".json");


                writeFile(JsonConvert.SerializeObject(translateGeometry(geoms, guids, currentInstanceName, Component), Newtonsoft.Json.Formatting.None), path);

                // get the key value pairs nicely wrapped up
                SuperKVP myKVP = getCurrentKVP(currentInstanceName);
                kvpairs.Add(myKVP);

                this.Message = currentCount + " / " + INSTANCECOUNT;
                string[] splitvals = myKVP.values.Split(',');

                int counter = 0;

                foreach (SuperProperty prop in myProperties)
                {
                    prop.addValue(splitvals[counter]);
                    counter++;
                }

                currentCount++;

                this.Message = currentCount + "\n---\n" + INSTANCECOUNT;
                //that means we have calculated all the required instances
                if (currentCount == INSTANCECOUNT)
                {
                    SOLVE = false;
                    string pathh = "";

                    // write the static geom file

                    List <Object> staticGeo = new List <Object>();

                    foreach (IGH_Param param in Component.Params.Input[3].Sources)
                    {
                        foreach (Object myObj in param.VolatileData.AllData(true))
                        {
                            staticGeo.Add(myObj); // these are the object geometries
                        }
                    }
                    pathh = Path.Combine(FOLDERLOCATION, "static.json");
                    writeFile(JsonConvert.SerializeObject(translateGeometry(staticGeo, new List <string>(), "staticGeo", Component), Newtonsoft.Json.Formatting.None), pathh);


                    OUTFILE            = new System.Dynamic.ExpandoObject();
                    OUTFILE.meta       = "ParametricSpaceExporter";
                    OUTFILE.parameters = new List <dynamic>();
                    OUTFILE.propNames  = new List <string>();
                    OUTFILE.kvpairs    = kvpairs;

                    foreach (IGH_Param param in Component.Params.Input[1].Sources)
                    {
                        //Print(getPanelNameAndVal(param));
                        var myprop = getPanelNameAndVal(param);
                        if (myprop != null)
                        {
                            string[] pops = myprop.Split(',');
                            OUTFILE.propNames.Add(pops[0]);
                        }
                    }

                    // populate the sliders
                    int k = 0;
                    foreach (List <double> mySliderVars in sliderValues)
                    {
                        dynamic Slider = new System.Dynamic.ExpandoObject();
                        Slider.name   = sliderNames.ElementAt(k++);
                        Slider.values = mySliderVars;
                        OUTFILE.parameters.Add(Slider);
                    }

                    OUTFILE.properties = myProperties;

                    pathh = Path.Combine(FOLDERLOCATION, "params.json");

                    writeFile(JsonConvert.SerializeObject(OUTFILE, Newtonsoft.Json.Formatting.None), pathh);

                    // copy/write the gh defintion in the folder

                    if (allowDefExport)
                    {
                        string     ghSavePath = Path.Combine(FOLDERLOCATION, "def.ghx");
                        GH_Archive myArchive  = new GH_Archive();
                        myArchive.Path = ghSavePath;
                        myArchive.AppendObject(GrasshopperDocument, "Definition");
                        myArchive.WriteToFile(ghSavePath, true, false);
                    }

                    // zip things up
                    string startPath = FOLDERLOCATION;

                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddDirectory(@startPath);
                        zip.Save(startPath + @"\" + GHDEFNAME + ".zip");
                    }

                    // delete the garbage data

                    System.IO.DirectoryInfo myDir = new DirectoryInfo(FOLDERLOCATION);

                    foreach (FileInfo file in myDir.GetFiles())
                    {
                        if (!(file.Extension == ".zip"))
                        {
                            file.Delete();
                        }
                    }

                    // open an explorer window to the location of the archive.
                    Process.Start("explorer.exe", FOLDERLOCATION);

                    PATHISSET      = false;
                    FOLDERLOCATION = "";

                    Component.ExpireSolution(true);
                }
            }
        }
コード例 #24
0
    // Start is called before the first frame update
    void Start()
    {
        client = new RestClient(serviceUrl);

        archive = new GH_Archive();
        archive.ReadFromFile(Application.streamingAssetsPath + "\\" + ghFile);

        var root = archive.GetRootNode;
        var def  = root.FindChunk("Definition") as GH_Chunk;
        var objs = def.FindChunk("DefinitionObjects") as GH_Chunk;

        if (objs != null)
        {
            int count = objs.GetInt32("ObjectCount");

            var inputGuids = new List <Guid>();
            var inputNames = new List <string>();

            for (int i = 0; i < count; i++)
            {
                var obj       = objs.FindChunk("Object", i) as GH_Chunk;
                var container = obj.FindChunk("Container") as GH_Chunk;

                var name = container.GetString("Name");
                if (name == "Group")
                {
                    var nickname = container.GetString("NickName");
                    if (nickname.IndexOf("RH_IN:") != -1)
                    {
                        var inputname = nickname.Replace("RH_IN:", "");
                        var itemguid  = container.GetGuid("ID", 0);
                        inputNames.Add(inputname);
                        inputGuids.Add(itemguid);
                    }
                }
            }

            for (int i = 0; i < count; i++)
            {
                var obj       = objs.FindChunk("Object", i) as GH_Chunk;
                var container = obj.FindChunk("Container") as GH_Chunk;

                var instanceguid = container.GetGuid("InstanceGuid");
                if (inputGuids.Contains(instanceguid))
                {
                    var    index        = inputGuids.IndexOf(instanceguid);
                    var    inputName    = inputNames[index];
                    var    componetName = container.GetString("Name");
                    object value        = null;
                    switch (componetName)
                    {
                    case ("Point"):
                        value = new float[] { 0.5f, 0.5f, 0.5f };
                        break;

                    case ("Number"):
                        value = 0.5f;
                        break;

                    case ("Integer"):
                        value = 10;
                        break;

                    default:
                        break;
                    }

                    var ghInput = new GHInput(componetName, inputName, value);
                    ghInputs.Add(ghInput);
                }
            }
        }

        SendGHData();
    }
コード例 #25
0
        public Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            // Load Grasshopper
            PlugIn.LoadPlugIn(new Guid(0xB45A29B1, 0x4343, 0x4035, 0x98, 0x9E, 0x04, 0x4E, 0x85, 0x80, 0xD9, 0xCF));

            string filePath;

            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Grasshopper Binary (*.gh)|*.gh|Grasshopper Xml (*.ghx)|*.ghx";
#if DEBUG
                openFileDialog.FilterIndex = 2;
#else
                openFileDialog.FilterIndex = 1;
#endif
                openFileDialog.RestoreDirectory = true;

                switch (openFileDialog.ShowDialog())
                {
                case DialogResult.OK:     filePath = openFileDialog.FileName; break;

                case DialogResult.Cancel: return(Result.Cancelled);

                default:                  return(Result.Failed);
                }
            }

            var transactionName = string.Empty;

            var archive = new GH_Archive();
            if (!archive.ReadFromFile(filePath))
            {
                return(Result.Failed);
            }

            var outputs = new List <KeyValuePair <string, List <GeometryBase> > >();
            using (var definition = new GH_Document())
            {
                if (!archive.ExtractObject(definition, "Definition"))
                {
                    return(Result.Failed);
                }

                transactionName = Path.GetFileNameWithoutExtension(definition.Properties.ProjectFileName);

                var inputs = new List <IGH_Param>();

                // Collect input params
                foreach (var obj in definition.Objects)
                {
                    if (!(obj is IGH_Param param))
                    {
                        continue;
                    }

                    if (param.Sources.Count != 0 || param.Recipients.Count == 0)
                    {
                        continue;
                    }

                    if (param.VolatileDataCount > 0)
                    {
                        continue;
                    }

                    if (param.Locked)
                    {
                        continue;
                    }

                    inputs.Add(param);
                }

                // Prompt for input values
                var values = new Dictionary <IGH_Param, IEnumerable <IGH_Goo> >();
                foreach (var input in inputs.OrderBy((x) => x.Attributes.Pivot.Y))
                {
                    switch (input)
                    {
                    case Param_Box box:
                        var boxes = PromptBox(data.Application.ActiveUIDocument, input.NickName);
                        if (boxes == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, boxes);
                        break;

                    case Param_Point point:
                        var points = PromptPoint(data.Application.ActiveUIDocument, input.NickName);
                        if (points == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, points);
                        break;

                    case Param_Curve curve:
                        var curves = PromptEdge(data.Application.ActiveUIDocument, input.NickName);
                        if (curves == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, curves);
                        break;

                    case Param_Surface surface:
                        var surfaces = PromptSurface(data.Application.ActiveUIDocument, input.NickName);
                        if (surfaces == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, surfaces);
                        break;

                    case Param_Brep brep:
                        var breps = PromptBrep(data.Application.ActiveUIDocument, input.NickName);
                        if (breps == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, breps);
                        break;
                    }
                }

                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    // Update input volatile data values
                    foreach (var value in values)
                    {
                        value.Key.AddVolatileDataList(new Grasshopper.Kernel.Data.GH_Path(0), value.Value);
                    }

                    // Collect output values
                    foreach (var obj in definition.Objects)
                    {
                        if (!(obj is IGH_Param param))
                        {
                            continue;
                        }

                        if (param.Sources.Count == 0 || param.Recipients.Count != 0)
                        {
                            continue;
                        }

                        if (param.Locked)
                        {
                            continue;
                        }

                        try
                        {
                            param.CollectData();
                            param.ComputeData();
                        }
                        catch (Exception e)
                        {
                            Debug.Fail(e.Source, e.Message);
                            param.Phase = GH_SolutionPhase.Failed;
                        }

                        if (param.Phase == GH_SolutionPhase.Failed)
                        {
                            return(Result.Failed);
                        }

                        var output       = new List <GeometryBase>();
                        var volatileData = param.VolatileData;
                        if (volatileData.PathCount > 0)
                        {
                            foreach (var value in param.VolatileData.AllData(true).Select(x => x.ScriptVariable()))
                            {
                                switch (value)
                                {
                                case Rhino.Geometry.Point3d point:          output.Add(new Rhino.Geometry.Point(point)); break;

                                case Rhino.Geometry.GeometryBase geometry:  output.Add(geometry); break;
                                }
                            }
                        }

                        if (output.Count > 0)
                        {
                            outputs.Add(new KeyValuePair <string, List <GeometryBase> >(param.NickName, output));
                        }
                    }
                }
                catch (Exception)
                {
                    return(Result.Failed);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }

            // Bake output geometry
            if (outputs.Count > 0)
            {
                var uiApp = data.Application;
                var doc   = uiApp.ActiveUIDocument.Document;

                using (var trans = new Transaction(doc, transactionName))
                {
                    if (trans.Start(MethodBase.GetCurrentMethod().DeclaringType.Name) == TransactionStatus.Started)
                    {
                        if (!Enum.TryParse(categoriesComboBox.Current.Name, out BuiltInCategory builtInCategory))
                        {
                            builtInCategory = BuiltInCategory.OST_GenericModel;
                        }

                        var categoryId = new ElementId(builtInCategory);

                        foreach (var output in outputs)
                        {
                            var ds = DirectShape.CreateElement(doc, categoryId);
                            ds.Name = output.Key;

                            foreach (var geometries in output.Value.ToHost())
                            {
                                if (geometries != null)
                                {
                                    ds.AppendShape(geometries);
                                }
                            }
                        }

                        trans.Commit();
                    }
                }
            }

            return(Result.Succeeded);
        }
コード例 #26
0
    void evaluateGHdef()
    {
        Debug.Log("1");

        string filePath = string.Empty;



        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            openFileDialog.Filter           = "Grasshopper Binary (*.gh)|*.gh|Grasshopper Xml (*.ghx)|*.ghx";
            openFileDialog.FilterIndex      = 1;
            openFileDialog.RestoreDirectory = true;

            switch (openFileDialog.ShowDialog())
            {
            case DialogResult.OK:     filePath = openFileDialog.FileName;
                Debug.Log(filePath);
                break;
            }
        }

        var archive = new GH_Archive();

        archive.ReadFromFile(filePath);


        var definition = new GH_Document();

        archive.ExtractObject(definition, "Definition");


        Debug.Log("4");
        var outputs = new List <KeyValuePair <string, List <GeometryBase> > >();

        foreach (var obj in definition.Objects)
        {
            var param = obj as IGH_Param;
            Debug.Log("5");
            if (param == null)
            {
                continue;
            }
            Debug.Log("6");
            if (param.Sources.Count == 0 || param.Recipients.Count != 0)
            {
                continue;
            }
            Debug.Log("7");
            try
            {
                param.CollectData();
                param.ComputeData();
            }
            catch (Exception e)
            {
                //Debug.Fail(e.Source, e.Message);
                Debug.Log("8");
                param.Phase = GH_SolutionPhase.Failed;
                //result = Result.Failed;
            }

            Debug.Log("9");
            var volatileData = param.VolatileData;
            for (int p = 0; p < volatileData.PathCount; ++p)
            {
                foreach (var goo in volatileData.get_Branch(p))
                {
                    switch (goo.GetType().ToString())
                    {
                    case "GH_Point":
                        GH_Point point = (GH_Point)goo;
                        output.Add(new Rhino.Geometry.Point(point.Value));
                        break;

                    case "GH_Curve":
                        GH_Curve curve = (GH_Curve)goo;
                        output.Add(curve.Value);
                        break;

                    case "GH_Brep":
                        GH_Brep brep = (GH_Brep)goo;
                        output.Add(brep.Value);
                        break;

                    case "GH_Mesh":
                        GH_Mesh mesh = (GH_Mesh)goo;
                        output.Add(mesh.Value);
                        break;
                    }
                }
            }
            Debug.Log("10");
            if (output.Count > 0)
            {
                outputs.Add(new KeyValuePair <string, List <GeometryBase> >(param.Name, output));
                Debug.Log("11");
            }
        }
        Debug.Log("There are " + output.Count() + "GH objects in your list");

        //return outputs;
    }
コード例 #27
0
ファイル: Parser.cs プロジェクト: mostaphaRoudsari/VVD
        //Actual constructor for use in the program
        public static CommonGraph CommonGraphFromGHFile(string file)
        {
            CommonGraph cg = new CommonGraph();



            //construct GH Archive object for XML Traversal
            GH_Archive archive = new GH_Archive();

            archive.ReadFromFile(file);

            MetaData graphMetaData = new MetaData();

            graphMetaData.Ignore = archive.Serialize_Xml();
            cg.MetaData          = graphMetaData;

            //traverse GH file tree
            var rootNode   = archive.GetRootNode;
            var definition = rootNode.FindChunk("Definition");
            var defObjects = definition.FindChunk("DefinitionObjects");
            int objCount   = defObjects.GetInt32("ObjectCount");


            //for every object in the definition object list:
            for (int i = 0; i < objCount; i++)
            {
                var singleObjectChunk = defObjects.Chunks[i] as GH_Chunk;

                Guid typeGuid = singleObjectChunk.GetGuid("GUID");

                var container = singleObjectChunk.FindChunk("Container");

                var attributes = container.FindChunk("Attributes");



                Guid   instanceGuid = container.GetGuid("InstanceGuid");
                string name         = singleObjectChunk.GetString("Name");

                IEnumerable <GH_IChunk> inputs;
                IEnumerable <GH_IChunk> outputs;

                //Components that implement variable parameters store their inputs/outputs one layer deeper.
                var  parameterData    = container.Chunks.Where <GH_IChunk>(C => C.Name == "ParameterData");
                bool hasParameterData = parameterData.Count() > 0;

                bool hasSourceCount = container.ItemExists("SourceCount");

                var paramChunks = container.Chunks;
                if (hasParameterData)
                {
                    paramChunks = parameterData.ToList()[0].Chunks;
                    inputs      = paramChunks.Where(C => C.Name == "InputParam");
                    outputs     = paramChunks.Where(C => C.Name == "OutputParam");
                }
                else
                {
                    inputs  = paramChunks.Where(C => C.Name == "param_input");
                    outputs = paramChunks.Where(C => C.Name == "param_output");
                }



                bool hasInputs  = inputs.Count() > 0;
                bool hasOutputs = outputs.Count() > 0;

                bool isComponent = hasInputs || hasOutputs || hasParameterData;

                bool isActiveObject = isComponent || hasSourceCount;



                //Debugging
                //Console.WriteLine(name);
                //Console.WriteLine("Is active object? " + isActiveObject.ToString());
                //Console.WriteLine("Is Component? " + isComponent.ToString());


                if (!isActiveObject)
                {
                    continue;
                }


                Node node = new Node();
                //type and instance
                node.Type         = typeGuid.ToString();
                node.InstanceGuid = instanceGuid.ToString();
                node.Name         = name;
                Position pos = new Position();
                try
                {
                    var locPoint = attributes.GetDrawingPointF("Pivot");
                    pos.X = locPoint.X;
                    pos.Y = locPoint.Y;
                }
                catch { }
                node.Position = pos;

                //Metadata
                MetaData md = new MetaData();
                md.Ignore = chunkToXmlString(singleObjectChunk);
                //TODO - REMOVE COMPONENTS OF XML THAT SHOULDN'T BE INSPECTED
                md.Inspect    = chunkToXmlString(singleObjectChunk);
                node.MetaData = md;

                List <Port> ports = new List <Port>();
                List <Edge> edges = new List <Edge>();
                if (isComponent) //if it's a component
                {
                    List <GH_IChunk> portChunks = new List <GH_IChunk>();
                    portChunks.AddRange(inputs);
                    portChunks.AddRange(outputs);


                    foreach (var portIChunk in portChunks) // for every port "chunk"
                    {
                        Port     port             = new Port();
                        GH_Chunk portChunk        = portIChunk as GH_Chunk;
                        Guid     portInstanceGuid = portChunk.GetGuid("InstanceGuid");
                        port.InstanceGuid = portInstanceGuid.ToString();
                        port.Name         = portChunk.GetString("Name");
                        MetaData portMetadata = new MetaData();
                        portMetadata.Ignore = chunkToXmlString(portChunk);
                        port.MetaData       = portMetadata; //REMEMBER TO UNCOMMENT
                        ports.Add(port);



                        var sources = portChunk.Items.Where(item => item.Name == "Source");
                        //Console.WriteLine("WE GOT THIS MANY SOURCES:" +sources.Count());
                        foreach (GH_Item item in sources)
                        {
                            //Console.WriteLine("EDGE");
                            Edge edge = new Edge();
                            edge.DestGuid = portInstanceGuid.ToString();
                            edge.SrcGuid  = item._guid.ToString();
                            edges.Add(edge);
                        }
                    }
                }
                else if (!isComponent && isActiveObject) //if it's a param
                {
                    Port port = new Port();
                    //wrapper for object - if it's a param, instance for virtual node and port are the same.
                    Guid portInstanceGuid = instanceGuid;
                    port.InstanceGuid = instanceGuid.ToString();
                    port.Name         = name;
                    ports.Add(port);

                    var sources = container.Items.Where(item => item.Name == "Source");

                    foreach (GH_Item source in sources)
                    {
                        Edge edge = new Edge();
                        edge.DestGuid = portInstanceGuid.ToString();
                        edge.SrcGuid  = source._guid.ToString();
                        edges.Add(edge);
                    }
                }

                node.Ports = ports;
                cg.Edges.AddRange(edges);
                cg.Nodes.Add(node);
            }

            return(cg);
        }
コード例 #28
0
ファイル: Parser.cs プロジェクト: oderby/VVD
        //Actual constructor for use in the program
        public static CommonGraph CommonGraphFromGHFile(string file)
        {
            CommonGraph cg = new CommonGraph();

            //construct GH Archive object for XML Traversal
            GH_Archive archive = new GH_Archive();
            archive.ReadFromFile(file);

            MetaData graphMetaData = new MetaData();
            graphMetaData.Ignore = archive.Serialize_Xml();
            cg.MetaData = graphMetaData;

            //traverse GH file tree
            var rootNode = archive.GetRootNode;
            var definition = rootNode.FindChunk("Definition");
            var defObjects = definition.FindChunk("DefinitionObjects");
            int objCount = defObjects.GetInt32("ObjectCount");

            //for every object in the definition object list:
            for (int i = 0; i < objCount; i++)
            {
                var singleObjectChunk = defObjects.Chunks[i] as GH_Chunk;

                Guid typeGuid = singleObjectChunk.GetGuid("GUID");

                var container = singleObjectChunk.FindChunk("Container");

                var attributes = container.FindChunk("Attributes");

                Guid instanceGuid = container.GetGuid("InstanceGuid");
                string name = singleObjectChunk.GetString("Name");

                IEnumerable<GH_IChunk> inputs;
                IEnumerable<GH_IChunk> outputs;

                //Components that implement variable parameters store their inputs/outputs one layer deeper.
                var parameterData = container.Chunks.Where<GH_IChunk>(C => C.Name == "ParameterData");
                bool hasParameterData = parameterData.Count() > 0;

                bool hasSourceCount = container.ItemExists("SourceCount");

                var paramChunks = container.Chunks;
                if (hasParameterData)
                {
                    paramChunks = parameterData.ToList()[0].Chunks;
                    inputs = paramChunks.Where(C => C.Name == "InputParam");
                    outputs = paramChunks.Where(C => C.Name == "OutputParam");
                }
                else
                {

                   inputs = paramChunks.Where(C => C.Name == "param_input");
                    outputs = paramChunks.Where(C => C.Name == "param_output");
                }

                bool hasInputs = inputs.Count() > 0;
                bool hasOutputs = outputs.Count() > 0;

                bool isComponent = hasInputs || hasOutputs || hasParameterData;

                bool isActiveObject = isComponent || hasSourceCount;

                //Debugging
                //Console.WriteLine(name);
                //Console.WriteLine("Is active object? " + isActiveObject.ToString());
                //Console.WriteLine("Is Component? " + isComponent.ToString());

                if (!isActiveObject) continue;

                Node node = new Node();
                //type and instance
                node.Type = typeGuid.ToString();
                node.InstanceGuid = instanceGuid.ToString();
                node.Name = name;
                Position pos = new Position();
                try
                {
                    var locPoint = attributes.GetDrawingPointF("Pivot");
                    pos.X = locPoint.X;
                    pos.Y = locPoint.Y;
                }
                catch { }
                node.Position = pos;

                //Metadata
                MetaData md = new MetaData();
                md.Ignore = chunkToXmlString(singleObjectChunk);
                //TODO - REMOVE COMPONENTS OF XML THAT SHOULDN'T BE INSPECTED
                md.Inspect = chunkToXmlString(singleObjectChunk);
               node.MetaData = md;

                List<Port> ports = new List<Port>();
                List<Edge> edges = new List<Edge>();
                if (isComponent) //if it's a component
                {
                    List<GH_IChunk> portChunks = new List<GH_IChunk>();
                    portChunks.AddRange(inputs);
                    portChunks.AddRange(outputs);

                    foreach (var portIChunk in portChunks) // for every port "chunk"
                    {
                        Port port = new Port();
                        GH_Chunk portChunk = portIChunk as GH_Chunk;
                        Guid portInstanceGuid = portChunk.GetGuid("InstanceGuid");
                        port.InstanceGuid = portInstanceGuid.ToString();
                        port.Name = portChunk.GetString("Name");
                        MetaData portMetadata = new MetaData();
                       portMetadata.Ignore = chunkToXmlString(portChunk);
                        port.MetaData = portMetadata; //REMEMBER TO UNCOMMENT
                        ports.Add(port);

                        var sources = portChunk.Items.Where(item => item.Name == "Source");
                        //Console.WriteLine("WE GOT THIS MANY SOURCES:" +sources.Count());
                        foreach(GH_Item item in sources){
                            //Console.WriteLine("EDGE");
                             Edge edge = new Edge();
                            edge.DestGuid = portInstanceGuid.ToString();
                            edge.SrcGuid = item._guid.ToString();
                            edges.Add(edge);
                        }

                    }

                }
                else if(!isComponent && isActiveObject) //if it's a param
                {
                    Port port = new Port();
                    //wrapper for object - if it's a param, instance for virtual node and port are the same.
                    Guid portInstanceGuid = instanceGuid;
                    port.InstanceGuid = instanceGuid.ToString();
                    port.Name = name;
                    ports.Add(port);

                    var sources = container.Items.Where(item => item.Name == "Source");

                    foreach (GH_Item source in sources)
                    {
                        Edge edge = new Edge();
                        edge.DestGuid = portInstanceGuid.ToString();
                        edge.SrcGuid = source._guid.ToString();
                        edges.Add(edge);
                    }

                }

                node.Ports = ports;
                cg.Edges.AddRange(edges);
                cg.Nodes.Add(node);
            }

            return cg;
        }
コード例 #29
0
        public static Response GetIoNames(NancyContext ctx)
        {
            // load grasshopper file
            var archive = new GH_Archive();
            // TODO: stream to string
            var body = ctx.Request.Body.ToString();
            //
            //var body = input.Algo;

            string json = string.Empty;

            using (var reader = new StreamReader(ctx.Request.Body))
            {
                json = reader.ReadToEnd();
            }

            IoQuerySchema input          = JsonConvert.DeserializeObject <IoQuerySchema>(json);
            string        pointer        = input.RequestedFile;
            string        grasshopperXml = GetGhxFromPointer(pointer);

            if (!archive.Deserialize_Xml(grasshopperXml))
            {
                throw new Exception();
            }

            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception();
            }

            // Parse input and output names
            List <string> InputNames  = new List <string>();
            List <string> OutputNames = new List <string>();

            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                if (group.NickName.Contains("RH_IN"))
                {
                    InputNames.Add(group.NickName);
                }
                else if (group.NickName.Contains("RH_OUT"))
                {
                    OutputNames.Add(group.NickName);
                }
            }

            IoResponseSchema response = new IoResponseSchema();

            response.InputNames  = InputNames;
            response.OutputNames = OutputNames;

            string jsonResponse = JsonConvert.SerializeObject(response);

            return(jsonResponse);
        }
コード例 #30
0
        public static Response Grasshopper(NancyContext ctx)
        {
            // load grasshopper file
            var archive = new GH_Archive();
            // TODO: stream to string
            var body = ctx.Request.Body.ToString();

            string json = string.Empty;

            using (var reader = new StreamReader(ctx.Request.Body))
            {
                json = reader.ReadToEnd();
            }

            //GrasshopperInput input = Newtonsoft.Json.JsonConvert.DeserializeObject<GrasshopperInput>(json);
            //JsonSerializerSettings settings = new JsonSerializerSettings();
            //settings.ContractResolver = new DictionaryAsArrayResolver();
            Schema input = JsonConvert.DeserializeObject <Schema>(json);

            string grasshopperXml = string.Empty;

            if (input.Algo != null)
            {
                // If request contains markup
                byte[] byteArray = Convert.FromBase64String(input.Algo);
                grasshopperXml = System.Text.Encoding.UTF8.GetString(byteArray);
            }
            else
            {
                // If request contains pointer
                string pointer = input.Pointer;
                grasshopperXml = GetGhxFromPointer(pointer);
            }
            if (!archive.Deserialize_Xml(grasshopperXml))
            {
                throw new Exception();
            }

            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception();
            }

            // Set input params
            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                if (group.NickName.Contains("RH_IN"))
                {
                    // It is a RestHopper input group!
                    GHTypeCodes code  = (GHTypeCodes)Int32.Parse(group.NickName.Split(':')[1]);
                    var         param = group.Objects()[0];
                    //GH_Param<IGH_Goo> goo = obj as GH_Param<IGH_Goo>;

                    // SetData
                    foreach (Resthopper.IO.DataTree <ResthopperObject> tree in input.Values)
                    {
                        string paramname = tree.ParamName;
                        if (group.NickName == paramname)
                        {
                            switch (code)
                            {
                            case GHTypeCodes.Boolean:
                                //PopulateParam<GH_Boolean>(goo, tree);
                                Param_Boolean boolParam = param as Param_Boolean;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Boolean> objectList = new List <GH_Boolean>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj = entree.Value[i];
                                        bool             boolean = JsonConvert.DeserializeObject <bool>(restobj.Data);
                                        GH_Boolean       data    = new GH_Boolean(boolean);
                                        boolParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Point:
                                //PopulateParam<GH_Point>(goo, tree);
                                Param_Point ptParam = param as Param_Point;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Point> objectList = new List <GH_Point>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject       restobj = entree.Value[i];
                                        Rhino.Geometry.Point3d rPt     = JsonConvert.DeserializeObject <Rhino.Geometry.Point3d>(restobj.Data);
                                        GH_Point data = new GH_Point(rPt);
                                        ptParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Vector:
                                //PopulateParam<GH_Vector>(goo, tree);
                                Param_Vector vectorParam = param as Param_Vector;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Vector> objectList = new List <GH_Vector>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject        restobj  = entree.Value[i];
                                        Rhino.Geometry.Vector3d rhVector = JsonConvert.DeserializeObject <Rhino.Geometry.Vector3d>(restobj.Data);
                                        GH_Vector data = new GH_Vector(rhVector);
                                        vectorParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Integer:
                                //PopulateParam<GH_Integer>(goo, tree);
                                Param_Integer integerParam = param as Param_Integer;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Integer> objectList = new List <GH_Integer>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj = entree.Value[i];
                                        int        rhinoInt      = JsonConvert.DeserializeObject <int>(restobj.Data);
                                        GH_Integer data          = new GH_Integer(rhinoInt);
                                        integerParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Number:
                                //PopulateParam<GH_Number>(goo, tree);
                                Param_Number numberParam = param as Param_Number;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Number> objectList = new List <GH_Number>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        double           rhNumber = JsonConvert.DeserializeObject <double>(restobj.Data);
                                        GH_Number        data     = new GH_Number(rhNumber);
                                        numberParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Text:
                                //PopulateParam<GH_String>(goo, tree);
                                Param_String stringParam = param as Param_String;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_String> objectList = new List <GH_String>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        string           rhString = JsonConvert.DeserializeObject <string>(restobj.Data);
                                        GH_String        data     = new GH_String(rhString);
                                        stringParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Line:
                                //PopulateParam<GH_Line>(goo, tree);
                                Param_Line lineParam = param as Param_Line;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path        path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Line> objectList = new List <GH_Line>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject    restobj = entree.Value[i];
                                        Rhino.Geometry.Line rhLine  = JsonConvert.DeserializeObject <Rhino.Geometry.Line>(restobj.Data);
                                        GH_Line             data    = new GH_Line(rhLine);
                                        lineParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Curve:
                                //PopulateParam<GH_Curve>(goo, tree);
                                Param_Curve curveParam = param as Param_Curve;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Curve> objectList = new List <GH_Curve>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj = entree.Value[i];
                                        GH_Curve         ghCurve;
                                        try
                                        {
                                            Rhino.Geometry.Polyline data = JsonConvert.DeserializeObject <Rhino.Geometry.Polyline>(restobj.Data);
                                            Rhino.Geometry.Curve    c    = new Rhino.Geometry.PolylineCurve(data);
                                            ghCurve = new GH_Curve(c);
                                        }
                                        catch
                                        {
                                            Rhino.Geometry.NurbsCurve data = JsonConvert.DeserializeObject <Rhino.Geometry.NurbsCurve>(restobj.Data);
                                            Rhino.Geometry.Curve      c    = new Rhino.Geometry.NurbsCurve(data);
                                            ghCurve = new GH_Curve(c);
                                        }
                                        curveParam.AddVolatileData(path, i, ghCurve);
                                    }
                                }
                                break;

                            case GHTypeCodes.Circle:
                                //PopulateParam<GH_Circle>(goo, tree);
                                Param_Circle circleParam = param as Param_Circle;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Circle> objectList = new List <GH_Circle>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject      restobj  = entree.Value[i];
                                        Rhino.Geometry.Circle rhCircle = JsonConvert.DeserializeObject <Rhino.Geometry.Circle>(restobj.Data);
                                        GH_Circle             data     = new GH_Circle(rhCircle);
                                        circleParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.PLane:
                                //PopulateParam<GH_Plane>(goo, tree);
                                Param_Plane planeParam = param as Param_Plane;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Plane> objectList = new List <GH_Plane>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject     restobj = entree.Value[i];
                                        Rhino.Geometry.Plane rhPlane = JsonConvert.DeserializeObject <Rhino.Geometry.Plane>(restobj.Data);
                                        GH_Plane             data    = new GH_Plane(rhPlane);
                                        planeParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Rectangle:
                                //PopulateParam<GH_Rectangle>(goo, tree);
                                Param_Rectangle rectangleParam = param as Param_Rectangle;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path             path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Rectangle> objectList = new List <GH_Rectangle>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject           restobj     = entree.Value[i];
                                        Rhino.Geometry.Rectangle3d rhRectangle = JsonConvert.DeserializeObject <Rhino.Geometry.Rectangle3d>(restobj.Data);
                                        GH_Rectangle data = new GH_Rectangle(rhRectangle);
                                        rectangleParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Box:
                                //PopulateParam<GH_Box>(goo, tree);
                                Param_Box boxParam = param as Param_Box;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path       path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Box> objectList = new List <GH_Box>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject   restobj = entree.Value[i];
                                        Rhino.Geometry.Box rhBox   = JsonConvert.DeserializeObject <Rhino.Geometry.Box>(restobj.Data);
                                        GH_Box             data    = new GH_Box(rhBox);
                                        boxParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Surface:
                                //PopulateParam<GH_Surface>(goo, tree);
                                Param_Surface surfaceParam = param as Param_Surface;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Surface> objectList = new List <GH_Surface>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject       restobj   = entree.Value[i];
                                        Rhino.Geometry.Surface rhSurface = JsonConvert.DeserializeObject <Rhino.Geometry.Surface>(restobj.Data);
                                        GH_Surface             data      = new GH_Surface(rhSurface);
                                        surfaceParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Brep:
                                //PopulateParam<GH_Brep>(goo, tree);
                                Param_Brep brepParam = param as Param_Brep;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path        path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Brep> objectList = new List <GH_Brep>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject    restobj = entree.Value[i];
                                        Rhino.Geometry.Brep rhBrep  = JsonConvert.DeserializeObject <Rhino.Geometry.Brep>(restobj.Data);
                                        GH_Brep             data    = new GH_Brep(rhBrep);
                                        brepParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Mesh:
                                //PopulateParam<GH_Mesh>(goo, tree);
                                Param_Mesh meshParam = param as Param_Mesh;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path        path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Mesh> objectList = new List <GH_Mesh>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject    restobj = entree.Value[i];
                                        Rhino.Geometry.Mesh rhMesh  = JsonConvert.DeserializeObject <Rhino.Geometry.Mesh>(restobj.Data);
                                        GH_Mesh             data    = new GH_Mesh(rhMesh);
                                        meshParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Slider:
                                //PopulateParam<GH_Number>(goo, tree);
                                GH_NumberSlider sliderParam = param as GH_NumberSlider;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Number> objectList = new List <GH_Number>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        double           rhNumber = JsonConvert.DeserializeObject <double>(restobj.Data);
                                        GH_Number        data     = new GH_Number(rhNumber);
                                        sliderParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.BooleanToggle:
                                //PopulateParam<GH_Boolean>(goo, tree);
                                GH_BooleanToggle toggleParam = param as GH_BooleanToggle;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Boolean> objectList = new List <GH_Boolean>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj   = entree.Value[i];
                                        bool             rhBoolean = JsonConvert.DeserializeObject <bool>(restobj.Data);
                                        GH_Boolean       data      = new GH_Boolean(rhBoolean);
                                        toggleParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Panel:
                                //PopulateParam<GH_String>(goo, tree);
                                GH_Panel panelParam = param as GH_Panel;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Panel> objectList = new List <GH_Panel>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        string           rhString = JsonConvert.DeserializeObject <string>(restobj.Data);
                                        GH_String        data     = new GH_String(rhString);
                                        panelParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }

            Schema OutputSchema = new Schema();

            OutputSchema.Algo = Utils.Base64Encode(string.Empty);

            // Parse output params
            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                if (group.NickName.Contains("RH_OUT"))
                {
                    // It is a RestHopper output group!
                    GHTypeCodes code  = (GHTypeCodes)Int32.Parse(group.NickName.Split(':')[1]);
                    var         param = group.Objects()[0] as IGH_Param;
                    if (param == null)
                    {
                        continue;
                    }

                    try
                    {
                        param.CollectData();
                        param.ComputeData();
                    }
                    catch (Exception)
                    {
                        param.Phase = GH_SolutionPhase.Failed;
                        // TODO: throw something better
                        throw;
                    }

                    // Get data
                    Resthopper.IO.DataTree <ResthopperObject> OutputTree = new Resthopper.IO.DataTree <ResthopperObject>();
                    OutputTree.ParamName = group.NickName;

                    var volatileData = param.VolatileData;
                    for (int p = 0; p < volatileData.PathCount; p++)
                    {
                        List <ResthopperObject> ResthopperObjectList = new List <ResthopperObject>();
                        foreach (var goo in volatileData.get_Branch(p))
                        {
                            if (goo == null)
                            {
                                continue;
                            }
                            else if (goo.GetType() == typeof(GH_Boolean))
                            {
                                GH_Boolean ghValue = goo as GH_Boolean;
                                bool       rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <bool>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Point))
                            {
                                GH_Point ghValue = goo as GH_Point;
                                Point3d  rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Point3d>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Vector))
                            {
                                GH_Vector ghValue = goo as GH_Vector;
                                Vector3d  rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Vector3d>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Integer))
                            {
                                GH_Integer ghValue = goo as GH_Integer;
                                int        rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <int>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Number))
                            {
                                GH_Number ghValue = goo as GH_Number;
                                double    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <double>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_String))
                            {
                                GH_String ghValue = goo as GH_String;
                                string    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <string>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Line))
                            {
                                GH_Line ghValue = goo as GH_Line;
                                Line    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Line>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Curve))
                            {
                                GH_Curve ghValue = goo as GH_Curve;
                                Curve    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Curve>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Circle))
                            {
                                GH_Circle ghValue = goo as GH_Circle;
                                Circle    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Circle>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Plane))
                            {
                                GH_Plane ghValue = goo as GH_Plane;
                                Plane    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Plane>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Rectangle))
                            {
                                GH_Rectangle ghValue = goo as GH_Rectangle;
                                Rectangle3d  rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Rectangle3d>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Box))
                            {
                                GH_Box ghValue = goo as GH_Box;
                                Box    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Box>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Surface))
                            {
                                GH_Surface ghValue = goo as GH_Surface;
                                Brep       rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Brep>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Brep))
                            {
                                GH_Brep ghValue = goo as GH_Brep;
                                Brep    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Brep>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Mesh))
                            {
                                GH_Mesh ghValue = goo as GH_Mesh;
                                Mesh    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Mesh>(rhValue));
                            }
                        }

                        GhPath path = new GhPath(new int[] { p });
                        OutputTree.Add(path.ToString(), ResthopperObjectList);
                    }

                    OutputSchema.Values.Add(OutputTree);
                }
            }


            if (OutputSchema.Values.Count < 1)
            {
                throw new System.Exceptions.PayAttentionException("Looks like you've missed something..."); // TODO
            }
            string returnJson = JsonConvert.SerializeObject(OutputSchema);

            return(returnJson);
        }
コード例 #31
0
        Result BakeDefinition(UIApplication application, string filePath)
        {
            if (!AddFileToMru(filePath))
            {
                return(Result.Failed);
            }

            // Load Grasshopper
            PlugIn.LoadPlugIn(new Guid(0xB45A29B1, 0x4343, 0x4035, 0x98, 0x9E, 0x04, 0x4E, 0x85, 0x80, 0xD9, 0xCF));

            var transactionName = string.Empty;

            var archive = new GH_Archive();

            if (!archive.ReadFromFile(filePath))
            {
                return(Result.Failed);
            }

            var outputs = new List <KeyValuePair <string, List <GeometryBase> > >();

            using (var definition = new GH_Document())
            {
                if (!archive.ExtractObject(definition, "Definition"))
                {
                    return(Result.Failed);
                }

                // Update Most recet used item extended ToolTip information
                {
                    mruPushPuttons[0].LongDescription = definition.Properties.Description;

                    if (archive.GetRootNode.FindChunk("Thumbnail")?.GetDrawingBitmap("Thumbnail") is System.Drawing.Bitmap bitmap)
                    {
                        mruPushPuttons[0].ToolTipImage = bitmap.ToBitmapImage(Math.Min(bitmap.Width, 355), Math.Min(bitmap.Height, 355));
                    }
                }

                transactionName = Path.GetFileNameWithoutExtension(definition.Properties.ProjectFileName);

                var inputs = new List <IGH_Param>();

                // Collect input params
                foreach (var obj in definition.Objects)
                {
                    if (!(obj is IGH_Param param))
                    {
                        continue;
                    }

                    if (param.Sources.Count != 0 || param.Recipients.Count == 0)
                    {
                        continue;
                    }

                    if (param.VolatileDataCount > 0)
                    {
                        continue;
                    }

                    if (param.Locked)
                    {
                        continue;
                    }

                    inputs.Add(param);
                }

                // Prompt for input values
                var values = new Dictionary <IGH_Param, IEnumerable <IGH_Goo> >();
                foreach (var input in inputs.OrderBy((x) => x.Attributes.Pivot.Y))
                {
                    switch (input)
                    {
                    case Param_Box box:
                        var boxes = PromptBox(application.ActiveUIDocument, input.NickName);
                        if (boxes == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, boxes);
                        break;

                    case Param_Point point:
                        var points = PromptPoint(application.ActiveUIDocument, input.NickName);
                        if (points == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, points);
                        break;

                    case Param_Curve curve:
                        var curves = PromptEdge(application.ActiveUIDocument, input.NickName);
                        if (curves == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, curves);
                        break;

                    case Param_Surface surface:
                        var surfaces = PromptSurface(application.ActiveUIDocument, input.NickName);
                        if (surfaces == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, surfaces);
                        break;

                    case Param_Brep brep:
                        var breps = PromptBrep(application.ActiveUIDocument, input.NickName);
                        if (breps == null)
                        {
                            return(Result.Cancelled);
                        }
                        values.Add(input, breps);
                        break;
                    }
                }

                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    // Update input volatile data values
                    foreach (var value in values)
                    {
                        value.Key.AddVolatileDataList(new Grasshopper.Kernel.Data.GH_Path(0), value.Value);
                    }

                    // Collect output values
                    foreach (var obj in definition.Objects)
                    {
                        if (!(obj is IGH_Param param))
                        {
                            continue;
                        }

                        if (param.Sources.Count == 0 || param.Recipients.Count != 0)
                        {
                            continue;
                        }

                        if (param.Locked)
                        {
                            continue;
                        }

                        try
                        {
                            param.CollectData();
                            param.ComputeData();
                        }
                        catch (Exception e)
                        {
                            Debug.Fail(e.Source, e.Message);
                            param.Phase = GH_SolutionPhase.Failed;
                        }

                        if (param.Phase == GH_SolutionPhase.Failed)
                        {
                            return(Result.Failed);
                        }

                        var output       = new List <GeometryBase>();
                        var volatileData = param.VolatileData;
                        if (volatileData.PathCount > 0)
                        {
                            foreach (var value in param.VolatileData.AllData(true).Select(x => x.ScriptVariable()))
                            {
                                switch (value)
                                {
                                case Rhino.Geometry.Point3d point:          output.Add(new Rhino.Geometry.Point(point)); break;

                                case Rhino.Geometry.GeometryBase geometry:  output.Add(geometry); break;
                                }
                            }
                        }

                        if (output.Count > 0)
                        {
                            outputs.Add(new KeyValuePair <string, List <GeometryBase> >(param.NickName, output));
                        }
                    }
                }
                catch (Exception)
                {
                    return(Result.Failed);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }

            // Bake output geometry
            if (outputs.Count > 0)
            {
                var doc = application.ActiveUIDocument.Document;

                using (var trans = new Transaction(doc, transactionName))
                {
                    if (trans.Start(MethodBase.GetCurrentMethod().DeclaringType.Name) == TransactionStatus.Started)
                    {
                        if (!Enum.TryParse(categoriesComboBox.Current.Name, out BuiltInCategory builtInCategory))
                        {
                            builtInCategory = BuiltInCategory.OST_GenericModel;
                        }

                        var categoryId = new ElementId(builtInCategory);

                        foreach (var output in outputs)
                        {
                            var ds = DirectShape.CreateElement(doc, categoryId);
                            ds.Name = output.Key;

                            foreach (var geometries in output.Value.ToHost())
                            {
                                if (geometries != null)
                                {
                                    ds.AppendShape(geometries);
                                }
                            }
                        }

                        trans.Commit();
                    }
                }
            }

            return(Result.Succeeded);
        }
コード例 #32
0
        static Response GetIoNames(NancyContext ctx)
        {
            string json = ctx.Request.Body.AsString();

            IoQuerySchema input   = JsonConvert.DeserializeObject <IoQuerySchema>(json);
            string        pointer = input.RequestedFile;
            GH_Archive    archive = DataCache.GetCachedArchive(pointer);

            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception("Unable to extract definition");
            }

            // Parse input and output names
            List <string> InputNames  = new List <string>();
            List <string> OutputNames = new List <string>();
            var           Inputs      = new List <IoParamSchema>();
            var           Outputs     = new List <IoParamSchema>();

            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                if (group.NickName.Contains("RH_IN"))
                {
                    InputNames.Add(group.NickName);

                    var i = new IoParamSchema
                    {
                        Name      = group.NickName,
                        ParamType = (group.Objects()[0] as IGH_Param).TypeName
                    };

                    Inputs.Add(i);
                }
                else if (group.NickName.Contains("RH_OUT"))
                {
                    OutputNames.Add(group.NickName);

                    var o = new IoParamSchema
                    {
                        Name      = group.NickName,
                        ParamType = (group.Objects()[0] as IGH_Param).TypeName
                    };

                    Outputs.Add(o);
                }
            }

            var response = new IoResponseSchema
            {
                InputNames  = InputNames,
                OutputNames = OutputNames,
                Inputs      = Inputs,
                Outputs     = Outputs
            };

            string jsonResponse = JsonConvert.SerializeObject(response);

            return(jsonResponse);
        }