public virtual void SetConverterFromKit(string kitName)
 {
     if (kitName == Kit?.Name)
     {
         return;
     }
     Kit             = KitManager.Kits.FirstOrDefault(k => k.Name == kitName);
     SelectedKitName = Kit.Name;
     Converter       = Kit.LoadConverter(Applications.Rhino);
     Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
     Message = $"Using the {Kit.Name} Converter";
 }
Example #2
0
 private void SetDefaultKitAndConverter()
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter = Kit.LoadConverter(Applications.Rhino);
         Converter.SetContextDocument(RhinoDoc.ActiveDoc);
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
Example #3
0
        public BatchConverter()
        {
            var kit = KitManager.GetDefaultKit();

            _converter = kit.LoadConverter(Applications.Dynamo);
            if (_converter == null)
            {
                throw new Exception("Cannot find the Dynamo converter, has it been copied to the Kit folder?");
            }
#if REVIT
            _converter.SetContextDocument(Globals.RevitDocument);
#endif
        }
 public virtual void SetConverterFromKit(string kitName)
 {
     if (kitName == Kit?.Name)
     {
         return;
     }
     Kit             = KitManager.Kits.FirstOrDefault(k => k.Name == kitName);
     SelectedKitName = Kit.Name;
     Converter       = Kit.LoadConverter(Applications.Rhino6);
     Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
     SpeckleGHSettings.OnMeshSettingsChanged +=
         (sender, args) => Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
     Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
     Message = $"Using the {Kit.Name} Converter";
 }
Example #5
0
        public SelectKitAsyncComponentBase(string name, string nickname, string description, string category, string subCategory) : base(name, nickname, description, category, subCategory)
        {
            var key = "Speckle2:kit.default.name";
            var n   = Grasshopper.Instances.Settings.GetValue(key, "Objects");

            Kit = KitManager.GetKitsWithConvertersForApp(Applications.Rhino).FirstOrDefault(kit => kit.Name == n);
            try
            {
                Converter = Kit.LoadConverter(Applications.Rhino);
                Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
                Message = $"{Kit.Name} Kit";
            }
            catch
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
            }
        }
 private void SetDefaultKitAndConverter()
 {
     try
     {
         Kit       = KitManager.GetDefaultKit();
         Converter = Kit.LoadConverter(Applications.Rhino6);
         Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
         SpeckleGHSettings.OnMeshSettingsChanged +=
             (sender, args) => Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
         Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
         foundKit = true;
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
         foundKit = false;
     }
 }
        public override void AddedToDocument(GH_Document document)
        {
            base.AddedToDocument(document);
            var key = "Speckle2:kit.default.name";
            var n   = Grasshopper.Instances.Settings.GetValue(key, "Objects");

            try
            {
                Kit       = KitManager.GetKitsWithConvertersForApp(Applications.Rhino).FirstOrDefault(kit => kit.Name == n);
                Converter = Kit.LoadConverter(Applications.Rhino);
                Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
                Message = $"{Kit.Name} Kit";
            }
            catch
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
            }
        }
 public override void AddedToDocument(GH_Document document)
 {
     base.AddedToDocument(document);
     try
     {
         Kit       = KitManager.GetKitsWithConvertersForApp(Applications.Rhino6).FirstOrDefault(kit => kit.Name == SpeckleGHSettings.SelectedKitName);
         Converter = Kit.LoadConverter(Applications.Rhino6);
         Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
         Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
         SpeckleGHSettings.OnMeshSettingsChanged +=
             (sender, args) => Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
         Message = $"{Kit.Name} Kit";
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
        public void SetConverterFromKit(string kitName)
        {
            if (kitName == Kit.Name)
            {
                return;
            }

            try
            {
                Kit       = KitManager.Kits.FirstOrDefault(k => k.Name == kitName);
                Converter = Kit.LoadConverter(Applications.Rhino);
                Converter.SetContextDocument(RhinoDoc.ActiveDoc);

                Message = $"Using the {Kit.Name} Converter";
                ExpireSolution(true);
            }
            catch (Exception e)
            {
                // TODO: handle this.
                Console.WriteLine(e);
            }
        }
        public BatchConverter()
        {
            var kit = KitManager.GetDefaultKit();

            if (kit == null)
            {
                throw new SpeckleException("Cannot find the Objects Kit. Has it been copied to the Kits folder?");
            }

            _converter = kit.LoadConverter(Utils.GetAppName());

            if (_converter == null)
            {
                throw new SpeckleException("Cannot find the Dynamo converter. Has it been copied to the Kits folder?");
            }

            // if in Revit, we have a doc, injected by the Extension
            if (Globals.RevitDocument != null)
            {
                _converter.SetContextDocument(Globals.RevitDocument);
            }
        }
        //GH_Structure<IGH_Goo> transportsInput;
        /// <summary>
        /// Registers all the output parameters for this component.
        /// </summary>
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();

            if (!foundKit)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No kit found on this machine.");
                return;
            }

            if (RunCount == 1)
            {
                CreateCancelationToken();
                OutputWrappers = new List <StreamWrapper>();
                DA.GetDataTree(0, out dataInput);

                //the active document may have changed
                Converter.SetContextDocument(RhinoDoc.ActiveDoc);

                // Note: this method actually converts the objects to speckle too
                converted = Extras.Utilities.DataTreeToNestedLists(dataInput, Converter, source.Token, () =>
                {
                    //ReportProgress("Conversion", Math.Round(convertedCount++ / (double)DataInput.DataCount, 2));
                });
            }

            //if (RunCount > 1)
            //  return;

            if (InPreSolve)
            {
                string messageInput = "";

                IGH_Goo transportInput = null;
                DA.GetData(1, ref transportInput);
                DA.GetData(2, ref messageInput);
                var transportsInput = new List <IGH_Goo> {
                    transportInput
                };
                //var transportsInput = Params.Input[1].VolatileData.AllData(true).Select(x => x).ToList();
                Tracker.TrackPageview("send", "sync");

                var task = Task.Run(async() =>
                {
                    if (converted.Count == 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Zero objects converted successfully. Send stopped.");
                        return(null);
                    }

                    var ObjectToSend      = new Base();
                    ObjectToSend["@data"] = converted;
                    var TotalObjectCount  = ObjectToSend.GetTotalChildrenCount();

                    if (source.Token.IsCancellationRequested)
                    {
                        Message = "Out of time";
                        return(null);
                    }

                    // Part 2: create transports
                    var Transports = new List <ITransport>();

                    if (transportsInput.Count() == 0)
                    {
                        // TODO: Set default account + "default" user stream
                    }

                    var transportBranches = new Dictionary <ITransport, string>();
                    int t = 0;
                    foreach (var data in transportsInput)
                    {
                        var transport = data.GetType().GetProperty("Value").GetValue(data);

                        if (transport is string s)
                        {
                            try
                            {
                                transport = new StreamWrapper(s);
                            }
                            catch (Exception e)
                            {
                                // TODO: Check this with team.
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                            }
                        }

                        if (transport is StreamWrapper sw)
                        {
                            if (sw.Type == StreamWrapperType.Undefined)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input stream is invalid.");
                                continue;
                            }

                            if (sw.Type == StreamWrapperType.Commit)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot push to a specific commit stream url.");
                                continue;
                            }

                            if (sw.Type == StreamWrapperType.Object)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot push to a specific object stream url.");
                                continue;
                            }

                            Account acc;
                            try
                            {
                                acc = sw.GetAccount().Result;
                            }
                            catch (Exception e)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.InnerException?.Message ?? e.Message);
                                continue;
                            }

                            var serverTransport = new ServerTransport(acc, sw.StreamId)
                            {
                                TransportName = $"T{t}"
                            };
                            transportBranches.Add(serverTransport, sw.BranchName ?? "main");
                            Transports.Add(serverTransport);
                        }
                        else if (transport is ITransport otherTransport)
                        {
                            otherTransport.TransportName = $"T{t}";
                            Transports.Add(otherTransport);
                        }

                        t++;
                    }

                    if (Transports.Count == 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Could not identify any valid transports to send to.");
                        return(null);
                    }

                    // Part 3: actually send stuff!
                    if (source.Token.IsCancellationRequested)
                    {
                        Message = "Out of time";
                        return(null);
                    }

                    // Part 3.1: persist the objects
                    var BaseId = await Operations.Send(
                        ObjectToSend,
                        source.Token,
                        Transports,
                        useDefaultCache: UseDefaultCache,
                        onProgressAction: y => { },
                        onErrorAction: (x, z) => { },
                        disposeTransports: true);

                    var message = messageInput;//.get_FirstItem(true).Value;
                    if (message == "")
                    {
                        message = $"Pushed {TotalObjectCount} elements from Grasshopper.";
                    }


                    var prevCommits = new List <StreamWrapper>();

                    foreach (var transport in Transports)
                    {
                        if (source.Token.IsCancellationRequested)
                        {
                            Message = "Out of time";
                            return(null);
                        }

                        if (!(transport is ServerTransport))
                        {
                            continue; // skip non-server transports (for now)
                        }

                        try
                        {
                            var client = new Client(((ServerTransport)transport).Account);
                            var branch = transportBranches.ContainsKey(transport) ? transportBranches[transport] : "main";

                            var commitCreateInput = new CommitCreateInput
                            {
                                branchName        = branch,
                                message           = message,
                                objectId          = BaseId,
                                streamId          = ((ServerTransport)transport).StreamId,
                                sourceApplication = Applications.Grasshopper
                            };

                            // Check to see if we have a previous commit; if so set it.
                            var prevCommit = prevCommits.FirstOrDefault(c =>
                                                                        c.ServerUrl == client.ServerUrl && c.StreamId == ((ServerTransport)transport).StreamId);
                            if (prevCommit != null)
                            {
                                commitCreateInput.parents = new List <string>()
                                {
                                    prevCommit.CommitId
                                };
                            }

                            var commitId = await client.CommitCreate(source.Token, commitCreateInput);

                            var wrapper = new StreamWrapper($"{client.Account.serverInfo.url}/streams/{((ServerTransport)transport).StreamId}/commits/{commitId}?u={client.Account.userInfo.id}");
                            prevCommits.Add(wrapper);
                        }
                        catch (Exception e)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                            return(null);
                        }
                    }

                    if (source.Token.IsCancellationRequested)
                    {
                        Message = "Out of time";
                        return(null);
                    }

                    return(prevCommits);
                }, source.Token);

                TaskList.Add(task);
                return;
            }

            if (source.IsCancellationRequested)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Run out of time!");
            }
            else if (!GetSolveResults(DA, out List <StreamWrapper> outputWrappers))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Not running multithread");
            }
            else
            {
                OutputWrappers.AddRange(outputWrappers);
                DA.SetDataList(0, outputWrappers);
                return;
            }
        }
Example #12
0
        private void ConvertCommit(Base commitObject, ISpeckleConverter converter, StreamState state, ProgressViewModel progress, Stream stream, string id)
        {
            using (DocumentLock l = Doc.LockDocument())
            {
                using (Transaction tr = Doc.Database.TransactionManager.StartTransaction())
                {
                    // set the context doc for conversion - this is set inside the transaction loop because the converter retrieves this transaction for all db editing when the context doc is set!
                    converter.SetContextDocument(Doc);

                    // keep track of conversion progress here
                    var conversionProgressDict = new ConcurrentDictionary <string, int>();
                    conversionProgressDict["Conversion"]      = 0;
                    Execute.PostToUIThread(() => progress.Max = state.SelectedObjectIds.Count());
                    Action updateProgressAction = () =>
                    {
                        conversionProgressDict["Conversion"]++;
                        progress.Update(conversionProgressDict);
                    };

                    // keep track of any layer name changes for notification here
                    bool changedLayerNames = false;

                    // create a commit prefix: used for layers and block definition names
                    var commitPrefix = DesktopUI.Utils.Formatting.CommitInfo(stream.name, state.BranchName, id);

                    // give converter a way to access the commit info
                    Doc.UserData.Add("commit", commitPrefix);

                    // delete existing commit layers
                    try
                    {
                        DeleteBlocksWithPrefix(commitPrefix, tr);
                        DeleteLayersWithPrefix(commitPrefix, tr);
                    }
                    catch
                    {
                        converter.Report.LogOperationError(new Exception($"Failed to remove existing layers or blocks starting with {commitPrefix} before importing new geometry."));
                    }

                    // flatten the commit object to retrieve children objs
                    int count      = 0;
                    var commitObjs = FlattenCommitObject(commitObject, converter, commitPrefix, state, ref count);

                    // open model space block table record for write
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(Doc.Database.CurrentSpaceId, OpenMode.ForWrite);

                    // More efficient this way than doing this per object
                    var lineTypeDictionary = new Dictionary <string, ObjectId>();
                    var lineTypeTable      = (LinetypeTable)tr.GetObject(Doc.Database.LinetypeTableId, OpenMode.ForRead);
                    foreach (ObjectId lineTypeId in lineTypeTable)
                    {
                        var linetype = (LinetypeTableRecord)tr.GetObject(lineTypeId, OpenMode.ForRead);
                        lineTypeDictionary.Add(linetype.Name, lineTypeId);
                    }

                    foreach (var commitObj in commitObjs)
                    {
                        // create the object's bake layer if it doesn't already exist
                        (Base obj, string layerName) = commitObj;

                        var converted       = converter.ConvertToNative(obj);
                        var convertedEntity = converted as Entity;

                        if (convertedEntity != null)
                        {
                            if (GetOrMakeLayer(layerName, tr, out string cleanName))
                            {
                                // record if layer name has been modified
                                if (!cleanName.Equals(layerName))
                                {
                                    changedLayerNames = true;
                                }

                                var res = convertedEntity.Append(cleanName);
                                if (res.IsValid)
                                {
                                    // handle display
                                    Base display = obj[@"displayStyle"] as Base;
                                    if (display != null)
                                    {
                                        var color     = display["color"] as int?;
                                        var lineType  = display["linetype"] as string;
                                        var lineWidth = display["lineweight"] as double?;

                                        if (color != null)
                                        {
                                            var systemColor = System.Drawing.Color.FromArgb((int)color);
                                            convertedEntity.Color        = Color.FromRgb(systemColor.R, systemColor.G, systemColor.B);
                                            convertedEntity.Transparency = new Transparency(systemColor.A);
                                        }

                                        if (lineWidth != null)
                                        {
                                            convertedEntity.LineWeight = Utils.GetLineWeight((double)lineWidth);
                                        }

                                        if (lineType != null)
                                        {
                                            if (lineTypeDictionary.ContainsKey(lineType))
                                            {
                                                convertedEntity.LinetypeId = lineTypeDictionary[lineType];
                                            }
                                        }
                                    }
                                    tr.TransactionManager.QueueForGraphicsFlush();
                                }
                                else
                                {
                                    progress.Report.LogConversionError(new Exception($"Failed to add converted object {obj.id} of type {obj.speckle_type} to the document."));
                                }
                            }
                            else
                            {
                                progress.Report.LogOperationError(new Exception($"Failed to create layer {layerName} to bake objects into."));
                            }
                        }
                        else if (converted == null)
                        {
                            progress.Report.LogConversionError(new Exception($"Failed to convert object {obj.id} of type {obj.speckle_type}."));
                        }
                    }
                    progress.Report.Merge(converter.Report);

                    if (changedLayerNames)
                    {
                        progress.Report.Log($"Layer names were modified: one or more layers contained invalid characters {Utils.invalidChars}");
                    }

                    // remove commit info from doc userdata
                    Doc.UserData.Remove("commit");

                    tr.Commit();
                }
            }
        }
 protected override void BeforeSolveInstance()
 {
     Converter?.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
     base.BeforeSolveInstance();
 }
 protected override void BeforeSolveInstance()
 {
     //Ensure converter document is up to date
     Converter.SetContextDocument(Rhino.RhinoDoc.ActiveDoc);
     base.BeforeSolveInstance();
 }