-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathPathOfTravel.cs
More file actions
571 lines (470 loc) · 21.8 KB
/
PathOfTravel.cs
File metadata and controls
571 lines (470 loc) · 21.8 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.DesignScript.Runtime;
using Autodesk.Revit.DB;
using Dynamo.Graph.Nodes;
using Revit.GeometryConversion;
using RevitServices.Persistence;
using RevitServices.Transactions;
using Rvt = Autodesk.Revit.DB;
using RvtAnalysis = Autodesk.Revit.DB.Analysis;
namespace Revit.Elements
{
/// <summary>
/// PathOfTravel Element.
/// </summary>
[DynamoServices.RegisterForTrace]
public class PathOfTravel : Element
{
#region Internal properties
/// <summary>
/// An internal handle on the Revit PathOfTravel element.
/// </summary>
RvtAnalysis.PathOfTravel m_rvtPathOfTravel = null;
/// <summary>
/// Reference to Revit PathOfTravel Element.
/// </summary>
[SupressImportIntoVM]
public override Rvt.Element InternalElement
{
get { return m_rvtPathOfTravel; }
}
#endregion
#region Private constructors
/// <summary>
/// PathOfTravel from existing
/// </summary>
/// <param name="rvtPathOfTravel">Revit PathOfTavel element</param>
private PathOfTravel(RvtAnalysis.PathOfTravel rvtPathOfTravel)
{
SafeInit(() => InitPathOfTravel(rvtPathOfTravel), true);
}
#endregion
#region Public constructors
/// <summary>
/// Calculates the longest PathOfTravel(s) of all shortest paths from rooms in the floor plan to the specified exit points.
/// </summary>
/// <param name="floorPlan">Floor plan view for which rooms will be used to retrieve longest paths to the specified exit points.</param>
/// <param name="endPtsList">List of end (exit) points.</param>
/// <returns>List of PathOfTravel elements corresponding to the longest of shortest exit paths from rooms.</returns>
[NodeCategory("Create")]
[AllowRankReduction]
public static PathOfTravel[] LongestOfShortestExitPaths(Revit.Elements.Views.FloorPlanView floorPlan, Autodesk.DesignScript.Geometry.Point[] endPtsList)
{
if (floorPlan == null)
throw new ArgumentNullException("floorPlan", Properties.Resources.InvalidView);
if (endPtsList == null)
throw new ArgumentNullException("endPtsList", Properties.Resources.InvalidEndPointList);
if (!endPtsList.Any())
throw new ArgumentException(Properties.Resources.EndPointListEmpty, "endPtsList");
if (endPtsList.Any(x => x == null))
throw new ArgumentException(Properties.Resources.EndPointListHasNulls, "endPtsList");
// Check that floor has some rooms
Rvt.Document doc = DocumentManager.Instance.CurrentDBDocument;
if(doc == null)
{
throw new ArgumentException(Properties.Resources.RoomsForLongestPathNotFound);
}
FilteredElementCollector collector = new Rvt.FilteredElementCollector(doc).OfCategory(Rvt.BuiltInCategory.OST_Rooms);
if(collector.ToElements().Count() == 0)
{
throw new ArgumentException(Properties.Resources.RoomsForLongestPathNotFound);
}
return InternalLongestOfShortestExitPaths(
(Rvt.View)floorPlan.InternalElement,
endPtsList.Select(x => x.ToXyz()));
}
/// <summary>
/// Constructs a list of PathOfTravel elements in a floor plan view between the specified start points and end points.
/// </summary>
/// <param name="floorPlan">Floor plan view to place paths of travel on</param>
/// <param name="startPtsList">List of start points</param>
/// <param name="endPtsList">List of end points</param>
/// <param name="manyToMany">If true, paths are created from every point in the start point list to all points in the end point list. If false, a path is created from every point in the start point list to a corresponding point in the end point list with the same index. The two lists must have the same size when not creating many-to-many paths.</param>
/// <returns>List of PathOfTravel elements; can contain null elements if there is no path between some points.</returns>
[NodeCategory("Create")]
[AllowRankReduction]
public static PathOfTravel[] ByFloorPlanPoints(Revit.Elements.Views.FloorPlanView floorPlan, Autodesk.DesignScript.Geometry.Point[] startPtsList, Autodesk.DesignScript.Geometry.Point[] endPtsList, bool manyToMany)
{
if (floorPlan == null)
throw new ArgumentNullException(Properties.Resources.InvalidView);
if (startPtsList == null)
throw new ArgumentNullException(Properties.Resources.InvalidStartPointList);
if (endPtsList == null)
throw new ArgumentNullException(Properties.Resources.InvalidEndPointList);
if (!startPtsList.Any())
throw new ArgumentNullException(Properties.Resources.StartPointListEmpty);
if (!endPtsList.Any())
throw new ArgumentNullException(Properties.Resources.EndPointListEmpty);
if (startPtsList.Any(x => x == null))
throw new ArgumentException(Properties.Resources.StartPointListHasNulls);
if (endPtsList.Any(x => x == null))
throw new ArgumentException(Properties.Resources.EndPointListHasNulls);
if (!manyToMany && (startPtsList.Count() != endPtsList.Count()))
throw new ArgumentException(Properties.Resources.StartEndListSizeMismatch);
if (manyToMany)
{
// although there is the many-to-many version of PathOfTravel creation API (the "mapped" version), the fact that some elements
// need to be reused between the node runs makes it difficult to use (see UpdateReusedElements, DeleteExtraElements and CreateAdditionalElements)
// so it's easier to flatten the lists manually and always use the same ("non-mapped") version of the API
List<Autodesk.DesignScript.Geometry.Point> newStartPointList = new List<Autodesk.DesignScript.Geometry.Point>();
List<Autodesk.DesignScript.Geometry.Point> newEndPointList = new List<Autodesk.DesignScript.Geometry.Point>();
foreach(var endPt in endPtsList)
{
foreach(var startPt in startPtsList)
{
newStartPointList.Add(startPt);
newEndPointList.Add(endPt);
}
}
startPtsList = newStartPointList.ToArray();
endPtsList = newEndPointList.ToArray();
}
return InternalByViewEndPoints(
(Rvt.View)floorPlan.InternalElement,
startPtsList.Select(x => x.ToXyz()),
endPtsList.Select(x => x.ToXyz()));
}
#endregion
#region Public methods
/// <summary>
/// Returns the WayPoints set from PathOfTravel element.
/// </summary>
/// <returns>List of WayPoints for the given PathOfTravel element.</returns>
[NodeCategory("Query")]
[AllowRankReduction]
public IList<XYZ> GetWayPoints()
{
if (m_rvtPathOfTravel is null)
throw new ArgumentException(Properties.Resources.InvalidPathOfTravel);
return m_rvtPathOfTravel.GetWaypoints();
}
/// <summary>
/// Removes WayPoint at the specified index from PathOfTravel element.
/// </summary>
/// <param name="index">Index of the WayPoint to be removed from the PathOfTravel element.</param>
/// <returns>The PathOfTravel element after the WayPoint was rmnoved.</returns>
[NodeCategory("Action")]
[AllowRankReduction]
public PathOfTravel RemoveWayPoint(int index)
{
if (m_rvtPathOfTravel is null)
throw new ArgumentException(Properties.Resources.InvalidPathOfTravel);
TransactionManager.Instance.EnsureInTransaction(Document);
m_rvtPathOfTravel.RemoveWaypoint(index);
TransactionManager.Instance.TransactionTaskDone();
return this;
}
/// <summary>
/// Inserts a WayPoint to PathOfTravel element at the specified index.
/// </summary>
/// <param name="wayPoint">The waypoint to insert.</param>
/// <param name="index">The index to insert the waypoint at.</param>
/// <returns>The PathOfTravel element after the WayPoint was inserted.</returns>
[NodeCategory("Action")]
[AllowRankReduction]
public PathOfTravel InsertWayPoint(Autodesk.DesignScript.Geometry.Point wayPoint, int index)
{
if (wayPoint is null)
throw new ArgumentNullException("wayPoint", Properties.Resources.PointRequired); //Please supply a point geometry.
if (m_rvtPathOfTravel is null)
throw new ArgumentException(Properties.Resources.InvalidPathOfTravel);
TransactionManager.Instance.EnsureInTransaction(Document);
m_rvtPathOfTravel.InsertWaypoint(wayPoint.ToXyz(), index);
TransactionManager.Instance.TransactionTaskDone();
return this;
}
/// <summary>
/// Updates WayPoint at the specified index to the new specified position.
/// </summary>
/// <param name="newPosition">The position to which WayPoint will be set.</param>
/// <param name="index">The index of WayPoint to update.</param>
/// <returns>The PathOfTravel element after the WayPoint was set.</returns>
[NodeCategory("Action")]
[AllowRankReduction]
public PathOfTravel SetWayPoint(Autodesk.DesignScript.Geometry.Point newPosition, int index)
{
if (newPosition is null)
throw new ArgumentNullException("newPosition", Properties.Resources.PointRequired); //Please supply a point geometry.
if (m_rvtPathOfTravel is null)
throw new ArgumentException(Properties.Resources.InvalidPathOfTravel);
TransactionManager.Instance.EnsureInTransaction(Document);
m_rvtPathOfTravel.SetWaypoint(newPosition.ToXyz(), index);
TransactionManager.Instance.TransactionTaskDone();
return this;
}
/// <summary>
/// Updates existing PathOfTravel.
/// </summary>
public static PathOfTravel[] Update(PathOfTravel[] elements)
{
List<PathOfTravel> updatedElements = new List<PathOfTravel>();
TransactionManager.Instance.EnsureInTransaction(Document);
IList<RvtAnalysis.PathOfTravelCalculationStatus> statuses;
RvtAnalysis.PathOfTravel.UpdateMultiple(Document, elements.Select(x => x.InternalElementId).ToList(), out statuses);
if(statuses != null)
{
int ii = 0;
foreach(var status in statuses)
{
if (status == RvtAnalysis.PathOfTravelCalculationStatus.Success)
updatedElements.Add(elements[ii]);
else
Document.Delete(elements[ii].InternalElementId);
++ii;
}
}
TransactionManager.Instance.TransactionTaskDone();
return updatedElements.ToArray();
}
#endregion
#region Private helpers
/// <summary>
/// Create from existing
/// </summary>
/// <param name="rvtPathOfTravel">Existing Revit PathOfTravel element</param>
/// <param name="isRevitOwned"></param>
/// <returns></returns>
internal static PathOfTravel FromExisting(RvtAnalysis.PathOfTravel rvtPathOfTravel, bool isRevitOwned)
{
return new PathOfTravel(rvtPathOfTravel)
{
IsRevitOwned = isRevitOwned
};
}
/// <summary>
/// [INTERNAL]: Calculates the longest PathOfTravel of all shortest paths from rooms in the floor plan to given exit points.
/// </summary>
/// <param name="rvtView">Floor plan view for which rooms will be used to retrieve longest paths to the given exit points.</param>
/// <param name="endPoints">List of end (exit) points.</param>
/// <returns>List of PathOfTravel elements corresponding to the longest of shortest exit paths from rooms.</returns>
///
private static PathOfTravel[] InternalLongestOfShortestExitPaths(Rvt.View rvtView, IEnumerable<XYZ> endPoints)
{
List<PathOfTravel> pathsOfTravel = new List<PathOfTravel>();
if(TransactionManager.Instance.DisableTransactions)
{
IEnumerable<RvtAnalysis.PathOfTravel> persistRvtElements = ElementBinder.GetElementsFromTrace<RvtAnalysis.PathOfTravel>(Document);
if(persistRvtElements != null)
{
foreach (var ele in persistRvtElements)
{
var persisEle = new PathOfTravel(ele);
pathsOfTravel.Add(persisEle);
}
return pathsOfTravel.ToArray();
}
}
TransactionManager.Instance.EnsureInTransaction(Document);
try
{
IList<XYZ> startsOfLongestPathsFromRooms = RvtAnalysis.PathOfTravel.FindStartsOfLongestPathsFromRooms(
rvtView,
endPoints.ToList());
if (startsOfLongestPathsFromRooms.Count() != 0)
{
IList<XYZ> endsOfShortestPaths = RvtAnalysis.PathOfTravel.FindEndsOfShortestPaths(
rvtView,
endPoints.ToList(),
startsOfLongestPathsFromRooms);
IList<RvtAnalysis.PathOfTravel> newRvtPathOfTravels = RvtAnalysis.PathOfTravel.CreateMultiple(
rvtView,
startsOfLongestPathsFromRooms.ToList(),
endsOfShortestPaths.ToList());
foreach (RvtAnalysis.PathOfTravel rvtPathOfTravel in newRvtPathOfTravels)
{
if (rvtPathOfTravel != null)
{
pathsOfTravel.Add(new PathOfTravel(rvtPathOfTravel));
}
}
ElementBinder.SetElementsForTrace(pathsOfTravel.Where(x => x != null).Select(x => x.InternalElement));
}
}
catch (Exception e)
{
//unregister the elements from the element life cycle manager and delete the elements
var elementManager = ElementIDLifecycleManager<int>.GetInstance();
if (pathsOfTravel != null)
{
foreach (var path in pathsOfTravel)
{
if (path != null)
{
elementManager.UnRegisterAssociation(path.InternalElementId.IntegerValue, path);
Document.Delete(path.InternalElementId);
}
}
}
throw e;
}
finally
{
TransactionManager.Instance.TransactionTaskDone();
}
return pathsOfTravel.ToArray();
}
/// <summary>
/// Construct a new Revit PathOfTravel in a floor plan view between the specified start point and end point
/// </summary>
/// <param name="rvtView"></param>
/// <param name="startPoints"></param>
/// <param name="endPoints"></param>
/// <returns></returns>
private static PathOfTravel[] InternalByViewEndPoints(Rvt.View rvtView, IEnumerable<XYZ> startPoints, IEnumerable<XYZ> endPoints)
{
List<PathOfTravel> pathsOfTravel = new List<PathOfTravel>();
if(TransactionManager.Instance.DisableTransactions)
{
IEnumerable<RvtAnalysis.PathOfTravel> persistRvtElements = ElementBinder.GetElementsFromTrace<RvtAnalysis.PathOfTravel>(Document);
if(persistRvtElements != null)
{
foreach (var ele in persistRvtElements)
{
var persisEle = new PathOfTravel(ele);
pathsOfTravel.Add(persisEle);
}
return pathsOfTravel.ToArray();
}
}
TransactionManager.Instance.EnsureInTransaction(Document);
try
{
// get previously created elements
IEnumerable<RvtAnalysis.PathOfTravel> existingRvtElements = ElementBinder.GetElementsFromTrace<RvtAnalysis.PathOfTravel>(Document);
// update elements that can be reused
IList<PathOfTravel> updatedPathsOfTravel = UpdateReusedElements(existingRvtElements, startPoints, endPoints);
pathsOfTravel.AddRange(updatedPathsOfTravel);
// delete elements that are not needed anymore
DeleteExtraElements(existingRvtElements, startPoints, endPoints);
// create additional elements
IList<PathOfTravel> newPathsOfTravel = CreateAdditionalElements(rvtView, existingRvtElements, startPoints, endPoints);
pathsOfTravel.AddRange(newPathsOfTravel);
ElementBinder.SetElementsForTrace(pathsOfTravel.Where(x => x != null).Select(x => x.InternalElement));
}
catch (Exception e)
{
// unregister the elements from the element life cycle manager and delete the elements
var elementManager = ElementIDLifecycleManager<int>.GetInstance();
if (pathsOfTravel != null)
{
foreach (var path in pathsOfTravel)
{
if (path != null)
{
elementManager.UnRegisterAssociation(path.InternalElementId.IntegerValue, path);
Document.Delete(path.InternalElementId);
}
}
}
throw e;
}
finally
{
TransactionManager.Instance.TransactionTaskDone();
}
return pathsOfTravel.ToArray();
}
static List<PathOfTravel> UpdateReusedElements(IEnumerable<RvtAnalysis.PathOfTravel> existingRvtElements, IEnumerable<XYZ> newStartPoints, IEnumerable<XYZ> newEndPoints)
{
List<PathOfTravel> updatedPathsOfTravel = new List<PathOfTravel>();
if ((existingRvtElements == null) || (existingRvtElements.Count() == 0))
{
// no elements to update
return updatedPathsOfTravel;
}
int existingCount = existingRvtElements.Count();
int requestedCount = newStartPoints.Count();
int elementsToReuse = Math.Min(existingCount, requestedCount);
// update elements that can be reused (set new start and endpoint)
if (elementsToReuse > 0)
{
for (int ii = 0; ii < elementsToReuse; ++ii)
{
existingRvtElements.ElementAt(ii).PathStart = newStartPoints.ElementAt(ii);
existingRvtElements.ElementAt(ii).PathEnd = newEndPoints.ElementAt(ii);
}
IList<RvtAnalysis.PathOfTravelCalculationStatus> statuses = null;
RvtAnalysis.PathOfTravel.UpdateMultiple(
Document,
existingRvtElements.Take(elementsToReuse).Select(x => x.Id).ToList(),
out statuses);
for (int ii = 0; ii < elementsToReuse; ++ii)
{
if (statuses[ii] == RvtAnalysis.PathOfTravelCalculationStatus.Success)
{
updatedPathsOfTravel.Add(new PathOfTravel(existingRvtElements.ElementAt(ii)));
}
else
{
Document.Delete(existingRvtElements.ElementAt(ii).Id);
updatedPathsOfTravel.Add(null);
}
}
}
return updatedPathsOfTravel;
}
static void DeleteExtraElements(IEnumerable<RvtAnalysis.PathOfTravel> existingRvtElements, IEnumerable<XYZ> newStartPoints, IEnumerable<XYZ> newEndPoints)
{
if ((existingRvtElements == null) || (existingRvtElements.Count() == 0))
{
// no elements to delete
return;
}
int existingCount = existingRvtElements.Count();
int requestedCount = newStartPoints.Count();
int elementsToDelete = Math.Max(existingCount - requestedCount, 0);
// delete elements that are not needed anymore (if the currently requested
// number of paths is smaller than previously created elements)
if (elementsToDelete > 0)
{
for (int ii = 0; ii < elementsToDelete; ++ii)
{
Document.Delete(existingRvtElements.ElementAt(existingCount - 1 - ii).Id);
}
}
}
static List<PathOfTravel> CreateAdditionalElements(Rvt.View rvtView, IEnumerable<RvtAnalysis.PathOfTravel> existingRvtElements, IEnumerable<XYZ> newStartPoints, IEnumerable<XYZ> newEndPoints)
{
List<PathOfTravel> newPathsOfTravel = new List<PathOfTravel>();
int existingCount = existingRvtElements == null ? 0 : existingRvtElements.Count();
int requestedCount = newStartPoints.Count();
int elementsToCreate = Math.Max(requestedCount - existingCount, 0);
// create additional elements (if the currently requested number of paths
// is greater than number of previously created elements)
if (elementsToCreate > 0)
{
IList<RvtAnalysis.PathOfTravel> newRvtElements = RvtAnalysis.PathOfTravel.CreateMultiple(
rvtView,
newStartPoints.Skip(existingCount).ToList(),
newEndPoints.Skip(existingCount).ToList());
foreach (RvtAnalysis.PathOfTravel rvtElement in newRvtElements)
{
if (rvtElement != null)
{
newPathsOfTravel.Add(new PathOfTravel(rvtElement));
}
else
{
newPathsOfTravel.Add(null);
}
}
}
return newPathsOfTravel;
}
/// <summary>
/// Initialize a PathOfTravel element from existing Revit element.
/// </summary>
private void InitPathOfTravel(RvtAnalysis.PathOfTravel rvtPathOfTravel)
{
m_rvtPathOfTravel = rvtPathOfTravel;
if (m_rvtPathOfTravel != null)
{
this.InternalElementId = m_rvtPathOfTravel.Id;
this.InternalUniqueId = m_rvtPathOfTravel.UniqueId;
}
}
#endregion
}
}