프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 209a7ef9

이력 | 보기 | 이력해설 | 다운로드 (188 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, 18);
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
                    // Clear Attribute
99
                    RunClearValueInconsistancy();
100
                    // EndBreak Modeling
101
                    RunEndBreakModeling();
102
                    // SpecBreak Modeling
103
                    RunSpecBreakModeling();
104
                    // Join SameConnector
105
                    RunJoinRunForSameConnector();
106
                    // Check FlowDirection
107
                    RunFlowDirection();
108
                    // Join Run
109
                    RunJoinRun();
110
                    //Line Number Modeling
111
                    RunLineNumberModeling();
112
                    // Note Modeling
113
                    RunNoteModeling();
114
                    // Text Modeling
115
                    RunTextModeling();
116
                    // Input LineNumber Attribute
117
                    RunInputLineNumberAttribute();
118
                    // Input Symbol Attribute
119
                    RunInputSymbolAttribute();
120
                    // Input SpecBreak Attribute
121
                    RunInputSpecBreakAttribute();
122
                    // Label Symbol Modeling
123
                    RunLabelSymbolModeling();
124

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

    
140
                if (currentDrawing != null)
141
                    ReleaseCOMObjects(currentDrawing);
142

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

    
149
                ReleaseCOMObjects(dataSource);
150
                ReleaseCOMObjects(_placement);
151

    
152
                Project_DB.InsertDrawingInfo(document.PATH, drawingNumber, drawingName, document);
153
                if (SplashScreenManager.Default.IsSplashFormVisible)
154
                {
155
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
156
                    SplashScreenManager.CloseForm(false);
157
                    Log.Write("\r\n");
158
                }
159
            }
160
        }
161
        private void RunEquipmentModeling()
162
        {
163
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
164
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
165
            foreach (Equipment item in document.Equipments)
166
            {
167
                try
168
                {
169
                    EquipmentModeling(item);
170
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
171
                }
172
                catch (Exception ex)
173
                {
174
                    Log.Write("Error in EquipmentModeling");
175
                    Log.Write("UID : " + item.UID);
176
                    Log.Write(ex.Message);
177
                    Log.Write(ex.StackTrace);
178
                }
179
            }
180
        }
181
        private void RunSymbolModeling()
182
        {
183
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
184
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
185
            prioritySymbols = GetPrioritySymbol();
186
            foreach (var item in prioritySymbols)
187
            {
188
                try
189
                {
190
                    SymbolModelingBySymbol(item);
191
                }
192
                catch (Exception ex)
193
                {
194
                    Log.Write("Error in SymbolModelingByPriority");
195
                    Log.Write("UID : " + item.UID);
196
                    Log.Write(ex.Message);
197
                    Log.Write(ex.StackTrace);
198
                }
199
            }
200
        }
201
        private void RunLineModeling()
202
        {
203
            List<Line> AllLine = document.LINES.ToList();
204
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
205
            !SPPIDUtil.IsBranchedLine(document, x));
206
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
207

    
208
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
209
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
210

    
211
            SetPriorityLine(step1_Line);
212
            foreach (var item in step1_Line)
213
            {
214
                try
215
                {
216
                    NewLineModeling(item);
217
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
218
                }
219
                catch (Exception ex)
220
                {
221
                    Log.Write("Error in NewLineModeling");
222
                    Log.Write("UID : " + item.UID);
223
                    Log.Write(ex.Message);
224
                    Log.Write(ex.StackTrace);
225
                }
226
            }
227

    
228
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
229
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
230
            int branchCount = BranchLines.Count;
231
            while (BranchLines.Count > 0)
232
            {
233
                try
234
                {
235
                    SortBranchLines();
236
                    Line item = BranchLines[0];
237
                    if (EnableBranchModeling(item))
238
                    {
239
                        NewLineModeling(item, true);
240
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
241
                    }
242
                    else
243
                        throw new Exception("Fail Branch Modeling");
244
                }
245
                catch (Exception ex)
246
                {
247
                    Log.Write("Error in NewLineModeling");
248
                    Log.Write("UID : " + BranchLines[0].UID);
249
                    Log.Write(ex.Message);
250
                    Log.Write(ex.StackTrace);
251
                    break;
252
                }
253

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

    
262
                    return result;
263
                }
264
            }
265

    
266
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
267
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
268
            foreach (var item in stepLast_Line)
269
            {
270
                try
271
                {
272
                    NewLineModeling(item);
273
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
274
                }
275
                catch (Exception ex)
276
                {
277
                    Log.Write("Error in NewLineModeling");
278
                    Log.Write("UID : " + item.UID);
279
                    Log.Write(ex.Message);
280
                    Log.Write(ex.StackTrace);
281
                }
282
            }
283
        }
284
        private void RunClearValueInconsistancy()
285
        {
286
            int count = 1;
287
            bool loop = true;
288
            while (loop)
289
            {
290
                loop = false;
291
                LMAFilter filter = new LMAFilter();
292
                LMACriterion criterion = new LMACriterion();
293
                filter.ItemType = "Relationship";
294
                criterion.SourceAttributeName = "SP_DRAWINGID";
295
                criterion.Operator = "=";
296
                criterion.set_ValueAttribute(currentDrawing.Id);
297
                filter.get_Criteria().Add(criterion);
298

    
299
                LMRelationships relationships = new LMRelationships();
300
                relationships.Collect(dataSource, Filter: filter);
301

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

    
501
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
502

    
503
                        ReleaseCOMObjects(modelItem);
504
                    }
505
                }
506

    
507
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
508
            }
509
            foreach (var modelId in ZeroLengthModelItemID)
510
            {
511
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
512
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
513
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
514
                {
515
                    attribute.set_Value("End 1 is upstream (Inlet)");
516
                    zeroLengthModelItem.Commit();
517
                }
518

    
519
                SetFlowDirectionByLine(modelId);
520

    
521
                ReleaseCOMObjects(zeroLengthModelItem);
522
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
523
            }
524
            foreach (var modelId in ZeroLengthModelItemIDReverse)
525
            {
526
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
527
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
528
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
529
                {
530
                    attribute.set_Value("End 1 is downstream (Outlet)");
531
                    zeroLengthModelItem.Commit();
532
                }
533

    
534
                SetFlowDirectionByLine(modelId);
535

    
536
                ReleaseCOMObjects(zeroLengthModelItem);
537
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
538
            }
539
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
540
            {
541
                SetFlowDirectionByLine(modelId);
542
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
543
            }
544

    
545
            void SetFlowDirectionByLine(string lineModelItemID)
546
            {
547
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
548
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
549
                {
550
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
551
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
552
                    {
553
                        string sFlowDirection = attribute.get_Value().ToString();
554
                        foreach (LMRepresentation rep in modelItem.Representations)
555
                        {
556
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
557
                            {
558
                                LMConnector connector = dataSource.GetConnector(rep.Id);
559

    
560
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
561
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
562
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
563
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
564

    
565
                                ReleaseCOMObjects(connector);
566
                            }
567
                        }
568
                    }
569
                    ReleaseCOMObjects(modelItem);
570
                }
571

    
572
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
573
                {
574
                    // Item2가 Symbol
575
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
576
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
577
                    {
578
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
579
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
580
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
581

    
582
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
583

    
584
                        symbolModelItem.Commit();
585
                        ReleaseCOMObjects(symbolModelItem);
586
                    }
587
                    // Item1이 Symbol
588
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
589
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
590
                    {
591
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
592
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
593
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
594

    
595
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
596

    
597
                        symbolModelItem.Commit();
598
                        ReleaseCOMObjects(symbolModelItem);
599
                    }
600
                }
601

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

    
747
            //current LMDrawing 가져오기
748
            LMAFilter filter = new LMAFilter();
749
            LMACriterion criterion = new LMACriterion();
750
            filter.ItemType = "Drawing";
751
            criterion.SourceAttributeName = "Name";
752
            criterion.Operator = "=";
753
            criterion.set_ValueAttribute(drawingName);
754
            filter.get_Criteria().Add(criterion);
755

    
756
            LMDrawings drawings = new LMDrawings();
757
            drawings.Collect(dataSource, Filter: filter);
758

    
759
            currentDrawing = ((dynamic)drawings).Nth(1);
760
        }
761

    
762
        /// <summary>
763
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
764
        /// </summary>
765
        /// <param name="drawingName"></param>
766
        /// <param name="drawingNumber"></param>
767
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
768
        {
769
            LMDrawings drawings = new LMDrawings();
770
            drawings.Collect(dataSource);
771

    
772
            List<string> drawingNameList = new List<string>();
773
            List<string> drawingNumberList = new List<string>();
774

    
775
            foreach (LMDrawing item in drawings)
776
            {
777
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
778
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
779
            }
780

    
781
            int nameLength = drawingName.Length;
782
            while (drawingNameList.Contains(drawingName))
783
            {
784
                if (nameLength == drawingName.Length)
785
                    drawingName += "-1";
786
                else
787
                {
788
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
789
                    drawingName = drawingName.Substring(0, nameLength + 1);
790
                    drawingName += ++index;
791
                }
792
            }
793

    
794
            int numberLength = drawingNumber.Length;
795
            while (drawingNameList.Contains(drawingNumber))
796
            {
797
                if (numberLength == drawingNumber.Length)
798
                    drawingNumber += "-1";
799
                else
800
                {
801
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
802
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
803
                    drawingNumber += ++index;
804
                }
805
            }
806

    
807
            ReleaseCOMObjects(drawings);
808
        }
809

    
810
        /// <summary>
811
        /// 도면 크기 구하는 메서드
812
        /// </summary>
813
        /// <returns></returns>
814
        private bool DocumentCoordinateCorrection()
815
        {
816
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
817
            {
818
                Log.Write("Setting Drawing X, Drawing Y");
819
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
820
                Log.Write("Start coordinate correction");
821
                document.CoordinateCorrection();
822
                return true;
823
            }
824
            else
825
            {
826
                Log.Write("Need Drawing X, Y");
827
                return false;
828
            }
829
        }
830

    
831
        /// <summary>
832
        /// 심볼을 실제로 Modeling 메서드
833
        /// </summary>
834
        /// <param name="symbol"></param>
835
        /// <param name="targetSymbol"></param>
836
        /// <param name="prevSymbol"></param>
837
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
838
        {
839
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
840
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
841
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
842
                return;
843
            // 이미 모델링 됐을 경우
844
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
845
                return;
846

    
847
            LMSymbol _LMSymbol = null;
848

    
849
            string mappingPath = symbol.SPPID.MAPPINGNAME;
850
            double x = symbol.SPPID.ORIGINAL_X;
851
            double y = symbol.SPPID.ORIGINAL_Y;
852
            int mirror = 0;
853
            double angle = symbol.ANGLE;
854

    
855
            // OPC 일경우 180도 일때 Mirror
856
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
857
                mirror = 1;
858

    
859
            // Mirror 계산
860
            if (symbol.FLIP == 1)
861
            {
862
                mirror = 1;
863
                angle += Math.PI;
864
            }
865

    
866
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
867
            {
868
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
869
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
870
                if (connector != null)
871
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
872

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

    
875
                if (_LMSymbol != null && _TargetItem != null)
876
                {
877
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
878

    
879
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
880
                    {
881
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
882
                        if (reModelingConnector != null)
883
                            ReModelingLMConnector(reModelingConnector);
884
                    }
885
                }
886

    
887
                ReleaseCOMObjects(_TargetItem);
888
            }
889
            else
890
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
891

    
892
            if (_LMSymbol != null)
893
            {
894
                _LMSymbol.Commit();
895
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
896
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
897
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
898

    
899
                foreach (var item in symbol.ChildSymbols)
900
                    CreateChildSymbol(item, _LMSymbol, symbol);
901

    
902
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
903
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
904

    
905
                double[] range = null;
906
                GetSPPIDSymbolRange(symbol, ref range);
907
                symbol.SPPID.SPPID_Min_X = range[0];
908
                symbol.SPPID.SPPID_Min_Y = range[1];
909
                symbol.SPPID.SPPID_Max_X = range[2];
910
                symbol.SPPID.SPPID_Max_Y = range[3];
911

    
912
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
913
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
914
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
915
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
916

    
917
                ReleaseCOMObjects(_LMSymbol);
918
            }
919
        }
920

    
921
        private void RemoveSymbol(Symbol symbol)
922
        {
923
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
924
            {
925
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
926
                if (_LMSymbol != null)
927
                {
928
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
929
                    ReleaseCOMObjects(_LMSymbol);
930
                }
931
            }
932

    
933
            symbol.SPPID.RepresentationId = string.Empty;
934
            symbol.SPPID.ModelItemID = string.Empty;
935
            symbol.SPPID.SPPID_X = double.NaN;
936
            symbol.SPPID.SPPID_Y = double.NaN;
937
            symbol.SPPID.SPPID_Min_X = double.NaN;
938
            symbol.SPPID.SPPID_Min_Y = double.NaN;
939
            symbol.SPPID.SPPID_Max_X = double.NaN;
940
            symbol.SPPID.SPPID_Max_Y = double.NaN;
941
        }
942

    
943
        private void RemoveSymbol(List<Symbol> symbols)
944
        {
945
            foreach (var symbol in symbols)
946
            {
947
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
948
                {
949
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
950
                    if (_LMSymbol != null)
951
                    {
952
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
953
                        ReleaseCOMObjects(_LMSymbol);
954
                    }
955
                }
956

    
957
                symbol.SPPID.RepresentationId = string.Empty;
958
                symbol.SPPID.ModelItemID = string.Empty;
959
                symbol.SPPID.SPPID_X = double.NaN;
960
                symbol.SPPID.SPPID_Y = double.NaN;
961
                symbol.SPPID.SPPID_Min_X = double.NaN;
962
                symbol.SPPID.SPPID_Min_Y = double.NaN;
963
                symbol.SPPID.SPPID_Max_X = double.NaN;
964
                symbol.SPPID.SPPID_Max_Y = double.NaN;
965
            }
966
        }
967

    
968
        /// <summary>
969
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
970
        /// </summary>
971
        /// <param name="targetConnector"></param>
972
        /// <param name="targetSymbol"></param>
973
        /// <param name="x"></param>
974
        /// <param name="y"></param>
975
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
976
        {
977
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
978

    
979
            double[] range = null;
980
            List<double[]> points = new List<double[]>();
981
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
982
            double x1 = range[0];
983
            double y1 = range[1];
984
            double x2 = range[2];
985
            double y2 = range[3];
986

    
987
            // Origin 기준 Connector의 위치차이
988
            double sceneX = 0;
989
            double sceneY = 0;
990
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
991
            double originX = 0;
992
            double originY = 0;
993
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
994
            double gapX = originX - sceneX;
995
            double gapY = originY - sceneY;
996

    
997
            // SPPID Symbol과 ID2 심볼의 크기 차이
998
            double sizeWidth = 0;
999
            double sizeHeight = 0;
1000
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1001
            if (sizeWidth == 0 || sizeHeight == 0)
1002
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1003

    
1004
            double percentX = (x2 - x1) / sizeWidth;
1005
            double percentY = (y2 - y1) / sizeHeight;
1006

    
1007
            double SPPIDgapX = gapX * percentX;
1008
            double SPPIDgapY = gapY * percentY;
1009

    
1010
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1011
            double distance = double.MaxValue;
1012
            double[] resultPoint;
1013
            foreach (var point in points)
1014
            {
1015
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1016
                if (distance > result)
1017
                {
1018
                    distance = result;
1019
                    resultPoint = point;
1020
                    x = point[0];
1021
                    y = point[1];
1022
                }
1023
            }
1024

    
1025
            ReleaseCOMObjects(_TargetItem);
1026
        }
1027

    
1028
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1029
        {
1030
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1031
            if (index == 0)
1032
            {
1033
                x = targetLine.SPPID.START_X;
1034
                y = targetLine.SPPID.START_Y;
1035
            }
1036
            else
1037
            {
1038
                x = targetLine.SPPID.END_X;
1039
                y = targetLine.SPPID.END_Y;
1040
            }
1041
        }
1042

    
1043
        /// <summary>
1044
        /// SPPID Symbol의 Range를 구한다.
1045
        /// </summary>
1046
        /// <param name="symbol"></param>
1047
        /// <param name="range"></param>
1048
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1049
        {
1050
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1051
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1052
            double x1 = 0;
1053
            double y1 = 0;
1054
            double x2 = 0;
1055
            double y2 = 0;
1056
            symbol2d.Range(out x1, out y1, out x2, out y2);
1057
            range = new double[] { x1, y1, x2, y2 };
1058

    
1059
            for (int i = 1; i < int.MaxValue; i++)
1060
            {
1061
                double connX = 0;
1062
                double connY = 0;
1063
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1064
                    points.Add(new double[] { connX, connY });
1065
                else
1066
                    break;
1067
            }
1068

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

    
1072
            ReleaseCOMObjects(_TargetItem);
1073
        }
1074

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

    
1088
                foreach (var childSymbol in symbol.ChildSymbols)
1089
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1090

    
1091
                ReleaseCOMObjects(_TargetItem);
1092
            }
1093
        }
1094

    
1095
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1096
        {
1097
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1098
            foreach (var symbol in symbols)
1099
            {
1100
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1101
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1102
                double x1 = 0;
1103
                double y1 = 0;
1104
                double x2 = 0;
1105
                double y2 = 0;
1106
                symbol2d.Range(out x1, out y1, out x2, out y2);
1107

    
1108
                tempRange[0] = Math.Min(tempRange[0], x1);
1109
                tempRange[1] = Math.Min(tempRange[1], y1);
1110
                tempRange[2] = Math.Max(tempRange[2], x2);
1111
                tempRange[3] = Math.Max(tempRange[3], y2);
1112

    
1113
                foreach (var childSymbol in symbol.ChildSymbols)
1114
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1115

    
1116
                ReleaseCOMObjects(_TargetItem);
1117
            }
1118

    
1119
            range = tempRange;
1120
        }
1121

    
1122
        /// <summary>
1123
        /// Child Modeling 된 Symbol의 Range를 구한다.
1124
        /// </summary>
1125
        /// <param name="childSymbol"></param>
1126
        /// <param name="range"></param>
1127
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1128
        {
1129
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1130
            if (_ChildSymbol != null)
1131
            {
1132
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1133
                double x1 = 0;
1134
                double y1 = 0;
1135
                double x2 = 0;
1136
                double y2 = 0;
1137
                symbol2d.Range(out x1, out y1, out x2, out y2);
1138
                range[0] = Math.Min(range[0], x1);
1139
                range[1] = Math.Min(range[1], y1);
1140
                range[2] = Math.Max(range[2], x2);
1141
                range[3] = Math.Max(range[3], y2);
1142

    
1143
                for (int i = 1; i < int.MaxValue; i++)
1144
                {
1145
                    double connX = 0;
1146
                    double connY = 0;
1147
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1148
                        points.Add(new double[] { connX, connY });
1149
                    else
1150
                        break;
1151
                }
1152

    
1153
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1154
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1155

    
1156
                ReleaseCOMObjects(_ChildSymbol);
1157
            }
1158
        }
1159

    
1160
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1161
        {
1162
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1163
            if (_ChildSymbol != null)
1164
            {
1165
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1166
                double x1 = 0;
1167
                double y1 = 0;
1168
                double x2 = 0;
1169
                double y2 = 0;
1170
                symbol2d.Range(out x1, out y1, out x2, out y2);
1171
                range[0] = Math.Min(range[0], x1);
1172
                range[1] = Math.Min(range[1], y1);
1173
                range[2] = Math.Max(range[2], x2);
1174
                range[3] = Math.Max(range[3], y2);
1175

    
1176
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1177
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1178
                ReleaseCOMObjects(_ChildSymbol);
1179
            }
1180
        }
1181

    
1182
        /// <summary>
1183
        /// Label Symbol Modeling
1184
        /// </summary>
1185
        /// <param name="symbol"></param>
1186
        private void LabelSymbolModeling(Symbol symbol)
1187
        {
1188
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1189
            {
1190
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1191
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1192
                    return;
1193
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1194

    
1195
                string symbolUID = itemAttribute.VALUE;
1196
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1197
                if (targetItem != null &&
1198
                    (targetItem.GetType() == typeof(Symbol) ||
1199
                    targetItem.GetType() == typeof(Equipment)))
1200
                {
1201
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1202
                    string sRep = null;
1203
                    if (targetItem.GetType() == typeof(Symbol))
1204
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1205
                    else if (targetItem.GetType() == typeof(Equipment))
1206
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1207
                    if (!string.IsNullOrEmpty(sRep))
1208
                    {
1209
                        // LEADER Line 검사
1210
                        bool leaderLine = false;
1211
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1212
                        if (symbolMapping != null)
1213
                            leaderLine = symbolMapping.LEADERLINE;
1214

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

    
1219
                        //Leader 선 센터로
1220
                        if (_LMLabelPresist != null)
1221
                        {
1222
                            // Target Item에 Label의 Attribute Input
1223
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1224

    
1225
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1226
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1227
                            if (dependency != null)
1228
                            {
1229
                                bool result = false;
1230
                                foreach (var attributes in dependency.AttributeSets)
1231
                                {
1232
                                    foreach (var attribute in attributes)
1233
                                    {
1234
                                        string name = attribute.Name;
1235
                                        string value = attribute.GetValue().ToString();
1236
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1237
                                        {
1238
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1239
                                            {
1240
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1241
                                                {
1242
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1243
                                                    double prevX = _TargetItem.get_XCoordinate();
1244
                                                    double prevY = _TargetItem.get_YCoordinate();
1245
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1246
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1247
                                                    result = true;
1248
                                                    break;
1249
                                                }
1250
                                            }
1251
                                        }
1252

    
1253
                                        if (result)
1254
                                            break;
1255
                                    }
1256

    
1257
                                    if (result)
1258
                                        break;
1259
                                }
1260
                            }
1261

    
1262
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1263
                            _LMLabelPresist.Commit();
1264
                            ReleaseCOMObjects(_LMLabelPresist);
1265
                        }
1266

    
1267
                        ReleaseCOMObjects(_TargetItem);
1268
                    }
1269
                }
1270
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1271
                {
1272
                    Line targetLine = targetItem as Line;
1273
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1274
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1275
                    if (connectedLMConnector != null)
1276
                    {
1277
                        // LEADER Line 검사
1278
                        bool leaderLine = false;
1279
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1280
                        if (symbolMapping != null)
1281
                            leaderLine = symbolMapping.LEADERLINE;
1282

    
1283
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1284
                        if (_LMLabelPresist != null)
1285
                        {
1286
                            _LMLabelPresist.Commit();
1287
                            ReleaseCOMObjects(_LMLabelPresist);
1288
                        }
1289
                        ReleaseCOMObjects(connectedLMConnector);
1290
                    }
1291

    
1292
                    foreach (var item in connectorVertices)
1293
                        if (item.Key != null)
1294
                            ReleaseCOMObjects(item.Key);
1295
                }
1296
            }
1297
        }
1298

    
1299
        /// <summary>
1300
        /// Equipment를 실제로 Modeling 메서드
1301
        /// </summary>
1302
        /// <param name="equipment"></param>
1303
        private void EquipmentModeling(Equipment equipment)
1304
        {
1305
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1306
                return;
1307

    
1308
            LMSymbol _LMSymbol = null;
1309
            LMSymbol targetItem = null;
1310
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1311
            double x = equipment.SPPID.ORIGINAL_X;
1312
            double y = equipment.SPPID.ORIGINAL_Y;
1313
            int mirror = 0;
1314
            double angle = equipment.ANGLE;
1315

    
1316
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1317

    
1318
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1319
            if (connector != null)
1320
            {
1321
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1322
                if (connEquipment != null)
1323
                {
1324
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1325
                        EquipmentModeling(connEquipment);
1326

    
1327
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1328
                    {
1329
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1330
                        if (targetItem != null)
1331
                        {
1332
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1333
                        }
1334
                        else
1335
                        {
1336
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1337
                        }
1338
                    }
1339
                    else
1340
                    {
1341
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1342
                    }
1343
                }
1344
                else
1345
                {
1346
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1347
                }
1348
            }
1349
            else
1350
            {
1351
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1352
            }
1353

    
1354
            if (_LMSymbol != null)
1355
            {
1356
                _LMSymbol.Commit();
1357
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1358
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1359
                ReleaseCOMObjects(_LMSymbol);
1360
            }
1361

    
1362
            if (targetItem != null)
1363
            {
1364
                ReleaseCOMObjects(targetItem);
1365
            }
1366

    
1367
            ReleaseCOMObjects(_LMSymbol);
1368
        }
1369

    
1370
        /// <summary>
1371
        /// 첫 진입점
1372
        /// </summary>
1373
        /// <param name="symbol"></param>
1374
        private void SymbolModelingBySymbol(Symbol symbol)
1375
        {
1376
            SymbolModeling(symbol, null);
1377
            List<object> endObjects = new List<object>();
1378
            endObjects.Add(symbol);
1379

    
1380
            foreach (var connector in symbol.CONNECTORS)
1381
            {
1382
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1383
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1384
                {
1385
                    endObjects.Add(connItem);
1386
                    if (connItem.GetType() == typeof(Symbol))
1387
                    {
1388
                        Symbol connSymbol = connItem as Symbol;
1389
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1390
                        {
1391
                            SymbolModeling(connSymbol, symbol);
1392
                        }
1393
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1394
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1395
                    }
1396
                    else if (connItem.GetType() == typeof(Line))
1397
                    {
1398
                        Line connLine = connItem as Line;
1399
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1400
                    }
1401
                }
1402
            }
1403
        }
1404

    
1405
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1406
        {
1407
            foreach (var connector in symbol.CONNECTORS)
1408
            {
1409
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1410
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1411
                {
1412
                    if (!endObjects.Contains(connItem))
1413
                    {
1414
                        endObjects.Add(connItem);
1415
                        if (connItem.GetType() == typeof(Symbol))
1416
                        {
1417
                            Symbol connSymbol = connItem as Symbol;
1418
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1419
                            {
1420
                                SymbolModeling(connSymbol, symbol);
1421
                            }
1422
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1423
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1424
                        }
1425
                        else if (connItem.GetType() == typeof(Line))
1426
                        {
1427
                            Line connLine = connItem as Line;
1428
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1429
                        }
1430
                    }
1431
                }
1432
            }
1433
        }
1434

    
1435
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1436
        {
1437
            foreach (var connector in line.CONNECTORS)
1438
            {
1439
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1440
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1441
                {
1442
                    if (!endObjects.Contains(connItem))
1443
                    {
1444
                        endObjects.Add(connItem);
1445
                        if (connItem.GetType() == typeof(Symbol))
1446
                        {
1447
                            Symbol connSymbol = connItem as Symbol;
1448
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1449
                            {
1450
                                List<Symbol> group = new List<Symbol>();
1451
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1452
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1453
                                List<Symbol> endModelingGroup = new List<Symbol>();
1454
                                if (priority != null)
1455
                                {
1456
                                    SymbolGroupModeling(priority, group);
1457

    
1458
                                    // Range 겹치는지 확인해야함
1459
                                    double[] prevRange = null;
1460
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1461
                                    double[] groupRange = null;
1462
                                    GetSPPIDSymbolRange(group, ref groupRange);
1463

    
1464
                                    double distanceX = 0;
1465
                                    double distanceY = 0;
1466
                                    bool overlapX = false;
1467
                                    bool overlapY = false;
1468
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1469
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1470
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1471
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1472
                                    {
1473
                                        RemoveSymbol(group);
1474
                                        foreach (var _temp in group)
1475
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1476

    
1477
                                        SymbolGroupModeling(priority, group);
1478
                                    }
1479
                                }
1480
                                else
1481
                                {
1482
                                    SymbolModeling(connSymbol, null);
1483
                                    // Range 겹치는지 확인해야함
1484
                                    double[] prevRange = null;
1485
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1486
                                    double[] connRange = null;
1487
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1488

    
1489
                                    double distanceX = 0;
1490
                                    double distanceY = 0;
1491
                                    bool overlapX = false;
1492
                                    bool overlapY = false;
1493
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1494
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1495
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1496
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1497
                                    {
1498
                                        RemoveSymbol(connSymbol);
1499
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1500

    
1501
                                        SymbolModeling(connSymbol, null);
1502
                                    }
1503
                                }
1504
                            }
1505
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1506
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1507
                        }
1508
                        else if (connItem.GetType() == typeof(Line))
1509
                        {
1510
                            Line connLine = connItem as Line;
1511
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1512
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1513
                        }
1514
                    }
1515
                }
1516
            }
1517
        }
1518

    
1519
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1520
        {
1521
            List<Symbol> endModelingGroup = new List<Symbol>();
1522
            SymbolModeling(firstSymbol, null);
1523
            endModelingGroup.Add(firstSymbol);
1524
            while (endModelingGroup.Count != group.Count)
1525
            {
1526
                foreach (var _symbol in group)
1527
                {
1528
                    if (!endModelingGroup.Contains(_symbol))
1529
                    {
1530
                        foreach (var _connector in _symbol.CONNECTORS)
1531
                        {
1532
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1533
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1534
                            {
1535
                                SymbolModeling(_symbol, _connSymbol);
1536
                                endModelingGroup.Add(_symbol);
1537
                                break;
1538
                            }
1539
                        }
1540
                    }
1541
                }
1542
            }
1543
        }
1544

    
1545
        /// <summary>
1546
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1547
        /// </summary>
1548
        /// <param name="childSymbol"></param>
1549
        /// <param name="parentSymbol"></param>
1550
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1551
        {
1552
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1553
            double x1 = 0;
1554
            double x2 = 0;
1555
            double y1 = 0;
1556
            double y2 = 0;
1557
            symbol2d.Range(out x1, out y1, out x2, out y2);
1558

    
1559
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1560
            if (_LMSymbol != null)
1561
            {
1562
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1563
                foreach (var item in childSymbol.ChildSymbols)
1564
                    CreateChildSymbol(item, _LMSymbol, parent);
1565
            }
1566

    
1567

    
1568
            ReleaseCOMObjects(_LMSymbol);
1569
        }
1570
        double index = 0;
1571
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1572
        {
1573
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1574
                return;
1575

    
1576
            List<Line> group = new List<Line>();
1577
            GetConnectedLineGroup(line, group);
1578
            LineCoordinateCorrection(group);
1579

    
1580
            foreach (var groupLine in group)
1581
            {
1582
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1583
                {
1584
                    BranchLines.Add(groupLine);
1585
                    continue;
1586
                }
1587

    
1588
                bool diagonal = false;
1589
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1590
                    diagonal = true;
1591
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1592
                LMSymbol _LMSymbolStart = null;
1593
                LMSymbol _LMSymbolEnd = null;
1594
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1595
                foreach (var connector in groupLine.CONNECTORS)
1596
                {
1597
                    double x = 0;
1598
                    double y = 0;
1599
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1600
                    if (connector.ConnectedObject == null)
1601
                    {
1602
                        placeRunInputs.AddPoint(x, y);
1603
                    }
1604
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1605
                    {
1606
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1607
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1608
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1609
                        {
1610
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1611
                            if (_LMSymbolStart != null)
1612
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1613
                            else
1614
                                placeRunInputs.AddPoint(x, y);
1615
                        }
1616
                        else
1617
                        {
1618
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1619
                            if (_LMSymbolEnd != null)
1620
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1621
                            else
1622
                                placeRunInputs.AddPoint(x, y);
1623
                        }
1624
                    }
1625
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1626
                    {
1627
                        Line targetLine = connector.ConnectedObject as Line;
1628
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1629
                        {
1630
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1631
                            if (targetConnector != null)
1632
                            {
1633
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1634
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1635
                            }
1636
                            else
1637
                            {
1638
                                placeRunInputs.AddPoint( x, y);
1639
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1640
                            }
1641
                        }
1642
                        else
1643
                        {
1644
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1645
                            {
1646
                                index += 0.01;
1647
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1648
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1649
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1650
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1651
                                else
1652
                                {
1653
                                    if (SPPIDUtil.CalcAngle(groupLine.SPPID.START_X, groupLine.SPPID.START_Y, groupLine.SPPID.END_X, groupLine.SPPID.END_Y) < 45)
1654
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1655
                                    else
1656
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1657
                                }
1658
                            }
1659

    
1660
                            placeRunInputs.AddPoint(x, y);
1661

    
1662
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1663
                            {
1664
                                index += 0.01;
1665
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1666
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1667
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1668
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1669
                                else
1670
                                {
1671
                                    if (SPPIDUtil.CalcAngle(groupLine.SPPID.START_X, groupLine.SPPID.START_Y, groupLine.SPPID.END_X, groupLine.SPPID.END_Y) < 45)
1672
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1673
                                    else
1674
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1675
                                }
1676
                            }
1677
                        }
1678
                    }
1679
                }
1680

    
1681
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1682
                if (_lMConnector != null)
1683
                {
1684
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1685
                    bool bRemodelingStart = false;
1686
                    if (_LMSymbolStart != null)
1687
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1688
                    bool bRemodelingEnd = false;
1689
                    if (_LMSymbolEnd != null)
1690
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1691

    
1692
                    if (bRemodelingStart || bRemodelingEnd)
1693
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1694

    
1695
                    FlowMarkModeling(groupLine);
1696
                    LineNumberModelingOnlyOne(groupLine);
1697

    
1698
                    ReleaseCOMObjects(_lMConnector);
1699
                }
1700
                else if (!isBranchModeling)
1701
                {
1702
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1703
                }
1704

    
1705
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1706
                x.ConnectedObject != null &&
1707
                x.ConnectedObject.GetType() == typeof(Line) &&
1708
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1709
                .Select(x => x.ConnectedObject)
1710
                .ToList();
1711

    
1712
                foreach (var item in removeLines)
1713
                    RemoveLineForModeling(item as Line);
1714

    
1715
                if (_LMAItem != null)
1716
                    ReleaseCOMObjects(_LMAItem);
1717
                if (placeRunInputs != null)
1718
                    ReleaseCOMObjects(placeRunInputs);
1719
                if (_LMSymbolStart != null)
1720
                    ReleaseCOMObjects(_LMSymbolStart);
1721
                if (_LMSymbolEnd != null)
1722
                    ReleaseCOMObjects(_LMSymbolEnd);
1723

    
1724
                if (isBranchModeling && BranchLines.Contains(groupLine))
1725
                    BranchLines.Remove(groupLine);
1726
            }
1727
        }
1728

    
1729
        private void RemoveLineForModeling(Line line)
1730
        {
1731
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1732
            if (modelItem != null)
1733
            {
1734
                foreach (LMRepresentation rep in modelItem.Representations)
1735
                {
1736
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1737
                    {
1738
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1739
                        dynamic OID = rep.get_GraphicOID().ToString();
1740
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1741
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1742
                        int verticesCount = lineStringGeometry.VertexCount;
1743
                        double[] vertices = null;
1744
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1745
                        for (int i = 0; i < verticesCount; i++)
1746
                        {
1747
                            double x = 0;
1748
                            double y = 0;
1749
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1750
                            if (verticesCount == 2 && (x < 0 || y < 0))
1751
                                _placement.PIDRemovePlacement(rep);
1752
                        }
1753
                        ReleaseCOMObjects(_LMConnector);
1754
                    }
1755
                }
1756

    
1757
                ReleaseCOMObjects(modelItem);
1758
            }
1759
        }
1760

    
1761
        private void GetConnectedLineGroup(Line line, List<Line> group)
1762
        {
1763
            if (!group.Contains(line))
1764
                group.Add(line);
1765
            foreach (var connector in line.CONNECTORS)
1766
            {
1767
                if (connector.ConnectedObject != null &&
1768
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1769
                    !group.Contains(connector.ConnectedObject) &&
1770
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1771
                {
1772
                    Line connLine = connector.ConnectedObject as Line;
1773
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1774
                    {
1775
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1776
                            group.Insert(0, connLine);
1777
                        else
1778
                            group.Add(connLine);
1779
                        GetConnectedLineGroup(connLine, group);
1780
                    }
1781
                }
1782
            }
1783
        }
1784

    
1785
        private void LineCoordinateCorrection(List<Line> group)
1786
        {
1787
            // 순서대로 전 Item 기준 정렬
1788
            LineCoordinateCorrectionByStart(group);
1789

    
1790
            // 역으로 심볼이 있을 경우 좌표 보정
1791
            LineCoordinateCorrectionForLastLine(group);
1792
        }
1793

    
1794
        private void LineCoordinateCorrectionByStart(List<Line> group)
1795
        {
1796
            for (int i = 0; i < group.Count; i++)
1797
            {
1798
                Line line = group[i];
1799
                if (i == 0)
1800
                {
1801
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1802
                    if (symbolConnector != null)
1803
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1804
                }
1805
                else if (i != 0)
1806
                {
1807
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1808
                }
1809
            }
1810
        }
1811

    
1812
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1813
        {
1814
            Line checkLine = group[group.Count - 1];
1815
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1816
            if (lastSymbolConnector != null)
1817
            {
1818
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1819
                for (int i = group.Count - 2; i >= 0; i--)
1820
                {
1821
                    Line line = group[i + 1];
1822
                    Line prevLine = group[i];
1823

    
1824
                    // 같으면 보정
1825
                    if (line.SlopeType == prevLine.SlopeType)
1826
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1827
                    else
1828
                    {
1829
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1830
                        {
1831
                            double prevX = 0;
1832
                            double prevY = 0;
1833
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1834
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1835

    
1836
                            double x = 0;
1837
                            double y = 0;
1838
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1839
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1840
                        }
1841
                        else if (line.SlopeType == SlopeType.VERTICAL)
1842
                        {
1843
                            double prevX = 0;
1844
                            double prevY = 0;
1845
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1846
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1847

    
1848
                            double x = 0;
1849
                            double y = 0;
1850
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1851
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1852
                        }
1853
                        break;
1854
                    }
1855
                }
1856
            }
1857
        }
1858

    
1859
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1860
        {
1861
            double x = 0;
1862
            double y = 0;
1863
            if (connItem.GetType() == typeof(Symbol))
1864
            {
1865
                Symbol targetSymbol = connItem as Symbol;
1866
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1867
                if (targetConnector != null)
1868
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
1869
                else
1870
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
1871
            }
1872
            else if (connItem.GetType() == typeof(Line))
1873
            {
1874
                Line targetLine = connItem as Line;
1875
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
1876
            }
1877

    
1878
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
1879
        }
1880

    
1881
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
1882
        {
1883
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1884
            int index = line.CONNECTORS.IndexOf(connector);
1885
            if (index == 0)
1886
            {
1887
                line.SPPID.START_X = x;
1888
                line.SPPID.START_Y = y;
1889
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1890
                    line.SPPID.END_Y = y;
1891
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1892
                    line.SPPID.END_X = x;
1893
            }
1894
            else
1895
            {
1896
                line.SPPID.END_X = x;
1897
                line.SPPID.END_Y = y;
1898
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1899
                    line.SPPID.START_Y = y;
1900
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1901
                    line.SPPID.START_X = x;
1902
            }
1903
        }
1904

    
1905
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
1906
        {
1907
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1908
            int index = line.CONNECTORS.IndexOf(connector);
1909
            if (index == 0)
1910
            {
1911
                line.SPPID.START_X = x;
1912
                if (line.SlopeType == SlopeType.VERTICAL)
1913
                    line.SPPID.END_X = x;
1914
            }
1915
            else
1916
            {
1917
                line.SPPID.END_X = x;
1918
                if (line.SlopeType == SlopeType.VERTICAL)
1919
                    line.SPPID.START_X = x;
1920
            }
1921
        }
1922

    
1923
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
1924
        {
1925
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1926
            int index = line.CONNECTORS.IndexOf(connector);
1927
            if (index == 0)
1928
            {
1929
                line.SPPID.START_Y = y;
1930
                if (line.SlopeType == SlopeType.HORIZONTAL)
1931
                    line.SPPID.END_Y = y;
1932
            }
1933
            else
1934
            {
1935
                line.SPPID.END_Y = y;
1936
                if (line.SlopeType == SlopeType.HORIZONTAL)
1937
                    line.SPPID.START_Y = y;
1938
            }
1939
        }
1940

    
1941
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
1942
        {
1943
            if (symbol != null)
1944
            {
1945
                string repID = symbol.AsLMRepresentation().Id;
1946
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
1947
                string lineUID = line.UID;
1948

    
1949
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
1950
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
1951
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
1952

    
1953
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
1954
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
1955
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
1956

    
1957
                if (startSpecBreak != null || startEndBreak != null)
1958
                    result = true;
1959
            }
1960
        }
1961

    
1962
        /// <summary>
1963
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
1964
        /// </summary>
1965
        /// <param name="lines"></param>
1966
        /// <param name="prevLMConnector"></param>
1967
        /// <param name="startSymbol"></param>
1968
        /// <param name="endSymbol"></param>
1969
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
1970
        {
1971
            string symbolPath = string.Empty;
1972
            #region get symbol path
1973
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
1974
            symbolPath = GetSPPIDFileName(modelItem);
1975
            ReleaseCOMObjects(modelItem);
1976
            #endregion
1977
            bool diagonal = false;
1978
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
1979
                diagonal = true;
1980
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
1981
            LMConnector newConnector = null;
1982
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
1983
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1984
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1985
            int verticesCount = lineStringGeometry.VertexCount;
1986
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1987

    
1988
            List<double[]> vertices = new List<double[]>();
1989
            for (int i = 1; i <= verticesCount; i++)
1990
            {
1991
                double x = 0;
1992
                double y = 0;
1993
                lineStringGeometry.GetVertex(i, ref x, ref y);
1994
                vertices.Add(new double[] { x, y });
1995
            }
1996

    
1997
            for (int i = 0; i < vertices.Count; i++)
1998
            {
1999
                double[] points = vertices[i];
2000
                // 시작 심볼이 있고 첫번째 좌표일 때
2001
                if (startSymbol != null && i == 0)
2002
                {
2003
                    if (bStart)
2004
                    {
2005
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2006
                        if (slopeType == SlopeType.HORIZONTAL)
2007
                            placeRunInputs.AddPoint(points[0], -0.1);
2008
                        else if (slopeType == SlopeType.VERTICAL)
2009
                            placeRunInputs.AddPoint(-0.1, points[1]);
2010
                        else
2011
                            placeRunInputs.AddPoint(points[0], -0.1);
2012

    
2013
                        placeRunInputs.AddPoint(points[0], points[1]);
2014
                    }
2015
                    else
2016
                    {
2017
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2018
                    }
2019
                }
2020
                // 마지막 심볼이 있고 마지막 좌표일 때
2021
                else if (endSymbol != null && i == vertices.Count - 1)
2022
                {
2023
                    if (bEnd)
2024
                    {
2025
                        placeRunInputs.AddPoint(points[0], points[1]);
2026

    
2027
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2028
                        if (slopeType == SlopeType.HORIZONTAL)
2029
                            placeRunInputs.AddPoint(points[0], -0.1);
2030
                        else if (slopeType == SlopeType.VERTICAL)
2031
                            placeRunInputs.AddPoint(-0.1, points[1]);
2032
                        else
2033
                            placeRunInputs.AddPoint(points[0], -0.1);
2034
                    }
2035
                    else
2036
                    {
2037
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2038
                    }
2039
                }
2040
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2041
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2042
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2043
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2044
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2045
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2046
                else
2047
                    placeRunInputs.AddPoint(points[0], points[1]);
2048
            }
2049

    
2050
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2051
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2052

    
2053
            ReleaseCOMObjects(placeRunInputs);
2054
            ReleaseCOMObjects(_LMAItem);
2055
            ReleaseCOMObjects(modelItem);
2056

    
2057
            if (newConnector != null)
2058
            {
2059
                if (startSymbol != null && bStart)
2060
                {
2061
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2062
                    placeRunInputs = new PlaceRunInputs();
2063
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2064
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2065
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2066
                    if (_LMConnector != null)
2067
                    {
2068
                        RemoveConnectorForReModelingLine(newConnector);
2069
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2070
                        ReleaseCOMObjects(_LMConnector);
2071
                    }
2072
                    ReleaseCOMObjects(placeRunInputs);
2073
                    ReleaseCOMObjects(_LMAItem);
2074
                }
2075

    
2076
                if (endSymbol != null && bEnd)
2077
                {
2078
                    if (startSymbol != null)
2079
                    {
2080
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2081
                        newConnector = dicVertices.First().Key;
2082
                    }
2083

    
2084
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2085
                    placeRunInputs = new PlaceRunInputs();
2086
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2087
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2088
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2089
                    if (_LMConnector != null)
2090
                    {
2091
                        RemoveConnectorForReModelingLine(newConnector);
2092
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2093
                        ReleaseCOMObjects(_LMConnector);
2094
                    }
2095
                    ReleaseCOMObjects(placeRunInputs);
2096
                    ReleaseCOMObjects(_LMAItem);
2097
                }
2098

    
2099
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2100
                ReleaseCOMObjects(newConnector);
2101
            }
2102

    
2103
            ReleaseCOMObjects(modelItem);
2104
        }
2105

    
2106
        /// <summary>
2107
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2108
        /// </summary>
2109
        /// <param name="connector"></param>
2110
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2111
        {
2112
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2113
            foreach (var item in dicVertices)
2114
            {
2115
                if (item.Value.Count == 2)
2116
                {
2117
                    bool result = false;
2118
                    foreach (var point in item.Value)
2119
                    {
2120
                        if (point[0] < 0 || point[1] < 0)
2121
                        {
2122
                            result = true;
2123
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2124
                            break;
2125
                        }
2126
                    }
2127

    
2128
                    if (result)
2129
                        break;
2130
                }
2131
            }
2132
            foreach (var item in dicVertices)
2133
                ReleaseCOMObjects(item.Key);
2134
        }
2135

    
2136
        /// <summary>
2137
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2138
        /// </summary>
2139
        /// <param name="symbol"></param>
2140
        /// <param name="line"></param>
2141
        /// <returns></returns>
2142
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2143
        {
2144
            LMSymbol _LMSymbol = null;
2145
            foreach (var connector in symbol.CONNECTORS)
2146
            {
2147
                if (connector.CONNECTEDITEM == line.UID)
2148
                {
2149
                    if (connector.Index == 0)
2150
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2151
                    else
2152
                    {
2153
                        ChildSymbol child = null;
2154
                        foreach (var childSymbol in symbol.ChildSymbols)
2155
                        {
2156
                            if (childSymbol.Connectors.Contains(connector))
2157
                                child = childSymbol;
2158
                            else
2159
                                child = GetChildSymbolByConnector(childSymbol, connector);
2160

    
2161
                            if (child != null)
2162
                                break;
2163
                        }
2164

    
2165
                        if (child != null)
2166
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2167
                    }
2168

    
2169
                    break;
2170
                }
2171
            }
2172

    
2173
            return _LMSymbol;
2174
        }
2175

    
2176
        /// <summary>
2177
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2178
        /// </summary>
2179
        /// <param name="item"></param>
2180
        /// <param name="connector"></param>
2181
        /// <returns></returns>
2182
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2183
        {
2184
            foreach (var childSymbol in item.ChildSymbols)
2185
            {
2186
                if (childSymbol.Connectors.Contains(connector))
2187
                    return childSymbol;
2188
                else
2189
                    return GetChildSymbolByConnector(childSymbol, connector);
2190
            }
2191

    
2192
            return null;
2193
        }
2194

    
2195
        /// <summary>
2196
        /// EndBreak 모델링 메서드
2197
        /// </summary>
2198
        /// <param name="endBreak"></param>
2199
        private void EndBreakModeling(EndBreak endBreak)
2200
        {
2201
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2202
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2203
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2204

    
2205
            if (targetLMConnector != null)
2206
            {
2207
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2208
                Array array = null;
2209
                if (point != null)
2210
                    array = new double[] { 0, point[0], point[1] };
2211
                else
2212
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2213
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2214
                if (_LmLabelPersist != null)
2215
                {
2216
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2217
                    if (_LmLabelPersist.ModelItemObject != null)
2218
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2219
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2220
                    ReleaseCOMObjects(_LmLabelPersist);
2221
                }
2222
                ReleaseCOMObjects(targetLMConnector);
2223
            }
2224
        }
2225

    
2226
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2227
        {
2228
            string symbolPath = string.Empty;
2229
            #region get symbol path
2230
            if (string.IsNullOrEmpty(changeSymbolPath))
2231
            {
2232
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2233
                symbolPath = GetSPPIDFileName(modelItem);
2234
                ReleaseCOMObjects(modelItem);
2235
            }
2236
            else
2237
                symbolPath = changeSymbolPath;
2238
            
2239
            #endregion
2240

    
2241
            LMConnector newConnector = null;
2242
            dynamic OID = connector.get_GraphicOID().ToString();
2243
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2244
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2245
            int verticesCount = lineStringGeometry.VertexCount;
2246
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2247
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2248

    
2249
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2250
            {
2251
                double[] vertices = null;
2252
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2253
                double x = 0;
2254
                double y = 0;
2255
                lineStringGeometry.GetVertex(1, ref x, ref y);
2256

    
2257
                string flowDirection = string.Empty;
2258
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2259
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2260
                    flowDirection = flowAttribute.get_Value().ToString();
2261

    
2262
                if (flowDirection == "End 1 is downstream (Outlet)")
2263
                {
2264
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2265
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2266
                    flowDirection = "End 1 is upstream (Inlet)";
2267
                }
2268
                else
2269
                {
2270
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2271
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2272
                }
2273

    
2274
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2275
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2276
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2277
                if (!string.IsNullOrEmpty(flowDirection))
2278
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2279
            }
2280
            else
2281
            {
2282
                List<double[]> vertices = new List<double[]>();
2283
                for (int i = 1; i <= verticesCount; i++)
2284
                {
2285
                    double x = 0;
2286
                    double y = 0;
2287
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2288
                    vertices.Add(new double[] { x, y });
2289
                }
2290

    
2291
                for (int i = 0; i < vertices.Count; i++)
2292
                {
2293
                    double[] points = vertices[i];
2294
                    if (i == 0)
2295
                    {
2296
                        if (connector.ConnectItem1SymbolObject != null)
2297
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2298
                        else
2299
                            placeRunInputs.AddPoint(points[0], points[1]);
2300
                    }
2301
                    else if (i == vertices.Count - 1)
2302
                    {
2303
                        if (connector.ConnectItem2SymbolObject != null)
2304
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2305
                        else
2306
                            placeRunInputs.AddPoint(points[0], points[1]);
2307
                    }
2308
                    else
2309
                        placeRunInputs.AddPoint(points[0], points[1]);
2310
                }
2311

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

    
2314
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2315
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2316

    
2317
                foreach (var line in lines)
2318
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2319
            }
2320

    
2321

    
2322
            return newConnector;
2323
        }
2324

    
2325
        /// <summary>
2326
        /// SpecBreak Modeling 메서드
2327
        /// </summary>
2328
        /// <param name="specBreak"></param>
2329
        private void SpecBreakModeling(SpecBreak specBreak)
2330
        {
2331
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2332
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2333

    
2334
            if (upStreamObj != null &&
2335
                downStreamObj != null)
2336
            {
2337
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2338

    
2339
                if (targetLMConnector != null)
2340
                {
2341
                    foreach (var attribute in specBreak.ATTRIBUTES)
2342
                    {
2343
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2344
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2345
                        {
2346
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2347
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2348
                            Array array = null;
2349
                            if (point != null)
2350
                                array = new double[] { 0, point[0], point[1] };
2351
                            else
2352
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2353
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2354

    
2355
                            if (_LmLabelPersist != null)
2356
                            {
2357
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2358
                                if (_LmLabelPersist.ModelItemObject != null)
2359
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2360
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2361
                                ReleaseCOMObjects(_LmLabelPersist);
2362
                            }
2363
                        }
2364
                    }
2365
                    ReleaseCOMObjects(targetLMConnector);
2366
                }
2367
            }
2368
        }
2369

    
2370
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2371
        {
2372
            LMConnector targetConnector = null;
2373
            Symbol targetSymbol = targetObj as Symbol;
2374
            Symbol connectedSymbol = connectedObj as Symbol;
2375
            Line targetLine = targetObj as Line;
2376
            Line connectedLine = connectedObj as Line;
2377
            if (targetSymbol != null && connectedSymbol != null)
2378
            {
2379
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2380
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2381

    
2382
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2383
                {
2384
                    if (connector.get_ItemStatus() != "Active")
2385
                        continue;
2386

    
2387
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2388
                    {
2389
                        targetConnector = connector;
2390
                        break;
2391
                    }
2392
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2393
                    {
2394
                        targetConnector = connector;
2395
                        break;
2396
                    }
2397
                }
2398

    
2399
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2400
                {
2401
                    if (connector.get_ItemStatus() != "Active")
2402
                        continue;
2403

    
2404
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2405
                    {
2406
                        targetConnector = connector;
2407
                        break;
2408
                    }
2409
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2410
                    {
2411
                        targetConnector = connector;
2412
                        break;
2413
                    }
2414
                }
2415

    
2416
                ReleaseCOMObjects(targetLMSymbol);
2417
                ReleaseCOMObjects(connectedLMSymbol);
2418
            }
2419
            else if (targetLine != null && connectedLine != null)
2420
            {
2421
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2422
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2423

    
2424
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2425
                {
2426
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2427
                    {
2428
                        if (targetConnector != null)
2429
                            break;
2430

    
2431
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2432
                        {
2433
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2434

    
2435
                            if (IsConnected(_LMConnector, connectedModelItem))
2436
                                targetConnector = _LMConnector;
2437
                            else
2438
                                ReleaseCOMObjects(_LMConnector);
2439
                        }
2440
                    }
2441

    
2442
                    ReleaseCOMObjects(targetModelItem);
2443
                }
2444
            }
2445
            else
2446
            {
2447
                LMSymbol connectedLMSymbol = null;
2448
                if (connectedSymbol != null)
2449
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2450
                else if (targetSymbol != null)
2451
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2452
                else
2453
                {
2454

    
2455
                }
2456
                LMModelItem targetModelItem = null;
2457
                if (targetLine != null)
2458
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2459
                else if (connectedLine != null)
2460
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2461
                else
2462
                {
2463

    
2464
                }
2465
                if (connectedLMSymbol != null && targetModelItem != null)
2466
                {
2467
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2468
                    {
2469
                        if (connector.get_ItemStatus() != "Active")
2470
                            continue;
2471

    
2472
                        if (IsConnected(connector, targetModelItem))
2473
                        {
2474
                            targetConnector = connector;
2475
                            break;
2476
                        }
2477
                    }
2478

    
2479
                    if (targetConnector == null)
2480
                    {
2481
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2482
                        {
2483
                            if (connector.get_ItemStatus() != "Active")
2484
                                continue;
2485

    
2486
                            if (IsConnected(connector, targetModelItem))
2487
                            {
2488
                                targetConnector = connector;
2489
                                break;
2490
                            }
2491
                        }
2492
                    }
2493
                }
2494

    
2495
            }
2496

    
2497
            return targetConnector;
2498
        }
2499

    
2500
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2501
        {
2502
            double[] result = null;
2503
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2504
            {
2505
                return GetConnectorVertices(targetConnector)[0];
2506
            }
2507
            else
2508
            {
2509
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
2510
                {
2511
                    Line line = connObj as Line;
2512
                    LMConnector connectedConnector = null;
2513
                    int connIndex = 0;
2514
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2515
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
2516

    
2517
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2518

    
2519
                    ReleaseCOMObjects(modelItem);
2520
                    ReleaseCOMObjects(connectedConnector);
2521

    
2522
                    if (vertices.Count > 0)
2523
                    {
2524
                        if (connIndex == 1)
2525
                            return vertices[0];
2526
                        else if (connIndex == 2)
2527
                            return vertices[vertices.Count - 1];
2528
                    }
2529
                }
2530
                else
2531
                {
2532
                    Log.Write("error in GetSegemtPoint");
2533
                }
2534
            }
2535

    
2536
            return result;
2537
        }
2538

    
2539
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2540
        {
2541
            bool result = false;
2542

    
2543
            foreach (LMRepresentation rep in modelItem.Representations)
2544
            {
2545
                if (result)
2546
                    break;
2547

    
2548
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2549
                {
2550
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2551

    
2552
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2553
                        connector.ConnectItem1SymbolObject != null &&
2554
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2555
                    {
2556
                        result = true;
2557
                        ReleaseCOMObjects(_LMConnector);
2558
                        break;
2559
                    }
2560
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2561
                        connector.ConnectItem2SymbolObject != null &&
2562
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2563
                    {
2564
                        result = true;
2565
                        ReleaseCOMObjects(_LMConnector);
2566
                        break;
2567
                    }
2568
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2569
                        connector.ConnectItem1SymbolObject != null &&
2570
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2571
                    {
2572
                        result = true;
2573
                        ReleaseCOMObjects(_LMConnector);
2574
                        break;
2575
                    }
2576
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2577
                        connector.ConnectItem2SymbolObject != null &&
2578
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2579
                    {
2580
                        result = true;
2581
                        ReleaseCOMObjects(_LMConnector);
2582
                        break;
2583
                    }
2584

    
2585
                    ReleaseCOMObjects(_LMConnector);
2586
                }
2587
            }
2588

    
2589

    
2590
            return result;
2591
        }
2592

    
2593
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2594
        {
2595
            foreach (LMRepresentation rep in modelItem.Representations)
2596
            {
2597
                if (connectedConnector != null)
2598
                    break;
2599

    
2600
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2601
                {
2602
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2603

    
2604
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2605
                        connector.ConnectItem1SymbolObject != null &&
2606
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2607
                    {
2608
                        connectedConnector = _LMConnector;
2609
                        connectorIndex = 1;
2610
                        break;
2611
                    }
2612
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2613
                        connector.ConnectItem2SymbolObject != null &&
2614
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2615
                    {
2616
                        connectedConnector = _LMConnector;
2617
                        connectorIndex = 2;
2618
                        break;
2619
                    }
2620
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2621
                        connector.ConnectItem1SymbolObject != null &&
2622
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2623
                    {
2624
                        connectedConnector = _LMConnector;
2625
                        connectorIndex = 1;
2626
                        break;
2627
                    }
2628
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2629
                        connector.ConnectItem2SymbolObject != null &&
2630
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2631
                    {
2632
                        connectedConnector = _LMConnector;
2633
                        connectorIndex = 2;
2634
                        break;
2635
                    }
2636

    
2637
                    if (connectedConnector == null)
2638
                        ReleaseCOMObjects(_LMConnector);
2639
                }
2640
            }
2641
        }
2642

    
2643
        /// <summary>
2644
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2645
        /// </summary>
2646
        /// <param name="modelItemID1"></param>
2647
        /// <param name="modelItemID2"></param>
2648
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2649
        {
2650
            try
2651
            {
2652
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2653
                _LMAItem item1 = modelItem1.AsLMAItem();
2654
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2655
                _LMAItem item2 = modelItem2.AsLMAItem();
2656

    
2657
                // item2가 item1으로 조인
2658
                _placement.PIDJoinRuns(ref item1, ref item2);
2659
                item1.Commit();
2660
                item2.Commit();
2661

    
2662
                string beforeID = string.Empty;
2663
                string afterID = string.Empty;
2664

    
2665
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2666
                {
2667
                    beforeID = modelItem2.Id;
2668
                    afterID = modelItem1.Id;
2669
                    survivorId = afterID;
2670
                    modelItem1.Attributes["FlowDirection"].set_Value("End 1 is upstream (Inlet)");
2671
                }
2672
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2673
                {
2674
                    beforeID = modelItem1.Id;
2675
                    afterID = modelItem2.Id;
2676
                    survivorId = afterID;
2677
                    modelItem2.Attributes["FlowDirection"].set_Value("End 1 is upstream (Inlet)");
2678
                }
2679
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2680
                    survivorId = null;
2681
                else
2682
                {
2683
                    Log.Write("잘못된 경우");
2684
                    survivorId = null;
2685
                }
2686

    
2687

    
2688
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2689
                {
2690
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2691
                    foreach (var line in lines)
2692
                        line.SPPID.ModelItemId = afterID;
2693
                }
2694

    
2695
                ReleaseCOMObjects(modelItem1);
2696
                ReleaseCOMObjects(item1);
2697
                ReleaseCOMObjects(modelItem2);
2698
                ReleaseCOMObjects(item2);
2699
            }
2700
            catch (Exception ex)
2701
            {
2702
                Log.Write("Join Error");
2703
                Log.Write(ex.Message);
2704
            }
2705
        }
2706

    
2707
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2708
        {
2709
            List<string> modelItemIDs = new List<string>();
2710
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2711
            {
2712
                LMModelItem modelItem = connector.ModelItemObject;
2713
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2714
                    modelItemIDs.Add(modelItem.Id);
2715
                ReleaseCOMObjects(modelItem);
2716
                ReleaseCOMObjects(connector);
2717
            }
2718

    
2719
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2720
            {
2721
                LMModelItem modelItem = connector.ModelItemObject;
2722
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2723
                    modelItemIDs.Add(modelItem.Id);
2724
                ReleaseCOMObjects(modelItem);
2725
                ReleaseCOMObjects(connector);
2726
            }
2727

    
2728

    
2729
            List<string> result = new List<string>();
2730
            modelItemIDs = modelItemIDs.Distinct().ToList();
2731
            string originalName = GetSPPIDFileName(modelId);
2732
            foreach (var item in modelItemIDs)
2733
            {
2734
                string fileName = GetSPPIDFileName(item);
2735
                if (originalName == fileName)
2736
                    result.Add(item);
2737
                else
2738
                {
2739
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2740
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()))
2741
                    {
2742
                        result.Add(item);
2743
                        ReleaseCOMObjects(connector);
2744
                    }
2745
                }
2746
            }
2747
            
2748
            return result;
2749
        }
2750

    
2751
        /// <summary>
2752
        /// PipeRun의 좌표를 가져오는 메서드
2753
        /// </summary>
2754
        /// <param name="modelId"></param>
2755
        /// <returns></returns>
2756
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2757
        {
2758
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2759
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2760

    
2761
            if (modelItem != null)
2762
            {
2763
                foreach (LMRepresentation rep in modelItem.Representations)
2764
                {
2765
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2766
                    {
2767
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2768
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2769
                        dynamic OID = rep.get_GraphicOID().ToString();
2770
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2771
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2772
                        int verticesCount = lineStringGeometry.VertexCount;
2773
                        double[] vertices = null;
2774
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2775
                        for (int i = 0; i < verticesCount; i++)
2776
                        {
2777
                            double x = 0;
2778
                            double y = 0;
2779
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2780
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
2781
                        }
2782
                    }
2783
                }
2784

    
2785
                ReleaseCOMObjects(modelItem);
2786
            }
2787

    
2788
            return connectorVertices;
2789
        }
2790

    
2791
        private List<double[]> GetConnectorVertices(LMConnector connector)
2792
        {
2793
            List<double[]> vertices = new List<double[]>();
2794
            if (connector != null)
2795
            {
2796
                dynamic OID = connector.get_GraphicOID().ToString();
2797
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2798
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2799
                int verticesCount = lineStringGeometry.VertexCount;
2800
                double[] value = null;
2801
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
2802
                for (int i = 0; i < verticesCount; i++)
2803
                {
2804
                    double x = 0;
2805
                    double y = 0;
2806
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2807
                    vertices.Add(new double[] { x, y });
2808
                }
2809
            }
2810
            return vertices;
2811
        }
2812

    
2813
        /// <summary>
2814
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
2815
        /// </summary>
2816
        /// <param name="connectorVertices"></param>
2817
        /// <param name="connX"></param>
2818
        /// <param name="connY"></param>
2819
        /// <returns></returns>
2820
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
2821
        {
2822
            double length = double.MaxValue;
2823
            LMConnector targetConnector = null;
2824
            foreach (var item in connectorVertices)
2825
            {
2826
                List<double[]> points = item.Value;
2827
                for (int i = 0; i < points.Count - 1; i++)
2828
                {
2829
                    double[] point1 = points[i];
2830
                    double[] point2 = points[i + 1];
2831
                    double x1 = Math.Min(point1[0], point2[0]);
2832
                    double y1 = Math.Min(point1[1], point2[1]);
2833
                    double x2 = Math.Max(point1[0], point2[0]);
2834
                    double y2 = Math.Max(point1[1], point2[1]);
2835

    
2836
                    if ((x1 <= connX && x2 >= connX) ||
2837
                        (y1 <= connY && y2 >= connY))
2838
                    {
2839
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
2840
                        if (length >= distance)
2841
                        {
2842
                            targetConnector = item.Key;
2843
                            length = distance;
2844
                        }
2845

    
2846
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
2847
                        if (length >= distance)
2848
                        {
2849
                            targetConnector = item.Key;
2850
                            length = distance;
2851
                        }
2852
                    }
2853
                }
2854
            }
2855

    
2856
            // 못찾았을때.
2857
            length = double.MaxValue;
2858
            if (targetConnector == null)
2859
            {
2860
                foreach (var item in connectorVertices)
2861
                {
2862
                    List<double[]> points = item.Value;
2863

    
2864
                    foreach (double[] point in points)
2865
                    {
2866
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
2867
                        if (length >= distance)
2868
                        {
2869
                            targetConnector = item.Key;
2870
                            length = distance;
2871
                        }
2872
                    }
2873
                }
2874
            }
2875

    
2876
            return targetConnector;
2877
        }
2878

    
2879
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
2880
        {
2881
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2882
            if (vertices.Count == 0)
2883
                return null;
2884

    
2885
            double length = double.MaxValue;
2886
            LMConnector targetConnector = null;
2887
            double[] resultPoint = null;
2888
            List<double[]> targetVertices = null;
2889

    
2890
            // Vertices 포인트에 제일 가까운곳
2891
            foreach (var item in vertices)
2892
            {
2893
                List<double[]> points = item.Value;
2894
                for (int i = 0; i < points.Count; i++)
2895
                {
2896
                    double[] point = points[i];
2897
                    double tempX = point[0];
2898
                    double tempY = point[1];
2899

    
2900
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
2901
                    if (length >= distance)
2902
                    {
2903
                        targetConnector = item.Key;
2904
                        length = distance;
2905
                        resultPoint = point;
2906
                        targetVertices = item.Value;
2907
                    }
2908
                }
2909
            }
2910

    
2911
            // Vertices Cross에 제일 가까운곳
2912
            foreach (var item in vertices)
2913
            {
2914
                List<double[]> points = item.Value;
2915
                for (int i = 0; i < points.Count - 1; i++)
2916
                {
2917
                    double[] point1 = points[i];
2918
                    double[] point2 = points[i + 1];
2919

    
2920
                    double maxLineX = Math.Max(point1[0], point2[0]);
2921
                    double minLineX = Math.Min(point1[0], point2[0]);
2922
                    double maxLineY = Math.Max(point1[1], point2[1]);
2923
                    double minLineY = Math.Min(point1[1], point2[1]);
2924

    
2925
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
2926

    
2927
                    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]);
2928
                    if (crossingPoint != null)
2929
                    {
2930
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
2931
                        if (length >= distance)
2932
                        {
2933
                            if (slope == SlopeType.Slope &&
2934
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
2935
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
2936
                            {
2937
                                targetConnector = item.Key;
2938
                                length = distance;
2939
                                resultPoint = crossingPoint;
2940
                                targetVertices = item.Value;
2941
                            }
2942
                            else if (slope == SlopeType.HORIZONTAL &&
2943
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
2944
                            {
2945
                                targetConnector = item.Key;
2946
                                length = distance;
2947
                                resultPoint = crossingPoint;
2948
                                targetVertices = item.Value;
2949
                            }
2950
                            else if (slope == SlopeType.VERTICAL &&
2951
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
2952
                            {
2953
                                targetConnector = item.Key;
2954
                                length = distance;
2955
                                resultPoint = crossingPoint;
2956
                                targetVertices = item.Value;
2957
                            }
2958
                        }
2959
                    }
2960
                }
2961
            }
2962

    
2963
            foreach (var item in vertices)
2964
                if (item.Key != null && item.Key != targetConnector)
2965
                    ReleaseCOMObjects(item.Key);
2966

    
2967
            if (SPPIDUtil.IsBranchLine(line, targetLine))
2968
            {
2969
                double tempResultX = resultPoint[0];
2970
                double tempResultY = resultPoint[1];
2971
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
2972

    
2973
                GridSetting gridSetting = GridSetting.GetInstance();
2974

    
2975
                for (int i = 0; i < targetVertices.Count; i++)
2976
                {
2977
                    double[] point = targetVertices[i];
2978
                    double tempX = targetVertices[i][0];
2979
                    double tempY = targetVertices[i][1];
2980
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
2981
                    if (tempX == tempResultX && tempY == tempResultY)
2982
                    {
2983
                        if (i == 0)
2984
                        {
2985
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
2986
                            bool containZeroLength = false;
2987
                            if (connSymbol != null)
2988
                            {
2989
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
2990
                                {
2991
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
2992
                                        containZeroLength = true;
2993
                                }
2994
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
2995
                                {
2996
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
2997
                                        containZeroLength = true;
2998
                                }
2999
                            }
3000

    
3001
                            if (connSymbol == null ||
3002
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3003
                                containZeroLength)
3004
                            {
3005
                                bool bCalcX = false;
3006
                                bool bCalcY = false;
3007
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3008
                                    bCalcX = true;
3009
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3010
                                    bCalcY = true;
3011
                                else
3012
                                {
3013
                                    bCalcX = true;
3014
                                    bCalcY = true;
3015
                                }
3016

    
3017
                                if (bCalcX)
3018
                                {
3019
                                    double nextX = targetVertices[i + 1][0];
3020
                                    double newX = 0;
3021
                                    if (nextX > tempX)
3022
                                    {
3023
                                        newX = tempX + gridSetting.Length;
3024
                                        if (newX > nextX)
3025
                                            newX = (point[0] + nextX) / 2;
3026
                                    }
3027
                                    else
3028
                                    {
3029
                                        newX = tempX - gridSetting.Length;
3030
                                        if (newX < nextX)
3031
                                            newX = (point[0] + nextX) / 2;
3032
                                    }
3033
                                    resultPoint = new double[] { newX, resultPoint[1] };
3034
                                }
3035

    
3036
                                if (bCalcY)
3037
                                {
3038
                                    double nextY = targetVertices[i + 1][1];
3039
                                    double newY = 0;
3040
                                    if (nextY > tempY)
3041
                                    {
3042
                                        newY = tempY + gridSetting.Length;
3043
                                        if (newY > nextY)
3044
                                            newY = (point[1] + nextY) / 2;
3045
                                    }
3046
                                    else
3047
                                    {
3048
                                        newY = tempY - gridSetting.Length;
3049
                                        if (newY < nextY)
3050
                                            newY = (point[1] + nextY) / 2;
3051
                                    }
3052
                                    resultPoint = new double[] { resultPoint[0], newY };
3053
                                }
3054
                            }
3055
                        }
3056
                        else if (i == targetVertices.Count - 1)
3057
                        {
3058
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3059
                            bool containZeroLength = false;
3060
                            if (connSymbol != null)
3061
                            {
3062
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3063
                                {
3064
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3065
                                        containZeroLength = true;
3066
                                }
3067
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3068
                                {
3069
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3070
                                        containZeroLength = true;
3071
                                }
3072
                            }
3073

    
3074
                            if (connSymbol == null ||
3075
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3076
                                containZeroLength)
3077
                            {
3078
                                bool bCalcX = false;
3079
                                bool bCalcY = false;
3080
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3081
                                    bCalcX = true;
3082
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3083
                                    bCalcY = true;
3084
                                else
3085
                                {
3086
                                    bCalcX = true;
3087
                                    bCalcY = true;
3088
                                }
3089

    
3090
                                if (bCalcX)
3091
                                {
3092
                                    double nextX = targetVertices[i - 1][0];
3093
                                    double newX = 0;
3094
                                    if (nextX > tempX)
3095
                                    {
3096
                                        newX = tempX + gridSetting.Length;
3097
                                        if (newX > nextX)
3098
                                            newX = (point[0] + nextX) / 2;
3099
                                    }
3100
                                    else
3101
                                    {
3102
                                        newX = tempX - gridSetting.Length;
3103
                                        if (newX < nextX)
3104
                                            newX = (point[0] + nextX) / 2;
3105
                                    }
3106
                                    resultPoint = new double[] { newX, resultPoint[1] };
3107
                                }
3108

    
3109
                                if (bCalcY)
3110
                                {
3111
                                    double nextY = targetVertices[i - 1][1];
3112
                                    double newY = 0;
3113
                                    if (nextY > tempY)
3114
                                    {
3115
                                        newY = tempY + gridSetting.Length;
3116
                                        if (newY > nextY)
3117
                                            newY = (point[1] + nextY) / 2;
3118
                                    }
3119
                                    else
3120
                                    {
3121
                                        newY = tempY - gridSetting.Length;
3122
                                        if (newY < nextY)
3123
                                            newY = (point[1] + nextY) / 2;
3124
                                    }
3125
                                    resultPoint = new double[] { resultPoint[0], newY };
3126
                                }
3127
                            }
3128
                        }
3129
                        break;
3130
                    }
3131
                }
3132
            }
3133

    
3134
            x = resultPoint[0];
3135
            y = resultPoint[1];
3136

    
3137
            return targetConnector;
3138
        }
3139

    
3140
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3141
        {
3142
            LMConnector result = null;
3143
            List<LMConnector> connectors = new List<LMConnector>();
3144
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3145

    
3146
            if (modelItem != null)
3147
            {
3148
                foreach (LMRepresentation rep in modelItem.Representations)
3149
                {
3150
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3151
                        connectors.Add(dataSource.GetConnector(rep.Id));
3152
                }
3153

    
3154
                ReleaseCOMObjects(modelItem);
3155
            }
3156

    
3157
            if (connectors.Count == 1)
3158
                result = connectors[0];
3159
            else
3160
                foreach (var item in connectors)
3161
                    ReleaseCOMObjects(item);
3162

    
3163
            return result;
3164
        }
3165

    
3166
        /// <summary>
3167
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3168
        /// </summary>
3169
        /// <param name="lineNumber"></param>
3170
        private void LineNumberModelingOnlyOne(Line line)
3171
        {
3172
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3173
            if (lineNumber != null)
3174
            {
3175
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3176
                if (connectedLMConnector != null)
3177
                {
3178
                    double x = 0;
3179
                    double y = 0;
3180
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3181

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

    
3185
                    if (_LmLabelPresist != null)
3186
                    {
3187
                        _LmLabelPresist.Commit();
3188
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3189
                        ReleaseCOMObjects(_LmLabelPresist);
3190
                    }
3191
                }
3192
            }
3193
        }
3194

    
3195
        private void LineNumberModeling(LineNumber lineNumber)
3196
        {
3197
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3198
            if (line != null)
3199
            {
3200
                double x = 0;
3201
                double y = 0;
3202
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3203

    
3204
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3205
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3206
                if (connectedLMConnector != null)
3207
                {
3208
                    Array points = new double[] { 0, x, y };
3209
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3210

    
3211
                    if (_LmLabelPresist != null)
3212
                    {
3213
                        _LmLabelPresist.Commit();
3214
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3215
                        ReleaseCOMObjects(_LmLabelPresist);
3216
                    }
3217
                }
3218

    
3219
                foreach (var item in connectorVertices)
3220
                    ReleaseCOMObjects(item.Key);
3221
            }
3222
        }
3223
        /// <summary>
3224
        /// Flow Mark Modeling
3225
        /// </summary>
3226
        /// <param name="line"></param>
3227
        private void FlowMarkModeling(Line line)
3228
        {
3229
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3230
            {
3231
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3232
                if (connector != null)
3233
                {
3234
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3235
                    List<double[]> vertices = GetConnectorVertices(connector);
3236
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3237
                    double[] point = vertices[vertices.Count - 1];
3238
                    Array array = new double[] { 0, point[0], point[1] };
3239
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3240
                    if (_LMLabelPersist != null)
3241
                        ReleaseCOMObjects(_LMLabelPersist);
3242
                }
3243
            }
3244
        }
3245

    
3246
        /// <summary>
3247
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3248
        /// </summary>
3249
        /// <param name="lineNumber"></param>
3250
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3251
        {
3252
            foreach (LineRun run in lineNumber.RUNS)
3253
            {
3254
                foreach (var item in run.RUNITEMS)
3255
                {
3256
                    if (item.GetType() == typeof(Symbol))
3257
                    {
3258
                        Symbol symbol = item as Symbol;
3259
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3260
                        if (_LMSymbol != null)
3261
                        {
3262
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3263

    
3264
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3265
                            {
3266
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3267
                                {
3268
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3269
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3270
                                    {
3271
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3272
                                        if (_LMAAttribute != null)
3273
                                        {
3274
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3275
                                                _LMAAttribute.set_Value(attribute.VALUE);
3276
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3277
                                                _LMAAttribute.set_Value(attribute.VALUE);
3278
                                        }
3279
                                    }
3280
                                }
3281
                                _LMModelItem.Commit();
3282
                            }
3283
                            if (_LMModelItem != null)
3284
                                ReleaseCOMObjects(_LMModelItem);
3285
                        }
3286
                        if (_LMSymbol != null)
3287
                            ReleaseCOMObjects(_LMSymbol);
3288
                    }
3289
                    else if (item.GetType() == typeof(Line))
3290
                    {
3291
                        Line line = item as Line;
3292
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3293
                        {
3294
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3295
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3296
                            {
3297
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3298
                                {
3299
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3300
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3301
                                    {
3302
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3303
                                        if (_LMAAttribute != null)
3304
                                        {
3305
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3306
                                                _LMAAttribute.set_Value(attribute.VALUE);
3307
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3308
                                                _LMAAttribute.set_Value(attribute.VALUE);
3309

    
3310
                                        }
3311
                                    }
3312
                                }
3313
                                _LMModelItem.Commit();
3314
                            }
3315
                            if (_LMModelItem != null)
3316
                                ReleaseCOMObjects(_LMModelItem);
3317
                            endLine.Add(line.SPPID.ModelItemId);
3318
                        }
3319
                    }
3320
                }
3321
            }
3322
        }
3323

    
3324
        /// <summary>
3325
        /// Symbol Attribute 입력 메서드
3326
        /// </summary>
3327
        /// <param name="item"></param>
3328
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3329
        {
3330
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3331
            string sRep = null;
3332
            if (targetItem.GetType() == typeof(Symbol))
3333
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3334
            else if (targetItem.GetType() == typeof(Equipment))
3335
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3336

    
3337
            if (!string.IsNullOrEmpty(sRep))
3338
            {
3339
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3340
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3341
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3342
                
3343
                foreach (var item in targetAttributes)
3344
                {
3345
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3346
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3347
                    {
3348
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3349
                        if (_Attribute != null)
3350
                        {
3351
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3352
                            if (associItem != null)
3353
                            {
3354
                                if (associItem.GetType() == typeof(Text))
3355
                                {
3356
                                    Text text = associItem as Text;
3357
                                    text.SPPID.RepresentationId = "Attribute";
3358
                                }
3359
                                else if (associItem.GetType() == typeof(Note))
3360
                                {
3361
                                    Note note = associItem as Note;
3362
                                    note.SPPID.RepresentationId = "Attribute";
3363
                                }
3364
                            }
3365
                            _Attribute.set_Value(item.VALUE);
3366
                        }
3367
                            
3368
                    }
3369
                }
3370
                _LMModelItem.Commit();
3371

    
3372
                ReleaseCOMObjects(_Attributes);
3373
                ReleaseCOMObjects(_LMModelItem);
3374
                ReleaseCOMObjects(_LMSymbol);
3375
            }
3376
        }
3377

    
3378
        /// <summary>
3379
        /// Input SpecBreak Attribute
3380
        /// </summary>
3381
        /// <param name="specBreak"></param>
3382
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3383
        {
3384
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3385
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3386

    
3387
            if (upStreamObj != null &&
3388
                downStreamObj != null)
3389
            {
3390
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3391

    
3392
                if (targetLMConnector != null)
3393
                {
3394
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3395
                    {
3396
                        string symbolPath = _LMLabelPersist.get_FileName();
3397
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3398
                        if (mapping != null)
3399
                        {
3400
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3401
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3402
                            {
3403
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3404
                                if (values.Length == 2)
3405
                                {
3406
                                    string upStreamValue = values[0];
3407
                                    string downStreamValue = values[1];
3408

    
3409
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3410
                                }
3411
                            }
3412
                        }
3413
                    }
3414

    
3415
                    ReleaseCOMObjects(targetLMConnector);
3416
                }
3417
            }
3418

    
3419

    
3420
            #region 내부에서만 쓰는 메서드
3421
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3422
            {
3423
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3424
                Line upStreamLine = _upStreamObj as Line;
3425
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3426
                Line downStreamLine = _downStreamObj as Line;
3427
                // 둘다 Line일 경우
3428
                if (upStreamLine != null && downStreamLine != null)
3429
                {
3430
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3431
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3432
                }
3433
                // 둘다 Symbol일 경우
3434
                else if (upStreamSymbol != null && downStreamSymbol != null)
3435
                {
3436
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3437
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3438
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3439

    
3440
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3441
                    {
3442
                        if (connector.get_ItemStatus() != "Active")
3443
                            continue;
3444

    
3445
                        if (connector.Id != zeroLenthConnector.Id)
3446
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3447
                    }
3448

    
3449
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3450
                    {
3451
                        if (connector.get_ItemStatus() != "Active")
3452
                            continue;
3453

    
3454
                        if (connector.Id != zeroLenthConnector.Id)
3455
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3456
                    }
3457

    
3458
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3459
                    {
3460
                        if (connector.get_ItemStatus() != "Active")
3461
                            continue;
3462

    
3463
                        if (connector.Id != zeroLenthConnector.Id)
3464
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3465
                    }
3466

    
3467
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3468
                    {
3469
                        if (connector.get_ItemStatus() != "Active")
3470
                            continue;
3471

    
3472
                        if (connector.Id != zeroLenthConnector.Id)
3473
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3474
                    }
3475

    
3476
                    ReleaseCOMObjects(zeroLenthConnector);
3477
                    ReleaseCOMObjects(upStreamLMSymbol);
3478
                    ReleaseCOMObjects(downStreamLMSymbol);
3479
                }
3480
                else if (upStreamSymbol != null && downStreamLine != null)
3481
                {
3482
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3483
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3484
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3485

    
3486
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3487
                    {
3488
                        if (connector.get_ItemStatus() != "Active")
3489
                            continue;
3490

    
3491
                        if (connector.Id == zeroLenthConnector.Id)
3492
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3493
                    }
3494

    
3495
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3496
                    {
3497
                        if (connector.get_ItemStatus() != "Active")
3498
                            continue;
3499

    
3500
                        if (connector.Id == zeroLenthConnector.Id)
3501
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3502
                    }
3503

    
3504
                    ReleaseCOMObjects(zeroLenthConnector);
3505
                    ReleaseCOMObjects(upStreamLMSymbol);
3506
                }
3507
                else if (upStreamLine != null && downStreamSymbol != null)
3508
                {
3509
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3510
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3511
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3512

    
3513
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3514
                    {
3515
                        if (connector.get_ItemStatus() != "Active")
3516
                            continue;
3517

    
3518
                        if (connector.Id == zeroLenthConnector.Id)
3519
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3520
                    }
3521

    
3522
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3523
                    {
3524
                        if (connector.get_ItemStatus() != "Active")
3525
                            continue;
3526

    
3527
                        if (connector.Id == zeroLenthConnector.Id)
3528
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3529
                    }
3530

    
3531
                    ReleaseCOMObjects(zeroLenthConnector);
3532
                    ReleaseCOMObjects(downStreamLMSymbol);
3533
                }
3534
            }
3535

    
3536
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3537
            {
3538
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3539
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3540
                {
3541
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3542
                    if (_LMAAttribute != null)
3543
                    {
3544
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3545
                            _LMAAttribute.set_Value(value);
3546
                        else if (_LMAAttribute.get_Value() != value)
3547
                            _LMAAttribute.set_Value(value);
3548
                    }
3549

    
3550
                    _LMModelItem.Commit();
3551
                }
3552
                if (_LMModelItem != null)
3553
                    ReleaseCOMObjects(_LMModelItem);
3554
            }
3555

    
3556
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3557
            {
3558
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3559
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3560
                {
3561
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3562
                    if (_LMAAttribute != null)
3563
                    {
3564
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3565
                            _LMAAttribute.set_Value(value);
3566
                        else if (_LMAAttribute.get_Value() != value)
3567
                            _LMAAttribute.set_Value(value);
3568
                    }
3569

    
3570
                    _LMModelItem.Commit();
3571
                }
3572
                if (_LMModelItem != null)
3573
                    ReleaseCOMObjects(_LMModelItem);
3574
            }
3575
            #endregion
3576
        }
3577

    
3578
        /// <summary>
3579
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3580
        /// </summary>
3581
        /// <param name="text"></param>
3582
        private void TextModeling(Text text)
3583
        {
3584
            LMSymbol _LMSymbol = null;
3585
            LMConnector connectedLMConnector = null;
3586
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3587
            if (text.ASSOCIATION)
3588
            {
3589
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3590
                if (owner != null && owner.GetType() == typeof(Symbol))
3591
                {
3592
                    Symbol symbol = owner as Symbol;
3593
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3594
                    if (_LMSymbol != null)
3595
                    {
3596
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3597
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3598
                        {
3599
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3600

    
3601
                            if (mapping != null)
3602
                            {
3603
                                double x = 0;
3604
                                double y = 0;
3605

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

    
3609
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3610
                                if (_LMLabelPersist != null)
3611
                                {
3612
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3613
                                    _LMLabelPersist.Commit();
3614
                                    ReleaseCOMObjects(_LMLabelPersist);
3615
                                }
3616
                            }
3617
                        }
3618
                    }
3619
                }
3620
                else if (owner != null && owner.GetType() == typeof(Line))
3621
                {
3622
                    Line line = owner as Line;
3623
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3624
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3625

    
3626
                    if (connectedLMConnector != null)
3627
                    {
3628
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3629
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3630
                        {
3631
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3632

    
3633
                            if (mapping != null)
3634
                            {
3635
                                double x = 0;
3636
                                double y = 0;
3637

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

    
3641
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3642
                                if (_LMLabelPersist != null)
3643
                                {
3644
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3645
                                    _LMLabelPersist.Commit();
3646
                                    ReleaseCOMObjects(_LMLabelPersist);
3647
                                }
3648
                            }
3649
                        }
3650
                    }
3651
                }
3652
            }
3653
            else
3654
            {
3655
                LMItemNote _LMItemNote = null;
3656
                LMAAttribute _LMAAttribute = null;
3657

    
3658
                double x = 0;
3659
                double y = 0;
3660
                double angle = text.ANGLE;
3661
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3662

    
3663
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3664
                if (_LMSymbol != null)
3665
                {
3666
                    _LMSymbol.Commit();
3667
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3668
                    if (_LMItemNote != null)
3669
                    {
3670
                        _LMItemNote.Commit();
3671
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3672
                        if (_LMAAttribute != null)
3673
                        {
3674
                            _LMAAttribute.set_Value(text.VALUE);
3675
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3676
                            _LMItemNote.Commit();
3677

    
3678
                            if (_LMAAttribute != null)
3679
                                ReleaseCOMObjects(_LMAAttribute);
3680
                            if (_LMItemNote != null)
3681
                                ReleaseCOMObjects(_LMItemNote);
3682
                        }
3683
                    }
3684
                }
3685
            }
3686
            if (_LMSymbol != null)
3687
                ReleaseCOMObjects(_LMSymbol);
3688
        }
3689

    
3690
        /// <summary>
3691
        /// Note Modeling
3692
        /// </summary>
3693
        /// <param name="note"></param>
3694
        private void NoteModeling(Note note)
3695
        {
3696
            LMSymbol _LMSymbol = null;
3697
            LMItemNote _LMItemNote = null;
3698
            LMAAttribute _LMAAttribute = null;
3699

    
3700
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3701
            {
3702
                double x = 0;
3703
                double y = 0;
3704

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

    
3707
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
3708
                if (_LMSymbol != null)
3709
                {
3710
                    _LMSymbol.Commit();
3711
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3712
                    if (_LMItemNote != null)
3713
                    {
3714
                        _LMItemNote.Commit();
3715
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3716
                        if (_LMAAttribute != null)
3717
                        {
3718
                            _LMAAttribute.set_Value(note.VALUE);
3719
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3720
                            _LMItemNote.Commit();
3721
                        }
3722
                    }
3723
                }
3724
            }
3725

    
3726
            if (_LMAAttribute != null)
3727
                ReleaseCOMObjects(_LMAAttribute);
3728
            if (_LMItemNote != null)
3729
                ReleaseCOMObjects(_LMItemNote);
3730
            if (_LMSymbol != null)
3731
                ReleaseCOMObjects(_LMSymbol);
3732
        }
3733

    
3734
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
3735
        {
3736
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
3737
            if (modelItem != null)
3738
            {
3739
                foreach (LMRepresentation rep in modelItem.Representations)
3740
                {
3741
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3742
                    {
3743
                        LMConnector connector = dataSource.GetConnector(rep.Id);
3744
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
3745
                        {
3746
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
3747
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3748
                            if (modelItemIds.Count == 1)
3749
                            {
3750
                                string joinModelItemId = modelItemIds[0];
3751
                                //CheckZeroLengthAndLabel(ref joinModelItemId);
3752
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3753
                                if (survivorId != null)
3754
                                    break;
3755
                            }
3756
                        }
3757
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
3758
                        {
3759
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
3760
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3761
                            if (modelItemIds.Count == 1)
3762
                            {
3763
                                string joinModelItemId = modelItemIds[0];
3764
                                //CheckZeroLengthAndLabel(ref joinModelItemId);
3765
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3766
                                if (survivorId != null)
3767
                                    break;
3768
                            }
3769
                        }
3770
                    }
3771
                }
3772
            }
3773

    
3774
            void CheckZeroLengthAndLabel(ref string _modelItemId)
3775
            {
3776
                LMConnector connector = GetLMConnectorOnlyOne(_modelItemId);
3777
                if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()) && connector.LabelPersists.Count == 0)
3778
                {
3779
                    string symbolPath = GetSPPIDFileName(modelItem);
3780
                    LMConnector newConnector = ReModelingLMConnector(connector, symbolPath);
3781
                    ReleaseCOMObjects(connector);
3782
                    _modelItemId = newConnector.ModelItemID;
3783
                    ReleaseCOMObjects(newConnector);
3784
                }
3785
            }
3786
        }
3787

    
3788
        /// <summary>
3789
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
3790
        /// </summary>
3791
        /// <param name="x"></param>
3792
        /// <param name="y"></param>
3793
        /// <param name="originX"></param>
3794
        /// <param name="originY"></param>
3795
        /// <param name="SPPIDLabelLocation"></param>
3796
        /// <param name="location"></param>
3797
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
3798
        {
3799
            if (location == Location.None)
3800
            {
3801
                x = originX;
3802
                y = originY;
3803
            }
3804
            else
3805
            {
3806
                if (location.HasFlag(Location.Center))
3807
                {
3808
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
3809
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
3810
                }
3811

    
3812
                if (location.HasFlag(Location.Left))
3813
                    x = SPPIDLabelLocation.X1;
3814
                else if (location.HasFlag(Location.Right))
3815
                    x = SPPIDLabelLocation.X2;
3816

    
3817
                if (location.HasFlag(Location.Down))
3818
                    y = SPPIDLabelLocation.Y1;
3819
                else if (location.HasFlag(Location.Up))
3820
                    y = SPPIDLabelLocation.Y2;
3821
            }
3822
        }
3823

    
3824
        /// <summary>
3825
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
3826
        /// 1. Angle Valve
3827
        /// 2. 3개로 이루어진 Symbol Group
3828
        /// </summary>
3829
        /// <returns></returns>
3830
        private List<Symbol> GetPrioritySymbol()
3831
        {
3832
            DataTable symbolTable = document.SymbolTable;
3833
            // List에 순서대로 쌓는다.
3834
            List<Symbol> symbols = new List<Symbol>();
3835

    
3836
            // Angle Valve 부터
3837
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
3838
            {
3839
                if (!symbols.Contains(symbol))
3840
                {
3841
                    double originX = 0;
3842
                    double originY = 0;
3843

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

    
3848
                    SlopeType slopeType1 = SlopeType.None;
3849
                    SlopeType slopeType2 = SlopeType.None;
3850
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
3851
                    {
3852
                        double connectorX = 0;
3853
                        double connectorY = 0;
3854
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
3855
                        if (slopeType1 == SlopeType.None)
3856
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3857
                        else
3858
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3859
                    }
3860

    
3861
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
3862
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
3863
                        symbols.Add(symbol);
3864
                }
3865
            }
3866

    
3867
            List<Symbol> tempSymbols = new List<Symbol>();
3868
            // Conn 갯수 기준
3869
            foreach (var item in document.SYMBOLS)
3870
            {
3871
                if (!symbols.Contains(item))
3872
                    tempSymbols.Add(item);
3873
            }
3874
            tempSymbols.Sort(SortSymbolPriority);
3875
            symbols.AddRange(tempSymbols);
3876

    
3877
            return symbols;
3878
        }
3879

    
3880
        private void SetPriorityLine(List<Line> lines)
3881
        {
3882
            lines.Sort(SortLinePriority);
3883

    
3884
            int SortLinePriority(Line a, Line b)
3885
            {
3886
                // Branch 없는것부터
3887
                int branchRetval = CompareBranchLine(a, b);
3888
                if (branchRetval != 0)
3889
                {
3890
                    return branchRetval;
3891
                }
3892
                else
3893
                {
3894
                    // Symbol 연결 갯수
3895
                    int connSymbolRetval = CompareConnSymbol(a, b);
3896
                    if (connSymbolRetval != 0)
3897
                    {
3898
                        return connSymbolRetval;
3899
                    }
3900
                    else
3901
                    {
3902
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
3903
                        int connItemRetval = CompareConnItem(a, b);
3904
                        if (connItemRetval != 0)
3905
                        {
3906
                            return connItemRetval;
3907
                        }
3908
                        else
3909
                        {
3910
                            // ConnectedItem이 없는것
3911
                            int noneConnRetval = CompareNoneConn(a, b);
3912
                            if (noneConnRetval != 0)
3913
                            {
3914
                                return noneConnRetval;
3915
                            }
3916
                            else
3917
                            {
3918

    
3919
                            }
3920
                        }
3921
                    }
3922
                }
3923

    
3924
                return 0;
3925
            }
3926

    
3927
            int CompareNotSegmentLine(Line a, Line b)
3928
            {
3929
                List<Connector> connectorsA = a.CONNECTORS
3930
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3931
                    .ToList();
3932

    
3933
                List<Connector> connectorsB = b.CONNECTORS
3934
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3935
                    .ToList();
3936

    
3937
                // 오름차순
3938
                return connectorsB.Count.CompareTo(connectorsA.Count);
3939
            }
3940

    
3941
            int CompareConnSymbol(Line a, Line b)
3942
            {
3943
                List<Connector> connectorsA = a.CONNECTORS
3944
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3945
                    .ToList();
3946

    
3947
                List<Connector> connectorsB = b.CONNECTORS
3948
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3949
                    .ToList();
3950

    
3951
                // 오름차순
3952
                return connectorsB.Count.CompareTo(connectorsA.Count);
3953
            }
3954

    
3955
            int CompareConnItem(Line a, Line b)
3956
            {
3957
                List<Connector> connectorsA = a.CONNECTORS
3958
                    .Where(conn => conn.ConnectedObject != null && 
3959
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
3960
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
3961
                    .ToList();
3962

    
3963
                List<Connector> connectorsB = b.CONNECTORS
3964
                    .Where(conn => conn.ConnectedObject != null &&
3965
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
3966
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
3967
                    .ToList();
3968

    
3969
                // 오름차순
3970
                return connectorsB.Count.CompareTo(connectorsA.Count);
3971
            }
3972

    
3973
            int CompareBranchLine(Line a, Line b)
3974
            {
3975
                List<Connector> connectorsA = a.CONNECTORS
3976
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
3977
                    .ToList();
3978
                List<Connector> connectorsB = b.CONNECTORS
3979
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
3980
                    .ToList();
3981

    
3982
                // 내림차순
3983
                return connectorsA.Count.CompareTo(connectorsB.Count);
3984
            }
3985

    
3986
            int CompareNoneConn(Line a, Line b)
3987
            {
3988
                List<Connector> connectorsA = a.CONNECTORS
3989
                    .Where(conn => conn.ConnectedObject == null)
3990
                    .ToList();
3991

    
3992
                List<Connector> connectorsB = b.CONNECTORS
3993
                    .Where(conn => conn.ConnectedObject == null)
3994
                    .ToList();
3995

    
3996
                // 오름차순
3997
                return connectorsB.Count.CompareTo(connectorsA.Count);
3998
            }
3999
        }
4000

    
4001
        private void SortBranchLines()
4002
        {
4003
            BranchLines.Sort(SortBranchLine);
4004
            int SortBranchLine(Line a, Line b)
4005
            {
4006
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4007
                 x.ConnectedObject.GetType() == typeof(Line) &&
4008
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
4009
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4010

    
4011
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4012
                 x.ConnectedObject.GetType() == typeof(Line) &&
4013
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4014
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4015

    
4016
                // 내림차순
4017
                return countA.CompareTo(countB);
4018
            }
4019
        }
4020

    
4021
        private static int SortSymbolPriority(Symbol a, Symbol b)
4022
        {
4023
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4024
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4025
            int retval = countB.CompareTo(countA);
4026
            if (retval != 0)
4027
                return retval;
4028
            else
4029
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
4030
        }
4031

    
4032
        private string GetSPPIDFileName(LMModelItem modelItem)
4033
        {
4034
            string symbolPath = null;
4035
            foreach (LMRepresentation rep in modelItem.Representations)
4036
            {
4037
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4038
                {
4039
                    symbolPath = rep.get_FileName();
4040
                    break;
4041
                }
4042
            }
4043
            return symbolPath;
4044
        }
4045

    
4046
        private string GetSPPIDFileName(string modelItemId)
4047
        {
4048
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4049
            string symbolPath = null;
4050
            foreach (LMRepresentation rep in modelItem.Representations)
4051
            {
4052
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4053
                {
4054
                    symbolPath = rep.get_FileName();
4055
                    break;
4056
                }
4057
            }
4058
            ReleaseCOMObjects(modelItem);
4059
            return symbolPath;
4060
        }
4061

    
4062
        /// <summary>
4063
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
4064
        /// </summary>
4065
        /// <param name="graphicOID"></param>
4066
        /// <param name="milliseconds"></param>
4067
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
4068
        {
4069
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
4070
            {
4071
                double minX = 0;
4072
                double minY = 0;
4073
                double maxX = 0;
4074
                double maxY = 0;
4075
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
4076
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
4077

    
4078
                Thread.Sleep(milliseconds);
4079
            }
4080
        }
4081

    
4082
        /// <summary>
4083
        /// ComObject를 Release
4084
        /// </summary>
4085
        /// <param name="objVars"></param>
4086
        public void ReleaseCOMObjects(params object[] objVars)
4087
        {
4088
            if (objVars != null)
4089
            {
4090
                int intNewRefCount = 0;
4091
                foreach (object obj in objVars)
4092
                {
4093
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
4094
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
4095
                }
4096
            }
4097
        }
4098
    }
4099
}
클립보드 이미지 추가 (최대 크기: 500 MB)