public static SpeckleObject fromMesh(Mesh o)
        {
            var encodedObj = "RH:" + SpeckleConverter.getBase64(o);

            Rhino.Geometry.VolumeMassProperties volumeProps = Rhino.Geometry.VolumeMassProperties.Compute(o);
            Rhino.Geometry.AreaMassProperties   areaProps   = Rhino.Geometry.AreaMassProperties.Compute(o);

            SpeckleObject obj = new SpeckleObject();

            obj.value      = new ExpandoObject();
            obj.properties = new ExpandoObject();


            obj.type = "Mesh";
            obj.hash = "Mesh." + SpeckleConverter.getHash(encodedObj);

            obj.value.vertices = o.Vertices.Select(pt => fromPoint(pt));
            obj.value.faces    = o.Faces;
            obj.value.colors   = o.VertexColors.Select(c => c.ToArgb());
            //o.UserData
            obj.properties.volume         = volumeProps.Volume;
            obj.properties.area           = areaProps.Area;
            obj.properties.volumeCentroid = fromPoint(volumeProps.Centroid);
            obj.properties.areaCentroid   = fromPoint(areaProps.Centroid);

            return(obj);
        }
        public static SpeckleObject fromBrep(Brep o, bool getEncoded, bool getAbstract)
        {
            var encodedObj = "RH:" + SpeckleConverter.getBase64(o);
            var ms         = getMeshFromBrep(o);

            Rhino.Geometry.VolumeMassProperties volumeProps = Rhino.Geometry.VolumeMassProperties.Compute(o);
            Rhino.Geometry.AreaMassProperties   areaProps   = Rhino.Geometry.AreaMassProperties.Compute(o);

            SpeckleObject obj = new SpeckleObject();

            obj.value      = new ExpandoObject();
            obj.properties = new ExpandoObject();

            obj.type                      = "Brep";
            obj.hash                      = "Brep." + SpeckleConverter.getHash(encodedObj);
            obj.encodedValue              = getEncoded ? encodedObj : "";
            obj.value.vertices            = ms.Vertices;
            obj.value.faces               = ms.Faces;
            obj.value.colors              = ms.VertexColors;
            obj.properties.volume         = volumeProps.Volume;
            obj.properties.area           = areaProps.Area;
            obj.properties.volumeCentroid = fromPoint(volumeProps.Centroid);
            obj.properties.areaCentroid   = fromPoint(areaProps.Centroid);

            return(obj);
        }
Esempio n. 3
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var xml_in = "";

            DA.GetData(0, ref xml_in);
            var xml = new XmlDocument();

            xml.LoadXml(xml_in);

            var jsonText = JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented, false);

            JsonSerializerSettings jsonSS = new JsonSerializerSettings();

            jsonSS.Formatting                 = Newtonsoft.Json.Formatting.Indented;
            jsonSS.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
            jsonSS.PreserveReferencesHandling = PreserveReferencesHandling.None;
            jsonSS.StringEscapeHandling       = StringEscapeHandling.EscapeNonAscii;
            jsonSS.NullValueHandling          = NullValueHandling.Include;
            jsonSS.Converters                 = new JsonConverter[] { new SpecklePropertiesConverter() };

            dynamic obj = JsonConvert.DeserializeObject <Dictionary <string, object> >(
                jsonText, jsonSS);

            var so = new SpeckleObject()
            {
                Properties = obj
            };

            DA.SetData("SpeckleObject", new GH_SpeckleObject(so));
            DA.SetData("Dictionary", obj);
        }
Esempio n. 4
0
        public static void SetBHoMData(SpeckleObject speckleObject, IObject bhObject, bool useSpeckleSerialiser = false)
        {
            speckleObject.Properties = new Dictionary <string, object>();

            // Serialise the IBHoMObject data and append it to the `Properties` of the SpeckleObject.
            if (useSpeckleSerialiser)
            {
                // Speckle "Serialiser" is very slow with BHoM classes.
                object serialisedBHoMData = SpeckleCore.Converter.Serialise(bhObject);
                speckleObject.Properties.Add("BHoM", serialisedBHoMData);
            }
            else
            {
                // Our ad-hoc Speckle Serialiser. Essentially the same with all non-needed Reflection things removed. x~100 faster.
                object serialisedRepresentation = Compute.SpeckleAbstract(bhObject);

                // You need to add the object "Serialised" representation as Speckle Viewer wants it,
                // in order for you to have object filtering/grouping/etc in the Viewer.
                speckleObject.Properties.Add(bhObject.GetType().Name, serialisedRepresentation);

                // This is the actual BHoM data.
                object serialisedBHoMData = BH.Engine.Serialiser.Convert.ToJson(bhObject);
                serialisedBHoMData = BH.Engine.Serialiser.Convert.ToZip(serialisedBHoMData as string); // zip the data so speckle doesn't try to process it, altering it.
                speckleObject.Properties.Add("BHoM", serialisedBHoMData);
            }
        }
        // sync method
        public override List <SpeckleObject> convert(IEnumerable <object> objects)
        {
            List <SpeckleObject> convertedObjects = new List <SpeckleObject>();

            foreach (object o in objects)
            {
                var myObj = fromGhRhObject(o, encodeObjectsToNative, encodeObjectsToSpeckle);

                if (nonHashedTypes.Contains((string)myObj.type))
                {
                    convertedObjects.Add(myObj);
                }
                else
                {
                    var isInCache = sent.Contains((string)myObj.hash);

                    if (!isInCache)
                    {
                        convertedObjects.Add(myObj);
                        temporaryCahce.Add(myObj.hash);
                    }
                    else
                    {
                        var temp = new SpeckleObject();
                        temp.hash = myObj.hash;
                        temp.type = myObj.type;
                        convertedObjects.Add(temp);
                    }
                }
            }

            return(convertedObjects);
        }
Esempio n. 6
0
        // FOR TESTING ONLY
        private static bool CheckZippedData(SpeckleObject speckleObject)
        {
            // -------------------------- //
            // For testing only           //
            // -------------------------- //

            // Extract BHoMData from the `BHoMZipped` key.
            // This data is serialised with our own Mongo Serialiser, and zipped to avoid modification from Speckle.

            object BHoMZippedData = null;

            try
            {
                object jsonBHoMDataObj = null;
                speckleObject.Properties.TryGetValue("BHoMZipped", out jsonBHoMDataObj);

                if (jsonBHoMDataObj != null)
                {
                    var jsonBHoMData = BH.Engine.Serialiser.Convert.FromZip(jsonBHoMDataObj.ToString()); //unzip
                    BHoMZippedData = BH.Engine.Serialiser.Convert.FromJson(jsonBHoMData);                //deserialise
                }
            }
            catch { }

            return(BHoMZippedData != null ? true : false);
        }
Esempio n. 7
0
    private bool GwaToCache(string gwaCommand, string streamId, SpeckleObject targetObject)
    {
      //At this point the SID will be filled with the application ID
      GSAProxy.ParseGeneralGwa(gwaCommand, out string keyword, out int? foundIndex, out string foundStreamId, out string foundApplicationId, out string gwaWithoutSet, out GwaSetCommandType? gwaSetCommandType, true);

      var originalSid = GSA.App.Proxy.FormatSidTags(foundStreamId, foundApplicationId);
      var newSid = GSA.App.Proxy.FormatSidTags(streamId, foundApplicationId);

      //If the SID tag has been set then update it with the stream
      if (string.IsNullOrEmpty(originalSid))
      {
        gwaWithoutSet = gwaWithoutSet.Replace(keyword, keyword + ":" + newSid);
      }
      else
      {
        gwaWithoutSet = gwaWithoutSet.Replace(originalSid, newSid);
      }

      //Only cache the object against, the top-level GWA command, not the sub-commands - this is what the SID value comparision is there for
      return GSA.App.LocalCache.Upsert(keyword.Split('.').First(),
        foundIndex.Value,
        gwaWithoutSet,
        foundApplicationId,
        so: (foundApplicationId != null
          && targetObject.ApplicationId != null
          && targetObject.ApplicationId.EqualsWithoutSpaces(foundApplicationId))
            ? targetObject
            : null,
        gwaSetCommandType: gwaSetCommandType ?? GwaSetCommandType.Set,
        streamId: streamId);
    }
Esempio n. 8
0
        protected SpeckleObject ToSpeckle(IBHoMObject bhomObject, SpecklePushConfig config)
        {
            // Assign SpeckleStreamId to the Fragments of the IBHoMObjects
            SetAdapterId(bhomObject, SpeckleClient.Stream.StreamId);

            // SpeckleObject "container". Top level has geometry representation of BHoM Object, so it can be visualised in the SpeckleViewer.
            SpeckleObject speckleObject = SpeckleRepresentation(bhomObject, config.RendermeshOptions);

            // If no Speckle representation is found, it will be sent as an "Abstract" SpeckleObject (no visualisation).
            if (speckleObject == null)
            {
                speckleObject = (SpeckleObject)SpeckleCore.Converter.Serialise(bhomObject);
            }

            // Save BHoMObject data inside the speckleObject.
            Modify.SetBHoMData(speckleObject, bhomObject, config.UseSpeckleSerialiser);

            speckleObject.SetDiffingHash(bhomObject, config);

            // If the BHoMObject has a "RevisionName" string field in the Customdata,
            // use that value to create a Layer for it, and set the SpeckleObject's layer.
            //object revisionValue = null;
            //string revisionName = "";
            //if (bhomObject.CustomData.TryGetValue("RevisionName", out revisionValue))
            //{
            //    revisionName = revisionValue as string;
            //    if (!string.IsNullOrWhiteSpace(revisionName))
            //        speckleObject.Properties["revisionName"] = revisionName;
            //}

            return(speckleObject);
        }
Esempio n. 9
0
        public static void SetDiffingHash(this SpeckleObject speckleObject, IObject sourceObj, SpecklePushConfig config)
        {
            // SETTING THE HASH(ES)
            // SpeckleObjects have 2 hash properties: `Hash` and `GeometryHash`.
            // `Hash` is the "main" one, on which Speckle bases its diffing.
            // Therefore, what we want is that `Hash` should be set based only on the BHoM class properties -
            // not on any Speckle Object property, because we use the SpeckleObject only as a Representational container for our BHoMObject.
            // This way objects from BHoM can be diffed by the Speckle Server the same way we would diff them on the client side.

            // HOWEVER
            // This poses an issue with the fact tha speckle will not update the view in SpeckleViewer if only changes to the object REPRESENTATION are made.
            // E.g. If at some point I change how I want to see the bars, from 'extruded' to 'simple line',
            // then SpeckleViewer will not update the view (bars will stay extruded);
            // only newly pushed bars will be simple lines.

            // This is because Speckle really does not make any use of the `GeometryHash`:
            speckleObject.GeometryHash = speckleObject.Hash; // this is unfortunately useless; Speckle doesn't use it.

            // Set the "main" speckle hash equal to the diffing hash, so Speckle can do the diffing as we expect.
            string diffingHash = BH.Engine.Diffing.Compute.DiffingHash(sourceObj, config.DiffConfig);

            speckleObject.Hash = diffingHash;

            // FOR DEVELOPMENT ONLY:
            if (config.UniqueRandomHash)
            {
                speckleObject.Hash += speckleObject.GeometryHash + System.DateTime.Now.Ticks;
            }
        }
Esempio n. 10
0
 public static void AddCustomStructuralProperty(SpeckleObject obj, string key, object value)
 {
     if (!obj.Properties.ContainsKey("structural"))
     {
         obj.Properties.Add("structural", new Dictionary <string, object>());
     }
     ((Dictionary <string, object>)obj.Properties["structural"]).Add("NativeId", value);
 }
Esempio n. 11
0
        /*
         * private static bool SendableValue(object v)
         * {
         * if (v == null)
         * {
         *  return false;
         * }
         * if (v is int)
         * {
         *  return ((int)v != 0);
         * }
         * else if (v is double)
         * {
         *  return ((double)v != 0);
         * }
         * else if (v is string)
         * {
         *  return (!string.IsNullOrEmpty((string)v) && !((string)v).Equals("null", StringComparison.InvariantCultureIgnoreCase));
         * }
         * return true;
         * }
         */

        //This is necessary because SpeckleCore swallows exceptions thrown within ToNative methods
        public static string ToNativeTryCatch(SpeckleObject so, Func <object> toNativeMethod)
        {
            if (so == null)
            {
                return("");
            }

            var retValue    = "";
            var streamId    = "";
            var speckleType = "";
            var id          = "";
            var url         = "";

            try
            {
                if (so.Properties.ContainsKey("StreamId"))
                {
                    streamId = so.Properties["StreamId"].ToString();
                }
                speckleType = so.Type;
                id          = so._id;
                url         = Initialiser.AppResources.Settings.ObjectUrl(id);
            }
            catch { }

            //In case of error
            var errContext = new List <string>()
            {
                "Receive", "StreamId=" + streamId, "SpeckleType=" + speckleType,
                "ApplicationId=" + (string.IsNullOrEmpty(so.ApplicationId) ? "" : so.ApplicationId),
                "_id=" + id, "Url=" + url
            };

            try
            {
                var methodReturnValue = toNativeMethod();

                if (methodReturnValue is string)
                {
                    retValue = (string)methodReturnValue;
                }
                else if (methodReturnValue is Exception)
                {
                    throw ((Exception)methodReturnValue);
                }
                else
                {
                    throw new Exception("Unexpected type returned by conversion code: " + methodReturnValue.GetType().Name);
                }
            }
            catch (Exception ex)
            {
                //These messages will have more information added to them in the app before they are logged to file
                Initialiser.AppResources.Messenger.Message(MessageIntent.TechnicalLog, MessageLevel.Error, ex, errContext.ToArray());
            }
            return(retValue);
        }
Esempio n. 12
0
        public override void AddSelectionToSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);

            var selectionIds = CurrentDoc.Selection.GetElementIds().Select(id => CurrentDoc.Document.GetElement(id).UniqueId);

            // LOCAL STATE management
            var spkObjectsToAdd = selectionIds.Select(id =>
            {
                var temp = new SpeckleObject();
                temp.Properties["revitUniqueId"] = id;
                temp.Properties["__type"]        = "Sent Object";
                return(temp);
            });

            var myStream = LocalState.FirstOrDefault(st => st.StreamId == (string)client.streamId);
            var added    = 0;

            foreach (var obj in spkObjectsToAdd)
            {
                var ind = myStream.Objects.FindIndex(o => (string)o.Properties["revitUniqueId"] == (string)obj.Properties["revitUniqueId"]);
                if (ind == -1)
                {
                    myStream.Objects.Add(obj);
                    added++;
                }
            }

            var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)client._id);

            myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects));

            // Persist state and clients to revit file
            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Adding Speckle Receiver"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();

            if (added != 0)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = client._id,
                    expired = true,
                    objects = myClient.objects,
                    message = String.Format("You have added {0} objects from this sender.", added)
                }));
            }
            //throw new NotImplementedException();
        }
Esempio n. 13
0
        public SpeckleExtrusion(SpeckleObject profile, double length, bool capped, string applicationId = null, Dictionary <string, object> properties = null)
        {
            this.Profile       = profile;
            this.Length        = length;
            this.Capped        = capped;
            this.ApplicationId = applicationId;
            this.Properties    = properties;

            GenerateHash();
        }
        public SpeckleObject Merge(SpeckleObject src, SpeckleObject dest)
        {
            if (src == dest)
            {
                return(dest);
            }
            var resultingObject = mapper.Map(src, dest);

            return(resultingObject);
        }
Esempio n. 15
0
        public static SpeckleObject ToSpeckle(this Curve curve)
        {
            var properties = curve.UserDictionary.ToSpeckle();

            if (curve is PolyCurve)
            {
                return((( PolyCurve )curve).ToSpeckle());
            }

            if (curve.IsArc())
            {
                Arc        getObj; curve.TryGetArc(out getObj);
                SpeckleArc myObject = getObj.ToSpeckle(); myObject.Properties = properties;
                return(myObject);
            }

            if (curve.IsCircle())
            {
                Circle        getObj; curve.TryGetCircle(out getObj);
                SpeckleCircle myObject = getObj.ToSpeckle(); myObject.Properties = properties;
                return(myObject);
            }

            if (curve.IsEllipse())
            {
                Ellipse        getObj; curve.TryGetEllipse(out getObj);
                SpeckleEllipse myObject = getObj.ToSpeckle(); myObject.Properties = properties;
                return(myObject);
            }

            if (curve.IsLinear() || curve.IsPolyline()) // defaults to polyline
            {
                Polyline      getObj; curve.TryGetPolyline(out getObj);
                SpeckleObject myObject = getObj.ToSpeckle(); myObject.Properties = properties;
                return(myObject);
            }

            Polyline poly;

            curve.ToPolyline(0, 1, 0, 0, 0, 0.1, 0, 0, true).TryGetPolyline(out poly);

            SpeckleCurve myCurve    = new SpeckleCurve((SpecklePolyline)poly.ToSpeckle(), properties: curve.UserDictionary.ToSpeckle());
            NurbsCurve   nurbsCurve = curve.ToNurbsCurve();

            myCurve.Weights  = nurbsCurve.Points.Select(ctp => ctp.Weight).ToList();
            myCurve.Points   = nurbsCurve.Points.Select(ctp => ctp.Location).ToFlatArray().ToList();
            myCurve.Knots    = nurbsCurve.Knots.ToList();
            myCurve.Degree   = nurbsCurve.Degree;
            myCurve.Periodic = nurbsCurve.IsPeriodic;
            myCurve.Rational = nurbsCurve.IsRational;
            myCurve.Domain   = nurbsCurve.Domain.ToSpeckle();

            myCurve.Properties = properties;
            return(myCurve);
        }
Esempio n. 16
0
        SpeckleObject ISpeckleSerializable.ToSpeckle()
        {
            ContainerIFC  container = new ContainerIFC(this);
            SpeckleObject result    = Converter.ToAbstract(container);

            if (this is IfcRoot root)
            {
                result.ApplicationId = root.GlobalId;
            }
            return(result);
        }
Esempio n. 17
0
        public override List <object> Push(IEnumerable <object> objects, string tag = "", PushType pushType = PushType.AdapterDefault, ActionConfig actionConfig = null)
        {
            // Clone objects for immutability in the UI
            List <object> objectsToPush = objects.Select(x => x.DeepClone()).ToList();

            // Initialize the SpeckleStream
            SpeckleClient.Stream.Objects = new List <SpeckleObject>(); // stream is immutable

            // //- Read config
            SpecklePushConfig pushConfig = (actionConfig as SpecklePushConfig) ?? new SpecklePushConfig();

            // //- Use "Speckle" history: produces a new stream at every push that corresponds to the old version. Enabled by default.
            if (pushConfig.EnableHistory)
            {
                SetupHistory();
            }

            // Actual creation and add to the stream
            for (int i = 0; i < objectsToPush.Count(); i++)
            {
                SpeckleObject speckleObject = ToSpeckle(objectsToPush[i] as dynamic, pushConfig); // Dynamic dispatch to most appropriate method

                // Add objects to the stream
                SpeckleClient.Stream.Objects.Add(speckleObject);
            }

            // // - Send the objects
            try
            {
                // Try the batch upload
                BatchUpdateStream(pushConfig);
            }
            catch (Exception e)
            {
                try
                {
                    // If the batch upload fails, try the standard SpeckleCore Update as a last resort.

                    //// - Issue: with `StreamUpdateAsync` Speckle doesn't seem to send anything if the Stream is initially empty.
                    //// - You need to Push twice if the Stream is initially empty.
                    var updateResponse = SpeckleClient.StreamUpdateAsync(SpeckleClient.Stream.StreamId, SpeckleClient.Stream).Result;
                    SpeckleClient.BroadcastMessage("stream", SpeckleClient.Stream.StreamId, new { eventType = "update-global" });
                }
                catch
                {
                    // If all has failed, return the first error.
                    BH.Engine.Reflection.Compute.RecordError($"Upload to Speckle failed. Message returned:\n{e.InnerException.Message}");
                    return(new List <object>());
                }
            }

            return(objectsToPush);
        }
        public static SpeckleObject fromInterval2d(UVInterval i)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value = new ExpandoObject();

            obj.type    = "Interval2d";
            obj.hash    = "NoHash";
            obj.value.u = fromInterval(i.U);
            obj.value.v = fromInterval(i.V);
            return(obj);
        }
        public static SpeckleObject fromInterval(Interval u)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value = new ExpandoObject();

            obj.type      = "Interval";
            obj.hash      = "NoHash";
            obj.value.min = u.Min;
            obj.value.max = u.Max;

            return(obj);
        }
        public static SpeckleObject fromPoint(Point3d o)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value = new ExpandoObject();

            obj.type    = "Point";
            obj.hash    = "NoHash";
            obj.value.x = o.X;
            obj.value.y = o.Y;
            obj.value.z = o.Z;
            return(obj);
        }
Esempio n. 21
0
        private int CompareForOutputFileOrdering(SpeckleObject a, SpeckleObject b)
        {
            var typeCompare = string.Compare(a.Type, b.Type);

            if (typeCompare == 0)
            {
                return(string.Compare(a.ApplicationId, b.ApplicationId));
            }
            else
            {
                return(typeCompare);
            }
        }
Esempio n. 22
0
 public GSACacheRecord(string keyword, int index, string gwa, string streamId = "", string applicationId = "", bool previous = false, bool latest = true, SpeckleObject so = null,
                       GwaSetCommandType gwaSetCommandType = GwaSetCommandType.Set)
 {
     Keyword  = keyword;
     Index    = index;
     Gwa      = gwa;
     Latest   = latest;
     Previous = previous;
     StreamId = streamId;
     //values cannot have spaces
     ApplicationId     = (applicationId == null) ? "" : applicationId.Replace(" ", "");
     SpeckleObj        = so;
     GwaSetCommandType = gwaSetCommandType;
 }
        public static SpeckleObject fromPlane(Plane p)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value = new ExpandoObject();

            obj.type         = "Plane";
            obj.hash         = "Plane." + SpeckleConverter.getHash("RH:" + SpeckleConverter.getBase64(p));
            obj.value.origin = fromPoint(p.Origin);
            obj.value.xdir   = fromVector(p.XAxis);
            obj.value.ydir   = fromVector(p.YAxis);
            obj.value.normal = fromVector(p.Normal);

            return(obj);
        }
Esempio n. 24
0
        //To cope with result objects not having an application Id
        private string SafeApplicationId(SpeckleObject so)
        {
            var appId = "";

            if (so is StructuralResultBase)
            {
                var resultObj = (StructuralResultBase)so;
                appId = (resultObj.TargetRef ?? "") + (resultObj.LoadCaseRef ?? "") + (resultObj.ResultSource ?? "") + (resultObj.Description ?? "");
            }
            else
            {
                appId = so.ApplicationId ?? "";
            }
            return(Helper.RemoveKeywordVersionFromApplicationIds(appId));
        }
Esempio n. 25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string inputType = "";

            if (!DA.GetData("SpeckleObjectType", ref inputType))
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No type specified.");
                return;
            }

            SpeckleObject inputObject = null;

            if (!DA.GetData("SpeckleObject", ref inputObject))
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No input object.");
                return;
            }

            // Try to find type in SpeckleInitializer
            Type objType = SpeckleCore.SpeckleInitializer.GetTypes().FirstOrDefault(t => t.Name == inputType);

            if (objType == null)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not find SpeckleObject of type " + inputType + ".");
                return;
            }

            SpeckleObject convertedObject = (SpeckleObject)Activator.CreateInstance(objType);

            // Check to see if one is a subclass of another
            if (!(inputObject.Type.Contains(convertedObject.Type)) && !(convertedObject.Type.Contains(inputObject.Type)))
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "SpeckleObject not convertible to type.");
                return;
            }

            foreach (PropertyInfo p in convertedObject.GetType().GetProperties().Where(p => p.CanWrite))
            {
                PropertyInfo inputProperty = inputObject.GetType().GetProperty(p.Name);
                if (inputProperty != null)
                {
                    p.SetValue(convertedObject, inputProperty.GetValue(inputObject));
                }
            }

            convertedObject.GenerateHash();
            DA.SetData("Result", convertedObject);
        }
Esempio n. 26
0
        public Structural1DProperty(SpeckleObject profile, Structural1DPropertyShape shape, bool hollow, double thickness, string catalogueName, string materialRef, string applicationId = null, Dictionary <string, object> properties = null)
        {
            this.Profile       = profile;
            this.Shape         = shape;
            this.Hollow        = hollow;
            this.Thickness     = thickness;
            this.CatalogueName = catalogueName;
            this.MaterialRef   = materialRef;
            this.ApplicationId = applicationId;
            if (properties != null)
            {
                this.Properties = properties;
            }

            GenerateHash();
        }
        public static SpeckleObject fromLine(Line o)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value      = new ExpandoObject();
            obj.properties = new ExpandoObject();

            obj.type = "Line";
            obj.hash = "NoHash";

            obj.value.start = fromPoint(o.From);
            obj.value.end   = fromPoint(o.To);

            obj.properties.length = o.Length;
            return(obj);
        }
Esempio n. 28
0
        public override object ToNative(SpeckleObject _object)
        {
            if ((string)_object.Properties[GlobalVar.discriminator] == "BeamBase")
            {
                return(BeamBase.FromSpeckle(((SpeckleBrep)_object)));
            }
            if ((string)_object.Properties[GlobalVar.discriminator] == "DetailedBeam")
            {
                return(DetailedBeam.FromSpeckle(((SpeckleBrep)_object)));
            }
            if ((string)_object.Properties[GlobalVar.discriminator] == "BeamJoint")
            {
                return(BeamJoint.FromSpeckle(((SpecklePoint)_object)));
            }

            // Graceful fail
            using (RhinoConverter rhConv = new RhinoConverter())
                return(rhConv.ToNative(_object));
        }
        public static SpeckleObject fromCircle(Circle circle)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value      = new ExpandoObject();
            obj.properties = new ExpandoObject();

            obj.type = "Circle";
            obj.hash = "Circle." + SpeckleConverter.getHash("RH:" + SpeckleConverter.getBase64(circle));

            obj.value.plane  = fromPlane(circle.Plane);
            obj.value.center = fromPoint(circle.Center);
            obj.value.normal = fromVector(circle.Plane.Normal);
            obj.value.radius = circle.Radius;

            obj.properties.length = circle.Circumference;

            return(obj);
        }
        public static SpeckleObject fromBox(Box box)
        {
            SpeckleObject obj = new SpeckleObject();

            obj.value      = new ExpandoObject();
            obj.properties = new ExpandoObject();

            obj.type              = "Box";
            obj.hash              = "Box." + SpeckleConverter.getHash("RH:" + SpeckleConverter.getBase64(box));
            obj.value.center      = fromPoint(box.Center);
            obj.value.normal      = fromVector(box.Plane.Normal); // use fromVector
            obj.value.plane       = fromPlane(box.Plane);         // to use fromPlane
            obj.value.X           = fromInterval(box.X);
            obj.value.Y           = fromInterval(box.Y);
            obj.value.Z           = fromInterval(box.Z);
            obj.properties.area   = box.Area;
            obj.properties.volume = box.Volume;

            return(obj);
        }