Ejemplo n.º 1
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     DA.DisableGapLogic();
     if (DA.Iteration <= 0)
     {
         // Solveinstance is being called as many times as the length
         // of the input data. Why? Dunno. But it messes things up, outputting
         // n*n data. 
         DA.SetDataTree(0, P.VolatileData);
         DA.SetDataTree(1, P.History);
         DA.SetData(2, lStep);
         DA.SetData(3, cStep);
     }
 }
Ejemplo n.º 2
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var elementIds = new List <Autodesk.Revit.DB.ElementId>();

            if (!DA.GetDataList("Elements", elementIds))
            {
                return;
            }

            var ids = elementIds.Where(x => x is object).ToArray();

            if (ids.Length > 0)
            {
                DA.SetData("Filter", new Autodesk.Revit.DB.ExclusionFilter(ids));
            }
            else
            {
                DA.DisableGapLogic();
            }
        }
Ejemplo n.º 3
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve boundary = null;
            DA.GetData("Boundary", ref boundary);

            Autodesk.Revit.DB.FloorType floorType = null;
            if (!DA.GetData("Type", ref floorType) && Params.Input[1].Sources.Count == 0)
            {
                floorType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.FloorType)) as FloorType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && boundary != null)
            {
                var boundaryBBox = boundary.GetBoundingBox(true);
                using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
                {
                    foreach (var levelN in collector.OfClass(typeof(Level)).ToElements().Cast <Level>().OrderBy(c => c.Elevation))
                    {
                        if (level == null)
                        {
                            level = levelN;
                        }
                        else if (boundaryBBox.Min.Z >= levelN.Elevation)
                        {
                            level = levelN;
                        }
                    }
                }
            }

            bool structural = true;

            DA.GetData("Structural", ref structural);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundary, floorType, level, structural));
        }
Ejemplo n.º 4
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            DA.DisableGapLogic();

            string msg = null;

            if (!DA.GetData(0, ref msg))
            {
                return;
            }

            // Output the values precomputed in the last solution.
            DA.SetData(0, _instruction);
            DA.SetData(1, _tcp);
            DA.SetDataList(2, _axes);
            DA.SetDataList(3, _externalAxes);

            // If on second solution, stop checking.
            if (_updateOutputs)
            {
                _updateOutputs = false;
                return;
            }

            // Otherwise, search for updated values (only if new messages have been received
            // by the Listener), and schedule a new solution if they are new.
            bool rescheduleRightAway = ReceivedNewMessage(msg);

            // If new data came in, schedule a new solution immediately and flag outputs to expire.
            if (rescheduleRightAway)
            {
                _updateOutputs = true;

                this.OnPingDocument().ScheduleSolution(5, doc =>
                {
                    this.ExpireSolution(false);
                });
            }
        }
Ejemplo n.º 5
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometry = new List <Rhino.Geometry.GeometryBase>();

            DA.GetDataList("Geometry", geometry);

            Autodesk.Revit.DB.Category category = null;
            if (!DA.GetData("Category", ref category) && Params.Input[1].Sources.Count == 0)
            {
                category = Autodesk.Revit.DB.Category.GetCategory(Revit.ActiveDBDocument, BuiltInCategory.OST_GenericModel);
            }

            string name = string.Empty;

            DA.GetData("Name", ref name);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, geometry, category, name));
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            DA.DisableGapLogic();

            string msg = null;

            //if (!DA.GetData(0, ref msg)) return;
            DA.GetData(0, ref msg);

            // Add message to list
            if (msg != null)
            {
                dynamic json  = _serializer.Deserialize <dynamic>(msg);
                string  eType = json["event"];
                if (eType.Equals(EVENT_NAME))
                {
                }
            }
        }
        protected override void SolveInstance(IGH_DataAccess access)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            access.DisableGapLogic();

            GH_Structure <GH_Integer> tree;

            // Get the current tree and immediately assign it to the output.
            // Better safe than sorry. Since we only selectively expire the
            // output we should still prevent updates, however there is no
            // reason to not have the most recent data always in the output.
            access.GetDataTree(0, out tree);
            access.SetDataTree(0, tree);

            string currentData = tree.DataDescription(false, true);

            access.SetData(1, currentData);

            // If we were supposed to update the output (meaning it was expired),
            // then we know for sure that we don't have to update again.
            if (UpdateOutput)
            {
                UpdateOutput = false;
                PreviousData = currentData;
                return;
            }

            // If the current data differs from the last time,
            // we need to remember that the output needs updating and
            // we need to schedule a new solution so we can actually do this.
            if (!string.Equals(PreviousData, currentData))
            {
                UpdateOutput = true;
                PreviousData = currentData;

                var doc = OnPingDocument();
                doc?.ScheduleSolution(5, Callback);
            }
        }
Ejemplo n.º 8
0
        protected override void TrySolveInstance(IGH_DataAccess DA, DB.Document doc)
        {
            DA.DisableGapLogic();

            DB.ElementFilter filter = null;
            if (!DA.GetData("Filter", ref filter))
            {
                return;
            }

            using (var collector = new DB.FilteredElementCollector(doc))
            {
                DA.SetDataList
                (
                    "Elements",
                    collector.
                    WherePasses(ElementFilter).
                    WherePasses(filter).
                    Select(x => Types.Element.FromElement(x))
                );
            }
        }
Ejemplo n.º 9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();

            Autodesk.Revit.DB.ElementFilter filter = null;
            if (!DA.GetData("Filter", ref filter))
            {
                return;
            }

            using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
            {
                DA.SetDataList
                (
                    "Elements",
                    collector.
                    WherePasses(ElementFilter).
                    WherePasses(filter).
                    Select(x => Types.Element.Make(x))
                );
            }
        }
Ejemplo n.º 10
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve boundary = null;
            DA.GetData("Boundary", ref boundary);

            Autodesk.Revit.DB.FloorType floorType = null;
            if (!DA.GetData("Type", ref floorType) && Params.Input[1].Sources.Count == 0)
            {
                floorType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.FloorType)) as FloorType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);

            bool structural = true;

            DA.GetData("Structural", ref structural);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundary, floorType, level, structural));
        }
Ejemplo n.º 11
0
        public override void GetData(IGH_DataAccess DA, GH_ComponentParamServer Params)
        {
            if (CancellationToken.IsCancellationRequested)
            {
                return;
            }
            DA.DisableGapLogic();
            GH_Structure <IGH_Goo> _objects;

            DA.GetDataTree(0, out _objects);

            var branchIndex = 0;

            foreach (var list in _objects.Branches)
            {
                var path = _objects.Paths[branchIndex];
                foreach (var item in list)
                {
                    Objects.Append(item, path);
                }
                branchIndex++;
            }
        }
Ejemplo n.º 12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve axis = null;
            DA.GetData("Curve", ref axis);

            GridType gridType = null;

            if (!DA.GetData("Type", ref gridType) && Params.Input[1].Sources.Count == 0)
            {
                gridType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.GridType)) as GridType;
            }

            if (gridType == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' There is no default level type loaded.", Params.Input[1].Name));
                DA.AbortComponentSolution();
                return;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, gridType));
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();
            // We need to call this always in here to be able to react and set events :/
            ParseInput(DA);

            if ((AutoReceive || CurrentComponentState == "primed_to_receive" || CurrentComponentState == "receiving") &&
                !JustPastedIn)
            {
                CurrentComponentState = "receiving";

                // Delegate control to parent async component.
                base.SolveInstance(DA);
                return;
            }

            // Force update output parameters
            // TODO: This is a hack due to the fact that GH_AsyncComponent overrides ExpireDownstreamObjects()
            // and will only propagate the call upwards to GH_Component if the private 'setData' prop  is == 1.
            // We should provide access to the non-overriden method, or a way to call Done() from inherited classes.

            // Set output data in a "first run" event. Note: we are not persisting the actual "sent" object as it can be very big.
            if (JustPastedIn)
            {
                // This ensures that we actually do a run. The worker will check and determine if it needs to pull an existing object or not.
                OnDisplayExpired(true);
                base.SolveInstance(DA);
            }
            else
            {
                CurrentComponentState = "expired";
                Message = "Expired";
                OnDisplayExpired(true);
                Params.Output.ForEach(p => p.ExpireSolution(true));
            }
        }
Ejemplo n.º 14
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometry = new List <IGH_GeometricGoo>();

            DA.GetDataList("Geometry", geometry);

            Autodesk.Revit.DB.Category category = null;
            if (!DA.GetData("Category", ref category) && Params.Input[1].Sources.Count == 0)
            {
                category = Autodesk.Revit.DB.Category.GetCategory(Revit.ActiveDBDocument, BuiltInCategory.OST_GenericModel);
            }

            string name = null;

            if (!DA.GetData("Name", ref name) && geometry.Count == 1 && (geometry[0]?.IsReferencedGeometry ?? false))
            {
                name = Rhino.RhinoDoc.ActiveDoc.Objects.FindId(geometry[0].ReferenceID)?.Name;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, geometry, category, name));
        }
Ejemplo n.º 15
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var axis = Rhino.Geometry.Line.Unset;

            if (DA.GetData("Axis", ref axis))
            {
                if (axis.FromZ > axis.ToZ)
                {
                    axis.Flip();
                }
            }

            FamilySymbol familySymbol = null;

            if (!DA.GetData("Type", ref familySymbol) && Params.Input[1].Sources.Count == 0)
            {
                familySymbol = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultFamilyTypeId(new ElementId(BuiltInCategory.OST_StructuralColumns))) as FamilySymbol;
            }

            if (!familySymbol.IsActive)
            {
                familySymbol.Activate();
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null)
            {
                level = Revit.ActiveDBDocument.FindLevelByElevation(axis.FromZ / Revit.ModelUnits);
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, familySymbol, level));
        }
Ejemplo n.º 16
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve boundary = null;
            DA.GetData("Boundary", ref boundary);

            Autodesk.Revit.DB.RoofType roofType = null;
            if (!DA.GetData("Type", ref roofType) && Params.Input[1].Sources.Count == 0)
            {
                roofType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.RoofType)) as RoofType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && boundary != null)
            {
                var boundaryBBox = boundary.GetBoundingBox(true);
                level = Revit.ActiveDBDocument.FindLevelByElevation(boundaryBBox.Min.Z / Revit.ModelUnits);
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundary, roofType, level));
        }
Ejemplo n.º 17
0
        /// <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)
        {
            string auth            = null;
            string projectName     = null;
            int?   projectNumber   = null;
            var    excludeChildren = true;
            var    refresh         = false;

            if (!DA.GetData(0, ref auth))
            {
                return;
            }
            if (!DA.GetData(1, ref projectName))
            {
                return;
            }
            DA.GetData(2, ref projectNumber);
            DA.GetData(3, ref excludeChildren);
            DA.GetData(4, ref refresh);

            // Get Cache to see if we already did this
            var cacheKey     = projectName + projectNumber + excludeChildren;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || refresh == true)
            {
                var queueName = "ListTasks" + cacheKey;

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            cachedValues = ProjectAndTask.GetTasks(
                                auth,
                                projectName,
                                projectNumber,
                                excludeChildren
                                );
                            StringCache.setCache(cacheKey, cachedValues);
                            StringCache.setCache(this.InstanceGuid.ToString(), "");
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            HandleErrors();

            // Read from Cache
            if (cachedValues != null)
            {
                var outputs = cachedValues.Split(';');
                if (outputs.Length > 1)
                {
                    outputs = outputs.OrderBy(task => task).ToArray();
                }
                DA.SetDataList(0, outputs);
            }
        }
        protected override void SafeSolveInstance(IGH_DataAccess da)
        {
            if (m_py == null)
              {
            da.SetData(0, "No Python engine available. This component needs Rhino v5");
            return;
              }

              if(!HiddenOutOutput)
            da.DisableGapLogic(0);

              m_py_output.Reset();

              var rhdoc = RhinoDoc.ActiveDoc;
              var prevEnabled = (rhdoc != null) && rhdoc.Views.RedrawEnabled;

              try
              {
            // set output variables to "None"
            for (int i = HiddenOutOutput ? 0 : 1; i < Params.Output.Count; i++)
            {
              string varname = Params.Output[i].NickName;
              m_py.SetVariable(varname, null);
            }

            // caching variable to keep things as fast as possible
            bool showing_code_input = !HiddenCodeInput;
            // Set all input variables. Even null variables may be used in the
            // script, so do not attempt to skip these for optimization purposes.
            // Skip "Code" input parameter
            // Please pay attention to the input data structure type
            for (int i = showing_code_input ? 1 : 0; i < Params.Input.Count; i++)
            {
              string varname = Params.Input[i].NickName;
              object o = m_marshal.GetInput(da, i);
              m_py.SetVariable(varname, o);
              m_py.SetIntellisenseVariable(varname, o);
            }

            // the "code" string could be embedded in the component itself
            if (showing_code_input || m_compiled_py == null)
            {
              string script;
              if (!showing_code_input)
            script = Code;
              else
              {
            script = null;
            da.GetData(0, ref script);
              }

              if (string.IsNullOrWhiteSpace(script))
              {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No script to execute");
            return;
              }

              if (m_compiled_py == null ||
              string.Compare(script, m_previousRunCode, StringComparison.InvariantCulture) != 0)
              {
            if (!(m_inDocStringsMode = DocStringUtils.FindApplyDocString(script, this)))
              ResetAllDescriptions();
            m_compiled_py = m_py.Compile(script);
            m_previousRunCode = script;
              }
            }

            if (m_compiled_py != null)
            {
              string localPath;
              bool added = AddLocalPath(out localPath);

              m_compiled_py.Execute(m_py);

              if (added) RemoveLocalPath(localPath);

              // Python script completed, attempt to set all of the
              // output paramerers
              for (int i = HiddenOutOutput ? 0 : 1; i < Params.Output.Count; i++)
              {
            string varname = Params.Output[i].NickName;
            object o = m_py.GetVariable(varname);
            m_marshal.SetOutput(o, da, i);
              }
            }
            else
            {
              m_py_output.Write("There was a permanent error parsing this script. Please report to [email protected].");
            }
              }
              catch (Exception ex)
              {
            AddErrorNicely(m_py_output, ex);
            SetFormErrorOrClearIt(da, m_py_output);
            throw;
              }
              finally
              {
            if (rhdoc != null && prevEnabled != rhdoc.Views.RedrawEnabled)
              rhdoc.Views.RedrawEnabled = true;
              }
              SetFormErrorOrClearIt(da, m_py_output);
        }
Ejemplo n.º 19
0
        /// <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)
        {
            string folder  = null;
            var    refresh = false;

            if (!DA.GetData(0, ref folder))
            {
                return;
            }
            DA.GetData(1, ref refresh);

            // Get Cache to see if we already did this
            var cacheKey     = folder;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || refresh)
            {
                const string queueName = "radiationProbeResults";
                StringCache.setCache(InstanceGuid.ToString(), "");

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey + "progress", "Loading...");

                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results  = RadiationProbeResult.ReadResults(folder);
                            probeResults = ConvertToDataTree(results);
                            info         = UpdateInfo(results);
                            StringCache.setCache(cacheKey + "progress", "Done");
                            StringCache.setCache(cacheKey, "results");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "progress", "");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                    ExpireSolutionThreadSafe(true);
                }
            }

            HandleErrors();

            if (info != null)
            {
                DA.SetDataTree(0, info);
            }

            if (probeResults != null)
            {
                DA.SetDataTree(1, probeResults);
            }

            Message = StringCache.getCache(cacheKey + "progress");
        }
Ejemplo n.º 20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var parameterId = ElementId.InvalidElementId;

            if (!DA.GetData("ParameterKey", ref parameterId))
            {
                return;
            }

            DA.DisableGapLogic();

            if (!TryGetParameterDefinition(Revit.ActiveDBDocument, parameterId, out var storageType, out var parameterType))
            {
                if (parameterId.TryGetBuiltInParameter(out var builtInParameter))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to found parameter '{LabelUtils.GetLabelFor(builtInParameter)}' in Revit document.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to found parameter '{parameterId.IntegerValue}' in Revit document.");
                }

                return;
            }

            var provider = new ParameterValueProvider(parameterId);

            Autodesk.Revit.DB.FilterRule rule = null;
            if (storageType == StorageType.String)
            {
                FilterStringRuleEvaluator ruleEvaluator = null;
                switch (Condition)
                {
                case ConditionType.NotEquals:
                case ConditionType.Equals:          ruleEvaluator = new FilterStringEquals(); break;

                case ConditionType.Greater:         ruleEvaluator = new FilterStringGreater(); break;

                case ConditionType.GreaterOrEqual:  ruleEvaluator = new FilterStringGreaterOrEqual(); break;

                case ConditionType.Less:            ruleEvaluator = new FilterStringLess(); break;

                case ConditionType.LessOrEqual:     ruleEvaluator = new FilterStringLessOrEqual(); break;
                }

                var goo = default(GH_String);
                if (DA.GetData("Value", ref goo))
                {
                    rule = new FilterStringRule(provider, ruleEvaluator, goo.Value, true);
                }
            }
            else
            {
                FilterNumericRuleEvaluator ruleEvaluator = null;
                switch (Condition)
                {
                case ConditionType.NotEquals:
                case ConditionType.Equals:          ruleEvaluator = new FilterNumericEquals(); break;

                case ConditionType.Greater:         ruleEvaluator = new FilterNumericGreater(); break;

                case ConditionType.GreaterOrEqual:  ruleEvaluator = new FilterNumericGreaterOrEqual(); break;

                case ConditionType.Less:            ruleEvaluator = new FilterNumericLess(); break;

                case ConditionType.LessOrEqual:     ruleEvaluator = new FilterNumericLessOrEqual(); break;
                }

                switch (storageType)
                {
                case StorageType.Integer:
                {
                    var goo = default(GH_Integer);
                    if (DA.GetData("Value", ref goo))
                    {
                        rule = new FilterIntegerRule(provider, ruleEvaluator, goo.Value);
                    }
                }
                break;

                case StorageType.Double:
                {
                    var goo = default(GH_Number);
                    if (DA.GetData("Value", ref goo))
                    {
                        if (Condition == ConditionType.Equals || Condition == ConditionType.NotEquals)
                        {
                            if (parameterType == ParameterType.Length || parameterType == ParameterType.Area || parameterType == ParameterType.Volume)
                            {
                                rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), ToHost(Revit.VertexTolerance, parameterType));
                            }
                            else
                            {
                                rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), 1e-6);
                            }
                        }
                        else
                        {
                            rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), 0.0);
                        }
                    }
                }
                break;

                case StorageType.ElementId:
                {
                    switch (parameterType)
                    {
                    case (ParameterType)int.MaxValue: // Category
                    {
                        var value = default(Types.Category);
                        if (DA.GetData("Value", ref value))
                        {
                            rule = new FilterElementIdRule(provider, ruleEvaluator, value);
                        }
                    }
                    break;

                    case ParameterType.FamilyType:
                    {
                        var value = default(Types.ElementType);
                        if (DA.GetData("Value", ref value))
                        {
                            rule = new FilterElementIdRule(provider, ruleEvaluator, value);
                        }
                    }
                    break;

                    default:
                    {
                        var value = default(Types.Element);
                        if (DA.GetData("Value", ref value))
                        {
                            rule = new FilterElementIdRule(provider, ruleEvaluator, value);
                        }
                    }
                    break;
                    }
                }
                break;
                }
            }

            if (rule is object)
            {
                if (Condition == ConditionType.NotEquals)
                {
                    DA.SetData("Rule", new FilterInverseRule(rule));
                }
                else
                {
                    DA.SetData("Rule", rule);
                }
            }
        }
Ejemplo n.º 21
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            DA.DisableGapLogic();

            string msg = null;

            if (!DA.GetData(0, ref msg))
            {
                return;
            }

            // Output the values precomputed in the last solution.
            DA.SetData(0, _lastTCP);
            DA.SetDataList(1, _lastAxes);
            DA.SetDataList(2, _lastExternalAxes);

            // Was any output flagged for an update?
            bool doneWithUpdates = false;

            for (int i = 0; i < _updateOutputs.Length; i++)
            {
                doneWithUpdates |= _updateOutputs[i];
                if (_updateOutputs[i])
                {
                    _updateOutputs[i] = false;
                }
            }

            // If on the second solution, stop checking and go back to autoupdate
            if (doneWithUpdates)
            {
                return;
            }

            // Otherwise, search for updated values (only if new messages have been received
            // by the Listener), and schedule a new solution if they are new.
            bool rescheduleRightAway = false;

            if (true)
            {
                UpdateCurrentValues(msg);

                // Check and flag each output individually
                bool equals;

                // Compare TCP by its string representation (urgh...)
                equals = string.Equals(_lastPosStr, _currPosStr) && string.Equals(_lastOriStr, _currOriStr);  // if nulls, this will also work
                rescheduleRightAway |= equals;
                if (!equals)
                {
                    _updateOutputs[0] = true;

                    _lastPosObj = _currPosObj;
                    _lastOriObj = _currOriObj;
                    _lastPosStr = _currPosStr;
                    _lastOriStr = _currOriStr;
                    _lastTCP    = PlaneFromDoubleObjects(_lastPosObj, _lastOriObj);
                }

                // Compare axes by string representation too
                equals = string.Equals(_lastAxesStr, _currAxesStr);
                rescheduleRightAway |= equals;
                if (!equals)
                {
                    _updateOutputs[1] = true;

                    _lastAxesObj = _currAxesObj;
                    _lastAxesStr = _currAxesStr;

                    _lastAxes = ListFromNullableDoubleObjects(_lastAxesObj);
                }

                // Compare external axes by string representation... OMG I hope no one ever reads this code...
                equals = string.Equals(_lastExtaxStr, _currExtaxStr);
                rescheduleRightAway |= equals;
                if (!equals)
                {
                    _updateOutputs[2] = true;

                    _lastExtaxObj = _currExtaxObj;
                    _lastExtaxStr = _currExtaxStr;

                    _lastExternalAxes = ListFromNullableDoubleObjects(_lastExtaxObj);
                }
            }

            if (rescheduleRightAway)
            {
                this.OnPingDocument().ScheduleSolution(5, doc =>
                {
                    this.ExpireSolution(false);
                });
            }
        }
Ejemplo n.º 22
0
        /// <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)
        {
            string inputJson   = null;
            var    points      = new GH_Structure <GH_Point>();
            var    names       = new List <string>();
            var    fields      = new List <string>();
            var    mesh        = new GH_Structure <GH_Mesh>();
            var    cpus        = 1;
            var    dependentOn = "VirtualWindTunnel";
            var    caseDir     = "VWT";
            var    overrides   = "";
            var    create      = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            if (!DA.GetDataTree(1, out points))
            {
                return;
            }
            if (!DA.GetDataList(2, names))
            {
                for (var i = 0; i < points.Branches.Count; i++)
                {
                    names.Add($"set{i.ToString()}");
                }
            }
            else
            {
                foreach (var name in names)
                {
                    ValidateName(name);
                }
            }

            if (!DA.GetDataList(3, fields))
            {
                fields.Add("U");
            }

            DA.GetDataTree(4, out mesh);
            DA.GetData(5, ref cpus);
            DA.GetData(6, ref dependentOn);
            DA.GetData(7, ref caseDir);
            DA.GetData(8, ref overrides);
            DA.GetData(9, ref create);

            var convertedPoints = Geometry.ConvertPointsToList(points);

            caseDir = caseDir.TrimEnd('/');

            // Get Cache to see if we already did this
            var cacheKey     = inputJson + string.Join("", points) + string.Join("", fields) + string.Join("", names);
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || create)
            {
                var queueName = "probe";

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var meshFile = Export.MeshToObj(mesh, names);
                            var results  = Probe.ProbePoints(
                                inputJson,
                                convertedPoints,
                                fields,
                                names,
                                ComponentUtils.ValidateCPUs(cpus),
                                meshFile,
                                dependentOn,
                                caseDir,
                                overrides,
                                create
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            if (create)
                            {
                                StringCache.setCache(cacheKey + "create", "true");
                            }
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "create", "");
                        }


                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            HandleErrors();
            Message = "";

            if (cachedValues != null)
            {
                DA.SetData(0, cachedValues);

                if (StringCache.getCache(cacheKey + "create") == "true")
                {
                    Message = "Task Created";
                }
            }
        }
Ejemplo n.º 23
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();
            GH_SpeckleStream ghSpeckleStream = null;
            string           name            = null;
            string           description     = null;
            bool             isPublic        = false;

            if (!DA.GetData(0, ref ghSpeckleStream))
            {
                return;
            }
            DA.GetData(1, ref name);
            DA.GetData(2, ref description);
            DA.GetData(3, ref isPublic);

            var streamWrapper = ghSpeckleStream.Value;

            if (error != null)
            {
                Message = null;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message);
                error = null;
            }
            else if (stream == null)
            {
                if (streamWrapper == null)
                {
                    Message = "";
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Not a stream wrapper!");
                    return;
                }
                Message = "Fetching";
                Task.Run(async() =>
                {
                    var account = streamWrapper.UserId == null ?
                                  AccountManager.GetDefaultAccount() :
                                  AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == streamWrapper.UserId);

                    if (account == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not find the specified account in this machine. Use the Speckle Manager to add an account, or modify the input stream with your credentials.");
                        return;
                    }

                    var client = new Client(account);
                    var input  = new StreamUpdateInput();
                    try
                    {
                        stream   = await client.StreamGet(streamWrapper.StreamId);
                        input.id = streamWrapper.StreamId;

                        input.name        = name ?? stream.name;
                        input.description = description ?? stream.description;

                        if (stream.isPublic != isPublic)
                        {
                            input.isPublic = isPublic;
                        }

                        await client.StreamUpdate(input);
                    }
                    catch (Exception e)
                    {
                        error = e;
                    }
                    finally
                    {
                        Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); });
                    }
                });
            }
            else
            {
                stream  = null;
                Message = "Done";
                DA.SetData(0, streamWrapper.StreamId);
            }
        }
Ejemplo n.º 24
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            var classNames = new List <string>();

            if (!DA.GetDataList("Classes", classNames))
            {
                return;
            }

            var filters = new List <DB.ElementFilter>();
            var classes = new HashSet <string>(classNames);

            if (classes.Remove("Autodesk.Revit.DB.Area"))
            {
                filters.Add(new DB.AreaFilter());
            }
            if (classes.Remove("Autodesk.Revit.DB.AreaTag"))
            {
                filters.Add(new DB.AreaTagFilter());
            }
            if (classes.Remove("Autodesk.Revit.DB.Architecture.Room"))
            {
                filters.Add(new DB.Architecture.RoomFilter());
            }
            if (classes.Remove("Autodesk.Revit.DB.Architecture.RoomTag"))
            {
                filters.Add(new DB.Architecture.RoomTagFilter());
            }

            try
            {
                var types = classes.Select(x => Type.GetType($"{x},RevitAPI", true)).ToList();

                if (types.Count > 0)
                {
                    if (types.Count == 1)
                    {
                        filters.Add(new DB.ElementClassFilter(types[0]));
                    }
                    else
                    {
                        filters.Add(new DB.ElementMulticlassFilter(types));
                    }
                }

                if (filters.Count == 0)
                {
                    DA.DisableGapLogic();
                }
                else
                {
                    if (filters.Count == 1)
                    {
                        DA.SetData("Filter", filters[0]);
                    }
                    else
                    {
                        DA.SetData("Filter", new DB.LogicalOrFilter(filters));
                    }
                }
            }
            catch (System.TypeLoadException e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
            }
            catch (Autodesk.Revit.Exceptions.ArgumentException e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message.Replace(". ", $".{Environment.NewLine}"));
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();
            GH_SpeckleStream ghSpeckleStream = null;
            string           name            = null;
            string           description     = null;
            bool             isPublic        = false;

            if (DA.Iteration == 0)
            {
                Tracker.TrackPageview(Tracker.STREAM_UPDATE);
            }

            if (!DA.GetData(0, ref ghSpeckleStream))
            {
                return;
            }
            DA.GetData(1, ref name);
            DA.GetData(2, ref description);
            DA.GetData(3, ref isPublic);

            var streamWrapper = ghSpeckleStream.Value;

            if (error != null)
            {
                Message = null;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message);
                error = null;
            }
            else if (stream == null)
            {
                if (streamWrapper == null)
                {
                    Message = "";
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Not a stream wrapper!");
                    return;
                }
                Message = "Fetching";
                Task.Run(async() =>
                {
                    try
                    {
                        var account = streamWrapper.GetAccount().Result;
                        var client  = new Client(account);
                        var input   = new StreamUpdateInput();
                        stream      = await client.StreamGet(streamWrapper.StreamId);
                        input.id    = streamWrapper.StreamId;

                        input.name        = name ?? stream.name;
                        input.description = description ?? stream.description;

                        if (stream.isPublic != isPublic)
                        {
                            input.isPublic = isPublic;
                        }

                        await client.StreamUpdate(input);
                    }
                    catch (Exception e)
                    {
                        error = e.InnerException ?? e;
                    }
                    finally
                    {
                        Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); });
                    }
                });
            }
            else
            {
                stream  = null;
                Message = "Done";
                DA.SetData(0, streamWrapper.StreamId);
            }
        }
Ejemplo n.º 26
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();
            if (DA.Iteration != 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "Cannot fetch multiple streams at the same time. This is an explicit guard against possibly unintended behaviour. If you want to get the details of another stream, please use a new component.");
                return;
            }

            string           accountId   = null;
            GH_SpeckleStream ghIdWrapper = null;

            DA.DisableGapLogic();
            DA.GetData(0, ref ghIdWrapper);
            DA.GetData(1, ref accountId);
            var account = string.IsNullOrEmpty(accountId) ? AccountManager.GetDefaultAccount() :
                          AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == accountId);

            var idWrapper = ghIdWrapper.Value;

            if (account == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not find default account in this machine. Use the Speckle Manager to add an account.");
                return;
            }

            Params.Input[1].AddVolatileData(new GH_Path(0), 0, account.userInfo.id);

            if (error != null)
            {
                Message = null;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message);
                error  = null;
                stream = null;
            }
            else if (stream == null)
            {
                Message = "Fetching";
                // Validation
                string errorMessage = null;
                if (!ValidateInput(account, idWrapper.StreamId, ref errorMessage))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errorMessage);
                    return;
                }

                // Run
                Task.Run(async() =>
                {
                    try
                    {
                        //Exists?
                        var client        = new Client(account);
                        var result        = await client.StreamGet(idWrapper.StreamId);
                        stream            = new StreamWrapper(result.id, account.userInfo.id, account.serverInfo.url);
                        stream.BranchName = idWrapper.BranchName;
                        stream.ObjectId   = idWrapper.ObjectId;
                        stream.CommitId   = idWrapper.CommitId;
                    }
                    catch (Exception e)
                    {
                        stream = null;
                        error  = e;
                    }
                    finally
                    {
                        Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); });
                    }
                });
            }
            else
            {
                Message = "Done";
                DA.SetData(0, new GH_SpeckleStream(stream));
                stream = null;
            }
        }
Ejemplo n.º 27
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            DA.DisableGapLogic();

            MachinaBridgeSocket ms = null;
            bool autoUpdate        = true;
            int  millis            = 1000;

            if (!DA.GetData(0, ref ms))
            {
                return;
            }
            if (!DA.GetData(1, ref autoUpdate))
            {
                return;
            }
            if (!DA.GetData(2, ref millis))
            {
                return;
            }

            // Some sanity
            if (millis < 10)
            {
                millis = 10;
            }
            if (ms == null || ms.socket == null || !ms.socket.IsAlive)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Not valid Bridge connection.");
                return;
            }

            // Output the last received message from the last cycle
            DA.SetData(0, _lastMsg);

            // Stop triggering expiration updates if the buffer is empty
            int size = ms.BufferSize();

            if (_updateOut && size == 0)
            {
                _updateOut = false;

                // And go back to regular autoupdate
                if (autoUpdate)
                {
                    this.OnPingDocument().ScheduleSolution(millis, doc => {
                        this.ExpireSolution(false);
                    });
                }

                return;
            }

            // If there are messagges logged by the MS, trigger a chain of expiration updates
            if (size > 0)
            {
                _updateOut = true;
                _lastMsg   = ms.FetchFirst(true);

                // Schedule a new solution right away
                this.OnPingDocument().ScheduleSolution(5, doc => {
                    this.ExpireSolution(false);
                });

                return;
            }

            // Otherwise, back to reguar autoupdate
            if (autoUpdate)
            {
                this.OnPingDocument().ScheduleSolution(millis, doc =>
                {
                    this.ExpireSolution(false);
                });
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();
            if (DA.Iteration != 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "Cannot fetch multiple streams at the same time. This is an explicit guard against possibly unintended behaviour. If you want to get the details of another stream, please use a new component.");
                return;
            }

            string           userId      = null;
            GH_SpeckleStream ghIdWrapper = null;

            DA.DisableGapLogic();
            if (!DA.GetData(0, ref ghIdWrapper))
            {
                return;
            }
            DA.GetData(1, ref userId);
            var idWrapper = ghIdWrapper.Value;
            var account   = string.IsNullOrEmpty(userId)
        ? AccountManager.GetAccounts().FirstOrDefault(a => a.serverInfo.url == idWrapper.ServerUrl) // If no user is passed in, get the first account for this server
        : AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == userId);                // If user is passed in, get matching user in the db

            if (account == null || account.serverInfo.url != idWrapper.ServerUrl)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  $"Could not find an account for server ${idWrapper.ServerUrl}. Use the Speckle Manager to add an account.");
                return;
            }

            if (error != null)
            {
                Message = null;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message);
                error  = null;
                stream = null;
            }
            else if (stream == null)
            {
                Message = "Fetching";
                // Validation
                string errorMessage = null;
                if (DA.Iteration == 0)
                {
                    Tracker.TrackPageview(Tracker.STREAM_GET);
                }

                if (!ValidateInput(account, idWrapper.StreamId, ref errorMessage))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errorMessage);
                    return;
                }

                // Run
                Task.Run(async() =>
                {
                    try
                    {
                        var acc = idWrapper.GetAccount().Result;
                        stream  = idWrapper;
                    }
                    catch (Exception e)
                    {
                        stream = null;
                        error  = e.InnerException ?? e;
                    }
                    finally
                    {
                        Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); });
                    }
                });
            }
            else
            {
                Message = "Done";
                DA.SetData(0, new GH_SpeckleStream(stream));
                stream = null;
            }
        }
        protected override void SolveInstance(IGH_DataAccess access)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            access.DisableGapLogic();


            // Get the current tree and immediately assign it to the output.
            // Better safe than sorry. Since we only selectively expire the
            // output we should still prevent updates, however there is no
            // reason to not have the most recent data always in the output.
            bool doneWithUpdates = false;
            GH_Structure <GH_Integer> tree;

            string[] currentData = new string[IOCount];
            for (int i = 0; i < IOCount; i++)
            {
                // Check if any input was flagged for an update.
                doneWithUpdates |= UpdateOutput[i];

                access.GetDataTree(i, out tree);
                access.SetDataTree(i, tree);

                currentData[i] = tree.DataDescription(false, true);

                // Unflag inputs that were due for updates.
                if (UpdateOutput[i])
                {
                    UpdateOutput[i] = false;
                    PreviousData[i] = currentData[i];
                }
            }

            // If any input was flagged for an update, the program is
            // executing the second solution and should stop solving,
            // e.g. if we were supposed to update the output (meaning it
            // was expired), then we know for sure that we don't have to
            // update again.
            if (doneWithUpdates)
            {
                return;
            }

            // If the current data differs from the last time,
            // we need to remember that the output needs updating and
            // we need to schedule a new solution so we can actually do this.
            bool scheduleSolution = false;

            for (int i = 0; i < IOCount; i++)
            {
                // Compare int trees by using string description including tree info
                if (!string.Equals(PreviousData[i], currentData[i]))
                {
                    UpdateOutput[i] = true;
                    PreviousData[i] = currentData[i];
                }

                // If flagged any UpdateOutput, we will need to schedule a new solution.
                scheduleSolution |= UpdateOutput[i];
            }

            // Schedule new solution if any ouput needed an update
            if (scheduleSolution)
            {
                var doc = OnPingDocument();
                doc?.ScheduleSolution(5, Callback);
            }
        }
        /// <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)
        {
            string inputJson = null;
            var    mesh      = new GH_Structure <GH_Mesh>();
            var    points    = new GH_Structure <GH_Point>();
            var    normals   = new GH_Structure <GH_Vector>();
            var    names     = new List <string>();
            var    create    = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            if (!DA.GetDataTree(1, out mesh))
            {
                return;
            }
            if (!DA.GetDataTree(2, out points))
            {
                return;
            }
            if (!DA.GetDataTree(3, out normals))
            {
                return;
            }
            if (!DA.GetDataList(4, names))
            {
                for (var i = 0; i < points.Branches.Count; i++)
                {
                    names.Add($"set{i.ToString()}");
                }
            }

            DA.GetData(5, ref create);



            // Get Cache to see if we already did this
            var cacheKey     = string.Join("", points) + string.Join("", names) + inputJson;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || create)
            {
                var queueName = "radiationProbe";

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var meshFile = Export.MeshToObj(mesh, names);
                            var results  = Probe.RadiationProbes(
                                inputJson,
                                Geometry.ConvertPointsToList(points),
                                Geometry.ConvertPointsToList(normals),
                                names,
                                meshFile,
                                create
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            if (create)
                            {
                                StringCache.setCache(cacheKey + "create", "true");
                            }
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "create", "");
                        }


                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            // Handle Errors
            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (errors != null)
            {
                if (errors.Contains("No object found"))
                {
                    Message = "No Probe Task found.";
                }
                else
                {
                    throw new Exception(errors);
                }
            }

            // Read from Cache
            Message = "";
            if (cachedValues != null)
            {
                var outputs = cachedValues;
                DA.SetData(0, outputs);
                if (StringCache.getCache(cacheKey + "create") == "true")
                {
                    Message = "Task Created";
                }
            }
        }
Ejemplo n.º 31
0
        /// <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)
        {
            string filepath;

            filepath = Path.GetDirectoryName(this.OnPingDocument().FilePath);
            string residualstxt = filepath + @"\\residual.txt";


            geoms = new List <DiscretizedGeometry>();
            if (!DA.GetDataList(0, geoms))
            {
                return;
            }
            ;

            List <double> xyzsize = new List <double>();

            if (!DA.GetDataList(1, xyzsize))
            {
                return;
            }
            ;

            List <int> Nxyz = new List <int>();

            if (!DA.GetDataList(2, Nxyz))
            {
                return;
            }
            ;
            int Nx = Nxyz[0];
            int Ny = Nxyz[1];
            int Nz = Nxyz[2];



            //terrain type
            int terrain = 3;

            if (!DA.GetData(3, ref terrain))
            {
                return;
            }

            // horizon
            double t_end = 1;

            if (!DA.GetData(4, ref t_end))
            {
                return;
            }

            // time step
            double dt = 0.1;

            if (!DA.GetData(5, ref dt))
            {
                return;
            }

            // wind speed
            double Vmet = 5;

            if (!DA.GetData(6, ref Vmet))
            {
                return;
            }



            string strparam = null;

            DA.GetData(7, ref strparam);
            string[] str_params = null;
            if (strparam != null)
            {
                str_params = strparam.Split(';');
            }


            bool run = false;

            if (!DA.GetData(8, ref run))
            {
                return;
            }

            int meanDt = 15;
            //DA.GetData(9, ref meanDt);

            bool stop = false;

            DA.GetData(9, ref stop);

            bool stopOne = false;

            DA.GetData(10, ref stopOne);



            if (stop)
            {
                StopAll();
            }

            if (stopOne)
            {
                StopOne();
            }



            if (skipSolution && (run == false))
            {
                skipSolution = false;
                DA.IncrementIteration();

                DA.SetDataList(0, ffdSolvers);

                Rhino.RhinoApp.WriteLine("Updated all outputs to GH");
                Grasshopper.Instances.RedrawAll();
            }
            else if (!componentBusy)
            {
                DA.DisableGapLogic();

                bool ReturnSomething()
                {
                    return(true);
                }

                Task <bool> computingTask = new Task <bool>(() => ReturnSomething()); //to create the scope ..


                if (run)
                {
                    Rhino.RhinoApp.WriteLine("..createall");
                    CreateAll(
                        this.OnPingDocument().FilePath,
                        Nxyz,
                        xyzsize,
                        t_end,
                        dt,
                        meanDt,
                        Vmet,
                        terrain,
                        strparam
                        );

                    computingTask = new Task <bool>(() => RunAll());
                }


                computingTask.ContinueWith(r =>
                {
                    if (r.Status == TaskStatus.RanToCompletion)
                    {
                        bool result = computingTask.Result;
                        if (result == true)
                        {
                            NickName     = "GS_GH_Wind - Finished!";
                            skipSolution = true;

                            pstagResults = ffdSolver.pstag;



                            p              = ffdSolver.p;
                            veloutCen      = ffdSolver.veloutCen;
                            veloutStag     = ffdSolver.veloutStag;
                            pstag          = ffdSolver.pstag;
                            de             = ffdSolver.de;
                            obstacle_cells = ffdSolver.obstacle_cells;


                            ExpireSolution(false);
                            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(false);
                        }
                        else
                        {
                            Rhino.RhinoApp.WriteLine("failed");
                            NickName = "GS_GH_Wind - Failed.";
                            Grasshopper.Instances.RedrawAll();
                        }
                        componentBusy = false;
                    }
                    else if (r.Status == TaskStatus.Faulted)
                    {
                        NickName = "GS_GH_Wind - Faulted.";
                        Grasshopper.Instances.RedrawAll();
                        componentBusy = false;
                    }
                },
                                           TaskScheduler.FromCurrentSynchronizationContext()


                                           );

                computingTask.Start();
                if (run)
                {
                    NickName = "GS_GH_Wind - Processing...";
                }
                Grasshopper.Instances.RedrawAll();
                componentBusy = true;
            }
        }
Ejemplo n.º 32
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var categoryType = Autodesk.Revit.DB.CategoryType.Invalid;
            {
                var categoryValue = (int)categoryType;
                DA.GetData("Type", ref categoryValue);
                categoryType = (Autodesk.Revit.DB.CategoryType)categoryValue;
            }

            bool AllowsParameters = false;
            bool nofilterParams   = (!DA.GetData("AllowsParameters", ref AllowsParameters) && Params.Input[1].Sources.Count == 0);

            bool HasMaterialQuantities = false;
            bool nofilterMaterials     = (!DA.GetData("HasMaterialQuantities", ref HasMaterialQuantities) && Params.Input[2].Sources.Count == 0);

            bool Cuttable         = false;
            bool nofilterCuttable = (!DA.GetData("Cuttable", ref Cuttable) && Params.Input[3].Sources.Count == 0);

            bool Hidden         = false;
            bool nofilterHidden = (!DA.GetData("Hidden", ref Hidden) && Params.Input[4].Sources.Count == 0);

            var categories = Revit.ActiveDBDocument.Settings.Categories.Cast <Category>();

            if (categoryType != Autodesk.Revit.DB.CategoryType.Invalid)
            {
                categories = categories.Where((x) => x.CategoryType == categoryType);
            }

            if (!nofilterParams)
            {
                categories = categories.Where((x) => x.AllowsBoundParameters == AllowsParameters);
            }

            if (!nofilterMaterials)
            {
                categories = categories.Where((x) => x.HasMaterialQuantities == HasMaterialQuantities);
            }

            if (!nofilterCuttable)
            {
                categories = categories.Where((x) => x.IsCuttable == Cuttable);
            }

            if (!nofilterHidden)
            {
                categories = categories.Where((x) => x.IsHidden() == Hidden);
            }

            IEnumerable <Category> list = null;

            foreach (var group in categories.GroupBy((x) => x.CategoryType).OrderBy((x) => x.Key))
            {
                var orderedGroup = group.OrderBy((x) => x.Name);
                list = list?.Concat(orderedGroup) ?? orderedGroup;
            }

            if (list is object)
            {
                DA.SetDataList("Categories", list);
            }
            else
            {
                DA.DisableGapLogic();
            }
        }
Ejemplo n.º 33
0
        protected override void SafeSolveInstance(IGH_DataAccess DA)
        {
            if (_py == null)
              {
            DA.SetData(0, "No Python engine available. This component needs Rhino v5");
            return;
              }

              DA.DisableGapLogic(0);

              m_py_output.Reset();

              var rhdoc = RhinoDoc.ActiveDoc;
              var prevEnabled = (rhdoc != null) && rhdoc.Views.RedrawEnabled;

              try
              {
            // set output variables to "None"
            for (int i = HideCodeOutput ? 0 : 1; i < Params.Output.Count; i++)
            {
              string varname = Params.Output[i].NickName;
              _py.SetVariable(varname, null);
            }

            // caching variable to keep things as fast as possible
            bool showing_code_input = CodeInputVisible;
            // Set all input variables. Even null variables may be used in the
            // script, so do not attempt to skip these for optimization purposes.
            // Skip "Code" input parameter
            // Please pay attention to the input data structure type
            for (int i = showing_code_input ? 1 : 0; i < Params.Input.Count; i++)
            {
              string varname = Params.Input[i].Name; // ksteinfe: changed from Params.Input[i].Nickname
              object o = _marshal.GetInput(DA, i);
              _py.SetVariable(varname, o);
            //_py.SetIntellisenseVariable(varname, o); // ksteinfe: i think this set the Intellisense thingos for all the input variables.  we are converting, so Intellisense would just be confusing.
            }

            // the "code" string could be embedded in the component itself
            if (showing_code_input || _compiled_py == null)
            {
              string script;
              if (!showing_code_input)
            script = CodeInput;
              else
              {
            script = null;
            DA.GetData(0, ref script);
              }

              if (string.IsNullOrWhiteSpace(script))
              {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No script to execute");
            return;
              }

            // ksteinfe - i think we put our hack here.
              //_py.ExecuteScript(DcPython.Decodes.DecodesAppendedCode.header);
              //script = script + DcPython.Decodes.DecodesAppendedCode.footer;
              script = DcPython.Decodes.DecodesAppendedCode.header + script + DcPython.Decodes.DecodesAppendedCode.footer;

              if (_compiled_py == null ||
              string.Compare(script, _previousRunCode, StringComparison.InvariantCulture) != 0)
              {
            if (!(_inDocStringsMode = DocStringUtils.FindApplyDocString(script, this)))
              ResetAllDescriptions();
            _compiled_py = _py.Compile(script);
            _previousRunCode = script;
              }
            }

            if (_compiled_py != null)
            {
              _compiled_py.Execute(_py);
              // Python script completed, attempt to set all of the
              // output paramerers
              for (int i = HideCodeOutput ? 0 : 1; i < Params.Output.Count; i++)
              {
            string varname = Params.Output[i].NickName;
            object o = _py.GetVariable(varname); // ksteinfe: this is a tree coming in from gh python out.  can we just scan the tree and grab the attributes to store somewhere, then bake each param?
            _marshal.SetOutput(o, DA, i);
              }
            }
            else
            {
              m_py_output.Write("There was a permanent error parsing this script. Please report to [email protected].");
            }
              }
              catch (Exception ex)
              {
            AddErrorNicely(m_py_output, ex);
            SetFormErrorOrClearIt(DA, m_py_output);
            throw;
              }
              finally
              {
            if (rhdoc != null && prevEnabled != rhdoc.Views.RedrawEnabled)
              rhdoc.Views.RedrawEnabled = true;
              }
              SetFormErrorOrClearIt(DA, m_py_output);
        }