public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var o = JObject.Load(reader);
			var fields = o.Properties().ToDictionary(p => p.Name, p => p.Value.ToObject<object>());
			var inferrer = serializer.GetConnectionSettings().Inferrer;
			var fieldValues = new FieldValues(inferrer, fields);
			return fieldValues;
		}
Beispiel #2
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            ExternalCommandData cdata = commandData;
             Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
             Document doc = commandData.Application.ActiveUIDocument.Document;
             UIDocument uiDoc = commandData.Application.ActiveUIDocument;

             SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);
             if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 1);

             IList<Reference> refList = new List<Reference>();
             refList = uiDoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Face);
                 foreach (Reference reference in refList)
                 {

                         IList<UV> uvPts = new List<UV>();

                         List<double> doubleList = new List<double>();
                         IList<ValueAtPoint> valList = new List<ValueAtPoint>();
                         Face face = doc.GetElement(reference).GetGeometryObjectFromReference(reference)as Face;
                         BoundingBoxUV bb = face.GetBoundingBox();
                         UV min = bb.Min;
                         UV max = bb.Max;

                         for (double u = min.U; u < max.U; u += (max.U - min.U) / 10)
                         {
                             for (double v = min.V; v < max.V; v += (max.V - min.V) / 10)
                             {
                                 UV uv = new UV(u, v);
                                 if (face.IsInside(uv))
                                 {
                                     uvPts.Add(uv);
                                     doubleList.Add(v + DateTime.Now.Second);
                                     valList.Add(new ValueAtPoint(doubleList));
                                     doubleList.Clear();
                                 }
                             }
                         }

                         FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                         FieldValues vals = new FieldValues(valList);
                         int idx = sfm.AddSpatialFieldPrimitive(reference);
                         AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
                         sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, sfm.RegisterResult(resultSchema));
                 }

             return Result.Succeeded;
        }
        /// <summary>
        /// Set the spatial field values for the current spatial field primitive.  The two 
        /// input sequences should be of the same length.
        /// </summary>
        /// <param name="sampleLocations"></param>
        /// <param name="samples"></param>
        private void InternalSetSpatialFieldValues(IEnumerable<XYZ> sampleLocations, IEnumerable<XYZ> samples)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // Convert the analysis values to a special Revit type
            var valList = samples.Select(n => new VectorAtPoint(new List<XYZ> { n })).ToList();
            var sampleValues = new FieldValues(valList);

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByXYZ(sampleLocations.ToList<XYZ>());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex();

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(SpatialFieldPrimitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #4
0
        public static void UpdateCO2eVisualization(SpatialFieldManager sfm, Element element)
        {
            try
            {
                logger.InfoFormat("Adding CO2e Analysis for element: {0}", element.Name);
                double CO2eForElement = 0;
                if (element.ParametersMap.Contains("CO2e"))
                {
                    CO2eForElement = element.ParametersMap.get_Item("CO2e").AsDouble();
                }

                int count = 0;
                foreach (Face face in GetFaces(element))
                {
                    var idx = sfm.AddSpatialFieldPrimitive(face.Reference);

                    IList<UV> uvPts = new List<UV>();
                    IList<ValueAtPoint> valList = new List<ValueAtPoint>();
                    var bb = face.GetBoundingBox();
                    AddMeasurement(CO2eForElement, bb.Min.U, bb.Min.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Min.U, bb.Max.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Max.U, bb.Max.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Max.U, bb.Min.V, uvPts, valList);

                    logger.DebugFormat("elementId: {0}, face: {1}, spf idx: {2}, bounding box: {3},{4},{5},{6}", element.Id.IntegerValue, count, idx, bb.Min.U, bb.Min.V, bb.Max.U, bb.Max.V);

                    var pnts = new FieldDomainPointsByUV(uvPts);
                    var vals = new FieldValues(valList);

                    var resultSchema1 = new AnalysisResultSchema("CO2e schema", "AMEE CO2e schema");

                    sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, GetFirstRegisteredResult(sfm, resultSchema1));
                    count++;
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
Beispiel #5
0
        public string UpdateCarInfo(ArrayList arr)
        {
            ISqlMapper NewMap = SqlMapper.Instance();

            NewMap.BeginTransaction();
            try
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    Type typeName = arr[i].GetType();
                    switch (typeName.FullName)
                    {
                    case "GModel.Car.CarInfo":
                        ExecuteUpdateTrans("CarInfo.UpdateCarInfo", (CarInfo)arr[i], NewMap);
                        break;

                    case "GModel.Car.FieldValues":
                        if (((FieldValues)arr[i]).FieldId.Trim() != "")
                        {
                            ExecuteUpdateTrans("FieldValues.UpdateFieldValues", (FieldValues)arr[i], NewMap);
                        }
                        else
                        {
                            FieldValues fv = (FieldValues)arr[i];
                            fv.FieldId = System.Guid.NewGuid().ToString();
                            ExecuteInsertTrans("FieldValues.InsertFieldValues", fv, NewMap);
                        }
                        break;
                    }
                }
                NewMap.CommitTransaction();
                return("true");
            }
            catch (Exception e)
            {
                NewMap.RollBackTransaction();
                return("false");
            }
        }
Beispiel #6
0
        public void AddRecords()
        {
            FileDb _db = new FileDb();
            _db.Open(DBFILE, false);
            var record = new FieldValues();
            record.Add("FirstName", "Nancy");
            record.Add("LastName", "Davolio");
            record.Add("BirthDate", new DateTime(1968, 12, 8));
            record.Add("IsCitizen", true);
            record.Add("DoubleField", 1.23);
            record.Add("ByteField", 1);
            record.Add("StringArrayField", new string[] { "s1", "s2", "s3" });
            record.Add("ByteArrayField", new Byte[] { 1, 2, 3, 4 });
            record.Add("IntArrayField", new int[] { 100, 200, 300, 400 });
            record.Add("DoubleArrayField", new double[] { 1.2, 2.4, 3.6, 4.8 });
            record.Add("DateTimeArrayField", new DateTime[]
                { DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now });
            record.Add("BoolArrayField", new bool[] { true, false, true, false });
            _db.AddRecord(record);
            _db.Dispose();

        }
        /// <summary>
        /// Change default import settigns
        /// </summary>
        /// <param name="importSettings"></param>
        private void AdaptImportSettigns(ImportSettings importSettings)
        {
            importSettings.CheckMatchingSublanguages = true;
            importSettings.ExistingTUsUpdateMode     = TUUpdateMode.Overwrite;
            //set behavior of existing field values during import
            importSettings.ExistingFieldsUpdateMode = ImportSettings.FieldUpdateMode.Merge;
            //set behavior of new fields during import
            importSettings.NewFields = ImportSettings.NewFieldsOption.AddToSetup;
            //create a field (now using field already existing in the TM setup)
            //set the field value object
            MultipleStringFieldValue cruVal = new MultipleStringFieldValue("Sample text field");

            //add new value (this time we use multiple string field value
            cruVal.Add("Added during import");
            //create field values object
            FieldValues fields = new FieldValues();

            //add the field value
            fields.Add(cruVal);
            //set the field values to the import settigns
            importSettings.ProjectSettings = fields;
        }
        private void BtnUpdateMatchingRecords_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string filter = "(~FirstName = 'andrew' OR ~FirstName = 'nancy') AND ~LastName = 'fuller'";
                FilterExpressionGroup filterExpGrp = FilterExpressionGroup.Parse(filter);
                Table table = _db.SelectRecords(filterExpGrp);
                displayRecords(table);

                // equivalent building it manually
                var fname1Exp = new FilterExpression("FirstName", "andrew", EqualityEnum.Equal, MatchTypeEnum.IgnoreCase);
                // the following two lines produce the same FilterExpression
                var fname2Exp = FilterExpression.Parse("~FirstName = nancy");
                fname2Exp = new FilterExpression("FirstName", "nancy", EqualityEnum.Equal, MatchTypeEnum.IgnoreCase);
                var lnameExp = new FilterExpression("LastName", "fuller", EqualityEnum.Equal, MatchTypeEnum.IgnoreCase);

                var fnamesGrp = new FilterExpressionGroup();
                fnamesGrp.Add(BoolOpEnum.Or, fname1Exp);
                fnamesGrp.Add(BoolOpEnum.Or, fname2Exp);
                var allNamesGrp = new FilterExpressionGroup();
                allNamesGrp.Add(BoolOpEnum.And, lnameExp);
                allNamesGrp.Add(BoolOpEnum.And, fnamesGrp);

                var fieldValues = new FieldValues();
                fieldValues.Add("IsCitizen", false);
                int nRecs = _db.UpdateRecords(allNamesGrp, fieldValues);

                table = _db.SelectRecords(allNamesGrp);
                displayRecords(table);

                // or easiest of all use the filter string directly
                table = _db.SelectRecords(filter);
                displayRecords(table);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Set the spatial field values for the current spatial field primitive.  The two
        /// input sequences should be of the same length.
        /// </summary>
        /// <param name="sampleLocations"></param>
        /// <param name="samples"></param>
        private void InternalSetSpatialFieldValues(int primitiveId, VectorAnalysisData data, string schemaName, string description, Type unitType)
        {
            var values = data.Results.Values;

            var height = values.First().Count();
            var width  = values.Count();

            // Transpose and convert the analysis values to a special Revit type
            var valList = new List <VectorAtPoint>();

            for (int i = 0; i < height; i++)
            {
                var lst = new List <XYZ>()
                {
                };

                for (int j = 0; j < width; j++)
                {
                    lst.Add(values.ElementAt(j).ElementAt(i).ToXyz());
                }
                valList.Add(new VectorAtPoint(lst));
            }

            TransactionManager.Instance.EnsureInTransaction(Document);

            var sampleValues = new FieldValues(valList);

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByXYZ(data.CalculationLocations.Select(p => p.ToXyz()).ToList());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex(schemaName, description, unitType);

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #10
0
        /// <summary>
        /// Convert fields according to the storage attribute. For newly created field assign default value to that field.
        /// </summary>
        /// <param name="sourceDataSourceDefinition"></param>
        /// <param name="destinationDataSourceDefinition"></param>
        /// <param name="sourceValues"></param>
        /// <param name="destinationValues"></param>
        private void ConvertFields(DataSourceDefinition sourceDataSourceDefinition, DataSourceDefinition destinationDataSourceDefinition,
                                   FieldValues sourceValues, FieldValues destinationValues)
        {
            FieldsMap  fieldsMap   = new FieldsMap(sourceDataSourceDefinition.Fields, destinationDataSourceDefinition.Fields);
            DBField    sourceField = null;
            FieldValue sourceValue = null;

            for (int destinationFieldIndex = 0; destinationFieldIndex < destinationDataSourceDefinition.Fields.Count; destinationFieldIndex++)
            {
                int sourceFieldIndex = fieldsMap.GetSourceFieldIndex(destinationFieldIndex);

                DBField    destinationField = destinationDataSourceDefinition.Fields[destinationFieldIndex];
                FieldValue destinationValue = destinationValues[destinationFieldIndex];

                // If source field exists and source and destination types are comapatible then convert field values.
                // Else assign default value to destination field.
                if (sourceFieldIndex != -1)
                {
                    sourceField = sourceDataSourceDefinition.Fields[sourceFieldIndex];
                    sourceValue = sourceValues[sourceFieldIndex];

                    if (StorageAttributeCheck.IsTypeCompatibile((StorageAttribute)sourceField.Attr, (StorageAttribute)destinationField.Attr))
                    {
                        ConvertFieldValue(sourceField, destinationField, sourceValue, destinationValue);
                    }
                    else
                    {
                        destinationValue.Value  = destinationField.DefaultValue;
                        destinationValue.IsNull = destinationField.DefaultNull;
                    }
                }
                else
                {
                    destinationValue.Value  = destinationField.DefaultValue;
                    destinationValue.IsNull = destinationField.DefaultNull;
                }
            }
        }
Beispiel #11
0
        public void AddRecords()
        {
            FileDb _db = new FileDb();

            _db.Open(DBFILE, false);
            var record = new FieldValues();

            record.Add("FirstName", "Nancy");
            record.Add("LastName", "Davolio");
            record.Add("BirthDate", new DateTime(1968, 12, 8));
            record.Add("IsCitizen", true);
            record.Add("DoubleField", 1.23);
            record.Add("ByteField", 1);
            record.Add("StringArrayField", new string[] { "s1", "s2", "s3" });
            record.Add("ByteArrayField", new Byte[] { 1, 2, 3, 4 });
            record.Add("IntArrayField", new int[] { 100, 200, 300, 400 });
            record.Add("DoubleArrayField", new double[] { 1.2, 2.4, 3.6, 4.8 });
            record.Add("DateTimeArrayField", new DateTime[]
                       { DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now });
            record.Add("BoolArrayField", new bool[] { true, false, true, false });
            _db.AddRecord(record);
            _db.Dispose();
        }
Beispiel #12
0
        private void AddOrUpdateRecord(string key, byte[] buffer, DateTime expiration)
        {
            var fieldValues = new FieldValues(3);

            fieldValues.Add(valueField, buffer ?? new byte[0]);
            fieldValues.Add(expiresField, expiration);

            try
            {
                if (fileDb.GetRecordByKey(key, new string[0], false) != null)
                {
                    fileDb.UpdateRecordByKey(key, fieldValues);
                }
                else
                {
                    fieldValues.Add(keyField, key);
                    fileDb.AddRecord(fieldValues);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"FileDbCache.AddOrUpdateRecord({key}): {ex.Message}");
            }
        }
Beispiel #13
0
        public XElement ToXml()
        {
            var operatorNode =
                new XElement(QueryFilter?.ToString() ?? string.Empty,
                             // attributes
                             FilterAttributes.Select(a => new XAttribute(a.Key, a.Value ?? string.Empty)),
                             // chieldNodes
                             new XElement("FieldRef",
                             // attributes
                                          new XAttribute("Name", FieldInternalName),
                                          FieldRefAttributes.Select(a => new XAttribute(a.Key, a.Value ?? string.Empty))
                                          ),
                             new XElement("Values",
                                          FieldValues
                                          .Where(value => !string.IsNullOrEmpty(value))
                                          .Select(value => new XElement("Value",
                                                                        new XAttribute("Type", FieldType),
                                                                        value
                                                                        ))
                                          )
                             );

            return(operatorNode);
        }
Beispiel #14
0
 public int ApplyFieldsToTranslationUnits(FieldValues values, bool overwrite, PersistentObjectToken[] translationUnitIds)
 {
     return(_tmlanguageDirection.ApplyFieldsToTranslationUnits(values, overwrite, translationUnitIds));
 }
Beispiel #15
0
        private void AddOrUpdateRecord(string key, object value, DateTime expires)
        {
            var fieldValues = new FieldValues(3); // capacity
            fieldValues.Add(valueField, value);
            fieldValues.Add(expiresField, expires);

            if (fileDb.GetRecordByKey(key, new string[0], false) == null)
            {
                fieldValues.Add(keyField, key);
                fileDb.AddRecord(fieldValues);
            }
            else
            {
                fileDb.UpdateRecordByKey(key, fieldValues);
            }
        }
Beispiel #16
0
        public bool AnalysisByElements()
        {
            bool result = false;

            try
            {
                if (areaDictionary.Count > 0)
                {
                    int  resultIndex = FindIndexOfResult(sfm);
                    bool firstLoop   = true;
                    foreach (int areaId in areaDictionary.Keys)
                    {
                        AreaProperties ap      = areaDictionary[areaId];
                        List <double>  dblList = new List <double>(); //double values to be displayed on the face.
                        Face           face    = ap.BaseFace;
                        dblList.Add(ap.FAR);

                        if (dblList.Count != sfm.NumberOfMeasurements)
                        {
                            continue;
                        }

                        int                  index   = sfm.AddSpatialFieldPrimitive(face, Transform.Identity);
                        IList <UV>           uvPts   = new List <UV>();
                        IList <ValueAtPoint> valList = new List <ValueAtPoint>();
                        BoundingBoxUV        bb      = face.GetBoundingBox();
                        UV faceCenter = (bb.Min + bb.Max) / 2; //only collect a center point.

                        uvPts.Add(faceCenter);
                        valList.Add(new ValueAtPoint(dblList));
                        //dblList.Clear();

                        FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPts);
                        FieldValues           values       = new FieldValues(valList);

                        AnalysisResultSchema resultSchema = new AnalysisResultSchema(settings.LegendTitle, settings.LegendDescription);
                        resultSchema.SetUnits(unitNames, multipliers);
                        if (unitNames.Contains(settings.Units))
                        {
                            resultSchema.CurrentUnits = unitNames.IndexOf(settings.Units);
                        }

                        if (overwriteResult)
                        {
                            sfm.SetResultSchema(resultIndex, resultSchema);
                        }
                        else if (firstLoop)
                        {
                            resultIndex = sfm.RegisterResult(resultSchema); firstLoop = false;
                        }
                        else
                        {
                            sfm.SetResultSchema(resultIndex, resultSchema);
                        }

                        sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
                    }
                    SetCurrentStyle();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to visulaize the FAR data. \n" + ex.Message, "FARCalculator : AnalysisByElements", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(result);
        }
 public FieldValue GetFieldValue(int fieldId)
 => FieldValues.SingleOrDefault(fv => fv.FieldId == fieldId);
        private static List <int> DomainCondition(string condition,
                                                  IDictionary <string, FieldValues> fieldNames,
                                                  out FieldValues fieldValues)
        {
            fieldValues = null;

            IList <string> terms  = Parse(condition);
            int            nTerms = terms.Count;

            string field;
            bool   isNull;
            int    iStart;

            if (terms[0].Equals("IsNull", StringComparison.InvariantCultureIgnoreCase))
            {
                if (!(nTerms > 7))
                {
                    return(null);
                }

                if (!Equals(terms[1], "("))
                {
                    return(null);
                }

                if (!Equals(terms[3], ","))
                {
                    return(null);
                }

                if (!Equals(terms[5], ")"))
                {
                    return(null);
                }

                field  = terms[2];
                isNull = true;

                iStart = 6;
            }
            else
            {
                field  = terms[0];
                isNull = false;

                iStart = 1;
            }

            field = field.ToUpper();

            if (fieldNames.TryGetValue(field.ToUpper(), out fieldValues) == false)
            {
                return(null);
            }

            var codes = new List <int>();

            if (terms[iStart] == "=")
            {
                if (iStart != nTerms - 2)
                {
                    return(null);
                }

                string subCode = isNull == false
                                                         ? terms[nTerms - 1].Trim('\'')
                                                         : _nullValue;

                int idx = fieldValues.IndexOfCodeValueString(subCode);

                codes.Add(idx);
            }
            else if (terms[iStart].Equals("in", StringComparison.InvariantCultureIgnoreCase))
            {
                if (!Equals(terms[iStart + 1], "("))
                {
                    return(null);
                }

                if (!Equals(terms[nTerms - 1], ")"))
                {
                    return(null);
                }

                for (int iTerm = iStart + 2; iTerm < nTerms - 1; iTerm += 2)
                {
                    if (!(iTerm == nTerms - 2 || terms[iTerm + 1] == ","))
                    {
                        return(null);
                    }

                    string subCode = terms[iTerm].Trim('\'');
                    int    idx     = fieldValues.IndexOfCodeValueString(subCode);
                    codes.Add(idx);
                }

                if (isNull)
                {
                    int idx = fieldValues.IndexOfCodeValueString(_nullValue);
                    codes.Add(idx);
                }
            }
            else
            {
                return(null);
            }

            return(codes);
        }
Beispiel #19
0
        public DataRow GetDataRowByKeys(FieldValues FVS)
        {
            if (_viewname != "")
            {
                string condition = " (1=1) ";
                for (int i = 0; i < FVS.Count; i++)
                {
                    string values = "";
                    FVOperater o = FVS[i].FVOperater;
                    switch (o)
                    {

                        case FVOperater.Great:
                            values = " > '" + FVS[i].Value + "' ";
                            break;
                        case FVOperater.Less:
                            values = " < '" + FVS[i].Value + "' ";
                            break;
                        case FVOperater.LikeB:
                            values = " Like '%" + FVS[i].Value + "' ";
                            break;
                        case FVOperater.LikeBE:
                            values = " Like '%" + FVS[i].Value + "%' ";
                            break;
                        case FVOperater.LikeE:
                            values = " Like '" + FVS[i].Value + "%' ";
                            break;
                        case FVOperater.NotGreat:
                            values = " <= '" + FVS[i].Value + "' ";
                            break;
                        case FVOperater.NotLess:
                            values = " >= '" + FVS[i].Value + "' ";
                            break;
                        case FVOperater.In:
                            values = " in (" + FVS[i].Value + ") ";
                            break;
                        case FVOperater.NotIn:
                            values = " not in (" + FVS[i].Value + ") ";
                            break;
                        case FVOperater.NotEqual:
                            values = " <> '" + FVS[i].Value + "' ";
                            break;
                        case FVOperater.Order:
                            break;
                        default:
                            values = " = '" + FVS[i].Value + "' ";
                            break;
                    }
                    condition = condition + _conditionOperater + FVS[i].FieldName + values;
                }
                string order = "";
                ArrayList orderlist = new ArrayList();
                ArrayList ordermethod = new ArrayList();
                for (int i = 0; i < FVS.Count; i++)
                {
                    if ((FVS[i].Ordered == true) & (orderlist.IndexOf(FVS[i].FieldName) == -1))
                        orderlist.Add(FVS[i].FieldName);
                    if (FVS[i].orderMethod == OrderMenthod.ASC)
                        ordermethod.Add(" ASC ");
                    else
                        ordermethod.Add(" DESC ");
                }
                for (int i = 0; i < orderlist.Count; i++)
                {
                    order = order + orderlist[i].ToString() + ordermethod[i].ToString() + ",";
                }
                if (order != "")
                {
                    order = " Order By " + order;
                    order = order.Substring(0, order.Length - 1);
                }
                SqlDataAdapter adapter = new SqlDataAdapter("select " + _columnNames + " from " + _viewname + " where " + condition + order, conn);
                adapter.SelectCommand.CommandTimeout = 0;
                DataSet ds = new DataSet(_viewname);
                adapter.Fill(ds, _viewname);
                if (ds.Tables[0].Rows.Count > 0)
                    return ds.Tables[0].Rows[0];
                else
                    return null;
            }
            else
                return null;
        }
Beispiel #20
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            this.ClearPreviousResults();

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(q => (double)((Value.Number)q).Item);

            var curve = (Curve)((Value.Container)args[1]).Item;
            SpatialFieldManager = (Autodesk.Revit.DB.Analysis.SpatialFieldManager)((Value.Container)args[2]).Item;

            if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList<int> arses = SpatialFieldManager.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = SpatialFieldManager.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

            var create = dynRevitSettings.Doc.Application.Application.Create;

            Transform t = curve.ComputeDerivatives(0, true);

            XYZ x = t.BasisX.Normalize();
            XYZ y = t.BasisX.IsAlmostEqualTo(XYZ.BasisZ) ?
                t.BasisX.CrossProduct(XYZ.BasisY).Normalize() :
                t.BasisX.CrossProduct(XYZ.BasisZ).Normalize();
            XYZ z = x.CrossProduct(y);

            Autodesk.Revit.DB.Ellipse arc1 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y,z,-Math.PI, 0);
            Autodesk.Revit.DB.Ellipse arc2 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, 0, Math.PI);

            var pathLoop = new Autodesk.Revit.DB.CurveLoop();
            pathLoop.Append(curve);
            var profileLoop = new Autodesk.Revit.DB.CurveLoop();
            profileLoop.Append(arc1);
            profileLoop.Append(arc2);

            double curveDomain = curve.get_EndParameter(1) - curve.get_EndParameter(0);

            int idx = -1;
            var s = GeometryCreationUtilities.CreateSweptGeometry(pathLoop, 0, 0, new List<Autodesk.Revit.DB.CurveLoop>{profileLoop});
            foreach (Face face in s.Faces)
            {
                //divide the V domain by the number of incoming
                BoundingBoxUV domain = face.GetBoundingBox();
                double vSpan = domain.Max.V - domain.Min.V;

                //analysis values
                idx = SpatialFieldManager.AddSpatialFieldPrimitive(face, trf);

                //a list to hold the analysis points
                IList<UV> uvPts = new List<UV>();

                //a list to hold the analysis values
                IList<ValueAtPoint> valList = new List<ValueAtPoint>();

                //int count = nvals.Count();

                //this is creating a lot of sample points, but if we used less
                //sampling points, AVF would draw the two surfaces as if there was a hard
                //edge between them. this provides a better blend.
                int count = 10;
                for (int i = 0; i < count; i ++)
                {
                    //get a UV point on the face
                    //find its XYZ location and project to
                    //the underlying curve. find the value which corresponds
                    //to the location on the curve
                    var uv = new UV(domain.Min.U, domain.Min.V + vSpan / count*(double) i);
                    var uv1 = new UV(domain.Max.U, domain.Min.V + vSpan / count * (double)i);
                    uvPts.Add(uv);
                    uvPts.Add(uv1);

                    XYZ facePt = face.Evaluate(uv);
                    IntersectionResult ir = curve.Project(facePt);
                    double curveParam = curve.ComputeNormalizedParameter(ir.Parameter);

                    if (curveParam < 0)
                        curveParam = 0;

                    if (curveParam > 1)
                        curveParam = 1;

                    var valueIndex = (int)Math.Floor(curveParam * (double)nvals.Count());
                    if (valueIndex >= nvals.Count())
                        valueIndex = nvals.Count() - 1;

                    //create list of values at this point - currently supporting only one
                    //var doubleList = new List<double> { nvals.ElementAt(i) };
                    var doubleList = new List<double> { nvals.ElementAt(valueIndex) };

                    //add value at point object containing the value list
                    valList.Add(new ValueAtPoint(doubleList));
                    valList.Add(new ValueAtPoint(doubleList));
                }

                var pnts = new FieldDomainPointsByUV(uvPts);
                var vals = new FieldValues(valList);

                SpatialFieldManager.UpdateSpatialFieldPrimitive(
                    idx, pnts, vals, schemaId);

                PastResultIds.Add(idx);
            }

            return Value.NewNumber(idx);
        }
Beispiel #21
0
        public void RenameKey( ConfigDbKey key, string keyName, string newKeyName )
        {
            checkDbOpen();

            if( key == ConfigDbKey.CurrentUser )
                key = OpenKey( key, String.Empty, true );
            
            if( keyName != null )
                keyName = keyName.Trim();

            if( newKeyName != null )
                newKeyName = newKeyName.Trim();

            if( string.IsNullOrEmpty( keyName ) || string.IsNullOrEmpty( newKeyName ) )
                throw new Exception( ErrKeysCannotBeEmpty );

            String filter = String.Format( "ID = {0}", (int) key );

            FieldValues fieldValues = new FieldValues( 1 );
            fieldValues.Add( StrName, newKeyName );
            int numUpdated = _db.UpdateRecords( FilterExpressionGroup.Parse( filter ), fieldValues );
        }
Beispiel #22
0
        public void RenameValue( ConfigDbKey key, string valueName, string newValueName )
        {
            checkDbOpen();

            if( key == ConfigDbKey.CurrentUser || key == ConfigDbKey.LocalMachine )
                throw new Exception( ErrCantHaveValues );

            if( valueName != null )
                valueName = valueName.Trim();

            if( newValueName != null )
                newValueName = newValueName.Trim();

            if( string.IsNullOrEmpty( valueName ) || string.IsNullOrEmpty( newValueName ) )
                throw new Exception( "Cannot rename default Value" );

            if( string.IsNullOrEmpty( newValueName ) )
                throw new Exception( "New Value name cannot be null or empty" );

            String filter = String.Format( "ParentID = {0} AND Type = {1} AND Name = '{2}'",
                                (int) key, (int) KeyValueType.Value, valueName );

            FieldValues fieldValues = new FieldValues( 1 );
            fieldValues.Add( StrName, newValueName );
            int numUpdated = _db.UpdateRecords( FilterExpressionGroup.Parse( filter ), fieldValues );
        }
Beispiel #23
0
        public void Execute(UpdaterData data)
        {
            Document doc = data.GetDocument();
             Autodesk.Revit.ApplicationServices.Application app = doc.Application;

             View view = doc.get_Element(viewID) as View;
             FamilyInstance sphere = doc.get_Element(sphereID) as FamilyInstance;
             LocationPoint sphereLP = sphere.Location as LocationPoint;
             XYZ sphereXYZ = sphereLP.Point;

             SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);
             if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point
             sfm.Clear();

             FilteredElementCollector collector = new FilteredElementCollector(doc,view.Id);
             ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
             ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass);
             LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter);
             ICollection<Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

             foreach (Face face in GetFaces(elements))
             {
            int idx = sfm.AddSpatialFieldPrimitive(face.Reference);
            List<double> doubleList = new List<double>();
            IList<UV> uvPts = new List<UV>();
            IList<ValueAtPoint> valList = new List<ValueAtPoint>();
            BoundingBoxUV bb = face.GetBoundingBox();
            for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15)
            {
               for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15)
               {
                  UV uvPnt = new UV(u, v);
                  uvPts.Add(uvPnt);
                  XYZ faceXYZ = face.Evaluate(uvPnt);
                   // Specify three values for each point
                  doubleList.Add(faceXYZ.DistanceTo(sphereXYZ));
                  doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ));
                  doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10);
                  valList.Add(new ValueAtPoint(doubleList));
                  doubleList.Clear();
               }
            }
            FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
            FieldValues vals = new FieldValues(valList);

            AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
            IList<int> registeredResults = new List<int>();
            registeredResults = sfm.GetRegisteredResults();
            int idx1 = 0;
            if (registeredResults.Count == 0)
            {
                idx1 = sfm.RegisterResult(resultSchema1);
            }
            else
            {
                idx1 = registeredResults.First();
            }
            sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1);
             }
        }
Beispiel #24
0
 public void Reparent( ConfigDbKey key, ConfigDbKey parentKey )
 {
     String filter = String.Format( "ID = {0}", (int) key );
     FieldValues fieldValues = new FieldValues( 1 );
     fieldValues.Add( StrParentID, (int) parentKey );
     int numUpdated = _db.UpdateRecords( FilterExpressionGroup.Parse( filter ), fieldValues );
 }
Beispiel #25
0
        /// <summary>
        /// Set the spatial field values for the current spatial field primitive.  The two 
        /// input sequences should be of the same length.
        /// </summary>
        /// <param name="pointLocations"></param>
        /// <param name="values"></param>
        private void InternalSetSpatialFieldValues(IEnumerable<XYZ> pointLocations, IEnumerable<double> values)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            var chunkSize = 1000;
            while (pointLocations.Any()) 
            {
                // Convert the analysis values to a special Revit type
                var pointLocationChunk = pointLocations.Take(chunkSize).ToList<XYZ>();
                var valuesChunk = values.Take(chunkSize).ToList();
                var valList = valuesChunk.Select(n => new ValueAtPoint(new List<double> { n })).ToList();

                // Convert the sample points to a special Revit Type
                var samplePts = new FieldDomainPointsByXYZ(pointLocationChunk.ToList<XYZ>());
                var sampleValues = new FieldValues(valList);

                // Get the analysis results schema
                var schemaIndex = GetAnalysisResultSchemaIndex();

                // Update the values
                var primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive();
                primitiveIds.Add(primitiveId);
                SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

                pointLocations = pointLocations.Skip(chunkSize);
                values = values.Skip(chunkSize);
            }

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #26
0
        private void BtnAddRecords_Click( object sender, RoutedEventArgs e )
        {
            try
            {
#if true
                Stream s = this.GetType().Assembly.GetManifestResourceStream( this.GetType(), "data.xml" );
                string xml;
                using( StreamReader reader = new StreamReader( s ) )
                {
                    xml = reader.ReadToEnd();
                }

                XDocument xmlDoc = XDocument.Parse(xml);

                // find the columns
                var rows = xmlDoc.Descendants( "row" );
                char[] toks = "|".ToCharArray();
                
                foreach( var row in rows )
                {
                    var columns = from col in row.Descendants( "col" )
                                  select new
                                  {
                                      value = col.Value
                                  };

                    var record = new FieldValues( 20 );
                    int idx = 0;

                    foreach( var col in columns )
                    {
                        string value = (string) col.value;
                        Field field = _db.Fields[idx];

                        if( !string.IsNullOrEmpty( value ) )
                        {
                            if( field.DataType == DataTypeEnum.Bool )
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<bool>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( bool.Parse( val ) );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    bool bval;
                                    if( bool.TryParse( value, out bval ) )
                                        record.Add( field.Name, bval );
                                }
                            }
                            else if( field.DataType == DataTypeEnum.Byte )
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<Byte>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( Byte.Parse( val ) );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    Byte bval;
                                    if( Byte.TryParse( value, out bval ) )
                                        record.Add( field.Name, bval );
                                }
                            }
                            else if( field.DataType == DataTypeEnum.Int )
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<Int32>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( Int32.Parse( val ) );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    Int32 ival;
                                    if( Int32.TryParse( value, out ival ) )
                                        record.Add( field.Name, ival );
                                }
                            }
                            else if( field.DataType == DataTypeEnum.UInt )
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<UInt32>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( UInt32.Parse( val ) );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    UInt32 ival;
                                    if( UInt32.TryParse( value, out ival ) )
                                        record.Add( field.Name, ival );
                                }
                            }
                            else if( field.DataType == DataTypeEnum.Float )
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<float>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( float.Parse( val ) );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    float dval;
                                    if( float.TryParse( value, out dval ) )
                                        record.Add( field.Name, dval );
                                }
                            }
                            else if( field.DataType == DataTypeEnum.Double )
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<double>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( double.Parse( val ) );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    double dval;
                                    if( double.TryParse( value, out dval ) )
                                        record.Add( field.Name, dval );
                                }
                            }
                            else // DateTime or String - DateTime is convertable to string in FileDb
                            {
                                if( field.IsArray )
                                {
                                    var list = new List<string>( 10 );
                                    string[] vals = value.Split( toks );
                                    foreach( string val in vals )
                                    {
                                        list.Add( val );
                                    }
                                    record.Add( field.Name, list.ToArray() );
                                }
                                else
                                {
                                    record.Add( field.Name, value );
                                }
                            }
                        }

                        idx++;
                    }

                    _db.AddRecord( record );
                }
#else                           
                var record = new FieldValues(20);
                record.Add( "FirstName", "Nancy" );
                record.Add( "LastName", "Davolio" );
                record.Add( "BirthDate", new DateTime( 1968, 12, 8 ) );
                record.Add( "IsCitizen", true );
                record.Add( "Float", 1.23 );
                record.Add( "Byte", 1 );
                record.Add( "StringArray", new string[] { "s1", "s2", "s3" } );
                record.Add( "ByteArray", new Byte[] { 1, 2, 3, 4 } );
                record.Add( "IntArray", new int[] { 100, 200, 300, 400 } );
                record.Add( "FloatArray", new double[] { 1.2, 2.4, 3.6, 4.8 } );
                record.Add( "DateTimeArray", new DateTime[] { DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now } );
                record.Add( "BoolArray", new bool[] { true, false, true, false } );
                _db.AddRecord( record );

                record = new FieldValues();
                record.Add( "FirstName", "Andrew" );
                record.Add( "LastName", "Fuller" );
                record.Add( "BirthDate", new DateTime( 1962, 1, 12 ) );
                record.Add( "IsCitizen", true );
                record.Add( "Float", 2.567 );
                record.Add( "Byte", 2 );
                _db.AddRecord( record );

                record = new FieldValues();
                record.Add( "FirstName", "Janet" );
                record.Add( "LastName", "Leverling" );
                record.Add( "BirthDate", new DateTime( 1963, 8, 30 ) );
                record.Add( "IsCitizen", false );
                record.Add( "Float", 3.14 );
                record.Add( "Byte", 3 );
                _db.AddRecord( record );

                record = new FieldValues();
                record.Add( "FirstName", "Margaret" );
                record.Add( "LastName", "Peacock" );
                record.Add( "BirthDate", new DateTime( 1957, 9, 19 ) );
                record.Add( "IsCitizen", false );
                record.Add( "Float", 4.96 );
                record.Add( "Byte", 4 );
                _db.AddRecord( record );

                record = new FieldValues();
                record.Add( "FirstName", "Steven" );
                record.Add( "LastName", "Buchanan" );
                record.Add( "BirthDate", new DateTime( 1965, 3, 4 ) );
                record.Add( "IsCitizen", true );
                record.Add( "Float", 5.7 );
                record.Add( "Byte", 5 );
                _db.AddRecord( record );
                #endif
            }
            catch( Exception ex )
            {
                MessageBox.Show( ex.Message );
            }
        }
Beispiel #27
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            SpatialFieldManager sfm = ((Value.Container)args[1]).Item as SpatialFieldManager;

            //first, cleanup the old one
            if(idxs.Count > 0)
            {
                foreach (int idx in idxs)
                {
                    sfm.RemoveSpatialFieldPrimitive(idx);
                }
            }

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList<int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                AnalysisResultSchema ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = sfm.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //get the list of pairs
            FSharpList<Value> listOfPairs = ((Value.List)args[0]).Item;
            foreach (Value expr in listOfPairs)
            {
                FSharpList<Value> pair = ((Value.List)expr).Item;

                XYZ start = (XYZ)((Value.Container)pair[0]).Item;
                XYZ end = (XYZ)((Value.Container)pair[1]).Item;
                XYZ start1 = start + XYZ.BasisZ * .1;
                XYZ end1 = end + XYZ.BasisZ * .1;

                //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

                var create = dynRevitSettings.Doc.Application.Application.Create;

                Line l1 = create.NewLineBound(start, end);
                Line l2 = create.NewLineBound(end, end1);
                Line l3 = create.NewLineBound(end1, start1);
                Line l4 = create.NewLineBound(start1, start);

                List<CurveLoop> loops = new List<CurveLoop>();
                CurveLoop cl = new CurveLoop();
                cl.Append(l1);
                cl.Append(l2);
                cl.Append(l3);
                cl.Append(l4);
                loops.Add(cl);
                Solid s = GeometryCreationUtilities.CreateExtrusionGeometry(loops, (end-start).CrossProduct(start1-start), .01);

                foreach (Face face in s.Faces)
                {
                    int idx = sfm.AddSpatialFieldPrimitive(face, trf);

                    //need to use double parameters because
                    //we're drawing lines
                    IList<UV> uvPts = new List<UV>();
                    uvPts.Add(face.GetBoundingBox().Min);

                    FieldDomainPointsByUV pnts
                      = new FieldDomainPointsByUV(uvPts);

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

                    doubleList.Add(0);

                    IList<ValueAtPoint> valList
                      = new List<ValueAtPoint>();

                    valList.Add(new ValueAtPoint(doubleList));

                    FieldValues vals = new FieldValues(valList);

                    sfm.UpdateSpatialFieldPrimitive(
                      idx, pnts, vals, schemaId);

                    idxs.Add(idx);
                }
            }

            return Value.NewList(Utils.SequenceToFSharpList(idxs.Select(x => Value.NewNumber(x))));
        }
        protected override void Execute(CodeActivityContext context)
        {
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                string userName;
                string password;
                userName = Username.Get(context);                              //username from context
                password = Password.Get(context) + SecurityToken.Get(context); //password+token from context


                SforceService SfdcBinding        = null;
                LoginResult   CurrentLoginResult = null;

                SfdcBinding = new SforceService();
                try
                {
                    CurrentLoginResult = SfdcBinding.login(userName, password);
                }
                catch (System.Web.Services.Protocols.SoapException e)
                {
                    // This is likley to be caused by bad username or password
                    SfdcBinding = null;
                    throw (e);
                }
                catch (Exception e)
                {
                    // This is something else, probably comminication
                    SfdcBinding = null;
                    throw (e);
                }

                //Change the binding to the new endpoint
                SfdcBinding.Url = CurrentLoginResult.serverUrl;

                //Console.WriteLine(SfdcBinding.Url);
                //Console.ReadLine();

                //Create a new session header object and set the session id to that returned by the login
                SfdcBinding.SessionHeaderValue           = new SessionHeader();
                SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;

                String[] fieldNames  = FieldNames.Get(context);
                String[] fieldValues = FieldValues.Get(context);

                sObject obj = new sObject();
                System.Xml.XmlElement[] objFields = new System.Xml.XmlElement[fieldNames.Length];

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                for (int i = 0; i < fieldNames.Length; i++)
                {
                    objFields[i] = doc.CreateElement(fieldNames[i]);
                }

                for (int j = 0; j < fieldValues.Length; j++)
                {
                    objFields[j].InnerText = fieldValues[j];
                }

                obj.type = ObjectName.Get(context);

                obj.Any = objFields;

                sObject[] objList = new sObject[1];
                objList[0] = obj;

                SaveResult[] results = SfdcBinding.create(objList);


                for (int j = 0; j < results.Length; j++)
                {
                    if (results[j].success)
                    {
                        RecordID.Set(context, results[j].id);
                    }
                    else
                    {
                        // There were errors during the create call,
                        // go through the errors array and write
                        // them to the console
                        String error;
                        for (int i = 0; i < results[j].errors.Length; i++)
                        {
                            Error err = results[j].errors[i];
                            error = "Errors was found on item " + j.ToString() + Environment.NewLine
                                    + "Error code is: " + err.statusCode.ToString() + Environment.NewLine
                                    + "Error message: " + err.message;
                            RecordID.Set(context, error);
                        }
                    }
                }
            }
        }
Beispiel #29
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            SpatialFieldManager sfm = ((Value.Container)args[2]).Item as SpatialFieldManager;

            // Place analysis results in the form of vectors at each of a beam or column's analytical model curve
            Curve curve = ((Value.Container)args[3]).Item as Curve;

            int index = sfm.AddSpatialFieldPrimitive(curve, Transform.Identity);

            IList<double> doubleList = new List<double>();
            doubleList.Add(curve.get_EndParameter(0)); // vectors will be at each end of the analytical model curve
            doubleList.Add(curve.get_EndParameter(1));
            FieldDomainPointsByParameter pointsByParameter = new FieldDomainPointsByParameter(doubleList);

            List<XYZ> xyzList = new List<XYZ>();
            xyzList.Add(curve.ComputeDerivatives(0, true).BasisX.Normalize()); // vectors will be tangent to the curve at its ends
            IList<VectorAtPoint> vectorList = new List<VectorAtPoint>();
            vectorList.Add(new VectorAtPoint(xyzList));
            xyzList.Clear();
            xyzList.Add(curve.ComputeDerivatives(1, true).BasisX.Normalize().Negate());
            vectorList.Add(new VectorAtPoint(xyzList));
            FieldDomainPointsByXYZ feildPoints = new FieldDomainPointsByXYZ(xyzList);
            FieldValues fieldValues = new FieldValues(vectorList);
            int n = 0;
            sfm.UpdateSpatialFieldPrimitive(index, feildPoints, fieldValues, n);

            /*
            //first, cleanup the old one
            if (idx != -1)
            {
                sfm.RemoveSpatialFieldPrimitive(idx);
            }

            Reference reference = ((Value.Container)args[3]).Item as Reference;
            idx = sfm.AddSpatialFieldPrimitive(reference);

            Face face = dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //unwrap the sample locations
            IEnumerable<UV> pts = ((Value.List)args[1]).Item.Select(
               x => (UV)((Value.Container)x).Item
            );
            FieldDomainPointsByUV sample_pts = new FieldDomainPointsByUV(pts.ToList<UV>());

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(
               x => (double)((Value.Number)x).Item
            );

            //for every sample location add a list
            //of valueatpoint objets. for now, we only
            //support one value per point
            IList<ValueAtPoint> valList = new List<ValueAtPoint>();
            foreach (var n in nvals)
            {
                valList.Add(new ValueAtPoint(new List<double> { n }));
            }
            FieldValues sample_values = new FieldValues(valList);

            int schemaIndex = 0;
            if (!sfm.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList<int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                AnalysisResultSchema ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = sfm.RegisterResult(ars);
            }

            sfm.UpdateSpatialFieldPrimitive(idx, sample_pts, sample_values, schemaIndex);
            */

            return Value.NewContainer(idx);
        }
Beispiel #30
0
        /// <summary>
        /// Paint solid by AVF
        /// </summary>
        /// <param name="solid">Solid to be painted</param>
        /// <param name="view">The view that shows solid</param>
        private void PaintSolid(Solid solid, View view)
        {
            String viewName = view.Name;
            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);
            if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);

            if (m_schemaId != -1)
            {
                IList<int> results = sfm.GetRegisteredResults();

                if (!results.Contains(m_schemaId))
                {
                    m_schemaId = -1;
                }
            }

            // set up the display style
            if (m_schemaId == -1)
            {
                AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid " + viewName, "Description");

                AnalysisDisplayStyle displayStyle = AnalysisDisplayStyle.CreateAnalysisDisplayStyle(this.RevitDoc, "Real_Color_Surface" + viewName, new AnalysisDisplayColoredSurfaceSettings(), new AnalysisDisplayColorSettings(), new AnalysisDisplayLegendSettings());

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                m_schemaId = sfm.RegisterResult(resultSchema1);
            }

            // get points of all faces in the solid
            FaceArray faces = solid.Faces;
            Transform trf = Transform.Identity;
            foreach (Face face in faces)
            {
                int idx = sfm.AddSpatialFieldPrimitive(face, trf);
                IList<UV> uvPts = null;
                IList<ValueAtPoint> valList = null;
                ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues vals = new FieldValues(valList);
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, m_schemaId);
            }
        }
Beispiel #31
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            this.ClearPreviousResults();

            //unwrap the values
            IEnumerable<XYZ> nvals = ((Value.List)args[0]).Item.Select(
               x => (XYZ)((Value.Container)x).Item
            );

            //unwrap the sample locations
            IEnumerable<XYZ> pts = ((Value.List)args[1]).Item.Select(
               x => (XYZ)((Value.Container)x).Item
            );
            SpatialFieldManager = ((Value.Container)args[2]).Item as Autodesk.Revit.DB.Analysis.SpatialFieldManager;

            int idx = SpatialFieldManager.AddSpatialFieldPrimitive();

            var samplePts = new FieldDomainPointsByXYZ(pts.ToList<XYZ>());

            //for every sample location add a list
            //of valueatpoint objects. for now, we only
            //support one value per point
            IList<VectorAtPoint> valList = nvals.Select(n => new VectorAtPoint(new List<XYZ> { n })).ToList();
            var sampleValues = new FieldValues(valList);

            int schemaIndex = 0;
            if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList<int> arses = SpatialFieldManager.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = SpatialFieldManager.RegisterResult(ars);
            }

            SpatialFieldManager.UpdateSpatialFieldPrimitive(idx, samplePts, sampleValues, schemaIndex);

            PastResultIds.Add(idx);

            return Value.NewContainer(idx);
        }
 public bool ApplyFieldsToTranslationUnit(FieldValues values, bool overwrite, PersistentObjectToken translationUnitId)
 {
     return _tmlanguageDirection.ApplyFieldsToTranslationUnit(values, overwrite, translationUnitId);
 }
Beispiel #33
0
        public bool AnalysisByElements()
        {
            bool result = false;

            try
            {
                if (radianceDictionary.Count > 0)
                {
                    int                  resultIndex = FindIndexOfResult(sfm);
                    bool                 firstLoop   = true;
                    int                  index       = sfm.AddSpatialFieldPrimitive();//not associated with any geometry
                    IList <XYZ>          xyzPoints   = new List <XYZ>();
                    IList <ValueAtPoint> valList     = new List <ValueAtPoint>();

                    foreach (int keyIndex in radianceDictionary.Keys)
                    {
                        RadianceResult rr      = radianceDictionary[keyIndex];
                        List <double>  dblList = new List <double>(); //double values to be displayed on the face.

                        dblList.Add(rr.Value1);
                        dblList.Add(rr.Value2);
                        dblList.Add(rr.Value3);

                        if (dblList.Count != sfm.NumberOfMeasurements)
                        {
                            continue;
                        }

                        xyzPoints.Add(rr.PointXYZ);
                        valList.Add(new ValueAtPoint(dblList));
                        //dblList.Clear();
                    }
                    FieldDomainPointsByXYZ domainPoints = new FieldDomainPointsByXYZ(xyzPoints);
                    FieldValues            values       = new FieldValues(valList);

                    AnalysisResultSchema resultSchema = new AnalysisResultSchema(settings.LegendTitle, settings.LegendDescription);
                    resultSchema.SetUnits(unitNames, multipliers);
                    if (unitNames.Contains(settings.Units))
                    {
                        resultSchema.CurrentUnits = unitNames.IndexOf(settings.Units);
                    }

                    if (overwriteResult)
                    {
                        sfm.SetResultSchema(resultIndex, resultSchema);
                    }
                    else if (firstLoop)
                    {
                        resultIndex = sfm.RegisterResult(resultSchema); firstLoop = false;
                    }
                    else
                    {
                        sfm.SetResultSchema(resultIndex, resultSchema);
                    }

                    sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);

                    SetCurrentStyle();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to visulaize the FAR data. \n" + ex.Message, "FARCalculator : AnalysisByElements", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(result);
        }
 public int ApplyFieldsToTranslationUnits(FieldValues values, bool overwrite, PersistentObjectToken[] translationUnitIds)
 {
     return _tmlanguageDirection.ApplyFieldsToTranslationUnits(values, overwrite, translationUnitIds);
 }
Beispiel #35
0
        /// <summary>
        /// Handle Revit Idling event.
        /// If less time elapsed than the specified interval, return immediately.
        /// Otherwise, download the current image frile from the specified URL.
        /// If it has not changed since the last update, return immediately.
        /// Otherwise, update the spatial field primitive with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // access active document from sender:

                    Application app = sender as Application;

                    Debug.Assert(null != app,
                                 "expected a valid Revit application instance");

                    UIApplication uiapp = new UIApplication(app);
                    UIDocument    uidoc = uiapp.ActiveUIDocument;
                    Document      doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

                    if (null == sfm)
                    {
                        sfm = SpatialFieldManager
                              .CreateSpatialFieldManager(view, 1);
                    }

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    // warning CS0618:
                    // GeometryObject is obsolete: Property will be removed.
                    // Use Element.GetGeometryObjectFromReference(Reference) instead

                    //Face face = _faceReference.GeometryObject as Face; // 2011

                    Face face = doc.get_Element(_elementId)
                                .GetGeometryObjectFromReference(
                        _faceReference) as Face; // 2012

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    // warning CS0618:
                    // UpdateSpatialFieldPrimitive(int, FieldDomainPoints, FieldValues) is obsolete:
                    // This method is obsolete in Revit 2012; use the overload accepting the result index instead.

                    //sfm.UpdateSpatialFieldPrimitive(
                    //  _sfp_index, fieldPoints, fieldValues ); // 2011

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues, _sfp_index); // 2012

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }
        /// <summary>
        /// Create Visualization framework for view
        /// </summary>
        /// <param name="uvPts"></param>
        /// <param name="valList"></param>
        /// <param name="calcFace"></param>
        /// <param name="faceTransform"></param>
        private void DoVisualization(IList<UV> uvPts, IList<ValueAtPoint> valList, Face calcFace, Transform faceTransform)
        {
            // Visualization framework
            FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
            FieldValues vals = new FieldValues(valList);
            AnalysisResultSchema resultSchema = new AnalysisResultSchema("Point by Point", "Illumination Point-by-Point");

            // Units
            IList<string> names = new List<string> { "FC" };
            IList<double> multipliers = new List<double> { 1 };
            resultSchema.SetUnits(names, multipliers);

            // Add field primative to view
            int idx = m_sfm.AddSpatialFieldPrimitive(calcFace, faceTransform);
            int resultIndex = m_sfm.RegisterResult(resultSchema);

            // Update Field Primatives
            m_sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, resultIndex);
        }
        /// <summary>
        /// Paint a solid in a new named view
        /// </summary>
        /// <param name="s">solid</param>
        /// <param name="viewName">Given the name of view</param>
        public void PaintSolid(Solid s, String viewName)
        {
            View view;
             if (!viewNameList.Contains(viewName))
             {
            view = m_doc.Create.NewView3D(new XYZ(1, 1, 1));
            view.Name = viewName;
            viewNameList.Add(viewName);
             }
             else
             {
            view = (((new FilteredElementCollector(m_doc).
               OfClass(typeof(View))).Cast<View>()).
               Where(e => e.Name == viewName)).First<View>();
             }

             SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);
             if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);

             if (SchemaId != -1)
             {
            IList<int> results = sfm.GetRegisteredResults();

            if (!results.Contains(SchemaId))
            {
               SchemaId = -1;
            }
             }

             if (SchemaId == -1)
             {
            AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid" + viewName, "Description");

            AnalysisDisplayStyle displayStyle = AnalysisDisplayStyle.CreateAnalysisDisplayStyle(
               m_doc,
               "Real_Color_Surface" + viewName,
               new AnalysisDisplayColoredSurfaceSettings(),
               new AnalysisDisplayColorSettings(),
               new AnalysisDisplayLegendSettings());

            resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

            SchemaId = sfm.RegisterResult(resultSchema1);
             }

             FaceArray faces = s.Faces;
             Transform trf = Transform.Identity;

             foreach (Face face in faces)
             {
            int idx = sfm.AddSpatialFieldPrimitive(face, trf);

            IList<UV> uvPts = null;
            IList<ValueAtPoint> valList = null;
            ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

            FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

            FieldValues vals = new FieldValues(valList);

            sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, SchemaId);
             }
        }
Beispiel #38
0
        private void BtnUpdateMatchingRecords_Click( object sender, RoutedEventArgs e )
        {
            try
            {
                string filter = "(~FirstName = 'andrew' OR ~FirstName = 'nancy') AND ~LastName = 'fuller'";

                FilterExpressionGroup filterExpGrp = FilterExpressionGroup.Parse( filter );
                FileDbNs.Table table = _db.SelectRecords( filterExpGrp );
                displayRecords( table );

                // equivalent building it manually
                var fname1Exp = new FilterExpression( "FirstName", "andrew", EqualityEnum.Equal, MatchTypeEnum.IgnoreCase );
                // the following lines produce the same FilterExpression
                var fname2Exp = FilterExpression.Parse( "~FirstName = nancy" );
                fname2Exp = new FilterExpression( "FirstName", "nancy", EqualityEnum.Equal, MatchTypeEnum.IgnoreCase );
                var lnameExp = new FilterExpression( "LastName", "fuller", EqualityEnum.Equal, MatchTypeEnum.IgnoreCase );

                var fnamesGrp = new FilterExpressionGroup();
                fnamesGrp.Add( BoolOpEnum.Or, fname1Exp );
                fnamesGrp.Add( BoolOpEnum.Or, fname2Exp );
                var allNamesGrp = new FilterExpressionGroup();
                allNamesGrp.Add( BoolOpEnum.And, lnameExp );
                allNamesGrp.Add( BoolOpEnum.And, fnamesGrp );
                table = _db.SelectRecords( allNamesGrp );
                displayRecords( table );

                // now update the matching Record
                var fieldValues = new FieldValues();
                fieldValues.Add( "IsCitizen", false );
                int nRecs = _db.UpdateRecords( allNamesGrp, fieldValues );

                table = _db.SelectRecords( allNamesGrp );
                displayRecords( table );

                // or easiest of all use the filter string directly
                table = _db.SelectRecords( filter );
                displayRecords( table );
            }
            catch( Exception ex )
            {
                MessageBox.Show( ex.Message );
            }
        }
        private RoomData FindVisibility(RoomData rd, ProgressBar progressBar)
        {
            RoomData updatedData = new RoomData(rd);

            try
            {
                LogicalOrFilter      orFilter    = new LogicalOrFilter(categoryFilters);
                ReferenceIntersector intersector = null;
                intersector = new ReferenceIntersector(orFilter, FindReferenceTarget.Face, m_view);
                intersector.FindReferencesInRevitLinks = true;

                Face          face = rd.RoomFace;
                BoundingBoxUV bb   = face.GetBoundingBox();

                IList <UV>           uvPoints = new List <UV>();
                IList <ValueAtPoint> valList  = new List <ValueAtPoint>();

                List <PointData> pointDataList = new List <PointData>();
                double           interval      = analysisSettings.Interval;
                List <double>    uList         = new List <double>();
                List <double>    vList         = new List <double>();
                GetUVArray(bb, interval, out uList, out vList);


                progressBar.Value   = 0;
                progressBar.Minimum = 0;
                progressBar.Maximum = uList.Count * vList.Count;
                UpdateProgressDelegate updateProgressDelegate = new UpdateProgressDelegate(progressBar.SetValue);


                List <XYZ> exteriorPoints = new List <XYZ>();
                List <XYZ> interiorPoints = new List <XYZ>();
                bool       sorted         = SortViewPoints(rd.BoundarySegments, out exteriorPoints, out interiorPoints);

                int    visibleCount  = 0;
                double progressValue = 0;
                foreach (double u in uList) //start from in the middle of grid
                {
                    foreach (double v in vList)
                    {
                        if (AbortFlag.GetAbortFlag())
                        {
                            return(updatedData);
                        }
                        Dispatcher.CurrentDispatcher.Invoke(updateProgressDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, progressValue });

                        UV uvPoint = new UV(u, v);
                        if (face.IsInside(uvPoint))
                        {
                            XYZ    evalPoint  = face.Evaluate(uvPoint);
                            XYZ    xyzPoint   = new XYZ(evalPoint.X, evalPoint.Y, evalPoint.Z + offsetHeight); //4.2 inches above from the floor
                            double pointValue = 0;

                            List <XYZ> viewPoints = new List <XYZ>();
                            if (exteriorPoints.Count > 0)
                            {
                                exteriorPoints = exteriorPoints.OrderBy(o => o.DistanceTo(xyzPoint)).ToList();
                                viewPoints.AddRange(exteriorPoints);
                            }
                            if (interiorPoints.Count > 0)
                            {
                                interiorPoints = interiorPoints.OrderBy(o => o.DistanceTo(xyzPoint)).ToList();
                                viewPoints.AddRange(interiorPoints);
                            }

                            if (viewPoints.Count > 0)
                            {
                                bool visible = CheckVisibilityByMaterial(intersector, xyzPoint, viewPoints);
                                if (visible)
                                {
                                    pointValue = 1; visibleCount++;
                                }
                                else
                                {
                                    pointValue = 0;
                                }
                            }

                            PointData pData = new PointData(uvPoint, xyzPoint, pointValue);
                            pointDataList.Add(pData);

                            uvPoints.Add(pData.UVPoint);
                            valList.Add(pData.ValueAtPoint);
                        }
                        progressValue++;
                    }
                }

                rd.PointDataList = pointDataList;
                double ratio = (double)visibleCount / (double)uvPoints.Count;
                rd.VisiblityRatio = ratio;
                rd.AreaWithViews  = rd.RoomArea * ratio;
                rd.SetResultParameterValue(LEEDParameters.LEED_AreaWithViews.ToString(), rd.AreaWithViews);

                //visualize
                Transform transform = Transform.CreateTranslation(new XYZ(0, 0, offsetHeight));

                int index = m_sfm.AddSpatialFieldPrimitive(face, transform);
                FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPoints);
                FieldValues           values       = new FieldValues(valList);

                m_sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to find visibility.\n" + ex.Message, "Find Visibility", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(updatedData);
        }
Beispiel #40
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            sfm = ((Value.Container)args[2]).Item as SpatialFieldManager;

            var reference = (args[3] as Value.Container).Item as Reference;
            var face      = (reference == null) ?
                            ((args[3] as Value.Container).Item as Face) :
                            dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //if we received a face instead of a reference
            //then use the reference from the face
            if (reference == null && face != null)
            {
                reference = face.Reference;
            }

            if (reference == null)
            {
                throw new Exception("Could not resolved a referenced for the face.");
            }

            int idx = sfm.AddSpatialFieldPrimitive(reference);

            //unwrap the sample locations
            IEnumerable <UV> pts = ((Value.List)args[1]).Item.Select(
                x => (UV)((Value.Container)x).Item
                );
            var samplePts = new FieldDomainPointsByUV(pts.ToList <UV>());

            //unwrap the values
            IEnumerable <double> nvals = ((Value.List)args[0]).Item.Select(
                x => (double)((Value.Number)x).Item
                );

            //for every sample location add a list
            //of valueatpoint objects. for now, we only
            //support one value per point
            IList <ValueAtPoint> valList = nvals.Select(n => new ValueAtPoint(new List <double> {
                n
            })).ToList();
            var sampleValues = new FieldValues(valList);

            int schemaIndex = 0;

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList <int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = sfm.RegisterResult(ars);
            }

            sfm.UpdateSpatialFieldPrimitive(idx, samplePts, sampleValues, schemaIndex);

            idxs.Add(idx);

            return(Value.NewContainer(idx));
        }
Beispiel #41
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            this.ClearPreviousResults();

            //allow the user to pass in a list or a single item.
            IEnumerable <double> nvals;

            if (args[0].IsList)
            {
                //unwrap the values
                nvals = ((Value.List)args[0]).Item.Select(
                    x => (double)((Value.Number)x).Item
                    );
            }
            else
            {
                //put the one value into the list
                nvals = new List <double> {
                    ((Value.Number)args[0]).Item
                };
            }

            //unwrap the sample locations
            IEnumerable <XYZ> pts = ((Value.List)args[1]).Item.Select(
                x => (XYZ)((Value.Container)x).Item
                );

            SpatialFieldManager = ((Value.Container)args[2]).Item as Autodesk.Revit.DB.Analysis.SpatialFieldManager;

            int idx = SpatialFieldManager.AddSpatialFieldPrimitive();

            var samplePts = new FieldDomainPointsByXYZ(pts.ToList <XYZ>());

            //for every sample location add a list
            //of valueatpoint objects. for now, we only
            //support one value per point
            IList <ValueAtPoint> valList = nvals.Select(n => new ValueAtPoint(new List <double> {
                n
            })).ToList();
            var sampleValues = new FieldValues(valList);

            int schemaIndex = 0;

            if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList <int> arses = SpatialFieldManager.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = SpatialFieldManager.RegisterResult(ars);
            }

            SpatialFieldManager.UpdateSpatialFieldPrimitive(idx, samplePts, sampleValues, schemaIndex);

            PastResultIds.Add(idx);

            return(Value.NewContainer(idx));
        }
Beispiel #42
0
 private Dictionary <string, FieldValue> GetFieldHash()
 {
     return(FieldValues.ToDictionary(value => value.Field.Name));
 }
Beispiel #43
0
        /// <summary>
        /// Set the spatial field values for the current spatial field primitive.  The two 
        /// input sequences should be of the same length.
        /// </summary>
        /// <param name="pointLocations"></param>
        /// <param name="values"></param>
        private void InternalSetSpatialFieldValues(PointAnalysisData data, ref List<int> primitiveIds, string schemaName, string description, Type unitType)
        {
            var values = data.Results.Values;

            var height = values.First().Count();
            var width = values.Count();

            // Transpose and convert the analysis values to a special Revit type
            var transposedVals = new List<List<double>>();
            for (int i = 0; i < height; i++)
            {
                var lst = new List<double>() { };

                for (int j = 0; j < width; j++)
                {
                    lst.Add(values.ElementAt(j).ElementAt(i));
                }
                transposedVals.Add(lst);
            }

            TransactionManager.Instance.EnsureInTransaction(Document);

            // We chunk here because the API has a limitation for the 
            // number of points that can be sent in one run.

            var chunkSize = 1000;
            var pointLocations = data.CalculationLocations.Select(l=>l.ToXyz());

            while (pointLocations.Any()) 
            {
                // Convert the analysis values to a special Revit type
                var pointLocationChunk = pointLocations.Take(chunkSize).ToList<XYZ>();
                var valuesChunk = transposedVals.Take(chunkSize).ToList();
                var valList = valuesChunk.Select(n => new ValueAtPoint(n)).ToList();

                // Convert the sample points to a special Revit Type
                var samplePts = new FieldDomainPointsByXYZ(pointLocationChunk.ToList<XYZ>());
                var sampleValues = new FieldValues(valList);

                // Get the analysis results schema
                var schemaIndex = GetAnalysisResultSchemaIndex(schemaName, description, unitType);

                // Update the values
                var primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive();
                primitiveIds.Add(primitiveId);
                SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

                pointLocations = pointLocations.Skip(chunkSize);
                transposedVals = transposedVals.Skip(chunkSize).ToList();
            }

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #44
0
        public void RenameKey( ConfigDbKey key, string newKeyName )
        {
            checkDbOpen();

            if( key == ConfigDbKey.CurrentUser || key == ConfigDbKey.LocalMachine )
                throw new Exception( "Cannot rename CurrentUser and LocalMachine root keys" );

            if( newKeyName != null )
                newKeyName = newKeyName.Trim();

            if( string.IsNullOrEmpty( newKeyName ) )
                throw new Exception( ErrKeysCannotBeEmpty );

            //String filter = String.Format( "ID = {0} AND Type = {1}", (int) key, (int) KeyValueType.Key );
            String filter = String.Format( "ID = {0}", (int) key );

            FieldValues fieldValues = new FieldValues( 1 );
            fieldValues.Add( StrName, newKeyName );
            int numUpdated = _db.UpdateRecords( FilterExpressionGroup.Parse( filter ), fieldValues );
        }
        public void Execute(UpdaterData data)
        {
            Document doc = data.GetDocument();

            Autodesk.Revit.ApplicationServices.Application app = doc.Application;

            View           view      = doc.GetElement(viewID) as View;
            FamilyInstance sphere    = doc.GetElement(sphereID) as FamilyInstance;
            LocationPoint  sphereLP  = sphere.Location as LocationPoint;
            XYZ            sphereXYZ = sphereLP.Point;

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3);              // Three measurement values for each point
            }
            sfm.Clear();

            FilteredElementCollector collector  = new FilteredElementCollector(doc, view.Id);
            ElementCategoryFilter    wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
            ElementCategoryFilter    massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass);
            LogicalOrFilter          filter     = new LogicalOrFilter(wallFilter, massFilter);
            ICollection <Element>    elements   = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

            foreach (Face face in GetFaces(elements))
            {
                int                  idx        = sfm.AddSpatialFieldPrimitive(face.Reference);
                List <double>        doubleList = new List <double>();
                IList <UV>           uvPts      = new List <UV>();
                IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                BoundingBoxUV        bb         = face.GetBoundingBox();
                for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15)
                {
                    for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15)
                    {
                        UV uvPnt = new UV(u, v);
                        uvPts.Add(uvPnt);
                        XYZ faceXYZ = face.Evaluate(uvPnt);
                        // Specify three values for each point
                        doubleList.Add(faceXYZ.DistanceTo(sphereXYZ));
                        doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ));
                        doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10);
                        valList.Add(new ValueAtPoint(doubleList));
                        doubleList.Clear();
                    }
                }
                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues           vals = new FieldValues(valList);

                AnalysisResultSchema resultSchema1     = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
                IList <int>          registeredResults = new List <int>();
                registeredResults = sfm.GetRegisteredResults();
                int idx1 = 0;
                if (registeredResults.Count == 0)
                {
                    idx1 = sfm.RegisterResult(resultSchema1);
                }
                else
                {
                    idx1 = registeredResults.First();
                }
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1);
            }
        }
Beispiel #46
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            SpatialFieldManager sfm = ((Value.Container)args[2]).Item as SpatialFieldManager;

            //first, cleanup the old one
            if (idx != -1)
            {
                sfm.RemoveSpatialFieldPrimitive(idx);
            }

            Reference reference = ((Value.Container)args[3]).Item as Reference;
            idx = sfm.AddSpatialFieldPrimitive(reference);

            Face face = dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //unwrap the sample locations
            IEnumerable<UV> pts = ((Value.List)args[1]).Item.Select(
               x => (UV)((Value.Container)x).Item
            );
            FieldDomainPointsByUV sample_pts = new FieldDomainPointsByUV(pts.ToList<UV>());

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(
               x => (double)((Value.Number)x).Item
            );

            //for every sample location add a list
            //of valueatpoint objets. for now, we only
            //support one value per point
            IList<ValueAtPoint> valList = new List<ValueAtPoint>();
            foreach (var n in nvals)
            {
                valList.Add(new ValueAtPoint(new List<double>{n}));
            }
            FieldValues sample_values = new FieldValues(valList);

            int schemaIndex = 0;
            if (!sfm.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList<int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                AnalysisResultSchema ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = sfm.RegisterResult(ars);
            }

            sfm.UpdateSpatialFieldPrimitive(idx, sample_pts, sample_values, schemaIndex);

            return Value.NewContainer(idx);
        }
Beispiel #47
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            //unwrap the values
            IEnumerable <double> nvals = ((Value.List)args[0]).Item.Select(q => (double)((Value.Number)q).Item);

            var curve = (Curve)((Value.Container)args[1]).Item;

            sfm = (SpatialFieldManager)((Value.Container)args[2]).Item;

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList <int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = sfm.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

            var create = dynRevitSettings.Doc.Application.Application.Create;

            Transform t = curve.ComputeDerivatives(0, true);

            XYZ x = t.BasisX.Normalize();
            XYZ y = t.BasisX.IsAlmostEqualTo(XYZ.BasisZ) ?
                    t.BasisX.CrossProduct(XYZ.BasisY).Normalize() :
                    t.BasisX.CrossProduct(XYZ.BasisZ).Normalize();
            XYZ z = x.CrossProduct(y);

            Ellipse arc1 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, -Math.PI, 0);
            Ellipse arc2 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, 0, Math.PI);

            var pathLoop = new CurveLoop();

            pathLoop.Append(curve);
            var profileLoop = new CurveLoop();

            profileLoop.Append(arc1);
            profileLoop.Append(arc2);

            double curveDomain = curve.get_EndParameter(1) - curve.get_EndParameter(0);

            int idx = -1;
            var s   = GeometryCreationUtilities.CreateSweptGeometry(pathLoop, 0, 0, new List <CurveLoop> {
                profileLoop
            });

            foreach (Face face in s.Faces)
            {
                //divide the V domain by the number of incoming
                BoundingBoxUV domain = face.GetBoundingBox();
                double        vSpan  = domain.Max.V - domain.Min.V;

                //analysis values
                idx = sfm.AddSpatialFieldPrimitive(face, trf);

                //a list to hold the analysis points
                IList <UV> uvPts = new List <UV>();

                //a list to hold the analysis values
                IList <ValueAtPoint> valList = new List <ValueAtPoint>();

                //int count = nvals.Count();

                //this is creating a lot of sample points, but if we used less
                //sampling points, AVF would draw the two surfaces as if there was a hard
                //edge between them. this provides a better blend.
                int count = 10;
                for (int i = 0; i < count; i++)
                {
                    //get a UV point on the face
                    //find its XYZ location and project to
                    //the underlying curve. find the value which corresponds
                    //to the location on the curve
                    var uv  = new UV(domain.Min.U, domain.Min.V + vSpan / count * (double)i);
                    var uv1 = new UV(domain.Max.U, domain.Min.V + vSpan / count * (double)i);
                    uvPts.Add(uv);
                    uvPts.Add(uv1);

                    XYZ facePt                    = face.Evaluate(uv);
                    IntersectionResult ir         = curve.Project(facePt);
                    double             curveParam = curve.ComputeNormalizedParameter(ir.Parameter);

                    if (curveParam < 0)
                    {
                        curveParam = 0;
                    }

                    if (curveParam > 1)
                    {
                        curveParam = 1;
                    }

                    var valueIndex = (int)Math.Floor(curveParam * (double)nvals.Count());
                    if (valueIndex >= nvals.Count())
                    {
                        valueIndex = nvals.Count() - 1;
                    }

                    //create list of values at this point - currently supporting only one
                    //var doubleList = new List<double> { nvals.ElementAt(i) };
                    var doubleList = new List <double> {
                        nvals.ElementAt(valueIndex)
                    };

                    //add value at point object containing the value list
                    valList.Add(new ValueAtPoint(doubleList));
                    valList.Add(new ValueAtPoint(doubleList));
                }

                var pnts = new FieldDomainPointsByUV(uvPts);
                var vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(
                    idx, pnts, vals, schemaId);

                idxs.Add(idx);
            }

            return(Value.NewNumber(idx));
        }
 public UpdateCommandBuilder AddFieldValues(IEnumerable <string> fieldValues)
 => this.Chain(() => FieldValues.AddRange(fieldValues));
Beispiel #49
0
        internal static void ShowVectors(Document doc, IList <Objects.VectorObject> points, bool scaleVectors)
        {
            double viewScale = 12.0 / Convert.ToDouble(doc.ActiveView.Scale);


            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 1);
            }

            if (sfm == null)
            {
                throw new System.ApplicationException("SFM still null!");
            }
            sfm.Clear();

            // schema
            if (_SchemaId != -1)
            {
                IList <int> results = sfm.GetRegisteredResults();

                if (!results.Contains(_SchemaId))
                {
                    _SchemaId = -1;
                }
            }

            if (_SchemaId == -1)
            {
                _SchemaId = registerResults(sfm, "ShowChanges", "Description");
            }



            IList <VectorAtPoint> valList   = new List <VectorAtPoint>();
            List <XYZ>            dummyList = new List <XYZ>();

            dummyList.Add(XYZ.BasisZ);

            FieldDomainPointsByXYZ pnts = null;

            FieldValues vals = null;

            List <XYZ>    tmpXYZ   = new List <XYZ>();
            List <string> tmpNames = new List <String>();

            int idx             = sfm.AddSpatialFieldPrimitive();
            int localPointCount = 0;
            int max             = points.Count;

            for (int i = 0; i < max; i++)
            {
                tmpXYZ.Add(points[i].Origin);


                if (scaleVectors)
                {
                    dummyList[0] = points[i].Vector.Multiply(viewScale);
                }
                else
                {
                    dummyList[0] = points[i].Vector;
                }
                valList.Add(new VectorAtPoint(dummyList));

                if (localPointCount > MAX_POINTS_PER_PRIMITIVE)
                {
                    pnts = new FieldDomainPointsByXYZ(tmpXYZ);
                    vals = new FieldValues(valList);
                    sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, _SchemaId);

                    // create a new primitive
                    idx = sfm.AddSpatialFieldPrimitive();

                    // reset
                    localPointCount = 0;
                    tmpXYZ          = new List <XYZ>();
                    valList         = new List <VectorAtPoint>();
                }


                localPointCount++;
            }

            // do it one more time if there are leftovers
            if (tmpXYZ.Count > 0)
            {
                pnts = new FieldDomainPointsByXYZ(tmpXYZ);
                vals = new FieldValues(valList);
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, _SchemaId);
            }



            updateView(doc.ActiveView, StyleEnum.Vectors);
        }
        /// <summary>
        /// Paint a solid in a new named view
        /// </summary>
        /// <param name="s">solid</param>
        /// <param name="viewName">Given the name of view</param>
        public void PaintSolid(Solid s, String viewName)
        {
            View view;

            if (!viewNameList.Contains(viewName))
            {
                view      = m_doc.Create.NewView3D(new XYZ(1, 1, 1));
                view.Name = viewName;
                viewNameList.Add(viewName);
            }
            else
            {
                view = (((new FilteredElementCollector(m_doc).
                          OfClass(typeof(View))).Cast <View>()).
                        Where(e => e.Name == viewName)).First <View>();
            }

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);
            }

            if (SchemaId != -1)
            {
                IList <int> results = sfm.GetRegisteredResults();

                if (!results.Contains(SchemaId))
                {
                    SchemaId = -1;
                }
            }

            if (SchemaId == -1)
            {
                AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid" + viewName, "Description");

                AnalysisDisplayStyle displayStyle = AnalysisDisplayStyle.CreateAnalysisDisplayStyle(
                    m_doc,
                    "Real_Color_Surface" + viewName,
                    new AnalysisDisplayColoredSurfaceSettings(),
                    new AnalysisDisplayColorSettings(),
                    new AnalysisDisplayLegendSettings());

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                SchemaId = sfm.RegisterResult(resultSchema1);
            }

            FaceArray faces = s.Faces;
            Transform trf   = Transform.Identity;

            foreach (Face face in faces)
            {
                int idx = sfm.AddSpatialFieldPrimitive(face, trf);

                IList <UV>           uvPts   = null;
                IList <ValueAtPoint> valList = null;
                ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                FieldValues vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, SchemaId);
            }
        }
 public WorkflowObjectValue this[string key]
 => key != null && FieldValues.ContainsKey(key) ? FieldValues[key] : null;
Beispiel #52
0
        /// <summary>
        /// Handle Revit Idling event.
        /// If less time elapsed than the specified interval, return immediately.
        /// Otherwise, download the current image frile from the specified URL.
        /// If it has not changed since the last update, return immediately.
        /// Otherwise, update the spatial field primitive with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // access active document from sender:

                    Application app = sender as Application;

                    Debug.Assert(null != app,
                                 "expected a valid Revit application instance");

                    UIApplication uiapp = new UIApplication(app);
                    UIDocument    uidoc = uiapp.ActiveUIDocument;
                    Document      doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

                    if (null == sfm)
                    {
                        sfm = SpatialFieldManager
                              .CreateSpatialFieldManager(view, 1);
                    }

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    Face face = _faceReference.GeometryObject
                                as Face;

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues);

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }
Beispiel #53
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            this.ClearPreviousResults();
            SpatialFieldManager = ((Value.Container)args[2]).Item as Autodesk.Revit.DB.Analysis.SpatialFieldManager;

            var reference = (args[3] as Value.Container).Item as Reference;
            var face = (reference == null) ?
                ((args[3] as Value.Container).Item as Face) :
                dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //if we received a face instead of a reference
            //then use the reference from the face
            if (reference == null && face != null)
                reference = face.Reference;

            if (reference == null)
                throw new Exception("Could not resolved a referenced for the face.");

            int idx = SpatialFieldManager.AddSpatialFieldPrimitive(reference);

            //unwrap the sample locations
            IEnumerable<UV> pts = ((Value.List)args[1]).Item.Select(
               x => (UV)((Value.Container)x).Item
            );
            var samplePts = new FieldDomainPointsByUV(pts.ToList<UV>());

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(
               x => (double)((Value.Number)x).Item
            );

            //for every sample location add a list
            //of valueatpoint objects. for now, we only
            //support one value per point
            IList<ValueAtPoint> valList = nvals.Select(n => new ValueAtPoint(new List<double> {n})).ToList();
            var sampleValues = new FieldValues(valList);

            int schemaIndex = 0;
            if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList<int> arses = SpatialFieldManager.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = SpatialFieldManager.RegisterResult(ars);
            }

            SpatialFieldManager.UpdateSpatialFieldPrimitive(idx, samplePts, sampleValues, schemaIndex);

            PastResultIds.Add(idx);

            return Value.NewContainer(idx);
        }
        private bool AddOrUpdateRecord(string key, byte[] value, DateTime expires)
        {
            var fieldValues = new FieldValues(3);
            fieldValues.Add(valueField, value);
            fieldValues.Add(expiresField, expires);

            bool recordExists;

            try
            {
                recordExists = fileDb.GetRecordByKey(key, new string[0], false) != null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("FileDbCache: FileDb.GetRecordByKey(\"{0}\") failed: {1}", key, ex.Message);
                return false;
            }

            if (recordExists)
            {
                try
                {
                    fileDb.UpdateRecordByKey(key, fieldValues);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("FileDbCache: FileDb.UpdateRecordByKey(\"{0}\") failed: {1}", key, ex.Message);
                    return false;
                }
            }
            else
            {
                try
                {
                    fieldValues.Add(keyField, key);
                    fileDb.AddRecord(fieldValues);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("FileDbCache: FileDb.AddRecord(\"{0}\") failed: {1}", key, ex.Message);
                    return false;
                }
            }

            //Debug.WriteLine("Cached item {0}, expires {1}", key, expires);
            return true;
        }
Beispiel #55
0
            /// <summary>
            /// The idling callback which adds data to the AVF results.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void UpdateWhileIdling(object sender, IdlingEventArgs e)
            {
                UIApplication uiApp = sender as UIApplication;

                // Get SpatialFieldManager

                AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema Name", "Description");
                SpatialFieldManager  sfm          = SpatialFieldManager.GetSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView);

                if (sfm == null)
                {
                    sfm = SpatialFieldManager.CreateSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView, 1);
                }
                int schemaIndex = sfm.RegisterResult(resultSchema);

                // If stopping, clear results and unset event.
                if (m_stop)
                {
                    lock (results)
                    {
                        results.Clear();
                    }
                    uiApp.Idling -= UpdateWhileIdling;
                    return;
                }

                // If document was closed and new document opened, do not run the update.
                if (uiApp.ActiveUIDocument.Document.PathName == m_docName)
                {
                    // Lock access to current calculated results
                    lock (results)
                    {
                        if (results.Count == 0)
                        {
                            return;
                        }

                        // Turn each result to an AVF ValueAtPoint
                        foreach (ResultsData rData in results)
                        {
                            uvPts.Add(new UV(rData.UV.U, rData.UV.V));
                            IList <double> doubleList = new List <double>();
                            doubleList.Add(rData.Value);
                            valList.Add(new ValueAtPoint(doubleList));
                        }
                        FieldDomainPointsByUV pntsByUV    = new FieldDomainPointsByUV(uvPts);
                        FieldValues           fieldValues = new FieldValues(valList);

                        // Update with calculated values
                        Transaction t = new Transaction(uiApp.ActiveUIDocument.Document);
                        t.SetName("AVF");
                        t.Start();
                        if (!m_stop)
                        {
                            sfm.UpdateSpatialFieldPrimitive(s_spatialFieldId, pntsByUV, fieldValues, schemaIndex);
                        }
                        t.Commit();

                        // Clear results already processed.
                        results.Clear();

                        // If no more results to process, remove the idling event
                        if (m_uvToCalculateCount == 0)
                        {
                            uiApp.Idling       -= UpdateWhileIdling;
                            s_oldViewId         = s_activeViewId;
                            s_oldSpatialFieldId = s_spatialFieldId;
                        }
                    }
                }
            }
Beispiel #56
0
        private void BtnUpdateRecordsRegex_Click( object sender, RoutedEventArgs e )
        {
            try
            {
                string searchVal = @"\bFull";
                var fieldSearchExp = new FilterExpression( "LastName", searchVal, EqualityEnum.Like );

                var fieldValues = new FieldValues();
                fieldValues.Add( "IsCitizen", true );
                int nRecs = _db.UpdateRecords( fieldSearchExp, fieldValues );

                FileDbNs.Table table = _db.SelectRecords( fieldSearchExp );
                displayRecords( table );
            }
            catch( Exception ex )
            {
                MessageBox.Show( ex.Message );
            }
        }
 public UpdateCommandBuilder AddFieldValues(params string[] fieldValues)
 => this.Chain(() => FieldValues.AddRange(fieldValues));
Beispiel #58
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            ExternalCommandData cdata = commandData;

            Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 1);
            }

            IList <Reference> refList = new List <Reference>();

            try
            {
                refList = uiDoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Face);
            }
            catch (Exception)
            {
                //    throw;
            }
            foreach (Reference reference in refList)
            {
                IList <UV> uvPts = new List <UV>();

                //List<double> doubleList = new List<double>();
                IList <ValueAtPoint> valList = new List <ValueAtPoint>();
                Face          face           = doc.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;
                BoundingBoxUV bb             = face.GetBoundingBox();
                UV            min            = bb.Min;
                UV            max            = bb.Max;

                uvPts.Add(min);
                uvPts.Add(max);
                valList.Add(new ValueAtPoint(new List <double>()
                {
                    0
                }));
                valList.Add(new ValueAtPoint(new List <double>()
                {
                    0
                }));

                /*
                 * for (double u = min.U; u < max.U; u += (max.U - min.U) / 10)
                 * {
                 *  for (double v = min.V; v < max.V; v += (max.V - min.V) / 10)
                 *  {
                 *      UV uv = new UV(u, v);
                 *      if (face.IsInside(uv))
                 *      {
                 *          uvPts.Add(uv);
                 *          doubleList.Add(0);
                 *          valList.Add(new ValueAtPoint(doubleList));
                 *          doubleList.Clear();
                 *      }
                 *  }
                 * }*/

                //FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                var points = new FieldDomainPointsByXYZ(new List <XYZ>()
                {
                    new XYZ(0, 0, 0), new XYZ(0, 0, 10)
                });

                FieldValues          vals         = new FieldValues(valList);
                int                  idx          = sfm.AddSpatialFieldPrimitive(reference);
                AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
                sfm.UpdateSpatialFieldPrimitive(idx, points, vals, sfm.RegisterResult(resultSchema));
            }



            return(Result.Succeeded);
        }
Beispiel #59
0
            /// <summary>
            /// The idling callback which adds data to the AVF results.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void UpdateWhileIdling(object sender, IdlingEventArgs e)
            {
                UIApplication uiApp = sender as UIApplication;

                // Get SpatialFieldManager
                SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView);
                if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView, 1);

                // If stopping, clear results and unset event.
                if (m_stop)
                {
                    lock (results)
                    {
                        results.Clear();
                    }
                    uiApp.Idling -= UpdateWhileIdling;
                    return;
                }

                // If document was closed and new document opened, do not run the update.
                if (uiApp.ActiveUIDocument.Document.PathName == m_docName)
                {
                    // Lock access to current calculated results
                    lock (results)
                    {
                        if (results.Count == 0) return;

                        // Turn each result to an AVF ValueAtPoint
                        foreach (ResultsData rData in results)
                        {
                            uvPts.Add(new UV(rData.UV.U, rData.UV.V));
                            IList<double> doubleList = new List<double>();
                            doubleList.Add(rData.Value);
                            valList.Add(new ValueAtPoint(doubleList));
                        }
                        FieldDomainPointsByUV pntsByUV = new FieldDomainPointsByUV(uvPts);
                        FieldValues fieldValues = new FieldValues(valList);

                        // Update with calculated values
                        Transaction t = new Transaction(uiApp.ActiveUIDocument.Document);
                        t.SetName("AVF");
                        t.Start();
                        if (!m_stop)
                            sfm.UpdateSpatialFieldPrimitive(s_spatialFieldId, pntsByUV, fieldValues);
                        t.Commit();

                        // Clear results already processed.
                        results.Clear();

                        // If no more results to process, remove the idling event
                        if (m_uvToCalculateCount == 0)
                        {
                            uiApp.Idling -= UpdateWhileIdling;
                            s_oldViewId = s_activeViewId;
                            s_oldSpatialFieldId = s_spatialFieldId;
                        }
                    }
                }
            }
Beispiel #60
0
        /// <summary>
        /// Handle Revit Idling event.
        /// Return immediately if less time elapsed than
        /// specified interval.
        /// Otherwise, download the current image file
        /// from the specified URL.
        /// If it has not changed since the last update,
        /// return immediately.
        /// Otherwise, update the spatial field primitive
        /// with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by
        /// defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // access active document from sender:

                    // Support both 2011, where sender is an
                    // Application instance, and 2012, where
                    // it is a UIApplication instance:

                    UIApplication uiapp
                        = sender is UIApplication
            ? sender as UIApplication                 // 2012
            : new UIApplication(
                              sender as Application); // 2011

                    Debug.Assert(null != uiapp,
                                 "expected a valid Revit UIApplication instance");

                    UIDocument uidoc = uiapp.ActiveUIDocument;
                    Document   doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

                    if (null == sfm)
                    {
                        sfm = SpatialFieldManager
                              .CreateSpatialFieldManager(view, 1);
                    }

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    // warning CS0618:
                    // GeometryObject is obsolete: Property will be removed.
                    // Use Element.GetGeometryObjectFromReference(Reference) instead

                    //Face face = _faceReference.GeometryObject as Face; // 2011

                    //Face face = doc.get_Element( _elementId )
                    //  .GetGeometryObjectFromReference(
                    //    _faceReference ) as Face; // 2012

                    // warning CS0618:
                    // Autodesk.Revit.DB.Document.get_Element(Autodesk.Revit.DB.ElementId) is obsolete:
                    // This method has been obsoleted. Use GetElement() instead.

                    //Element eFace = doc.get_Element( _elementId ); // 2012

                    Element eFace = doc.GetElement(_elementId); // 2013

                    Face face = eFace.GetGeometryObjectFromReference(
                        _faceReference) as Face; // 2012

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    int         result_index;
                    IList <int> registeredResults = sfm.GetRegisteredResults();
                    if (0 == registeredResults.Count)
                    {
                        AnalysisResultSchema resultSchema
                            = new AnalysisResultSchema(
                                  "Schema 1", "Schema 1 Description");

                        result_index = sfm.RegisterResult(
                            resultSchema);
                    }
                    else
                    {
                        result_index = registeredResults.First();
                    }

                    // warning CS0618:
                    // UpdateSpatialFieldPrimitive(int, FieldDomainPoints, FieldValues) is obsolete:
                    // This method is obsolete in Revit 2012; use the overload accepting the result index instead.

                    //sfm.UpdateSpatialFieldPrimitive(
                    //  _sfp_index, fieldPoints, fieldValues ); // 2011

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues,
                        result_index); // 2012

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }