-
Notifications
You must be signed in to change notification settings - Fork 187
/
Element.cs
710 lines (614 loc) · 25.5 KB
/
Element.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Interfaces;
using Autodesk.DesignScript.Runtime;
using Autodesk.Revit.DB;
using DynamoServices;
using DynamoUnits;
using Revit.GeometryConversion;
using Revit.GeometryReferences;
using RevitServices.Persistence;
using RevitServices.Transactions;
using Color = DSCore.Color;
using Area = DynamoUnits.Area;
using Curve = Autodesk.DesignScript.Geometry.Curve;
using RevitServices.Elements;
namespace Revit.Elements
{
/// <summary>
/// Superclass of all Revit element wrappers
/// </summary>
//[SupressImportIntoVM]
public abstract class Element : IDisposable, IGraphicItem, IFormattable
{
/// <summary>
/// Handling exceptions when calling the initializing function
/// </summary>
/// <param name="init"></param>
protected void SafeInit(Action init)
{
var elementManager = ElementIDLifecycleManager<int>.GetInstance();
var element = ElementBinder.GetElementFromTrace<Autodesk.Revit.DB.Element>(Document);
int count = 0;
int id = 0;
if (null != element)
{
id = element.Id.IntegerValue;
count = elementManager.GetRegisteredCount(id);
}
try
{
init();
}
catch (Exception e)
{
//If the element is newly created and bound but the creation is aborted because
//of an exception, it need to be unregistered.
if (element == null && InternalElementId != null)
{
elementManager.UnRegisterAssociation(Id, this);
internalId = null;
throw e;
}
else if (element != null)
{
//If the internal element has already been bound, and if the registered count has increased,
//it need to be unregistered.
if (elementManager.GetRegisteredCount(id) == count + 1)
{
elementManager.UnRegisterAssociation(Id, this);
internalId = null;
}
//It means that the updating operation failed, an attemption of making a new element is made.
ElementBinder.SetRawDataForTrace(null);
SafeInit(init);
}
else
{
throw e;
}
}
}
/// <summary>
/// A reference to the current Document.
/// </summary>
internal static Document Document
{
get { return DocumentManager.Instance.CurrentDBDocument; }
}
/// <summary>
/// Indicates whether the element is owned by Revit or not. If the element
/// is Revit owned, it should not be deleted by Dispose().
/// </summary>
internal bool IsRevitOwned = false;
/// <summary>
/// Obtain all of the Parameters from an Element
/// </summary>
public Parameter[] Parameters
{
get
{
var parms = InternalElement.Parameters;
return parms.Cast<Autodesk.Revit.DB.Parameter>().Select(x => new Parameter(x)).ToArray();
}
}
/// <summary>
/// Get the Name of the Element
/// </summary>
public string Name
{
get
{
return InternalElement.Name;
}
}
/// <summary>
/// Get an Axis-aligned BoundingBox of the Element
/// </summary>
public BoundingBox BoundingBox
{
get
{
TransactionManager.Instance.EnsureInTransaction(Document);
DocumentManager.Regenerate();
var bb = InternalElement.get_BoundingBox(null);
TransactionManager.Instance.TransactionTaskDone();
return bb.ToProtoType();
}
}
/// <summary>
/// Get the Element Id for this element
/// </summary>
public int Id
{
get
{
return InternalElementId.IntegerValue;
}
}
/// <summary>
/// Get the Element Unique Id for this element
/// </summary>
public string UniqueId
{
get
{
return InternalUniqueId;
}
}
/// <summary>
/// A reference to the element
/// </summary>
[SupressImportIntoVM]
public abstract Autodesk.Revit.DB.Element InternalElement
{
get;
}
private ElementId internalId;
/// <summary>
/// The element id for this element
/// </summary>
protected ElementId InternalElementId
{
get
{
if (internalId == null)
return InternalElement != null ? InternalElement.Id : null;
return internalId;
}
set {
internalId = value;
var elementManager = ElementIDLifecycleManager<int>.GetInstance();
elementManager.RegisterAsssociation(Id, this);
}
}
/// <summary>
/// The unique id for this element
/// </summary>
protected string InternalUniqueId;
/// <summary>
/// Set the element's freeze state. If the node is set to freeze
/// all the elements for that node will be set to freeze.
/// </summary>
public bool IsFrozen = false;
/// <summary>
/// Default implementation of dispose that removes the element from the
/// document
/// </summary>
[IsVisibleInDynamoLibrary(false)]
public virtual void Dispose()
{
// Do not cleanup Revit elements if we are shutting down Dynamo or
// closing homeworkspace or the element itself is frozen.
if (DisposeLogic.IsShuttingDown || DisposeLogic.IsClosingHomeworkspace || IsFrozen)
return;
bool didRevitDelete = ElementIDLifecycleManager<int>.GetInstance().IsRevitDeleted(Id);
var elementManager = ElementIDLifecycleManager<int>.GetInstance();
int remainingBindings = elementManager.UnRegisterAssociation(Id, this);
// Do not delete Revit owned elements
if (!IsRevitOwned && remainingBindings == 0 && !didRevitDelete)
{
DocumentManager.Instance.DeleteElement(new ElementUUID(InternalUniqueId));
}
else
{
//This element has gone
//but there was something else holding onto the Revit object so don't purge it
internalId = null;
}
}
/// <summary>
/// A basic implementation of ToString for Elements
/// </summary>
/// <returns></returns>
[IsVisibleInDynamoLibrary(false)]
public override string ToString()
{
return GetType().Name;
}
/// <summary>
/// Implement Equals() method.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[IsVisibleInDynamoLibrary(false)]
public override bool Equals(object obj)
{
Element otherElement = obj as Element;
if (otherElement == null)
{
return false;
}
return UniqueId.Equals(otherElement.UniqueId);
}
/// <summary>
/// Get hash code.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[IsVisibleInDynamoLibrary(false)]
public override int GetHashCode()
{
return UniqueId.GetHashCode();
}
public virtual string ToString(string format, IFormatProvider formatProvider)
{
// As a default, return the standard string representation.
// Override ToString with format information in children.
return ToString();
}
[IsVisibleInDynamoLibrary(false)]
public void Tessellate(IRenderPackage package, TessellationParameters parameters)
{
// Do nothing. We implement this method only to prevent the GraphicDataProvider from
// attempting to interrogate the public properties, some of which may require regeneration
// or transactions and which must necessarily be threaded in a specific way.
}
internal static bool IsConvertableParameterType(ParameterType paramType)
{
return paramType == ParameterType.Length || paramType == ParameterType.Area ||
paramType == ParameterType.Volume || paramType == ParameterType.Angle ||
paramType == ParameterType.Slope || paramType == ParameterType.Currency ||
paramType == ParameterType.MassDensity;
}
internal static UnitType ParameterTypeToUnitType(ParameterType parameterType)
{
switch (parameterType)
{
case ParameterType.Length:
return UnitType.UT_Length;
case ParameterType.Area:
return UnitType.UT_Area;
case ParameterType.Volume:
return UnitType.UT_Volume;
case ParameterType.Angle:
return UnitType.UT_Angle;
case ParameterType.Slope:
return UnitType.UT_Slope;
case ParameterType.Currency:
return UnitType.UT_Currency;
case ParameterType.MassDensity:
return UnitType.UT_MassDensity;
default:
throw new Exception(Properties.Resources.UnitTypeConversionError);
}
}
/// <summary>
/// Get the value of one of the element's parameters.
/// </summary>
/// <param name="parameterName">The name of the parameter whose value you want to obtain.</param>
/// <returns></returns>
public object GetParameterValueByName(string parameterName)
{
object result;
var param =
// We don't use Element.GetOrderedParameters(), it only returns ordered parameters
// as show in the UI
InternalElement.Parameters.Cast<Autodesk.Revit.DB.Parameter>()
// Element.Parameters returns a differently ordered list on every invocation.
// We must sort it to get sensible results.
.OrderBy(x => x.Id.IntegerValue)
.FirstOrDefault(x => x.Definition.Name == parameterName);
if (param == null || !param.HasValue)
return string.Empty;
switch (param.StorageType)
{
case StorageType.ElementId:
int valueId = param.AsElementId().IntegerValue;
if (valueId > 0)
{
// When the element is obtained here, to convert it to our element wrapper, it
// need to be figured out whether this element is created by us. Here the existing
// element wrappers will be checked. If there is one, its property to specify
// whether it is created by us will be followed. If there is none, it means the
// element is not created by us.
var elem = ElementIDLifecycleManager<int>.GetInstance().GetFirstWrapper(valueId) as Element;
result = ElementSelector.ByElementId(valueId, elem == null ? true : elem.IsRevitOwned);
}
else
{
int paramId = param.Id.IntegerValue;
if (paramId == (int)BuiltInParameter.ELEM_CATEGORY_PARAM || paramId == (int)BuiltInParameter.ELEM_CATEGORY_PARAM_MT)
{
var categories = DocumentManager.Instance.CurrentDBDocument.Settings.Categories;
result = new Category(categories.get_Item((BuiltInCategory)valueId));
}
else
{
// For other cases, return a localized string
result = param.AsValueString();
}
}
break;
case StorageType.String:
result = param.AsString();
break;
case StorageType.Integer:
result = param.AsInteger();
break;
case StorageType.Double:
var paramType = param.Definition.ParameterType;
if (IsConvertableParameterType(paramType))
result = param.AsDouble() * UnitConverter.HostToDynamoFactor(
ParameterTypeToUnitType(paramType));
else
result = param.AsDouble();
break;
default:
throw new Exception(string.Format(Properties.Resources.ParameterWithoutStorageType, param));
}
return result;
}
/// <summary>
/// Override the element's color in the active view.
/// </summary>
/// <param name="color">The color to apply to a solid fill on the element.</param>
public Element OverrideColorInView(Color color)
{
TransactionManager.Instance.EnsureInTransaction(DocumentManager.Instance.CurrentDBDocument);
var view = DocumentManager.Instance.CurrentUIDocument.ActiveView;
var ogs = new OverrideGraphicSettings();
var patternCollector = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument);
patternCollector.OfClass(typeof(FillPatternElement));
FillPatternElement solidFill = patternCollector.ToElements().Cast<FillPatternElement>().First(x => x.GetFillPattern().IsSolidFill);
var overrideColor = new Autodesk.Revit.DB.Color(color.Red, color.Green, color.Blue);
ogs.SetProjectionFillColor(overrideColor);
ogs.SetProjectionFillPatternId(solidFill.Id);
ogs.SetProjectionLineColor(overrideColor);
view.SetElementOverrides(InternalElementId, ogs);
TransactionManager.Instance.TransactionTaskDone();
return this;
}
/// <summary>
/// Set one of the element's parameters.
/// </summary>
/// <param name="parameterName">The name of the parameter to set.</param>
/// <param name="value">The value.</param>
public Element SetParameterByName(string parameterName, object value)
{
var param = InternalElement.Parameters.Cast<Autodesk.Revit.DB.Parameter>().FirstOrDefault(x => x.Definition.Name == parameterName);
if (param == null)
throw new Exception(Properties.Resources.ParameterNotFound);
TransactionManager.Instance.EnsureInTransaction(DocumentManager.Instance.CurrentDBDocument);
var dynval = value as dynamic;
SetParameterValue(param, dynval);
TransactionManager.Instance.TransactionTaskDone();
return this;
}
#region dynamic parameter setting methods
private static void SetParameterValue(Autodesk.Revit.DB.Parameter param, double value)
{
if (param.StorageType != StorageType.Integer && param.StorageType != StorageType.Double)
throw new Exception(Properties.Resources.ParameterStorageNotNumber);
var valueToSet = GetConvertedParameterValue(param, value);
param.Set(valueToSet);
}
private static void SetParameterValue(Autodesk.Revit.DB.Parameter param, Element value)
{
if (param.StorageType != StorageType.ElementId)
throw new Exception(Properties.Resources.ParameterStorageNotElement);
param.Set(value.InternalElementId);
}
private static void SetParameterValue(Autodesk.Revit.DB.Parameter param, int value)
{
if (param.StorageType != StorageType.Integer && param.StorageType != StorageType.Double)
throw new Exception(Properties.Resources.ParameterStorageNotNumber);
var valueToSet = GetConvertedParameterValue(param, value);
param.Set(valueToSet);
}
private static void SetParameterValue(Autodesk.Revit.DB.Parameter param, string value)
{
if (param.StorageType != StorageType.String)
throw new Exception(Properties.Resources.ParameterStorageNotString);
param.Set(value);
}
private static void SetParameterValue(Autodesk.Revit.DB.Parameter param, bool value)
{
if (param.StorageType != StorageType.Integer)
throw new Exception(Properties.Resources.ParameterStorageNotInteger);
param.Set(value == false ? 0 : 1);
}
private static double GetConvertedParameterValue(Autodesk.Revit.DB.Parameter param, double value)
{
var paramType = param.Definition.ParameterType;
if (IsConvertableParameterType(paramType))
{
return value * UnitConverter.DynamoToHostFactor(ParameterTypeToUnitType(paramType));
}
return value;
}
#endregion
/// <summary>
/// Get all of the Geometry associated with this object
/// </summary>
public object[] Geometry()
{
var converted = new List<object>();
foreach (var geometryObject in InternalGeometry())
{
var geoObj = geometryObject.Convert();
if (geoObj != null)
{
converted.Add(geoObj);
}
else
{
var solid = geometryObject as Autodesk.Revit.DB.Solid;
if (solid != null)
{
var geomObjs = solid.ConvertToMany();
converted.AddRange(geomObjs.Where(x => { return x != null; }));
}
}
}
return converted.ToArray();
}
#region Geometry extraction
/// <summary>
/// Extract the Revit GeometryObject's from a Revit Element
/// </summary>
/// <returns></returns>
internal IEnumerable<Autodesk.Revit.DB.GeometryObject> InternalGeometry(bool useSymbolGeometry = false)
{
DocumentManager.Regenerate();
var thisElement = InternalElement;
var goptions0 = new Options { ComputeReferences = true };
var geomElement = thisElement.get_Geometry(goptions0);
// GenericForm is a special case
if ((thisElement is GenericForm) && (!geomElement.Any()))
{
var gF = (GenericForm)thisElement;
if (!gF.Combinations.IsEmpty)
{
var goptions1 = new Options
{
IncludeNonVisibleObjects = true,
ComputeReferences = true
};
geomElement = thisElement.get_Geometry(goptions1);
}
}
return CollectConcreteGeometry(geomElement, useSymbolGeometry);
}
/// <summary>
/// Collects the concrete GeometryObject's in a GeometryElement, which is a recursive collection of GeometryObject's.
/// </summary>
/// <param name="geometryElement">The Geometry collection</param>
/// <param name="useSymbolGeometry">When encountering a GeometryInstance, use GetSymbolGeometry() which obtains usable Reference objects</param>
/// <returns></returns>
private static IEnumerable<GeometryObject> CollectConcreteGeometry(GeometryElement geometryElement, bool useSymbolGeometry = false)
{
var instanceGeometryObjects = new List<GeometryObject>();
if (geometryElement == null) return instanceGeometryObjects;
foreach (GeometryObject geob in geometryElement)
{
var geomInstance = geob as GeometryInstance;
var geomElement = geob as GeometryElement;
if (geomInstance != null)
{
var instanceGeom = useSymbolGeometry ? geomInstance.GetSymbolGeometry() : geomInstance.GetInstanceGeometry();
instanceGeometryObjects.AddRange( CollectConcreteGeometry(instanceGeom) );
}
else if (geomElement != null)
{
instanceGeometryObjects.AddRange( CollectConcreteGeometry(geometryElement) );
}
else
{
instanceGeometryObjects.Add(geob);
}
}
// Certain kinds of Elements will return Solids with zero faces - make sure to filter them out
return
instanceGeometryObjects.Where(
x =>
!(x is Autodesk.Revit.DB.Solid) || (x as Autodesk.Revit.DB.Solid).Faces.Size > 0);
}
/// <summary>
/// A generic method extract all GeometryObject's of the supplied type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private IEnumerable<T> InternalGeometry<T>(bool useSymbolGeometry = false) where T : GeometryObject
{
return this.InternalGeometry(useSymbolGeometry).OfType<T>();
}
/// <summary>
/// The Solids in this Element
/// </summary>
public Autodesk.DesignScript.Geometry.Solid[] Solids
{
get
{
return
this.InternalGeometry<Autodesk.Revit.DB.Solid>()
.Select(x => x.ToProtoType())
.ToArray();
}
}
/// <summary>
/// The Curves in this Element
/// </summary>
public Curve[] Curves
{
get
{
// This is the correctly translated geometry, obtained from GetInstanceGeometry
var geoms = this.InternalGeometry<Autodesk.Revit.DB.Curve>();
// The is the geometry with the correctly computed References, from GetSymbolGeometry
var refs = InternalGeometry<Autodesk.Revit.DB.Curve>(true).Select(x => x.Reference);
return geoms.Zip( refs, (geom, reference) => geom.ToProtoType(true, reference))
.ToArray();
}
}
/// <summary>
/// The Faces in this Element
/// </summary>
public Surface[] Faces
{
get
{
// This is the correctly translated geometry, obtained from GetInstanceGeometry
var geoms = InternalGeometry<Autodesk.Revit.DB.Solid>()
.SelectMany(x => x.Faces.OfType<Autodesk.Revit.DB.Face>());
// The is the geometry with the correctly computed References, from GetSymbolGeometry
var refs = InternalGeometry<Autodesk.Revit.DB.Solid>(true)
.SelectMany(x => x.Faces.OfType<Autodesk.Revit.DB.Face>())
.Select(x => x.Reference);
return
geoms.Zip(refs, (geom, reference) => geom.ToProtoType(true, reference))
.SelectMany(x => x).ToArray();
}
}
/// <summary>
/// The ElementCurveReference's in this Element. Useful for downstream
/// Element creation.
/// </summary>
public ElementCurveReference[] ElementCurveReferences
{
get
{
return
this.InternalGeometry<Autodesk.Revit.DB.Curve>(true)
.Select(ElementCurveReference.FromExisting)
.ToArray();
}
}
/// <summary>
/// The ElementFaceReference's in this Element. Useful for downstream
/// Element creation.
/// </summary>
public ElementFaceReference[] ElementFaceReferences
{
get
{
return
this.InternalGeometry<Autodesk.Revit.DB.Solid>(true)
.SelectMany(x => x.Faces.OfType<Autodesk.Revit.DB.Face>())
.Select(ElementFaceReference.FromExisting)
.ToArray();
}
}
#endregion
/// <summary>
/// Is this element still alive in Revit, and good to be drawn, queried etc.
/// </summary>
protected bool IsAlive
{
get
{
if (InternalElementId == null)
{
return false;
}
//Ensure that the object is still alive
//Check whether the internal element Id is null
if (null == InternalElementId)
return false;
return !ElementIDLifecycleManager<int>.GetInstance().IsRevitDeleted(InternalElementId.IntegerValue);
}
}
}
}