프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 8701de36

이력 | 보기 | 이력해설 | 다운로드 (182 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Data;
7
using Llama;
8
using Plaice;
9
using Ingr.RAD2D.Interop.RAD2D;
10
using Ingr.RAD2D.Internal;
11
using Ingr.RAD2D.Helper;
12
using Converter.BaseModel;
13
using Converter.SPPID.Model;
14
using Converter.SPPID.Properties;
15
using Converter.SPPID.Util;
16
using Converter.SPPID.DB;
17
using Ingr.RAD2D.MacroControls.CmdCtrl;
18
using Ingr.RAD2D;
19
using System.Windows;
20
using System.Threading;
21
using System.Drawing;
22
using Microsoft.VisualBasic;
23
using Newtonsoft.Json;
24
using DevExpress.XtraSplashScreen;
25
namespace Converter.SPPID
26
{
27
    public class AutoModeling
28
    {
29
        Placement _placement;
30
        LMADataSource dataSource;
31
        LMDrawing currentDrawing;
32
        dynamic newDrawing;
33
        dynamic application;
34
        Ingr.RAD2D.Application radApp;
35
        SPPID_Document document;
36
        ETCSetting _ETCSetting;
37

    
38
        public string DocumentLabelText { get; set; }
39

    
40
        List<Line> BranchLines = new List<Line>();
41
        List<string> ZeroLengthSymbolToSymbolModelItemID = new List<string>();
42
        List<string> ZeroLengthModelItemID = new List<string>();
43
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
44
        List<Symbol> prioritySymbols;
45

    
46
        public AutoModeling(SPPID_Document document, dynamic application, Ingr.RAD2D.Application radApp)
47
        {
48
            this.document = document;
49
            this.application = application;
50
            this.radApp = radApp;
51
            this._ETCSetting = ETCSetting.GetInstance();
52
        }
53

    
54
        private void SetSystemEditingCommand(bool value)
55
        {
56
            foreach (var item in radApp.Commands)
57
            {
58
                if (item.Argument == "SystemEditingCmd.SystemEditing")
59
                {
60
                    if (item.Checked != value)
61
                    {
62
                        radApp.RunMacro("systemeditingcmd.dll");
63
                        break;
64
                    }
65

    
66
                }
67
            }
68
        }
69

    
70
        /// <summary>
71
        /// 도면 단위당 실행되는 메서드
72
        /// </summary>
73
        public void Run()
74
        {
75
            string drawingNumber = document.DrawingNumber;
76
            string drawingName = document.DrawingName;
77
            try
78
            {
79
                _placement = new Placement();
80
                dataSource = _placement.PIDDataSource;
81

    
82
                CreateDocument(ref drawingNumber, ref drawingName);
83

    
84
                if (DocumentCoordinateCorrection())
85
                {
86
                    Log.Write("Start Modeling");
87
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
88
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
89
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 17);
90
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
91

    
92
                    // Equipment Modeling
93
                    RunEquipmentModeling();
94
                    // Symbol Modeling
95
                    RunSymbolModeling();
96
                    // LineRun Line Modeling
97
                    RunLineModeling();
98
                    // Branch Line Modeling
99
                    RunBranchLineModeling();
100
                    // Clear Attribute
101
                    RunClearValueInconsistancy();
102
                    // EndBreak Modeling
103
                    RunEndBreakModeling();
104
                    // SpecBreak Modeling
105
                    RunSpecBreakModeling();
106
                    // Join SameConnector
107
                    RunJoinRunForSameConnector();
108
                    // Check FlowDirection
109
                    RunFlowDirection();
110
                    // Join Run
111
                    RunJoinRun();
112
                    //Line Number Modeling
113
                    RunLineNumberModeling();
114
                    // Note Modeling
115
                    RunNoteModeling();
116
                    // Text Modeling
117
                    RunTextModeling();
118
                    // Input LineNumber Attribute
119
                    RunInputLineNumberAttribute();
120
                    // Input Symbol Attribute
121
                    RunInputSymbolAttribute();
122
                    // Input SpecBreak Attribute
123
                    RunInputSpecBreakAttribute();
124
                    // Label Symbol Modeling
125
                    RunLabelSymbolModeling();
126

    
127
                    // Result Logging
128
                    document.CheckModelingResult();
129
                }
130
            }
131
            catch (Exception ex)
132
            {
133
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
134
                SplashScreenManager.CloseForm(false);
135
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
136
            }
137
            finally
138
            {
139
                Log.Write("End Modeling");
140
                application.ActiveWindow.Fit();
141

    
142
                if (currentDrawing != null)
143
                    ReleaseCOMObjects(currentDrawing);
144

    
145
                if (radApp.ActiveDocument != null)
146
                {
147
                    radApp.ActiveDocument.Save();
148
                    ReleaseCOMObjects(newDrawing);
149
                }
150

    
151
                ReleaseCOMObjects(dataSource);
152
                ReleaseCOMObjects(_placement);
153

    
154
                Project_DB.InsertDrawingInfo(document.PATH, drawingNumber, drawingName, document);
155
                if (SplashScreenManager.Default.IsSplashFormVisible)
156
                {
157
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
158
                    SplashScreenManager.CloseForm(false);
159
                    Log.Write("\r\n");
160
                }
161
            }
162
        }
163
        private void RunEquipmentModeling()
164
        {
165
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
166
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
167
            foreach (Equipment item in document.Equipments)
168
            {
169
                try
170
                {
171
                    EquipmentModeling(item);
172
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
173
                }
174
                catch (Exception ex)
175
                {
176
                    Log.Write("Error in EquipmentModeling");
177
                    Log.Write("UID : " + item.UID);
178
                    Log.Write(ex.Message);
179
                    Log.Write(ex.StackTrace);
180
                }
181
            }
182
        }
183
        private void RunSymbolModeling()
184
        {
185
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
186
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
187
            prioritySymbols = GetPrioritySymbol();
188
            foreach (var item in prioritySymbols)
189
            {
190
                try
191
                {
192
                    SymbolModelingBySymbol(item);
193
                }
194
                catch (Exception ex)
195
                {
196
                    Log.Write("Error in SymbolModelingByPriority");
197
                    Log.Write("UID : " + item.UID);
198
                    Log.Write(ex.Message);
199
                    Log.Write(ex.StackTrace);
200
                }
201
            }
202
        }
203
        private void RunLineModeling()
204
        {
205
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
206
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Lines Modeling");
207
            SetPriorityLine();
208
            foreach (var item in document.LINES)
209
            {
210
                try
211
                {
212
                    NewLineModeling(item);
213
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
214
                }
215
                catch (Exception ex)
216
                {
217
                    Log.Write("Error in NewLineModeling");
218
                    Log.Write("UID : " + item.UID);
219
                    Log.Write(ex.Message);
220
                    Log.Write(ex.StackTrace);
221
                }
222
            }
223
        }
224
        private void RunBranchLineModeling()
225
        {
226
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
227
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Branch Lines Modeling");
228
            int branchCount = BranchLines.Count;
229
            while (BranchLines.Count > 0)
230
            {
231
                try
232
                {
233
                    SortBranchLines();
234
                    Line item = BranchLines[0];
235
                    if (EnableBranchModeling(item))
236
                    {
237
                        NewLineModeling(item, true);
238
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
239
                    }
240
                    else
241
                        throw new Exception("Fail Branch Modeling");
242
                }
243
                catch (Exception ex)
244
                {
245
                    Log.Write("Error in NewLineModeling");
246
                    Log.Write("UID : " + BranchLines[0].UID);
247
                    Log.Write(ex.Message);
248
                    Log.Write(ex.StackTrace);
249
                    break;
250
                }
251
            }
252

    
253
            bool EnableBranchModeling(Line line)
254
            {
255
                bool result = true;
256
                if (line.CONNECTORS.FindAll(x => x.ConnectedObject != null && 
257
                x.ConnectedObject.GetType() == typeof(Line) && 
258
                string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count > 0)
259
                    result = false;
260

    
261
                return result;
262
            }
263
        }
264
        private void RunClearValueInconsistancy()
265
        {
266
            int count = 1;
267
            bool loop = true;
268
            while (loop)
269
            {
270
                loop = false;
271
                LMAFilter filter = new LMAFilter();
272
                LMACriterion criterion = new LMACriterion();
273
                filter.ItemType = "Relationship";
274
                criterion.SourceAttributeName = "SP_DRAWINGID";
275
                criterion.Operator = "=";
276
                criterion.set_ValueAttribute(currentDrawing.Id);
277
                filter.get_Criteria().Add(criterion);
278

    
279
                LMRelationships relationships = new LMRelationships();
280
                relationships.Collect(dataSource, Filter: filter);
281

    
282
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
283
                if (count > 1)
284
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
285
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
286
                foreach (LMRelationship relationship in relationships)
287
                {
288
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
289
                    {
290
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
291
                        {
292
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
293
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
294
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
295
                            if (modelItem1 != null)
296
                            {
297
                                string attrName = array[0];
298
                                if (attrName.Contains("PipingPoint"))
299
                                {
300
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
301
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
302
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
303
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
304
                                    {
305
                                        loop = true;
306
                                        attribute1.set_Value(DBNull.Value);
307
                                    }
308
                                }
309
                                else
310
                                {
311
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
312
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
313
                                    {
314
                                        loop = true;
315
                                        attribute1.set_Value(DBNull.Value);
316
                                    }
317
                                }
318
                                modelItem1.Commit();
319
                            }
320
                            if (modelItem2 != null)
321
                            {
322
                                string attrName = array[1];
323
                                if (attrName.Contains("PipingPoint"))
324
                                {
325
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
326
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
327
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
328
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
329
                                    {
330
                                        attribute2.set_Value(DBNull.Value);
331
                                        loop = true;
332
                                    }
333
                                }
334
                                else
335
                                {
336
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
337
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
338
                                    {
339
                                        attribute2.set_Value(DBNull.Value);
340
                                        loop = true;
341
                                    }
342
                                }
343
                                modelItem2.Commit();
344
                            }
345
                            if (modelItem1 != null)
346
                                ReleaseCOMObjects(modelItem1);
347
                            if (modelItem2 != null)
348
                                ReleaseCOMObjects(modelItem2);
349
                            inconsistency.Commit();
350
                        }
351
                    }
352
                    relationship.Commit();
353
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
354
                }
355
                ReleaseCOMObjects(filter);
356
                ReleaseCOMObjects(criterion);
357
                ReleaseCOMObjects(relationships);
358
                count++;
359
            }
360
        }
361
        private void RunEndBreakModeling()
362
        {
363
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
364
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
365
            foreach (var item in document.EndBreaks)
366
                try
367
                {
368
                    EndBreakModeling(item);
369
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
370
                }
371
                catch (Exception ex)
372
                {
373
                    Log.Write("Error in EndBreakModeling");
374
                    Log.Write("UID : " + item.UID);
375
                    Log.Write(ex.Message);
376
                    Log.Write(ex.StackTrace);
377
                }
378
        }
379
        private void RunSpecBreakModeling()
380
        {
381
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
382
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
383
            foreach (var item in document.SpecBreaks)
384
                try
385
                {
386
                    SpecBreakModeling(item);
387
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
388
                }
389
                catch (Exception ex)
390
                {
391
                    Log.Write("Error in SpecBreakModeling");
392
                    Log.Write("UID : " + item.UID);
393
                    Log.Write(ex.Message);
394
                    Log.Write(ex.StackTrace);
395
                }
396
        }
397
        private void RunJoinRunForSameConnector()
398
        {
399
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
400
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
401
            foreach (var line in document.LINES)
402
            {
403
                if (!SPPIDUtil.IsSegmentLine(document, line))
404
                {
405
                    foreach (var connector in line.CONNECTORS)
406
                    {
407
                        if (connector.ConnectedObject != null &&
408
                            connector.ConnectedObject.GetType() == typeof(Line) &&
409
                            !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
410
                        {
411
                            Line connLine = connector.ConnectedObject as Line;
412
                            if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(connLine.SPPID.ModelItemId))
413
                            {
414
                                string survivorId = string.Empty;
415
                                JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
416
                            }
417
                                
418
                        }
419
                    }
420
                }
421
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
422
            }
423
        }
424
        private void RunJoinRun()
425
        {
426
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
427
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
428
            List<string> endModelID = new List<string>();
429
            foreach (var line in document.LINES)
430
            {
431
                if (!endModelID.Contains(line.SPPID.ModelItemId))
432
                {
433
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
434
                    {
435
                        string survivorId = string.Empty;
436
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
437
                        if (string.IsNullOrEmpty(survivorId))
438
                        {
439
                            endModelID.Add(line.SPPID.ModelItemId);
440
                        }
441
                    }
442
                }
443
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
444
            }
445
        }
446
        private void RunLineNumberModeling()
447
        {
448
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
449
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
450
            foreach (var item in document.LINENUMBERS)
451
            {
452
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
453
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
454
                {
455
                    ReleaseCOMObjects(label);
456
                    item.SPPID.RepresentationId = null;
457
                    LineNumberModeling(item);
458
                }
459
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
460
            }
461
        }
462
        private void RunFlowDirection()
463
        {
464
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 
465
                document.LINES.Count + ZeroLengthModelItemID.Count + ZeroLengthModelItemIDReverse.Count + ZeroLengthSymbolToSymbolModelItemID.Count);
466
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Check Flow Direction");
467
            foreach (var line in document.LINES)
468
            {
469
                if (!string.IsNullOrEmpty(line.SPPID.ModelItemId))
470
                {
471
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
472
                    if (modelItem != null && modelItem.get_ItemStatus() == "Active")
473
                    {
474
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
475
                        if (attribute != null)
476
                        {
477
                            attribute.set_Value("End 1 is upstream (Inlet)");
478
                            modelItem.Commit();
479
                        }
480

    
481
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
482

    
483
                        ReleaseCOMObjects(modelItem);
484
                    }
485
                }
486

    
487
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
488
            }
489
            foreach (var modelId in ZeroLengthModelItemID)
490
            {
491
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
492
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
493
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
494
                {
495
                    attribute.set_Value("End 1 is upstream (Inlet)");
496
                    zeroLengthModelItem.Commit();
497
                }
498

    
499
                SetFlowDirectionByLine(modelId);
500

    
501
                ReleaseCOMObjects(zeroLengthModelItem);
502
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
503
            }
504
            foreach (var modelId in ZeroLengthModelItemIDReverse)
505
            {
506
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
507
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
508
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
509
                {
510
                    attribute.set_Value("End 1 is downstream (Outlet)");
511
                    zeroLengthModelItem.Commit();
512
                }
513

    
514
                SetFlowDirectionByLine(modelId);
515

    
516
                ReleaseCOMObjects(zeroLengthModelItem);
517
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
518
            }
519
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
520
            {
521
                SetFlowDirectionByLine(modelId);
522
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
523
            }
524

    
525
            void SetFlowDirectionByLine(string lineModelItemID)
526
            {
527
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
528
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
529
                {
530
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
531
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
532
                    {
533
                        string sFlowDirection = attribute.get_Value().ToString();
534
                        foreach (LMRepresentation rep in modelItem.Representations)
535
                        {
536
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
537
                            {
538
                                LMConnector connector = dataSource.GetConnector(rep.Id);
539

    
540
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
541
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
542
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
543
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
544

    
545
                                ReleaseCOMObjects(connector);
546
                            }
547
                        }
548
                    }
549
                    ReleaseCOMObjects(modelItem);
550
                }
551

    
552
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
553
                {
554
                    // Item2가 Symbol
555
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
556
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
557
                    {
558
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
559
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
560
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
561

    
562
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
563

    
564
                        symbolModelItem.Commit();
565
                        ReleaseCOMObjects(symbolModelItem);
566
                    }
567
                    // Item1이 Symbol
568
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
569
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
570
                    {
571
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
572
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
573
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
574

    
575
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
576

    
577
                        symbolModelItem.Commit();
578
                        ReleaseCOMObjects(symbolModelItem);
579
                    }
580
                }
581

    
582
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
583
                {
584
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
585
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
586
                    if (attribute != null)
587
                    {
588
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
589
                            attribute.set_Value("End 1 is downstream (Outlet)");
590
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
591
                            attribute.set_Value("End 1 is upstream (Inlet)");
592
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
593
                            attribute.set_Value("End 1 is upstream (Inlet)");
594
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
595
                            attribute.set_Value("End 1 is downstream (Outlet)");
596
                    }
597
                }
598
            }
599
        }
600
        private void RunNoteModeling()
601
        {
602
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
603
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
604
            foreach (var item in document.NOTES)
605
                try
606
                {
607
                    NoteModeling(item);
608
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
609
                }
610
                catch (Exception ex)
611
                {
612
                    Log.Write("Error in NoteModeling");
613
                    Log.Write("UID : " + item.UID);
614
                    Log.Write(ex.Message);
615
                    Log.Write(ex.StackTrace);
616
                }
617
        }
618
        private void RunTextModeling()
619
        {
620
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
621
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
622
            foreach (var item in document.TEXTINFOS)
623
                try
624
                {
625
                    TextModeling(item);
626
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
627
                }
628
                catch (Exception ex)
629
                {
630
                    Log.Write("Error in TextModeling");
631
                    Log.Write("UID : " + item.UID);
632
                    Log.Write(ex.Message);
633
                    Log.Write(ex.StackTrace);
634
                }
635
        }
636
        private void RunInputLineNumberAttribute()
637
        {
638
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
639
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
640
            List<string> endLine = new List<string>();
641
            foreach (var item in document.LINENUMBERS)
642
                try
643
                {
644
                    InputLineNumberAttribute(item, endLine);
645
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
646
                }
647
                catch (Exception ex)
648
                {
649
                    Log.Write("Error in InputLineNumberAttribute");
650
                    Log.Write("UID : " + item.UID);
651
                    Log.Write(ex.Message);
652
                    Log.Write(ex.StackTrace);
653
                }
654
        }
655
        private void RunInputSymbolAttribute()
656
        {
657
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
658
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
659
            foreach (var item in document.SYMBOLS)
660
                try
661
                {
662
                    InputSymbolAttribute(item, item.ATTRIBUTES);
663
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
664
                }
665
                catch (Exception ex)
666
                {
667
                    Log.Write("Error in InputSymbolAttribute");
668
                    Log.Write("UID : " + item.UID);
669
                    Log.Write(ex.Message);
670
                    Log.Write(ex.StackTrace);
671
                }
672
        }
673
        private void RunInputSpecBreakAttribute()
674
        {
675
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
676
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
677
            foreach (var item in document.SpecBreaks)
678
                try
679
                {
680
                    InputSpecBreakAttribute(item);
681
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
682
                }
683
                catch (Exception ex)
684
                {
685
                    Log.Write("Error in InputSpecBreakAttribute");
686
                    Log.Write("UID : " + item.UID);
687
                    Log.Write(ex.Message);
688
                    Log.Write(ex.StackTrace);
689
                }
690
        }
691
        private void RunLabelSymbolModeling()
692
        {
693
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
694
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
695
            foreach (var item in document.SYMBOLS)
696
                try
697
                {
698
                    LabelSymbolModeling(item);
699
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
700
                }
701
                catch (Exception ex)
702
                {
703
                    Log.Write("Error in LabelSymbolModeling");
704
                    Log.Write("UID : " + item.UID);
705
                    Log.Write(ex.Message);
706
                    Log.Write(ex.StackTrace);
707
                }
708
        }
709
        
710
        /// <summary>
711
        /// 도면 생성 메서드
712
        /// </summary>
713
        private void CreateDocument(ref string drawingNumber, ref string drawingName)
714
        {
715
            Log.Write("------------------ Start create document ------------------");
716
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
717
            Log.Write("Drawing name : " + drawingName);
718
            Log.Write("Drawing number : " + drawingNumber);
719
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
720
            document.SPPID_DrawingNumber = drawingNumber;
721
            document.SPPID_DrawingName = drawingName;
722
            application.ActiveWindow.Fit();
723
            Thread.Sleep(1000);
724
            application.ActiveWindow.Zoom = 2000;
725
            Thread.Sleep(2000);
726

    
727
            //current LMDrawing 가져오기
728
            LMAFilter filter = new LMAFilter();
729
            LMACriterion criterion = new LMACriterion();
730
            filter.ItemType = "Drawing";
731
            criterion.SourceAttributeName = "Name";
732
            criterion.Operator = "=";
733
            criterion.set_ValueAttribute(drawingName);
734
            filter.get_Criteria().Add(criterion);
735

    
736
            LMDrawings drawings = new LMDrawings();
737
            drawings.Collect(dataSource, Filter: filter);
738

    
739
            currentDrawing = ((dynamic)drawings).Nth(1);
740
        }
741

    
742
        /// <summary>
743
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
744
        /// </summary>
745
        /// <param name="drawingName"></param>
746
        /// <param name="drawingNumber"></param>
747
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
748
        {
749
            LMDrawings drawings = new LMDrawings();
750
            drawings.Collect(dataSource);
751

    
752
            List<string> drawingNameList = new List<string>();
753
            List<string> drawingNumberList = new List<string>();
754

    
755
            foreach (LMDrawing item in drawings)
756
            {
757
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
758
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
759
            }
760

    
761
            int nameLength = drawingName.Length;
762
            while (drawingNameList.Contains(drawingName))
763
            {
764
                if (nameLength == drawingName.Length)
765
                    drawingName += "-1";
766
                else
767
                {
768
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
769
                    drawingName = drawingName.Substring(0, nameLength + 1);
770
                    drawingName += ++index;
771
                }
772
            }
773

    
774
            int numberLength = drawingNumber.Length;
775
            while (drawingNameList.Contains(drawingNumber))
776
            {
777
                if (numberLength == drawingNumber.Length)
778
                    drawingNumber += "-1";
779
                else
780
                {
781
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
782
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
783
                    drawingNumber += ++index;
784
                }
785
            }
786

    
787
            ReleaseCOMObjects(drawings);
788
        }
789

    
790
        /// <summary>
791
        /// 도면 크기 구하는 메서드
792
        /// </summary>
793
        /// <returns></returns>
794
        private bool DocumentCoordinateCorrection()
795
        {
796
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
797
            {
798
                Log.Write("Setting Drawing X, Drawing Y");
799
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
800
                Log.Write("Start coordinate correction");
801
                document.CoordinateCorrection();
802
                return true;
803
            }
804
            else
805
            {
806
                Log.Write("Need Drawing X, Y");
807
                return false;
808
            }
809
        }
810

    
811
        /// <summary>
812
        /// 심볼을 실제로 Modeling 메서드
813
        /// </summary>
814
        /// <param name="symbol"></param>
815
        /// <param name="targetSymbol"></param>
816
        /// <param name="prevSymbol"></param>
817
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
818
        {
819
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
820
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
821
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
822
                return;
823
            // 이미 모델링 됐을 경우
824
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
825
                return;
826

    
827
            LMSymbol _LMSymbol = null;
828

    
829
            string mappingPath = symbol.SPPID.MAPPINGNAME;
830
            double x = symbol.SPPID.ORIGINAL_X;
831
            double y = symbol.SPPID.ORIGINAL_Y;
832
            int mirror = 0;
833
            double angle = symbol.ANGLE;
834

    
835
            // OPC 일경우 180도 일때 Mirror
836
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
837
                mirror = 1;
838

    
839
            // Mirror 계산
840
            if (symbol.FLIP == 1)
841
            {
842
                mirror = 1;
843
                angle += Math.PI;
844
            }
845

    
846
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
847
            {
848
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
849
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
850
                if (connector != null)
851
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
852

    
853
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
854

    
855
                if (_LMSymbol != null && _TargetItem != null)
856
                {
857
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
858

    
859
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
860
                    {
861
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
862
                        if (reModelingConnector != null)
863
                            ReModelingLMConnector(reModelingConnector);
864
                    }
865
                }
866

    
867
                ReleaseCOMObjects(_TargetItem);
868
            }
869
            else
870
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
871

    
872
            if (_LMSymbol != null)
873
            {
874
                _LMSymbol.Commit();
875
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
876
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
877
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
878

    
879
                foreach (var item in symbol.ChildSymbols)
880
                    CreateChildSymbol(item, _LMSymbol, symbol);
881

    
882
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
883
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
884

    
885
                double[] range = null;
886
                GetSPPIDSymbolRange(symbol, ref range);
887
                symbol.SPPID.SPPID_Min_X = range[0];
888
                symbol.SPPID.SPPID_Min_Y = range[1];
889
                symbol.SPPID.SPPID_Max_X = range[2];
890
                symbol.SPPID.SPPID_Max_Y = range[3];
891

    
892
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
893
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
894
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
895
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
896

    
897
                ReleaseCOMObjects(_LMSymbol);
898
            }
899
        }
900

    
901
        private void RemoveSymbol(Symbol symbol)
902
        {
903
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
904
            {
905
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
906
                if (_LMSymbol != null)
907
                {
908
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
909
                    ReleaseCOMObjects(_LMSymbol);
910
                }
911
            }
912

    
913
            symbol.SPPID.RepresentationId = string.Empty;
914
            symbol.SPPID.ModelItemID = string.Empty;
915
            symbol.SPPID.SPPID_X = double.NaN;
916
            symbol.SPPID.SPPID_Y = double.NaN;
917
            symbol.SPPID.SPPID_Min_X = double.NaN;
918
            symbol.SPPID.SPPID_Min_Y = double.NaN;
919
            symbol.SPPID.SPPID_Max_X = double.NaN;
920
            symbol.SPPID.SPPID_Max_Y = double.NaN;
921
        }
922

    
923
        private void RemoveSymbol(List<Symbol> symbols)
924
        {
925
            foreach (var symbol in symbols)
926
            {
927
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
928
                {
929
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
930
                    if (_LMSymbol != null)
931
                    {
932
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
933
                        ReleaseCOMObjects(_LMSymbol);
934
                    }
935
                }
936

    
937
                symbol.SPPID.RepresentationId = string.Empty;
938
                symbol.SPPID.ModelItemID = string.Empty;
939
                symbol.SPPID.SPPID_X = double.NaN;
940
                symbol.SPPID.SPPID_Y = double.NaN;
941
                symbol.SPPID.SPPID_Min_X = double.NaN;
942
                symbol.SPPID.SPPID_Min_Y = double.NaN;
943
                symbol.SPPID.SPPID_Max_X = double.NaN;
944
                symbol.SPPID.SPPID_Max_Y = double.NaN;
945
            }
946
        }
947

    
948
        /// <summary>
949
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
950
        /// </summary>
951
        /// <param name="targetConnector"></param>
952
        /// <param name="targetSymbol"></param>
953
        /// <param name="x"></param>
954
        /// <param name="y"></param>
955
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
956
        {
957
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
958

    
959
            double[] range = null;
960
            List<double[]> points = new List<double[]>();
961
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
962
            double x1 = range[0];
963
            double y1 = range[1];
964
            double x2 = range[2];
965
            double y2 = range[3];
966

    
967
            // Origin 기준 Connector의 위치차이
968
            double sceneX = 0;
969
            double sceneY = 0;
970
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
971
            double originX = 0;
972
            double originY = 0;
973
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
974
            double gapX = originX - sceneX;
975
            double gapY = originY - sceneY;
976

    
977
            // SPPID Symbol과 ID2 심볼의 크기 차이
978
            double sizeWidth = 0;
979
            double sizeHeight = 0;
980
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
981
            if (sizeWidth == 0 || sizeHeight == 0)
982
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
983

    
984
            double percentX = (x2 - x1) / sizeWidth;
985
            double percentY = (y2 - y1) / sizeHeight;
986

    
987
            double SPPIDgapX = gapX * percentX;
988
            double SPPIDgapY = gapY * percentY;
989

    
990
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
991
            double distance = double.MaxValue;
992
            double[] resultPoint;
993
            foreach (var point in points)
994
            {
995
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
996
                if (distance > result)
997
                {
998
                    distance = result;
999
                    resultPoint = point;
1000
                    x = point[0];
1001
                    y = point[1];
1002
                }
1003
            }
1004

    
1005
            ReleaseCOMObjects(_TargetItem);
1006
        }
1007

    
1008
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1009
        {
1010
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1011
            if (index == 0)
1012
            {
1013
                x = targetLine.SPPID.START_X;
1014
                y = targetLine.SPPID.START_Y;
1015
            }
1016
            else
1017
            {
1018
                x = targetLine.SPPID.END_X;
1019
                y = targetLine.SPPID.END_Y;
1020
            }
1021
        }
1022

    
1023
        /// <summary>
1024
        /// SPPID Symbol의 Range를 구한다.
1025
        /// </summary>
1026
        /// <param name="symbol"></param>
1027
        /// <param name="range"></param>
1028
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1029
        {
1030
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1031
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1032
            double x1 = 0;
1033
            double y1 = 0;
1034
            double x2 = 0;
1035
            double y2 = 0;
1036
            symbol2d.Range(out x1, out y1, out x2, out y2);
1037
            range = new double[] { x1, y1, x2, y2 };
1038

    
1039
            for (int i = 1; i < int.MaxValue; i++)
1040
            {
1041
                double connX = 0;
1042
                double connY = 0;
1043
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1044
                    points.Add(new double[] { connX, connY });
1045
                else
1046
                    break;
1047
            }
1048

    
1049
            foreach (var childSymbol in symbol.ChildSymbols)
1050
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1051

    
1052
            ReleaseCOMObjects(_TargetItem);
1053
        }
1054

    
1055
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range)
1056
        {
1057
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1058
            if (_TargetItem != null)
1059
            {
1060
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1061
                double x1 = 0;
1062
                double y1 = 0;
1063
                double x2 = 0;
1064
                double y2 = 0;
1065
                symbol2d.Range(out x1, out y1, out x2, out y2);
1066
                range = new double[] { x1, y1, x2, y2 };
1067

    
1068
                foreach (var childSymbol in symbol.ChildSymbols)
1069
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1070

    
1071
                ReleaseCOMObjects(_TargetItem);
1072
            }
1073
        }
1074

    
1075
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1076
        {
1077
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1078
            foreach (var symbol in symbols)
1079
            {
1080
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1081
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1082
                double x1 = 0;
1083
                double y1 = 0;
1084
                double x2 = 0;
1085
                double y2 = 0;
1086
                symbol2d.Range(out x1, out y1, out x2, out y2);
1087

    
1088
                tempRange[0] = Math.Min(tempRange[0], x1);
1089
                tempRange[1] = Math.Min(tempRange[1], y1);
1090
                tempRange[2] = Math.Max(tempRange[2], x2);
1091
                tempRange[3] = Math.Max(tempRange[3], y2);
1092

    
1093
                foreach (var childSymbol in symbol.ChildSymbols)
1094
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1095

    
1096
                ReleaseCOMObjects(_TargetItem);
1097
            }
1098

    
1099
            range = tempRange;
1100
        }
1101

    
1102
        /// <summary>
1103
        /// Child Modeling 된 Symbol의 Range를 구한다.
1104
        /// </summary>
1105
        /// <param name="childSymbol"></param>
1106
        /// <param name="range"></param>
1107
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1108
        {
1109
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1110
            if (_ChildSymbol != null)
1111
            {
1112
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1113
                double x1 = 0;
1114
                double y1 = 0;
1115
                double x2 = 0;
1116
                double y2 = 0;
1117
                symbol2d.Range(out x1, out y1, out x2, out y2);
1118
                range[0] = Math.Min(range[0], x1);
1119
                range[1] = Math.Min(range[1], y1);
1120
                range[2] = Math.Max(range[2], x2);
1121
                range[3] = Math.Max(range[3], y2);
1122

    
1123
                for (int i = 1; i < int.MaxValue; i++)
1124
                {
1125
                    double connX = 0;
1126
                    double connY = 0;
1127
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1128
                        points.Add(new double[] { connX, connY });
1129
                    else
1130
                        break;
1131
                }
1132

    
1133
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1134
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1135

    
1136
                ReleaseCOMObjects(_ChildSymbol);
1137
            }
1138
        }
1139

    
1140
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1141
        {
1142
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1143
            if (_ChildSymbol != null)
1144
            {
1145
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1146
                double x1 = 0;
1147
                double y1 = 0;
1148
                double x2 = 0;
1149
                double y2 = 0;
1150
                symbol2d.Range(out x1, out y1, out x2, out y2);
1151
                range[0] = Math.Min(range[0], x1);
1152
                range[1] = Math.Min(range[1], y1);
1153
                range[2] = Math.Max(range[2], x2);
1154
                range[3] = Math.Max(range[3], y2);
1155

    
1156
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1157
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1158
                ReleaseCOMObjects(_ChildSymbol);
1159
            }
1160
        }
1161

    
1162
        /// <summary>
1163
        /// Label Symbol Modeling
1164
        /// </summary>
1165
        /// <param name="symbol"></param>
1166
        private void LabelSymbolModeling(Symbol symbol)
1167
        {
1168
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1169
            {
1170
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1171
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1172
                    return;
1173
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1174

    
1175
                string symbolUID = itemAttribute.VALUE;
1176
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1177
                if (targetItem != null &&
1178
                    (targetItem.GetType() == typeof(Symbol) ||
1179
                    targetItem.GetType() == typeof(Equipment)))
1180
                {
1181
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1182
                    string sRep = null;
1183
                    if (targetItem.GetType() == typeof(Symbol))
1184
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1185
                    else if (targetItem.GetType() == typeof(Equipment))
1186
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1187
                    if (!string.IsNullOrEmpty(sRep))
1188
                    {
1189
                        // LEADER Line 검사
1190
                        bool leaderLine = false;
1191
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1192
                        if (symbolMapping != null)
1193
                            leaderLine = symbolMapping.LEADERLINE;
1194

    
1195
                        // Target Symbol Item 가져오고 Label Modeling
1196
                        LMSymbol _TargetItem = dataSource.GetSymbol(sRep);
1197
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: _TargetItem.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1198

    
1199
                        //Leader 선 센터로
1200
                        if (_LMLabelPresist != null)
1201
                        {
1202
                            // Target Item에 Label의 Attribute Input
1203
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1204

    
1205
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1206
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1207
                            if (dependency != null)
1208
                            {
1209
                                bool result = false;
1210
                                foreach (var attributes in dependency.AttributeSets)
1211
                                {
1212
                                    foreach (var attribute in attributes)
1213
                                    {
1214
                                        string name = attribute.Name;
1215
                                        string value = attribute.GetValue().ToString();
1216
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1217
                                        {
1218
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1219
                                            {
1220
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1221
                                                {
1222
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1223
                                                    double prevX = _TargetItem.get_XCoordinate();
1224
                                                    double prevY = _TargetItem.get_YCoordinate();
1225
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1226
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1227
                                                    result = true;
1228
                                                    break;
1229
                                                }
1230
                                            }
1231
                                        }
1232

    
1233
                                        if (result)
1234
                                            break;
1235
                                    }
1236

    
1237
                                    if (result)
1238
                                        break;
1239
                                }
1240
                            }
1241

    
1242
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1243
                            _LMLabelPresist.Commit();
1244
                            ReleaseCOMObjects(_LMLabelPresist);
1245
                        }
1246

    
1247
                        ReleaseCOMObjects(_TargetItem);
1248
                    }
1249
                }
1250
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1251
                {
1252
                    Line targetLine = targetItem as Line;
1253
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1254
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1255
                    if (connectedLMConnector != null)
1256
                    {
1257
                        // LEADER Line 검사
1258
                        bool leaderLine = false;
1259
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1260
                        if (symbolMapping != null)
1261
                            leaderLine = symbolMapping.LEADERLINE;
1262

    
1263
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1264
                        if (_LMLabelPresist != null)
1265
                        {
1266
                            _LMLabelPresist.Commit();
1267
                            ReleaseCOMObjects(_LMLabelPresist);
1268
                        }
1269
                        ReleaseCOMObjects(connectedLMConnector);
1270
                    }
1271

    
1272
                    foreach (var item in connectorVertices)
1273
                        if (item.Key != null)
1274
                            ReleaseCOMObjects(item.Key);
1275
                }
1276
            }
1277
        }
1278

    
1279
        /// <summary>
1280
        /// Equipment를 실제로 Modeling 메서드
1281
        /// </summary>
1282
        /// <param name="equipment"></param>
1283
        private void EquipmentModeling(Equipment equipment)
1284
        {
1285
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1286
                return;
1287

    
1288
            LMSymbol _LMSymbol = null;
1289
            LMSymbol targetItem = null;
1290
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1291
            double x = equipment.SPPID.ORIGINAL_X;
1292
            double y = equipment.SPPID.ORIGINAL_Y;
1293
            int mirror = 0;
1294
            double angle = equipment.ANGLE;
1295

    
1296
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1297

    
1298
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1299
            if (connector != null)
1300
            {
1301
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1302
                if (connEquipment != null)
1303
                {
1304
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1305
                        EquipmentModeling(connEquipment);
1306

    
1307
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1308
                    {
1309
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1310
                        if (targetItem != null)
1311
                        {
1312
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1313
                        }
1314
                        else
1315
                        {
1316
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1317
                        }
1318
                    }
1319
                    else
1320
                    {
1321
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1322
                    }
1323
                }
1324
                else
1325
                {
1326
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1327
                }
1328
            }
1329
            else
1330
            {
1331
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1332
            }
1333

    
1334
            if (_LMSymbol != null)
1335
            {
1336
                _LMSymbol.Commit();
1337
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1338
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1339
                ReleaseCOMObjects(_LMSymbol);
1340
            }
1341

    
1342
            if (targetItem != null)
1343
            {
1344
                ReleaseCOMObjects(targetItem);
1345
            }
1346

    
1347
            ReleaseCOMObjects(_LMSymbol);
1348
        }
1349

    
1350
        /// <summary>
1351
        /// 첫 진입점
1352
        /// </summary>
1353
        /// <param name="symbol"></param>
1354
        private void SymbolModelingBySymbol(Symbol symbol)
1355
        {
1356
            SymbolModeling(symbol, null);
1357
            List<object> endObjects = new List<object>();
1358
            endObjects.Add(symbol);
1359

    
1360
            foreach (var connector in symbol.CONNECTORS)
1361
            {
1362
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1363
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1364
                {
1365
                    endObjects.Add(connItem);
1366
                    if (connItem.GetType() == typeof(Symbol))
1367
                    {
1368
                        Symbol connSymbol = connItem as Symbol;
1369
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1370
                        {
1371
                            SymbolModeling(connSymbol, symbol);
1372
                        }
1373
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1374
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1375
                    }
1376
                    else if (connItem.GetType() == typeof(Line))
1377
                    {
1378
                        Line connLine = connItem as Line;
1379
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1380
                    }
1381
                }
1382
            }
1383
        }
1384

    
1385
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1386
        {
1387
            foreach (var connector in symbol.CONNECTORS)
1388
            {
1389
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1390
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1391
                {
1392
                    if (!endObjects.Contains(connItem))
1393
                    {
1394
                        endObjects.Add(connItem);
1395
                        if (connItem.GetType() == typeof(Symbol))
1396
                        {
1397
                            Symbol connSymbol = connItem as Symbol;
1398
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1399
                            {
1400
                                SymbolModeling(connSymbol, symbol);
1401
                            }
1402
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1403
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1404
                        }
1405
                        else if (connItem.GetType() == typeof(Line))
1406
                        {
1407
                            Line connLine = connItem as Line;
1408
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1409
                        }
1410
                    }
1411
                }
1412
            }
1413
        }
1414

    
1415
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1416
        {
1417
            foreach (var connector in line.CONNECTORS)
1418
            {
1419
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1420
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1421
                {
1422
                    if (!endObjects.Contains(connItem))
1423
                    {
1424
                        endObjects.Add(connItem);
1425
                        if (connItem.GetType() == typeof(Symbol))
1426
                        {
1427
                            Symbol connSymbol = connItem as Symbol;
1428
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1429
                            {
1430
                                List<Symbol> group = new List<Symbol>();
1431
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1432
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1433
                                List<Symbol> endModelingGroup = new List<Symbol>();
1434
                                if (priority != null)
1435
                                {
1436
                                    SymbolGroupModeling(priority, group);
1437

    
1438
                                    // Range 겹치는지 확인해야함
1439
                                    double[] prevRange = null;
1440
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1441
                                    double[] groupRange = null;
1442
                                    GetSPPIDSymbolRange(group, ref groupRange);
1443

    
1444
                                    double distanceX = 0;
1445
                                    double distanceY = 0;
1446
                                    bool overlapX = false;
1447
                                    bool overlapY = false;
1448
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1449
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1450
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1451
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1452
                                    {
1453
                                        RemoveSymbol(group);
1454
                                        foreach (var _temp in group)
1455
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1456

    
1457
                                        SymbolGroupModeling(priority, group);
1458
                                    }
1459
                                }
1460
                                else
1461
                                {
1462
                                    SymbolModeling(connSymbol, null);
1463
                                    // Range 겹치는지 확인해야함
1464
                                    double[] prevRange = null;
1465
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1466
                                    double[] connRange = null;
1467
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1468

    
1469
                                    double distanceX = 0;
1470
                                    double distanceY = 0;
1471
                                    bool overlapX = false;
1472
                                    bool overlapY = false;
1473
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1474
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1475
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1476
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1477
                                    {
1478
                                        RemoveSymbol(connSymbol);
1479
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1480

    
1481
                                        SymbolModeling(connSymbol, null);
1482
                                    }
1483
                                }
1484
                            }
1485
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1486
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1487
                        }
1488
                        else if (connItem.GetType() == typeof(Line))
1489
                        {
1490
                            Line connLine = connItem as Line;
1491
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1492
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1493
                        }
1494
                    }
1495
                }
1496
            }
1497
        }
1498

    
1499
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1500
        {
1501
            List<Symbol> endModelingGroup = new List<Symbol>();
1502
            SymbolModeling(firstSymbol, null);
1503
            endModelingGroup.Add(firstSymbol);
1504
            while (endModelingGroup.Count != group.Count)
1505
            {
1506
                foreach (var _symbol in group)
1507
                {
1508
                    if (!endModelingGroup.Contains(_symbol))
1509
                    {
1510
                        foreach (var _connector in _symbol.CONNECTORS)
1511
                        {
1512
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1513
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1514
                            {
1515
                                SymbolModeling(_symbol, _connSymbol);
1516
                                endModelingGroup.Add(_symbol);
1517
                                break;
1518
                            }
1519
                        }
1520
                    }
1521
                }
1522
            }
1523
        }
1524

    
1525
        /// <summary>
1526
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1527
        /// </summary>
1528
        /// <param name="childSymbol"></param>
1529
        /// <param name="parentSymbol"></param>
1530
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1531
        {
1532
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1533
            double x1 = 0;
1534
            double x2 = 0;
1535
            double y1 = 0;
1536
            double y2 = 0;
1537
            symbol2d.Range(out x1, out y1, out x2, out y2);
1538

    
1539
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1540
            if (_LMSymbol != null)
1541
            {
1542
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1543
                foreach (var item in childSymbol.ChildSymbols)
1544
                    CreateChildSymbol(item, _LMSymbol, parent);
1545
            }
1546

    
1547

    
1548
            ReleaseCOMObjects(_LMSymbol);
1549
        }
1550
        double index = 0;
1551
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1552
        {
1553
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1554
                return;
1555

    
1556
            List<Line> group = new List<Line>();
1557
            GetConnectedLineGroup(line, group);
1558
            LineCoordinateCorrection(group);
1559

    
1560
            foreach (var groupLine in group)
1561
            {
1562
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1563
                {
1564
                    BranchLines.Add(groupLine);
1565
                    continue;
1566
                }
1567

    
1568
                bool diagonal = false;
1569
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1570
                    diagonal = true;
1571
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1572
                LMSymbol _LMSymbolStart = null;
1573
                LMSymbol _LMSymbolEnd = null;
1574
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1575
                foreach (var connector in groupLine.CONNECTORS)
1576
                {
1577
                    double x = 0;
1578
                    double y = 0;
1579
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1580
                    if (connector.ConnectedObject == null)
1581
                    {
1582
                        placeRunInputs.AddPoint(x, y);
1583
                    }
1584
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1585
                    {
1586
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1587
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1588
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1589
                        {
1590
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1591
                            if (_LMSymbolStart != null)
1592
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1593
                            else
1594
                                placeRunInputs.AddPoint(x, y);
1595
                        }
1596
                        else
1597
                        {
1598
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1599
                            if (_LMSymbolEnd != null)
1600
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1601
                            else
1602
                                placeRunInputs.AddPoint(x, y);
1603
                        }
1604
                    }
1605
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1606
                    {
1607
                        Line targetLine = connector.ConnectedObject as Line;
1608
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1609
                        {
1610
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1611
                            if (targetConnector != null)
1612
                            {
1613
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1614
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1615
                            }
1616
                            else
1617
                            {
1618
                                placeRunInputs.AddPoint( x, y);
1619
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1620
                            }
1621
                        }
1622
                        else
1623
                        {
1624
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1625
                            {
1626
                                index += 0.01;
1627
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1628
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1629
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1630
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1631
                                else
1632
                                {
1633
                                    if (SPPIDUtil.CalcAngle(groupLine.SPPID.START_X, groupLine.SPPID.START_Y, groupLine.SPPID.END_X, groupLine.SPPID.END_Y) < 45)
1634
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1635
                                    else
1636
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1637
                                }
1638
                            }
1639

    
1640
                            placeRunInputs.AddPoint(x, y);
1641

    
1642
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1643
                            {
1644
                                index += 0.01;
1645
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1646
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1647
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1648
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1649
                                else
1650
                                {
1651
                                    if (SPPIDUtil.CalcAngle(groupLine.SPPID.START_X, groupLine.SPPID.START_Y, groupLine.SPPID.END_X, groupLine.SPPID.END_Y) < 45)
1652
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1653
                                    else
1654
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1655
                                }
1656
                            }
1657
                        }
1658
                    }
1659
                }
1660

    
1661
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1662
                if (_lMConnector != null)
1663
                {
1664
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1665
                    bool bRemodelingStart = false;
1666
                    if (_LMSymbolStart != null)
1667
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1668
                    bool bRemodelingEnd = false;
1669
                    if (_LMSymbolEnd != null)
1670
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1671

    
1672
                    if (bRemodelingStart || bRemodelingEnd)
1673
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1674

    
1675
                    FlowMarkModeling(groupLine);
1676
                    LineNumberModelingOnlyOne(groupLine);
1677

    
1678
                    ReleaseCOMObjects(_lMConnector);
1679
                }
1680
                else if (!isBranchModeling)
1681
                {
1682
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1683
                }
1684

    
1685
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1686
                x.ConnectedObject != null &&
1687
                x.ConnectedObject.GetType() == typeof(Line) &&
1688
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1689
                .Select(x => x.ConnectedObject)
1690
                .ToList();
1691

    
1692
                foreach (var item in removeLines)
1693
                    RemoveLineForModeling(item as Line);
1694

    
1695
                if (_LMAItem != null)
1696
                    ReleaseCOMObjects(_LMAItem);
1697
                if (placeRunInputs != null)
1698
                    ReleaseCOMObjects(placeRunInputs);
1699
                if (_LMSymbolStart != null)
1700
                    ReleaseCOMObjects(_LMSymbolStart);
1701
                if (_LMSymbolEnd != null)
1702
                    ReleaseCOMObjects(_LMSymbolEnd);
1703

    
1704
                if (isBranchModeling && BranchLines.Contains(groupLine))
1705
                    BranchLines.Remove(groupLine);
1706
            }
1707
        }
1708

    
1709
        private void RemoveLineForModeling(Line line)
1710
        {
1711
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1712
            if (modelItem != null)
1713
            {
1714
                foreach (LMRepresentation rep in modelItem.Representations)
1715
                {
1716
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1717
                    {
1718
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1719
                        dynamic OID = rep.get_GraphicOID().ToString();
1720
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1721
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1722
                        int verticesCount = lineStringGeometry.VertexCount;
1723
                        double[] vertices = null;
1724
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1725
                        for (int i = 0; i < verticesCount; i++)
1726
                        {
1727
                            double x = 0;
1728
                            double y = 0;
1729
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1730
                            if (verticesCount == 2 && (x < 0 || y < 0))
1731
                                _placement.PIDRemovePlacement(rep);
1732
                        }
1733
                        ReleaseCOMObjects(_LMConnector);
1734
                    }
1735
                }
1736

    
1737
                ReleaseCOMObjects(modelItem);
1738
            }
1739
        }
1740

    
1741
        private void GetConnectedLineGroup(Line line, List<Line> group)
1742
        {
1743
            if (!group.Contains(line))
1744
                group.Add(line);
1745
            foreach (var connector in line.CONNECTORS)
1746
            {
1747
                if (connector.ConnectedObject != null &&
1748
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1749
                    !group.Contains(connector.ConnectedObject) &&
1750
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1751
                {
1752
                    Line connLine = connector.ConnectedObject as Line;
1753
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1754
                    {
1755
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1756
                            group.Insert(0, connLine);
1757
                        else
1758
                            group.Add(connLine);
1759
                        GetConnectedLineGroup(connLine, group);
1760
                    }
1761
                }
1762
            }
1763
        }
1764

    
1765
        private void LineCoordinateCorrection(List<Line> group)
1766
        {
1767
            // 순서대로 전 Item 기준 정렬
1768
            LineCoordinateCorrectionByStart(group);
1769

    
1770
            // 역으로 심볼이 있을 경우 좌표 보정
1771
            LineCoordinateCorrectionForLastLine(group);
1772
        }
1773

    
1774
        private void LineCoordinateCorrectionByStart(List<Line> group)
1775
        {
1776
            for (int i = 0; i < group.Count; i++)
1777
            {
1778
                Line line = group[i];
1779
                if (i == 0)
1780
                {
1781
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1782
                    if (symbolConnector != null)
1783
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1784
                }
1785
                else if (i != 0)
1786
                {
1787
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1788
                }
1789
            }
1790
        }
1791

    
1792
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1793
        {
1794
            Line checkLine = group[group.Count - 1];
1795
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1796
            if (lastSymbolConnector != null)
1797
            {
1798
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1799
                for (int i = group.Count - 2; i >= 0; i--)
1800
                {
1801
                    Line line = group[i + 1];
1802
                    Line prevLine = group[i];
1803

    
1804
                    // 같으면 보정
1805
                    if (line.SlopeType == prevLine.SlopeType)
1806
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1807
                    else
1808
                    {
1809
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1810
                        {
1811
                            double prevX = 0;
1812
                            double prevY = 0;
1813
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1814
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1815

    
1816
                            double x = 0;
1817
                            double y = 0;
1818
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1819
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1820
                        }
1821
                        else if (line.SlopeType == SlopeType.VERTICAL)
1822
                        {
1823
                            double prevX = 0;
1824
                            double prevY = 0;
1825
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1826
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1827

    
1828
                            double x = 0;
1829
                            double y = 0;
1830
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1831
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1832
                        }
1833
                        break;
1834
                    }
1835
                }
1836
            }
1837
        }
1838

    
1839
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1840
        {
1841
            double x = 0;
1842
            double y = 0;
1843
            if (connItem.GetType() == typeof(Symbol))
1844
            {
1845
                Symbol targetSymbol = connItem as Symbol;
1846
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1847
                if (targetConnector != null)
1848
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
1849
                else
1850
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
1851
            }
1852
            else if (connItem.GetType() == typeof(Line))
1853
            {
1854
                Line targetLine = connItem as Line;
1855
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
1856
            }
1857

    
1858
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
1859
        }
1860

    
1861
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
1862
        {
1863
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1864
            int index = line.CONNECTORS.IndexOf(connector);
1865
            if (index == 0)
1866
            {
1867
                line.SPPID.START_X = x;
1868
                line.SPPID.START_Y = y;
1869
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1870
                    line.SPPID.END_Y = y;
1871
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1872
                    line.SPPID.END_X = x;
1873
            }
1874
            else
1875
            {
1876
                line.SPPID.END_X = x;
1877
                line.SPPID.END_Y = y;
1878
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1879
                    line.SPPID.START_Y = y;
1880
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1881
                    line.SPPID.START_X = x;
1882
            }
1883
        }
1884

    
1885
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
1886
        {
1887
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1888
            int index = line.CONNECTORS.IndexOf(connector);
1889
            if (index == 0)
1890
            {
1891
                line.SPPID.START_X = x;
1892
                if (line.SlopeType == SlopeType.VERTICAL)
1893
                    line.SPPID.END_X = x;
1894
            }
1895
            else
1896
            {
1897
                line.SPPID.END_X = x;
1898
                if (line.SlopeType == SlopeType.VERTICAL)
1899
                    line.SPPID.START_X = x;
1900
            }
1901
        }
1902

    
1903
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
1904
        {
1905
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1906
            int index = line.CONNECTORS.IndexOf(connector);
1907
            if (index == 0)
1908
            {
1909
                line.SPPID.START_Y = y;
1910
                if (line.SlopeType == SlopeType.HORIZONTAL)
1911
                    line.SPPID.END_Y = y;
1912
            }
1913
            else
1914
            {
1915
                line.SPPID.END_Y = y;
1916
                if (line.SlopeType == SlopeType.HORIZONTAL)
1917
                    line.SPPID.START_Y = y;
1918
            }
1919
        }
1920

    
1921
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
1922
        {
1923
            if (symbol != null)
1924
            {
1925
                string repID = symbol.AsLMRepresentation().Id;
1926
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
1927
                string lineUID = line.UID;
1928

    
1929
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
1930
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
1931
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
1932

    
1933
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
1934
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
1935
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
1936

    
1937
                if (startSpecBreak != null || startEndBreak != null)
1938
                    result = true;
1939
            }
1940
        }
1941

    
1942
        /// <summary>
1943
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
1944
        /// </summary>
1945
        /// <param name="lines"></param>
1946
        /// <param name="prevLMConnector"></param>
1947
        /// <param name="startSymbol"></param>
1948
        /// <param name="endSymbol"></param>
1949
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
1950
        {
1951
            string symbolPath = string.Empty;
1952
            #region get symbol path
1953
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
1954
            symbolPath = GetSPPIDFileName(modelItem);
1955
            ReleaseCOMObjects(modelItem);
1956
            #endregion
1957
            bool diagonal = false;
1958
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
1959
                diagonal = true;
1960
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
1961
            LMConnector newConnector = null;
1962
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
1963
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1964
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1965
            int verticesCount = lineStringGeometry.VertexCount;
1966
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1967

    
1968
            List<double[]> vertices = new List<double[]>();
1969
            for (int i = 1; i <= verticesCount; i++)
1970
            {
1971
                double x = 0;
1972
                double y = 0;
1973
                lineStringGeometry.GetVertex(i, ref x, ref y);
1974
                vertices.Add(new double[] { x, y });
1975
            }
1976

    
1977
            for (int i = 0; i < vertices.Count; i++)
1978
            {
1979
                double[] points = vertices[i];
1980
                // 시작 심볼이 있고 첫번째 좌표일 때
1981
                if (startSymbol != null && i == 0)
1982
                {
1983
                    if (bStart)
1984
                    {
1985
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
1986
                        if (slopeType == SlopeType.HORIZONTAL)
1987
                            placeRunInputs.AddPoint(points[0], -0.1);
1988
                        else if (slopeType == SlopeType.VERTICAL)
1989
                            placeRunInputs.AddPoint(-0.1, points[1]);
1990
                        else
1991
                            placeRunInputs.AddPoint(points[0], -0.1);
1992

    
1993
                        placeRunInputs.AddPoint(points[0], points[1]);
1994
                    }
1995
                    else
1996
                    {
1997
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
1998
                    }
1999
                }
2000
                // 마지막 심볼이 있고 마지막 좌표일 때
2001
                else if (endSymbol != null && i == vertices.Count - 1)
2002
                {
2003
                    if (bEnd)
2004
                    {
2005
                        placeRunInputs.AddPoint(points[0], points[1]);
2006

    
2007
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2008
                        if (slopeType == SlopeType.HORIZONTAL)
2009
                            placeRunInputs.AddPoint(points[0], -0.1);
2010
                        else if (slopeType == SlopeType.VERTICAL)
2011
                            placeRunInputs.AddPoint(-0.1, points[1]);
2012
                        else
2013
                            placeRunInputs.AddPoint(points[0], -0.1);
2014
                    }
2015
                    else
2016
                    {
2017
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2018
                    }
2019
                }
2020
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2021
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2022
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2023
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2024
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2025
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2026
                else
2027
                    placeRunInputs.AddPoint(points[0], points[1]);
2028
            }
2029

    
2030
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2031
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2032

    
2033
            ReleaseCOMObjects(placeRunInputs);
2034
            ReleaseCOMObjects(_LMAItem);
2035
            ReleaseCOMObjects(modelItem);
2036

    
2037
            if (newConnector != null)
2038
            {
2039
                if (startSymbol != null && bStart)
2040
                {
2041
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2042
                    placeRunInputs = new PlaceRunInputs();
2043
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2044
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2045
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2046
                    if (_LMConnector != null)
2047
                    {
2048
                        RemoveConnectorForReModelingLine(newConnector);
2049
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2050
                        ReleaseCOMObjects(_LMConnector);
2051
                    }
2052
                    ReleaseCOMObjects(placeRunInputs);
2053
                    ReleaseCOMObjects(_LMAItem);
2054
                }
2055

    
2056
                if (endSymbol != null && bEnd)
2057
                {
2058
                    if (startSymbol != null)
2059
                    {
2060
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2061
                        newConnector = dicVertices.First().Key;
2062
                    }
2063

    
2064
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2065
                    placeRunInputs = new PlaceRunInputs();
2066
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2067
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2068
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2069
                    if (_LMConnector != null)
2070
                    {
2071
                        RemoveConnectorForReModelingLine(newConnector);
2072
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2073
                        ReleaseCOMObjects(_LMConnector);
2074
                    }
2075
                    ReleaseCOMObjects(placeRunInputs);
2076
                    ReleaseCOMObjects(_LMAItem);
2077
                }
2078

    
2079
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2080
                ReleaseCOMObjects(newConnector);
2081
            }
2082

    
2083
            ReleaseCOMObjects(modelItem);
2084
        }
2085

    
2086
        /// <summary>
2087
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2088
        /// </summary>
2089
        /// <param name="connector"></param>
2090
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2091
        {
2092
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2093
            foreach (var item in dicVertices)
2094
            {
2095
                if (item.Value.Count == 2)
2096
                {
2097
                    bool result = false;
2098
                    foreach (var point in item.Value)
2099
                    {
2100
                        if (point[0] < 0 || point[1] < 0)
2101
                        {
2102
                            result = true;
2103
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2104
                            break;
2105
                        }
2106
                    }
2107

    
2108
                    if (result)
2109
                        break;
2110
                }
2111
            }
2112
            foreach (var item in dicVertices)
2113
                ReleaseCOMObjects(item.Key);
2114
        }
2115

    
2116
        /// <summary>
2117
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2118
        /// </summary>
2119
        /// <param name="symbol"></param>
2120
        /// <param name="line"></param>
2121
        /// <returns></returns>
2122
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2123
        {
2124
            LMSymbol _LMSymbol = null;
2125
            foreach (var connector in symbol.CONNECTORS)
2126
            {
2127
                if (connector.CONNECTEDITEM == line.UID)
2128
                {
2129
                    if (connector.Index == 0)
2130
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2131
                    else
2132
                    {
2133
                        ChildSymbol child = null;
2134
                        foreach (var childSymbol in symbol.ChildSymbols)
2135
                        {
2136
                            if (childSymbol.Connectors.Contains(connector))
2137
                                child = childSymbol;
2138
                            else
2139
                                child = GetChildSymbolByConnector(childSymbol, connector);
2140

    
2141
                            if (child != null)
2142
                                break;
2143
                        }
2144

    
2145
                        if (child != null)
2146
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2147
                    }
2148

    
2149
                    break;
2150
                }
2151
            }
2152

    
2153
            return _LMSymbol;
2154
        }
2155

    
2156
        /// <summary>
2157
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2158
        /// </summary>
2159
        /// <param name="item"></param>
2160
        /// <param name="connector"></param>
2161
        /// <returns></returns>
2162
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2163
        {
2164
            foreach (var childSymbol in item.ChildSymbols)
2165
            {
2166
                if (childSymbol.Connectors.Contains(connector))
2167
                    return childSymbol;
2168
                else
2169
                    return GetChildSymbolByConnector(childSymbol, connector);
2170
            }
2171

    
2172
            return null;
2173
        }
2174

    
2175
        /// <summary>
2176
        /// EndBreak 모델링 메서드
2177
        /// </summary>
2178
        /// <param name="endBreak"></param>
2179
        private void EndBreakModeling(EndBreak endBreak)
2180
        {
2181
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2182
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2183
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2184

    
2185
            if (targetLMConnector != null)
2186
            {
2187
                Array array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2188
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, Rotation: 0, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2189
                if (_LmLabelPersist != null)
2190
                {
2191
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2192
                    if (_LmLabelPersist.ModelItemObject != null)
2193
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2194
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2195
                    ReleaseCOMObjects(_LmLabelPersist);
2196
                }
2197
                ReleaseCOMObjects(targetLMConnector);
2198
            }
2199
        }
2200

    
2201
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2202
        {
2203
            string symbolPath = string.Empty;
2204
            #region get symbol path
2205
            if (string.IsNullOrEmpty(changeSymbolPath))
2206
            {
2207
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2208
                symbolPath = GetSPPIDFileName(modelItem);
2209
                ReleaseCOMObjects(modelItem);
2210
            }
2211
            else
2212
                symbolPath = changeSymbolPath;
2213
            
2214
            #endregion
2215

    
2216
            LMConnector newConnector = null;
2217
            dynamic OID = connector.get_GraphicOID().ToString();
2218
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2219
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2220
            int verticesCount = lineStringGeometry.VertexCount;
2221
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2222
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2223

    
2224
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2225
            {
2226
                double[] vertices = null;
2227
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2228
                double x = 0;
2229
                double y = 0;
2230
                lineStringGeometry.GetVertex(1, ref x, ref y);
2231

    
2232
                string flowDirection = string.Empty;
2233
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2234
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2235
                    flowDirection = flowAttribute.get_Value().ToString();
2236

    
2237
                if (flowDirection == "End 1 is downstream (Outlet)")
2238
                {
2239
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2240
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2241
                    flowDirection = "End 1 is upstream (Inlet)";
2242
                }
2243
                else
2244
                {
2245
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2246
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2247
                }
2248

    
2249
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2250
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2251
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2252
                if (!string.IsNullOrEmpty(flowDirection))
2253
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2254
            }
2255
            else
2256
            {
2257
                List<double[]> vertices = new List<double[]>();
2258
                for (int i = 1; i <= verticesCount; i++)
2259
                {
2260
                    double x = 0;
2261
                    double y = 0;
2262
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2263
                    vertices.Add(new double[] { x, y });
2264
                }
2265

    
2266
                for (int i = 0; i < vertices.Count; i++)
2267
                {
2268
                    double[] points = vertices[i];
2269
                    if (i == 0)
2270
                    {
2271
                        if (connector.ConnectItem1SymbolObject != null)
2272
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2273
                        else
2274
                            placeRunInputs.AddPoint(points[0], points[1]);
2275
                    }
2276
                    else if (i == vertices.Count - 1)
2277
                    {
2278
                        if (connector.ConnectItem2SymbolObject != null)
2279
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2280
                        else
2281
                            placeRunInputs.AddPoint(points[0], points[1]);
2282
                    }
2283
                    else
2284
                        placeRunInputs.AddPoint(points[0], points[1]);
2285
                }
2286

    
2287
                List<Line> lines = SPPIDUtil.FindLinesByModelId(document, connector.ModelItemID);
2288

    
2289
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2290
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2291

    
2292
                foreach (var line in lines)
2293
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2294
            }
2295

    
2296

    
2297
            return newConnector;
2298
        }
2299

    
2300
        /// <summary>
2301
        /// SpecBreak Modeling 메서드
2302
        /// </summary>
2303
        /// <param name="specBreak"></param>
2304
        private void SpecBreakModeling(SpecBreak specBreak)
2305
        {
2306
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2307
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2308

    
2309
            if (upStreamObj != null &&
2310
                downStreamObj != null)
2311
            {
2312
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2313

    
2314
                if (targetLMConnector != null)
2315
                {
2316
                    foreach (var attribute in specBreak.ATTRIBUTES)
2317
                    {
2318
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2319
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2320
                        {
2321
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2322
                            Array array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2323
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, Rotation: specBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2324

    
2325
                            if (_LmLabelPersist != null)
2326
                            {
2327
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2328
                                if (_LmLabelPersist.ModelItemObject != null)
2329
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2330
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2331
                                ReleaseCOMObjects(_LmLabelPersist);
2332
                            }
2333
                        }
2334
                    }
2335
                    ReleaseCOMObjects(targetLMConnector);
2336
                }
2337
            }
2338
        }
2339

    
2340
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2341
        {
2342
            LMConnector targetConnector = null;
2343
            Symbol targetSymbol = targetObj as Symbol;
2344
            Symbol connectedSymbol = connectedObj as Symbol;
2345
            Line targetLine = targetObj as Line;
2346
            Line connectedLine = connectedObj as Line;
2347
            if (targetSymbol != null && connectedSymbol != null)
2348
            {
2349
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2350
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2351

    
2352
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2353
                {
2354
                    if (connector.get_ItemStatus() != "Active")
2355
                        continue;
2356

    
2357
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2358
                    {
2359
                        targetConnector = connector;
2360
                        break;
2361
                    }
2362
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2363
                    {
2364
                        targetConnector = connector;
2365
                        break;
2366
                    }
2367
                }
2368

    
2369
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2370
                {
2371
                    if (connector.get_ItemStatus() != "Active")
2372
                        continue;
2373

    
2374
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2375
                    {
2376
                        targetConnector = connector;
2377
                        break;
2378
                    }
2379
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2380
                    {
2381
                        targetConnector = connector;
2382
                        break;
2383
                    }
2384
                }
2385

    
2386
                ReleaseCOMObjects(targetLMSymbol);
2387
                ReleaseCOMObjects(connectedLMSymbol);
2388
            }
2389
            else if (targetLine != null && connectedLine != null)
2390
            {
2391
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2392
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2393

    
2394
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2395
                {
2396
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2397
                    {
2398
                        if (targetConnector != null)
2399
                            break;
2400

    
2401
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2402
                        {
2403
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2404

    
2405
                            if (IsConnected(_LMConnector, connectedModelItem))
2406
                                targetConnector = _LMConnector;
2407
                            else
2408
                                ReleaseCOMObjects(_LMConnector);
2409
                        }
2410
                    }
2411

    
2412
                    ReleaseCOMObjects(targetModelItem);
2413
                }
2414
            }
2415
            else
2416
            {
2417
                LMSymbol connectedLMSymbol = null;
2418
                if (connectedSymbol != null)
2419
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2420
                else if (targetSymbol != null)
2421
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2422
                else
2423
                {
2424

    
2425
                }
2426
                LMModelItem targetModelItem = null;
2427
                if (targetLine != null)
2428
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2429
                else if (connectedLine != null)
2430
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2431
                else
2432
                {
2433

    
2434
                }
2435
                if (connectedLMSymbol != null && targetModelItem != null)
2436
                {
2437
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2438
                    {
2439
                        if (connector.get_ItemStatus() != "Active")
2440
                            continue;
2441

    
2442
                        if (IsConnected(connector, targetModelItem))
2443
                        {
2444
                            targetConnector = connector;
2445
                            break;
2446
                        }
2447
                    }
2448

    
2449
                    if (targetConnector == null)
2450
                    {
2451
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2452
                        {
2453
                            if (connector.get_ItemStatus() != "Active")
2454
                                continue;
2455

    
2456
                            if (IsConnected(connector, targetModelItem))
2457
                            {
2458
                                targetConnector = connector;
2459
                                break;
2460
                            }
2461
                        }
2462
                    }
2463
                }
2464

    
2465
            }
2466

    
2467
            return targetConnector;
2468
        }
2469

    
2470
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2471
        {
2472
            bool result = false;
2473

    
2474
            foreach (LMRepresentation rep in modelItem.Representations)
2475
            {
2476
                if (result)
2477
                    break;
2478

    
2479
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2480
                {
2481
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2482

    
2483
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2484
                        connector.ConnectItem1SymbolObject != null &&
2485
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2486
                    {
2487
                        result = true;
2488
                        ReleaseCOMObjects(_LMConnector);
2489
                        break;
2490
                    }
2491
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2492
                        connector.ConnectItem2SymbolObject != null &&
2493
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2494
                    {
2495
                        result = true;
2496
                        ReleaseCOMObjects(_LMConnector);
2497
                        break;
2498
                    }
2499
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2500
                        connector.ConnectItem1SymbolObject != null &&
2501
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2502
                    {
2503
                        result = true;
2504
                        ReleaseCOMObjects(_LMConnector);
2505
                        break;
2506
                    }
2507
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2508
                        connector.ConnectItem2SymbolObject != null &&
2509
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2510
                    {
2511
                        result = true;
2512
                        ReleaseCOMObjects(_LMConnector);
2513
                        break;
2514
                    }
2515

    
2516
                    ReleaseCOMObjects(_LMConnector);
2517
                }
2518
            }
2519

    
2520

    
2521
            return result;
2522
        }
2523

    
2524
        /// <summary>
2525
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2526
        /// </summary>
2527
        /// <param name="modelItemID1"></param>
2528
        /// <param name="modelItemID2"></param>
2529
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2530
        {
2531
            try
2532
            {
2533
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2534
                _LMAItem item1 = modelItem1.AsLMAItem();
2535
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2536
                _LMAItem item2 = modelItem2.AsLMAItem();
2537

    
2538
                // item2가 item1으로 조인
2539
                _placement.PIDJoinRuns(ref item1, ref item2);
2540
                item1.Commit();
2541
                item2.Commit();
2542

    
2543
                string beforeID = string.Empty;
2544
                string afterID = string.Empty;
2545

    
2546
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2547
                {
2548
                    beforeID = modelItem2.Id;
2549
                    afterID = modelItem1.Id;
2550
                    survivorId = afterID;
2551
                }
2552
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2553
                {
2554
                    beforeID = modelItem1.Id;
2555
                    afterID = modelItem2.Id;
2556
                    survivorId = afterID;
2557
                }
2558
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2559
                    survivorId = null;
2560
                else
2561
                {
2562
                    Log.Write("잘못된 경우");
2563
                    survivorId = null;
2564
                }
2565

    
2566

    
2567
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2568
                {
2569
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2570
                    foreach (var line in lines)
2571
                        line.SPPID.ModelItemId = afterID;
2572
                }
2573

    
2574
                ReleaseCOMObjects(modelItem1);
2575
                ReleaseCOMObjects(item1);
2576
                ReleaseCOMObjects(modelItem2);
2577
                ReleaseCOMObjects(item2);
2578
            }
2579
            catch (Exception ex)
2580
            {
2581
                Log.Write("Join Error");
2582
                Log.Write(ex.Message);
2583
            }
2584
        }
2585

    
2586
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2587
        {
2588
            List<string> modelItemIDs = new List<string>();
2589
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2590
            {
2591
                LMModelItem modelItem = connector.ModelItemObject;
2592
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2593
                    modelItemIDs.Add(modelItem.Id);
2594
                ReleaseCOMObjects(modelItem);
2595
                ReleaseCOMObjects(connector);
2596
            }
2597

    
2598
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2599
            {
2600
                LMModelItem modelItem = connector.ModelItemObject;
2601
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2602
                    modelItemIDs.Add(modelItem.Id);
2603
                ReleaseCOMObjects(modelItem);
2604
                ReleaseCOMObjects(connector);
2605
            }
2606

    
2607

    
2608
            List<string> result = new List<string>();
2609
            modelItemIDs = modelItemIDs.Distinct().ToList();
2610
            string originalName = GetSPPIDFileName(modelId);
2611
            foreach (var item in modelItemIDs)
2612
            {
2613
                string fileName = GetSPPIDFileName(item);
2614
                if (originalName == fileName)
2615
                    result.Add(item);
2616
                else
2617
                {
2618
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2619
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()))
2620
                    {
2621
                        result.Add(item);
2622
                        ReleaseCOMObjects(connector);
2623
                    }
2624
                }
2625
            }
2626
            
2627
            return result;
2628
        }
2629

    
2630
        /// <summary>
2631
        /// PipeRun의 좌표를 가져오는 메서드
2632
        /// </summary>
2633
        /// <param name="modelId"></param>
2634
        /// <returns></returns>
2635
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2636
        {
2637
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2638
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2639

    
2640
            if (modelItem != null)
2641
            {
2642
                foreach (LMRepresentation rep in modelItem.Representations)
2643
                {
2644
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2645
                    {
2646
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2647
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2648
                        dynamic OID = rep.get_GraphicOID().ToString();
2649
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2650
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2651
                        int verticesCount = lineStringGeometry.VertexCount;
2652
                        double[] vertices = null;
2653
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2654
                        for (int i = 0; i < verticesCount; i++)
2655
                        {
2656
                            double x = 0;
2657
                            double y = 0;
2658
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2659
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
2660
                        }
2661
                    }
2662
                }
2663

    
2664
                ReleaseCOMObjects(modelItem);
2665
            }
2666

    
2667
            return connectorVertices;
2668
        }
2669

    
2670
        private List<double[]> GetConnectorVertices(LMConnector connector)
2671
        {
2672
            List<double[]> vertices = new List<double[]>();
2673
            dynamic OID = connector.get_GraphicOID().ToString();
2674
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2675
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2676
            int verticesCount = lineStringGeometry.VertexCount;
2677
            double[] value = null;
2678
            lineStringGeometry.GetVertices(ref verticesCount, ref value);
2679
            for (int i = 0; i < verticesCount; i++)
2680
            {
2681
                double x = 0;
2682
                double y = 0;
2683
                lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2684
                vertices.Add(new double[] { x, y });
2685
            }
2686
            return vertices;
2687
        }
2688

    
2689
        /// <summary>
2690
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
2691
        /// </summary>
2692
        /// <param name="connectorVertices"></param>
2693
        /// <param name="connX"></param>
2694
        /// <param name="connY"></param>
2695
        /// <returns></returns>
2696
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
2697
        {
2698
            double length = double.MaxValue;
2699
            LMConnector targetConnector = null;
2700
            foreach (var item in connectorVertices)
2701
            {
2702
                List<double[]> points = item.Value;
2703
                for (int i = 0; i < points.Count - 1; i++)
2704
                {
2705
                    double[] point1 = points[i];
2706
                    double[] point2 = points[i + 1];
2707
                    double x1 = Math.Min(point1[0], point2[0]);
2708
                    double y1 = Math.Min(point1[1], point2[1]);
2709
                    double x2 = Math.Max(point1[0], point2[0]);
2710
                    double y2 = Math.Max(point1[1], point2[1]);
2711

    
2712
                    if ((x1 <= connX && x2 >= connX) ||
2713
                        (y1 <= connY && y2 >= connY))
2714
                    {
2715
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
2716
                        if (length >= distance)
2717
                        {
2718
                            targetConnector = item.Key;
2719
                            length = distance;
2720
                        }
2721

    
2722
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
2723
                        if (length >= distance)
2724
                        {
2725
                            targetConnector = item.Key;
2726
                            length = distance;
2727
                        }
2728
                    }
2729
                }
2730
            }
2731

    
2732
            // 못찾았을때.
2733
            length = double.MaxValue;
2734
            if (targetConnector == null)
2735
            {
2736
                foreach (var item in connectorVertices)
2737
                {
2738
                    List<double[]> points = item.Value;
2739

    
2740
                    foreach (double[] point in points)
2741
                    {
2742
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
2743
                        if (length >= distance)
2744
                        {
2745
                            targetConnector = item.Key;
2746
                            length = distance;
2747
                        }
2748
                    }
2749
                }
2750
            }
2751

    
2752
            return targetConnector;
2753
        }
2754

    
2755
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
2756
        {
2757
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2758
            if (vertices.Count == 0)
2759
                return null;
2760

    
2761
            double length = double.MaxValue;
2762
            LMConnector targetConnector = null;
2763
            double[] resultPoint = null;
2764
            List<double[]> targetVertices = null;
2765

    
2766
            // Vertices 포인트에 제일 가까운곳
2767
            foreach (var item in vertices)
2768
            {
2769
                List<double[]> points = item.Value;
2770
                for (int i = 0; i < points.Count; i++)
2771
                {
2772
                    double[] point = points[i];
2773
                    double tempX = point[0];
2774
                    double tempY = point[1];
2775

    
2776
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
2777
                    if (length >= distance)
2778
                    {
2779
                        targetConnector = item.Key;
2780
                        length = distance;
2781
                        resultPoint = point;
2782
                        targetVertices = item.Value;
2783
                    }
2784
                }
2785
            }
2786

    
2787
            // Vertices Cross에 제일 가까운곳
2788
            foreach (var item in vertices)
2789
            {
2790
                List<double[]> points = item.Value;
2791
                for (int i = 0; i < points.Count - 1; i++)
2792
                {
2793
                    double[] point1 = points[i];
2794
                    double[] point2 = points[i + 1];
2795

    
2796
                    double maxLineX = Math.Max(point1[0], point2[0]);
2797
                    double minLineX = Math.Min(point1[0], point2[0]);
2798
                    double maxLineY = Math.Max(point1[1], point2[1]);
2799
                    double minLineY = Math.Min(point1[1], point2[1]);
2800

    
2801
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
2802

    
2803
                    double[] crossingPoint = SPPIDUtil.CalcLineCrossingPoint(line.SPPID.START_X, line.SPPID.START_Y, line.SPPID.END_X, line.SPPID.END_Y, point1[0], point1[1], point2[0], point2[1]);
2804
                    if (crossingPoint != null)
2805
                    {
2806
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
2807
                        if (length >= distance)
2808
                        {
2809
                            if (slope == SlopeType.Slope &&
2810
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
2811
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
2812
                            {
2813
                                targetConnector = item.Key;
2814
                                length = distance;
2815
                                resultPoint = crossingPoint;
2816
                                targetVertices = item.Value;
2817
                            }
2818
                            else if (slope == SlopeType.HORIZONTAL &&
2819
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
2820
                            {
2821
                                targetConnector = item.Key;
2822
                                length = distance;
2823
                                resultPoint = crossingPoint;
2824
                                targetVertices = item.Value;
2825
                            }
2826
                            else if (slope == SlopeType.VERTICAL &&
2827
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
2828
                            {
2829
                                targetConnector = item.Key;
2830
                                length = distance;
2831
                                resultPoint = crossingPoint;
2832
                                targetVertices = item.Value;
2833
                            }
2834
                        }
2835
                    }
2836
                }
2837
            }
2838

    
2839
            foreach (var item in vertices)
2840
                if (item.Key != null && item.Key != targetConnector)
2841
                    ReleaseCOMObjects(item.Key);
2842

    
2843
            if (SPPIDUtil.IsBranchLine(line, targetLine))
2844
            {
2845
                double tempResultX = resultPoint[0];
2846
                double tempResultY = resultPoint[1];
2847
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
2848

    
2849
                GridSetting gridSetting = GridSetting.GetInstance();
2850

    
2851
                for (int i = 0; i < targetVertices.Count; i++)
2852
                {
2853
                    double[] point = targetVertices[i];
2854
                    double tempX = targetVertices[i][0];
2855
                    double tempY = targetVertices[i][1];
2856
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
2857
                    if (tempX == tempResultX && tempY == tempResultY)
2858
                    {
2859
                        if (i == 0)
2860
                        {
2861
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
2862
                            bool containZeroLength = false;
2863
                            if (connSymbol != null)
2864
                            {
2865
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
2866
                                {
2867
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
2868
                                        containZeroLength = true;
2869
                                }
2870
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
2871
                                {
2872
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
2873
                                        containZeroLength = true;
2874
                                }
2875
                            }
2876

    
2877
                            if (connSymbol == null ||
2878
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
2879
                                containZeroLength)
2880
                            {
2881
                                bool bCalcX = false;
2882
                                bool bCalcY = false;
2883
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
2884
                                    bCalcX = true;
2885
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
2886
                                    bCalcY = true;
2887
                                else
2888
                                {
2889
                                    bCalcX = true;
2890
                                    bCalcY = true;
2891
                                }
2892

    
2893
                                if (bCalcX)
2894
                                {
2895
                                    double nextX = targetVertices[i + 1][0];
2896
                                    double newX = 0;
2897
                                    if (nextX > tempX)
2898
                                    {
2899
                                        newX = tempX + gridSetting.Length;
2900
                                        if (newX > nextX)
2901
                                            newX = (point[0] + nextX) / 2;
2902
                                    }
2903
                                    else
2904
                                    {
2905
                                        newX = tempX - gridSetting.Length;
2906
                                        if (newX < nextX)
2907
                                            newX = (point[0] + nextX) / 2;
2908
                                    }
2909
                                    resultPoint = new double[] { newX, resultPoint[1] };
2910
                                }
2911

    
2912
                                if (bCalcY)
2913
                                {
2914
                                    double nextY = targetVertices[i + 1][1];
2915
                                    double newY = 0;
2916
                                    if (nextY > tempY)
2917
                                    {
2918
                                        newY = tempY + gridSetting.Length;
2919
                                        if (newY > nextY)
2920
                                            newY = (point[1] + nextY) / 2;
2921
                                    }
2922
                                    else
2923
                                    {
2924
                                        newY = tempY - gridSetting.Length;
2925
                                        if (newY < nextY)
2926
                                            newY = (point[1] + nextY) / 2;
2927
                                    }
2928
                                    resultPoint = new double[] { resultPoint[0], newY };
2929
                                }
2930
                            }
2931
                        }
2932
                        else if (i == targetVertices.Count - 1)
2933
                        {
2934
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
2935
                            bool containZeroLength = false;
2936
                            if (connSymbol != null)
2937
                            {
2938
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
2939
                                {
2940
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
2941
                                        containZeroLength = true;
2942
                                }
2943
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
2944
                                {
2945
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
2946
                                        containZeroLength = true;
2947
                                }
2948
                            }
2949

    
2950
                            if (connSymbol == null ||
2951
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
2952
                                containZeroLength)
2953
                            {
2954
                                bool bCalcX = false;
2955
                                bool bCalcY = false;
2956
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
2957
                                    bCalcX = true;
2958
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
2959
                                    bCalcY = true;
2960
                                else
2961
                                {
2962
                                    bCalcX = true;
2963
                                    bCalcY = true;
2964
                                }
2965

    
2966
                                if (bCalcX)
2967
                                {
2968
                                    double nextX = targetVertices[i - 1][0];
2969
                                    double newX = 0;
2970
                                    if (nextX > tempX)
2971
                                    {
2972
                                        newX = tempX + gridSetting.Length;
2973
                                        if (newX > nextX)
2974
                                            newX = (point[0] + nextX) / 2;
2975
                                    }
2976
                                    else
2977
                                    {
2978
                                        newX = tempX - gridSetting.Length;
2979
                                        if (newX < nextX)
2980
                                            newX = (point[0] + nextX) / 2;
2981
                                    }
2982
                                    resultPoint = new double[] { newX, resultPoint[1] };
2983
                                }
2984

    
2985
                                if (bCalcY)
2986
                                {
2987
                                    double nextY = targetVertices[i - 1][1];
2988
                                    double newY = 0;
2989
                                    if (nextY > tempY)
2990
                                    {
2991
                                        newY = tempY + gridSetting.Length;
2992
                                        if (newY > nextY)
2993
                                            newY = (point[1] + nextY) / 2;
2994
                                    }
2995
                                    else
2996
                                    {
2997
                                        newY = tempY - gridSetting.Length;
2998
                                        if (newY < nextY)
2999
                                            newY = (point[1] + nextY) / 2;
3000
                                    }
3001
                                    resultPoint = new double[] { resultPoint[0], newY };
3002
                                }
3003
                            }
3004
                        }
3005
                        break;
3006
                    }
3007
                }
3008
            }
3009

    
3010
            x = resultPoint[0];
3011
            y = resultPoint[1];
3012

    
3013
            return targetConnector;
3014
        }
3015

    
3016
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3017
        {
3018
            LMConnector result = null;
3019
            List<LMConnector> connectors = new List<LMConnector>();
3020
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3021

    
3022
            if (modelItem != null)
3023
            {
3024
                foreach (LMRepresentation rep in modelItem.Representations)
3025
                {
3026
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3027
                        connectors.Add(dataSource.GetConnector(rep.Id));
3028
                }
3029

    
3030
                ReleaseCOMObjects(modelItem);
3031
            }
3032

    
3033
            if (connectors.Count == 1)
3034
                result = connectors[0];
3035
            else
3036
                foreach (var item in connectors)
3037
                    ReleaseCOMObjects(item);
3038

    
3039
            return result;
3040
        }
3041

    
3042
        /// <summary>
3043
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3044
        /// </summary>
3045
        /// <param name="lineNumber"></param>
3046
        private void LineNumberModelingOnlyOne(Line line)
3047
        {
3048
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3049
            if (lineNumber != null)
3050
            {
3051
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3052
                if (connectedLMConnector != null)
3053
                {
3054
                    double x = 0;
3055
                    double y = 0;
3056
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3057

    
3058
                    Array points = new double[] { 0, x, y };
3059
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3060

    
3061
                    if (_LmLabelPresist != null)
3062
                    {
3063
                        _LmLabelPresist.Commit();
3064
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3065
                        ReleaseCOMObjects(_LmLabelPresist);
3066
                    }
3067
                }
3068
            }
3069
        }
3070
        private void LineNumberModeling(LineNumber lineNumber)
3071
        {
3072
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3073
            if (line != null)
3074
            {
3075
                double x = 0;
3076
                double y = 0;
3077
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3078

    
3079
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3080
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3081
                if (connectedLMConnector != null)
3082
                {
3083
                    Array points = new double[] { 0, x, y };
3084
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3085

    
3086
                    if (_LmLabelPresist != null)
3087
                    {
3088
                        _LmLabelPresist.Commit();
3089
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3090
                        ReleaseCOMObjects(_LmLabelPresist);
3091
                    }
3092
                }
3093

    
3094
                foreach (var item in connectorVertices)
3095
                    ReleaseCOMObjects(item.Key);
3096
            }
3097
        }
3098
        /// <summary>
3099
        /// Flow Mark Modeling
3100
        /// </summary>
3101
        /// <param name="line"></param>
3102
        private void FlowMarkModeling(Line line)
3103
        {
3104
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3105
            {
3106
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3107
                if (connector != null)
3108
                {
3109
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3110
                    List<double[]> vertices = GetConnectorVertices(connector);
3111
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3112
                    double[] point = vertices[vertices.Count - 1];
3113
                    Array array = new double[] { 0, point[0], point[1] };
3114
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3115
                    if (_LMLabelPersist != null)
3116
                        ReleaseCOMObjects(_LMLabelPersist);
3117
                }
3118
            }
3119
        }
3120

    
3121
        /// <summary>
3122
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3123
        /// </summary>
3124
        /// <param name="lineNumber"></param>
3125
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3126
        {
3127
            foreach (LineRun run in lineNumber.RUNS)
3128
            {
3129
                foreach (var item in run.RUNITEMS)
3130
                {
3131
                    if (item.GetType() == typeof(Symbol))
3132
                    {
3133
                        Symbol symbol = item as Symbol;
3134
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3135
                        if (_LMSymbol != null)
3136
                        {
3137
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3138

    
3139
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3140
                            {
3141
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3142
                                {
3143
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3144
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3145
                                    {
3146
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3147
                                        if (_LMAAttribute != null)
3148
                                        {
3149
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3150
                                                _LMAAttribute.set_Value(attribute.VALUE);
3151
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3152
                                                _LMAAttribute.set_Value(attribute.VALUE);
3153
                                        }
3154
                                    }
3155
                                }
3156
                                _LMModelItem.Commit();
3157
                            }
3158
                            if (_LMModelItem != null)
3159
                                ReleaseCOMObjects(_LMModelItem);
3160
                        }
3161
                        if (_LMSymbol != null)
3162
                            ReleaseCOMObjects(_LMSymbol);
3163
                    }
3164
                    else if (item.GetType() == typeof(Line))
3165
                    {
3166
                        Line line = item as Line;
3167
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3168
                        {
3169
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3170
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3171
                            {
3172
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3173
                                {
3174
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3175
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3176
                                    {
3177
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3178
                                        if (_LMAAttribute != null)
3179
                                        {
3180
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3181
                                                _LMAAttribute.set_Value(attribute.VALUE);
3182
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3183
                                                _LMAAttribute.set_Value(attribute.VALUE);
3184

    
3185
                                        }
3186
                                    }
3187
                                }
3188
                                _LMModelItem.Commit();
3189
                            }
3190
                            if (_LMModelItem != null)
3191
                                ReleaseCOMObjects(_LMModelItem);
3192
                            endLine.Add(line.SPPID.ModelItemId);
3193
                        }
3194
                    }
3195
                }
3196
            }
3197
        }
3198

    
3199
        /// <summary>
3200
        /// Symbol Attribute 입력 메서드
3201
        /// </summary>
3202
        /// <param name="item"></param>
3203
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3204
        {
3205
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3206
            string sRep = null;
3207
            if (targetItem.GetType() == typeof(Symbol))
3208
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3209
            else if (targetItem.GetType() == typeof(Equipment))
3210
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3211

    
3212
            if (!string.IsNullOrEmpty(sRep))
3213
            {
3214
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3215
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3216
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3217
                
3218
                foreach (var item in targetAttributes)
3219
                {
3220
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3221
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3222
                    {
3223
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3224
                        if (_Attribute != null)
3225
                        {
3226
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3227
                            if (associItem != null)
3228
                            {
3229
                                if (associItem.GetType() == typeof(Text))
3230
                                {
3231
                                    Text text = associItem as Text;
3232
                                    text.SPPID.RepresentationId = "Attribute";
3233
                                }
3234
                                else if (associItem.GetType() == typeof(Note))
3235
                                {
3236
                                    Note note = associItem as Note;
3237
                                    note.SPPID.RepresentationId = "Attribute";
3238
                                }
3239
                            }
3240
                            _Attribute.set_Value(item.VALUE);
3241
                        }
3242
                            
3243
                    }
3244
                }
3245
                _LMModelItem.Commit();
3246

    
3247
                ReleaseCOMObjects(_Attributes);
3248
                ReleaseCOMObjects(_LMModelItem);
3249
                ReleaseCOMObjects(_LMSymbol);
3250
            }
3251
        }
3252

    
3253
        /// <summary>
3254
        /// Input SpecBreak Attribute
3255
        /// </summary>
3256
        /// <param name="specBreak"></param>
3257
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3258
        {
3259
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3260
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3261

    
3262
            if (upStreamObj != null &&
3263
                downStreamObj != null)
3264
            {
3265
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3266

    
3267
                if (targetLMConnector != null)
3268
                {
3269
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3270
                    {
3271
                        string symbolPath = _LMLabelPersist.get_FileName();
3272
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3273
                        if (mapping != null)
3274
                        {
3275
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3276
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3277
                            {
3278
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3279
                                if (values.Length == 2)
3280
                                {
3281
                                    string upStreamValue = values[0];
3282
                                    string downStreamValue = values[1];
3283

    
3284
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3285
                                }
3286
                            }
3287
                        }
3288
                    }
3289

    
3290
                    ReleaseCOMObjects(targetLMConnector);
3291
                }
3292
            }
3293

    
3294

    
3295
            #region 내부에서만 쓰는 메서드
3296
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3297
            {
3298
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3299
                Line upStreamLine = _upStreamObj as Line;
3300
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3301
                Line downStreamLine = _downStreamObj as Line;
3302
                // 둘다 Line일 경우
3303
                if (upStreamLine != null && downStreamLine != null)
3304
                {
3305
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3306
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3307
                }
3308
                // 둘다 Symbol일 경우
3309
                else if (upStreamSymbol != null && downStreamSymbol != null)
3310
                {
3311
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3312
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3313
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3314

    
3315
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3316
                    {
3317
                        if (connector.get_ItemStatus() != "Active")
3318
                            continue;
3319

    
3320
                        if (connector.Id != zeroLenthConnector.Id)
3321
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3322
                    }
3323

    
3324
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3325
                    {
3326
                        if (connector.get_ItemStatus() != "Active")
3327
                            continue;
3328

    
3329
                        if (connector.Id != zeroLenthConnector.Id)
3330
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3331
                    }
3332

    
3333
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3334
                    {
3335
                        if (connector.get_ItemStatus() != "Active")
3336
                            continue;
3337

    
3338
                        if (connector.Id != zeroLenthConnector.Id)
3339
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3340
                    }
3341

    
3342
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3343
                    {
3344
                        if (connector.get_ItemStatus() != "Active")
3345
                            continue;
3346

    
3347
                        if (connector.Id != zeroLenthConnector.Id)
3348
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3349
                    }
3350

    
3351
                    ReleaseCOMObjects(zeroLenthConnector);
3352
                    ReleaseCOMObjects(upStreamLMSymbol);
3353
                    ReleaseCOMObjects(downStreamLMSymbol);
3354
                }
3355
                else if (upStreamSymbol != null && downStreamLine != null)
3356
                {
3357
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3358
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3359
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3360

    
3361
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3362
                    {
3363
                        if (connector.get_ItemStatus() != "Active")
3364
                            continue;
3365

    
3366
                        if (connector.Id != zeroLenthConnector.Id)
3367
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3368
                    }
3369

    
3370
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3371
                    {
3372
                        if (connector.get_ItemStatus() != "Active")
3373
                            continue;
3374

    
3375
                        if (connector.Id != zeroLenthConnector.Id)
3376
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3377
                    }
3378

    
3379
                    ReleaseCOMObjects(zeroLenthConnector);
3380
                    ReleaseCOMObjects(upStreamLMSymbol);
3381
                }
3382
                else if (upStreamLine != null && downStreamSymbol != null)
3383
                {
3384
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3385
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3386
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3387

    
3388
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3389
                    {
3390
                        if (connector.get_ItemStatus() != "Active")
3391
                            continue;
3392

    
3393
                        if (connector.Id != zeroLenthConnector.Id)
3394
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3395
                    }
3396

    
3397
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3398
                    {
3399
                        if (connector.get_ItemStatus() != "Active")
3400
                            continue;
3401

    
3402
                        if (connector.Id != zeroLenthConnector.Id)
3403
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3404
                    }
3405

    
3406
                    ReleaseCOMObjects(zeroLenthConnector);
3407
                    ReleaseCOMObjects(downStreamLMSymbol);
3408
                }
3409
            }
3410

    
3411
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3412
            {
3413
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3414
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3415
                {
3416
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3417
                    if (_LMAAttribute != null)
3418
                    {
3419
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3420
                            _LMAAttribute.set_Value(value);
3421
                        else if (_LMAAttribute.get_Value() != value)
3422
                            _LMAAttribute.set_Value(value);
3423
                    }
3424

    
3425
                    _LMModelItem.Commit();
3426
                }
3427
                if (_LMModelItem != null)
3428
                    ReleaseCOMObjects(_LMModelItem);
3429
            }
3430

    
3431
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3432
            {
3433
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3434
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3435
                {
3436
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3437
                    if (_LMAAttribute != null)
3438
                    {
3439
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3440
                            _LMAAttribute.set_Value(value);
3441
                        else if (_LMAAttribute.get_Value() != value)
3442
                            _LMAAttribute.set_Value(value);
3443
                    }
3444

    
3445
                    _LMModelItem.Commit();
3446
                }
3447
                if (_LMModelItem != null)
3448
                    ReleaseCOMObjects(_LMModelItem);
3449
            }
3450
            #endregion
3451
        }
3452

    
3453
        /// <summary>
3454
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3455
        /// </summary>
3456
        /// <param name="text"></param>
3457
        private void TextModeling(Text text)
3458
        {
3459
            LMSymbol _LMSymbol = null;
3460
            LMConnector connectedLMConnector = null;
3461
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3462
            if (text.ASSOCIATION)
3463
            {
3464
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3465
                if (owner != null && owner.GetType() == typeof(Symbol))
3466
                {
3467
                    Symbol symbol = owner as Symbol;
3468
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3469
                    if (_LMSymbol != null)
3470
                    {
3471
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3472
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3473
                        {
3474
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3475

    
3476
                            if (mapping != null)
3477
                            {
3478
                                double x = 0;
3479
                                double y = 0;
3480

    
3481
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3482
                                Array array = new double[] { 0, x, y };
3483

    
3484
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3485
                                if (_LMLabelPersist != null)
3486
                                {
3487
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3488
                                    _LMLabelPersist.Commit();
3489
                                    ReleaseCOMObjects(_LMLabelPersist);
3490
                                }
3491
                            }
3492
                        }
3493
                    }
3494
                }
3495
                else if (owner != null && owner.GetType() == typeof(Line))
3496
                {
3497
                    Line line = owner as Line;
3498
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3499
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3500

    
3501
                    if (connectedLMConnector != null)
3502
                    {
3503
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3504
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3505
                        {
3506
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3507

    
3508
                            if (mapping != null)
3509
                            {
3510
                                double x = 0;
3511
                                double y = 0;
3512

    
3513
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3514
                                Array array = new double[] { 0, x, y };
3515

    
3516
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3517
                                if (_LMLabelPersist != null)
3518
                                {
3519
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3520
                                    _LMLabelPersist.Commit();
3521
                                    ReleaseCOMObjects(_LMLabelPersist);
3522
                                }
3523
                            }
3524
                        }
3525
                    }
3526
                }
3527
            }
3528
            else
3529
            {
3530
                LMItemNote _LMItemNote = null;
3531
                LMAAttribute _LMAAttribute = null;
3532

    
3533
                double x = 0;
3534
                double y = 0;
3535
                double angle = text.ANGLE;
3536
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3537

    
3538
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3539
                if (_LMSymbol != null)
3540
                {
3541
                    _LMSymbol.Commit();
3542
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3543
                    if (_LMItemNote != null)
3544
                    {
3545
                        _LMItemNote.Commit();
3546
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3547
                        if (_LMAAttribute != null)
3548
                        {
3549
                            _LMAAttribute.set_Value(text.VALUE);
3550
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3551
                            _LMItemNote.Commit();
3552

    
3553
                            if (_LMAAttribute != null)
3554
                                ReleaseCOMObjects(_LMAAttribute);
3555
                            if (_LMItemNote != null)
3556
                                ReleaseCOMObjects(_LMItemNote);
3557
                        }
3558
                    }
3559
                }
3560
            }
3561
            if (_LMSymbol != null)
3562
                ReleaseCOMObjects(_LMSymbol);
3563
        }
3564

    
3565
        /// <summary>
3566
        /// Note Modeling
3567
        /// </summary>
3568
        /// <param name="note"></param>
3569
        private void NoteModeling(Note note)
3570
        {
3571
            LMSymbol _LMSymbol = null;
3572
            LMItemNote _LMItemNote = null;
3573
            LMAAttribute _LMAAttribute = null;
3574

    
3575
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3576
            {
3577
                double x = 0;
3578
                double y = 0;
3579

    
3580
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
3581

    
3582
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
3583
                if (_LMSymbol != null)
3584
                {
3585
                    _LMSymbol.Commit();
3586
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3587
                    if (_LMItemNote != null)
3588
                    {
3589
                        _LMItemNote.Commit();
3590
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3591
                        if (_LMAAttribute != null)
3592
                        {
3593
                            _LMAAttribute.set_Value(note.VALUE);
3594
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3595
                            _LMItemNote.Commit();
3596
                        }
3597
                    }
3598
                }
3599
            }
3600

    
3601
            if (_LMAAttribute != null)
3602
                ReleaseCOMObjects(_LMAAttribute);
3603
            if (_LMItemNote != null)
3604
                ReleaseCOMObjects(_LMItemNote);
3605
            if (_LMSymbol != null)
3606
                ReleaseCOMObjects(_LMSymbol);
3607
        }
3608

    
3609
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
3610
        {
3611
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
3612
            if (modelItem != null)
3613
            {
3614
                foreach (LMRepresentation rep in modelItem.Representations)
3615
                {
3616
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3617
                    {
3618
                        LMConnector connector = dataSource.GetConnector(rep.Id);
3619
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
3620
                        {
3621
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
3622
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3623
                            if (modelItemIds.Count == 1)
3624
                            {
3625
                                string joinModelItemId = modelItemIds[0];
3626
                                CheckZeroLengthAndLabel(ref joinModelItemId);
3627
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3628
                                if (survivorId != null)
3629
                                    break;
3630
                            }
3631
                        }
3632
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
3633
                        {
3634
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
3635
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3636
                            if (modelItemIds.Count == 1)
3637
                            {
3638
                                string joinModelItemId = modelItemIds[0];
3639
                                CheckZeroLengthAndLabel(ref joinModelItemId);
3640
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3641
                                if (survivorId != null)
3642
                                    break;
3643
                            }
3644
                        }
3645
                    }
3646
                }
3647
            }
3648

    
3649
            void CheckZeroLengthAndLabel(ref string _modelItemId)
3650
            {
3651
                LMConnector connector = GetLMConnectorOnlyOne(_modelItemId);
3652
                if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()) && connector.LabelPersists.Count == 0)
3653
                {
3654
                    string symbolPath = GetSPPIDFileName(modelItem);
3655
                    LMConnector newConnector = ReModelingLMConnector(connector, symbolPath);
3656
                    ReleaseCOMObjects(connector);
3657
                    _modelItemId = newConnector.ModelItemID;
3658
                    ReleaseCOMObjects(newConnector);
3659
                }
3660
            }
3661
        }
3662

    
3663
        /// <summary>
3664
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
3665
        /// </summary>
3666
        /// <param name="x"></param>
3667
        /// <param name="y"></param>
3668
        /// <param name="originX"></param>
3669
        /// <param name="originY"></param>
3670
        /// <param name="SPPIDLabelLocation"></param>
3671
        /// <param name="location"></param>
3672
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
3673
        {
3674
            if (location == Location.None)
3675
            {
3676
                x = originX;
3677
                y = originY;
3678
            }
3679
            else
3680
            {
3681
                if (location.HasFlag(Location.Center))
3682
                {
3683
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
3684
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
3685
                }
3686

    
3687
                if (location.HasFlag(Location.Left))
3688
                    x = SPPIDLabelLocation.X1;
3689
                else if (location.HasFlag(Location.Right))
3690
                    x = SPPIDLabelLocation.X2;
3691

    
3692
                if (location.HasFlag(Location.Down))
3693
                    y = SPPIDLabelLocation.Y1;
3694
                else if (location.HasFlag(Location.Up))
3695
                    y = SPPIDLabelLocation.Y2;
3696
            }
3697
        }
3698

    
3699
        /// <summary>
3700
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
3701
        /// 1. Angle Valve
3702
        /// 2. 3개로 이루어진 Symbol Group
3703
        /// </summary>
3704
        /// <returns></returns>
3705
        private List<Symbol> GetPrioritySymbol()
3706
        {
3707
            DataTable symbolTable = document.SymbolTable;
3708
            // List에 순서대로 쌓는다.
3709
            List<Symbol> symbols = new List<Symbol>();
3710

    
3711
            // Angle Valve 부터
3712
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
3713
            {
3714
                if (!symbols.Contains(symbol))
3715
                {
3716
                    double originX = 0;
3717
                    double originY = 0;
3718

    
3719
                    // ID2 Table에서 Original Point 가져옴.
3720
                    string OriginalPoint = symbolTable.Select(string.Format("UID = {0}", symbol.DBUID))[0]["OriginalPoint"].ToString();
3721
                    SPPIDUtil.ConvertPointBystring(OriginalPoint, ref originX, ref originY);
3722

    
3723
                    SlopeType slopeType1 = SlopeType.None;
3724
                    SlopeType slopeType2 = SlopeType.None;
3725
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
3726
                    {
3727
                        double connectorX = 0;
3728
                        double connectorY = 0;
3729
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
3730
                        if (slopeType1 == SlopeType.None)
3731
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3732
                        else
3733
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3734
                    }
3735

    
3736
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
3737
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
3738
                        symbols.Add(symbol);
3739
                }
3740
            }
3741

    
3742
            List<Symbol> tempSymbols = new List<Symbol>();
3743
            // Conn 갯수 기준
3744
            foreach (var item in document.SYMBOLS)
3745
            {
3746
                if (!symbols.Contains(item))
3747
                    tempSymbols.Add(item);
3748
            }
3749
            tempSymbols.Sort(SortSymbolPriority);
3750
            symbols.AddRange(tempSymbols);
3751

    
3752
            return symbols;
3753
        }
3754

    
3755
        private void SetPriorityLine()
3756
        {
3757
            document.LINES.Sort(SortLinePriority);
3758

    
3759
            int SortLinePriority(Line a, Line b)
3760
            {
3761
                // Branch 없는것부터
3762
                int branchRetval = CompareBranchLine(a, b);
3763
                if (branchRetval != 0)
3764
                {
3765
                    return branchRetval;
3766
                }
3767
                else
3768
                {
3769
                    // Symbol 연결 갯수
3770
                    int connSymbolRetval = CompareConnSymbol(a, b);
3771
                    if (connSymbolRetval != 0)
3772
                    {
3773
                        return connSymbolRetval;
3774
                    }
3775
                    else
3776
                    {
3777
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
3778
                        int connItemRetval = CompareConnItem(a, b);
3779
                        if (connItemRetval != 0)
3780
                        {
3781
                            return connItemRetval;
3782
                        }
3783
                        else
3784
                        {
3785
                            // ConnectedItem이 없는것
3786
                            int noneConnRetval = CompareNoneConn(a, b);
3787
                            if (noneConnRetval != 0)
3788
                            {
3789
                                return noneConnRetval;
3790
                            }
3791
                            else
3792
                            {
3793

    
3794
                            }
3795
                        }
3796
                    }
3797
                }
3798

    
3799
                return 0;
3800
            }
3801

    
3802
            int CompareNotSegmentLine(Line a, Line b)
3803
            {
3804
                List<Connector> connectorsA = a.CONNECTORS
3805
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3806
                    .ToList();
3807

    
3808
                List<Connector> connectorsB = b.CONNECTORS
3809
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3810
                    .ToList();
3811

    
3812
                // 오름차순
3813
                return connectorsB.Count.CompareTo(connectorsA.Count);
3814
            }
3815

    
3816
            int CompareConnSymbol(Line a, Line b)
3817
            {
3818
                List<Connector> connectorsA = a.CONNECTORS
3819
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3820
                    .ToList();
3821

    
3822
                List<Connector> connectorsB = b.CONNECTORS
3823
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3824
                    .ToList();
3825

    
3826
                // 오름차순
3827
                return connectorsB.Count.CompareTo(connectorsA.Count);
3828
            }
3829

    
3830
            int CompareConnItem(Line a, Line b)
3831
            {
3832
                List<Connector> connectorsA = a.CONNECTORS
3833
                    .Where(conn => conn.ConnectedObject != null && 
3834
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
3835
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
3836
                    .ToList();
3837

    
3838
                List<Connector> connectorsB = b.CONNECTORS
3839
                    .Where(conn => conn.ConnectedObject != null &&
3840
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
3841
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
3842
                    .ToList();
3843

    
3844
                // 오름차순
3845
                return connectorsB.Count.CompareTo(connectorsA.Count);
3846
            }
3847

    
3848
            int CompareBranchLine(Line a, Line b)
3849
            {
3850
                List<Connector> connectorsA = a.CONNECTORS
3851
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
3852
                    .ToList();
3853
                List<Connector> connectorsB = b.CONNECTORS
3854
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
3855
                    .ToList();
3856

    
3857
                // 내림차순
3858
                return connectorsA.Count.CompareTo(connectorsB.Count);
3859
            }
3860

    
3861
            int CompareNoneConn(Line a, Line b)
3862
            {
3863
                List<Connector> connectorsA = a.CONNECTORS
3864
                    .Where(conn => conn.ConnectedObject == null)
3865
                    .ToList();
3866

    
3867
                List<Connector> connectorsB = b.CONNECTORS
3868
                    .Where(conn => conn.ConnectedObject == null)
3869
                    .ToList();
3870

    
3871
                // 오름차순
3872
                return connectorsB.Count.CompareTo(connectorsA.Count);
3873
            }
3874
        }
3875

    
3876
        private void SortBranchLines()
3877
        {
3878
            BranchLines.Sort(SortBranchLine);
3879
            int SortBranchLine(Line a, Line b)
3880
            {
3881
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
3882
                 x.ConnectedObject.GetType() == typeof(Line) &&
3883
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
3884
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
3885

    
3886
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
3887
                 x.ConnectedObject.GetType() == typeof(Line) &&
3888
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
3889
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
3890

    
3891
                // 내림차순
3892
                return countA.CompareTo(countB);
3893
            }
3894
        }
3895

    
3896
        private static int SortSymbolPriority(Symbol a, Symbol b)
3897
        {
3898
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
3899
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
3900
            int retval = countB.CompareTo(countA);
3901
            if (retval != 0)
3902
                return retval;
3903
            else
3904
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
3905
        }
3906

    
3907
        private string GetSPPIDFileName(LMModelItem modelItem)
3908
        {
3909
            string symbolPath = null;
3910
            foreach (LMRepresentation rep in modelItem.Representations)
3911
            {
3912
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
3913
                {
3914
                    symbolPath = rep.get_FileName();
3915
                    break;
3916
                }
3917
            }
3918
            return symbolPath;
3919
        }
3920

    
3921
        private string GetSPPIDFileName(string modelItemId)
3922
        {
3923
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
3924
            string symbolPath = null;
3925
            foreach (LMRepresentation rep in modelItem.Representations)
3926
            {
3927
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
3928
                {
3929
                    symbolPath = rep.get_FileName();
3930
                    break;
3931
                }
3932
            }
3933
            ReleaseCOMObjects(modelItem);
3934
            return symbolPath;
3935
        }
3936

    
3937
        /// <summary>
3938
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
3939
        /// </summary>
3940
        /// <param name="graphicOID"></param>
3941
        /// <param name="milliseconds"></param>
3942
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
3943
        {
3944
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
3945
            {
3946
                double minX = 0;
3947
                double minY = 0;
3948
                double maxX = 0;
3949
                double maxY = 0;
3950
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
3951
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
3952

    
3953
                Thread.Sleep(milliseconds);
3954
            }
3955
        }
3956

    
3957
        /// <summary>
3958
        /// ComObject를 Release
3959
        /// </summary>
3960
        /// <param name="objVars"></param>
3961
        public void ReleaseCOMObjects(params object[] objVars)
3962
        {
3963
            int intNewRefCount = 0;
3964
            foreach (object obj in objVars)
3965
            {
3966
                if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
3967
                    intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
3968
            }
3969
        }
3970
    }
3971
}
클립보드 이미지 추가 (최대 크기: 500 MB)