프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 4941f5fe

이력 | 보기 | 이력해설 | 다운로드 (191 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
        string drawingID;
32
        dynamic newDrawing;
33
        dynamic application;
34
        bool closeDocument;
35
        Ingr.RAD2D.Application radApp;
36
        SPPID_Document document;
37
        ETCSetting _ETCSetting;
38

    
39
        public string DocumentLabelText { get; set; }
40

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

    
47
        public AutoModeling(SPPID_Document document, bool closeDocument)
48
        {
49
            application = Interaction.GetObject("", "PIDAutomation.Application");
50
            WrapperApplication wApp = new WrapperApplication(application.Application);
51
            radApp = wApp.RADApplication;
52

    
53
            this.closeDocument = closeDocument;
54
            this.document = document;
55
            this._ETCSetting = ETCSetting.GetInstance();
56
        }
57

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

    
70
                }
71
            }
72
        }
73

    
74
        /// <summary>
75
        /// 도면 단위당 실행되는 메서드
76
        /// </summary>
77
        public void Run()
78
        {
79
            string drawingNumber = document.DrawingNumber;
80
            string drawingName = document.DrawingName;
81
            try
82
            {
83
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
84
                {
85
                    Log.Write("Start Modeling");
86
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
87
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
88
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 18);
89
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
90

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

    
124
                    // Result Logging
125
                    document.CheckModelingResult();
126
                }
127
            }
128
            catch (Exception ex)
129
            {
130
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
131
                {
132
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
133
                    SplashScreenManager.CloseForm(false);
134
                    Log.Write("\r\n");
135
                }
136
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
137
            }
138
            finally
139
            {
140
                Project_DB.InsertDrawingInfo(document.PATH, drawingNumber, drawingName, document);
141
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
142
                {
143
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
144
                    SplashScreenManager.CloseForm(false);
145
                    Log.Write("\r\n");
146
                }
147
                Thread.Sleep(1000);
148

    
149
                Log.Write("End Modeling");
150
                radApp.ActiveWindow.Fit();
151

    
152
                ReleaseCOMObjects(application);
153
                application = null;
154
                if (radApp.ActiveDocument != null)
155
                {
156
                    if (closeDocument && newDrawing != null)
157
                    {
158
                        newDrawing.Save();
159
                        newDrawing.CloseDrawing(true);
160
                        ReleaseCOMObjects(newDrawing);
161
                        newDrawing = null;
162
                    }
163
                    else if (newDrawing == null)
164
                    {
165
                        Log.Write("error document");
166
                    }
167
                }
168

    
169
                ReleaseCOMObjects(dataSource);
170
                dataSource = null;
171
                ReleaseCOMObjects(_placement);
172
                _placement = null;
173

    
174
                Thread.Sleep(1000);
175
            }
176
        }
177
        
178
        private void RunEquipmentModeling()
179
        {
180
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
181
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
182
            foreach (Equipment item in document.Equipments)
183
            {
184
                try
185
                {
186
                    EquipmentModeling(item);
187
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
188
                }
189
                catch (Exception ex)
190
                {
191
                    Log.Write("Error in EquipmentModeling");
192
                    Log.Write("UID : " + item.UID);
193
                    Log.Write(ex.Message);
194
                    Log.Write(ex.StackTrace);
195
                }
196
            }
197
        }
198
        private void RunSymbolModeling()
199
        {
200
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
201
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
202
            prioritySymbols = GetPrioritySymbol();
203
            foreach (var item in prioritySymbols)
204
            {
205
                try
206
                {
207
                    SymbolModelingBySymbol(item);
208
                }
209
                catch (Exception ex)
210
                {
211
                    Log.Write("Error in SymbolModelingByPriority");
212
                    Log.Write("UID : " + item.UID);
213
                    Log.Write(ex.Message);
214
                    Log.Write(ex.StackTrace);
215
                }
216
            }
217
        }
218
        private void RunLineModeling()
219
        {
220
            List<Line> AllLine = document.LINES.ToList();
221
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
222
            !SPPIDUtil.IsBranchedLine(document, x));
223
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
224

    
225
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
226
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
227

    
228
            SetPriorityLine(step1_Line);
229
            foreach (var item in step1_Line)
230
            {
231
                try
232
                {
233
                    NewLineModeling(item);
234
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
235
                }
236
                catch (Exception ex)
237
                {
238
                    Log.Write("Error in NewLineModeling");
239
                    Log.Write("UID : " + item.UID);
240
                    Log.Write(ex.Message);
241
                    Log.Write(ex.StackTrace);
242
                }
243
            }
244

    
245
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
246
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
247
            int branchCount = BranchLines.Count;
248
            while (BranchLines.Count > 0)
249
            {
250
                try
251
                {
252
                    SortBranchLines();
253
                    Line item = BranchLines[0];
254
                    NewLineModeling(item, true);
255
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
256
                }
257
                catch (Exception ex)
258
                {
259
                    Log.Write("Error in NewLineModeling");
260
                    Log.Write("UID : " + BranchLines[0].UID);
261
                    Log.Write(ex.Message);
262
                    Log.Write(ex.StackTrace);
263
                    break;
264
                }
265
            }
266

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

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

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

    
511
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
512

    
513
                        ReleaseCOMObjects(modelItem);
514
                    }
515
                }
516

    
517
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
518
            }
519
            foreach (var modelId in ZeroLengthModelItemID)
520
            {
521
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
522
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
523
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
524
                {
525
                    attribute.set_Value("End 1 is upstream (Inlet)");
526
                    zeroLengthModelItem.Commit();
527
                }
528

    
529
                SetFlowDirectionByLine(modelId);
530

    
531
                ReleaseCOMObjects(zeroLengthModelItem);
532
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
533
            }
534
            foreach (var modelId in ZeroLengthModelItemIDReverse)
535
            {
536
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
537
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
538
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
539
                {
540
                    attribute.set_Value("End 1 is downstream (Outlet)");
541
                    zeroLengthModelItem.Commit();
542
                }
543

    
544
                SetFlowDirectionByLine(modelId);
545

    
546
                ReleaseCOMObjects(zeroLengthModelItem);
547
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
548
            }
549
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
550
            {
551
                SetFlowDirectionByLine(modelId);
552
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
553
            }
554

    
555
            void SetFlowDirectionByLine(string lineModelItemID)
556
            {
557
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
558
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
559
                {
560
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
561
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
562
                    {
563
                        string sFlowDirection = attribute.get_Value().ToString();
564
                        foreach (LMRepresentation rep in modelItem.Representations)
565
                        {
566
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
567
                            {
568
                                LMConnector connector = dataSource.GetConnector(rep.Id);
569

    
570
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
571
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
572
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
573
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
574

    
575
                                ReleaseCOMObjects(connector);
576
                            }
577
                        }
578
                    }
579
                    ReleaseCOMObjects(modelItem);
580
                }
581

    
582
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
583
                {
584
                    // Item2가 Symbol
585
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
586
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
587
                    {
588
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
589
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
590
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
591

    
592
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
593

    
594
                        symbolModelItem.Commit();
595
                        ReleaseCOMObjects(symbolModelItem);
596
                    }
597
                    // Item1이 Symbol
598
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
599
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
600
                    {
601
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
602
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
603
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
604

    
605
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
606

    
607
                        symbolModelItem.Commit();
608
                        ReleaseCOMObjects(symbolModelItem);
609
                    }
610
                }
611

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

    
763
                _placement = new Placement();
764
                dataSource = _placement.PIDDataSource;
765

    
766
                //current LMDrawing 가져오기
767
                LMAFilter filter = new LMAFilter();
768
                LMACriterion criterion = new LMACriterion();
769
                filter.ItemType = "Drawing";
770
                criterion.SourceAttributeName = "Name";
771
                criterion.Operator = "=";
772
                criterion.set_ValueAttribute(drawingName);
773
                filter.get_Criteria().Add(criterion);
774

    
775
                LMDrawings drawings = new LMDrawings();
776
                drawings.Collect(dataSource, Filter: filter);
777

    
778
                drawingID = ((dynamic)drawings).Nth(1).Id;
779
                ReleaseCOMObjects(filter);
780
                ReleaseCOMObjects(criterion);
781
                ReleaseCOMObjects(drawings);
782
                filter = null;
783
                criterion = null;
784
                drawings = null;
785
            }
786
            else
787
                Log.Write("Fail Create Drawing");
788

    
789
            if (newDrawing != null)
790
                return true;
791
            else
792
                return false;
793
        }
794

    
795
        /// <summary>
796
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
797
        /// </summary>
798
        /// <param name="drawingName"></param>
799
        /// <param name="drawingNumber"></param>
800
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
801
        {
802
            LMADataSource dataSource = new LMADataSource();
803
            LMDrawings drawings = new LMDrawings();
804
            drawings.Collect(dataSource);
805

    
806
            List<string> drawingNameList = new List<string>();
807
            List<string> drawingNumberList = new List<string>();
808

    
809
            foreach (LMDrawing item in drawings)
810
            {
811
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
812
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
813
            }
814

    
815
            int nameLength = drawingName.Length;
816
            while (drawingNameList.Contains(drawingName))
817
            {
818
                if (nameLength == drawingName.Length)
819
                    drawingName += "-1";
820
                else
821
                {
822
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
823
                    drawingName = drawingName.Substring(0, nameLength + 1);
824
                    drawingName += ++index;
825
                }
826
            }
827

    
828
            int numberLength = drawingNumber.Length;
829
            while (drawingNameList.Contains(drawingNumber))
830
            {
831
                if (numberLength == drawingNumber.Length)
832
                    drawingNumber += "-1";
833
                else
834
                {
835
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
836
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
837
                    drawingNumber += ++index;
838
                }
839
            }
840
            ReleaseCOMObjects(dataSource);
841
            dataSource = null;
842
            ReleaseCOMObjects(drawings);
843
            drawings = null;
844
        }
845

    
846
        /// <summary>
847
        /// 도면 크기 구하는 메서드
848
        /// </summary>
849
        /// <returns></returns>
850
        private bool DocumentCoordinateCorrection()
851
        {
852
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
853
            {
854
                Log.Write("Setting Drawing X, Drawing Y");
855
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
856
                Log.Write("Start coordinate correction");
857
                document.CoordinateCorrection();
858
                return true;
859
            }
860
            else
861
            {
862
                Log.Write("Need Drawing X, Y");
863
                return false;
864
            }
865
        }
866

    
867
        /// <summary>
868
        /// 심볼을 실제로 Modeling 메서드
869
        /// </summary>
870
        /// <param name="symbol"></param>
871
        /// <param name="targetSymbol"></param>
872
        /// <param name="prevSymbol"></param>
873
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
874
        {
875
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
876
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
877
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
878
                return;
879
            // 이미 모델링 됐을 경우
880
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
881
                return;
882

    
883
            LMSymbol _LMSymbol = null;
884

    
885
            string mappingPath = symbol.SPPID.MAPPINGNAME;
886
            double x = symbol.SPPID.ORIGINAL_X;
887
            double y = symbol.SPPID.ORIGINAL_Y;
888
            int mirror = 0;
889
            double angle = symbol.ANGLE;
890

    
891
            // OPC 일경우 180도 일때 Mirror
892
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
893
                mirror = 1;
894

    
895
            // Mirror 계산
896
            if (symbol.FLIP == 1)
897
            {
898
                mirror = 1;
899
                angle += Math.PI;
900
            }
901

    
902
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
903
            {
904
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
905
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
906
                if (connector != null)
907
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
908

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

    
911
                if (_LMSymbol != null && _TargetItem != null)
912
                {
913
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
914

    
915
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
916
                    {
917
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
918
                        if (reModelingConnector != null)
919
                            ReModelingLMConnector(reModelingConnector);
920
                    }
921
                }
922

    
923
                ReleaseCOMObjects(_TargetItem);
924
            }
925
            else
926
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
927

    
928
            if (_LMSymbol != null)
929
            {
930
                _LMSymbol.Commit();
931

    
932
                // ConnCheck
933
                List<string> ids = new List<string>();
934
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
935
                {
936
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
937
                        ids.Add(item.Id);
938
                    ReleaseCOMObjects(item);
939
                }
940
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
941
                {
942
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
943
                        ids.Add(item.Id);
944
                    ReleaseCOMObjects(item);
945
                }
946

    
947
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
948
                if (targetSymbol == null && ids.Count != createdSymbolCount)
949
                {
950
                    double currentX = _LMSymbol.get_XCoordinate();
951
                    double currentY = _LMSymbol.get_YCoordinate();
952

    
953

    
954
                }
955

    
956
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
957
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
958
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
959

    
960
                foreach (var item in symbol.ChildSymbols)
961
                    CreateChildSymbol(item, _LMSymbol, symbol);
962

    
963
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
964
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
965

    
966
                double[] range = null;
967
                GetSPPIDSymbolRange(symbol, ref range);
968
                symbol.SPPID.SPPID_Min_X = range[0];
969
                symbol.SPPID.SPPID_Min_Y = range[1];
970
                symbol.SPPID.SPPID_Max_X = range[2];
971
                symbol.SPPID.SPPID_Max_Y = range[3];
972

    
973
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
974
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
975
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
976
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
977

    
978
                ReleaseCOMObjects(_LMSymbol);
979
            }
980
        }
981

    
982
        private void RemoveSymbol(Symbol symbol)
983
        {
984
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
985
            {
986
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
987
                if (_LMSymbol != null)
988
                {
989
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
990
                    ReleaseCOMObjects(_LMSymbol);
991
                }
992
            }
993

    
994
            symbol.SPPID.RepresentationId = string.Empty;
995
            symbol.SPPID.ModelItemID = string.Empty;
996
            symbol.SPPID.SPPID_X = double.NaN;
997
            symbol.SPPID.SPPID_Y = double.NaN;
998
            symbol.SPPID.SPPID_Min_X = double.NaN;
999
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1000
            symbol.SPPID.SPPID_Max_X = double.NaN;
1001
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1002
        }
1003

    
1004
        private void RemoveSymbol(List<Symbol> symbols)
1005
        {
1006
            foreach (var symbol in symbols)
1007
            {
1008
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1009
                {
1010
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1011
                    if (_LMSymbol != null)
1012
                    {
1013
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1014
                        ReleaseCOMObjects(_LMSymbol);
1015
                    }
1016
                }
1017

    
1018
                symbol.SPPID.RepresentationId = string.Empty;
1019
                symbol.SPPID.ModelItemID = string.Empty;
1020
                symbol.SPPID.SPPID_X = double.NaN;
1021
                symbol.SPPID.SPPID_Y = double.NaN;
1022
                symbol.SPPID.SPPID_Min_X = double.NaN;
1023
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1024
                symbol.SPPID.SPPID_Max_X = double.NaN;
1025
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1026
            }
1027
        }
1028

    
1029
        /// <summary>
1030
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1031
        /// </summary>
1032
        /// <param name="targetConnector"></param>
1033
        /// <param name="targetSymbol"></param>
1034
        /// <param name="x"></param>
1035
        /// <param name="y"></param>
1036
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1037
        {
1038
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1039

    
1040
            double[] range = null;
1041
            List<double[]> points = new List<double[]>();
1042
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1043
            double x1 = range[0];
1044
            double y1 = range[1];
1045
            double x2 = range[2];
1046
            double y2 = range[3];
1047

    
1048
            // Origin 기준 Connector의 위치차이
1049
            double sceneX = 0;
1050
            double sceneY = 0;
1051
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1052
            double originX = 0;
1053
            double originY = 0;
1054
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1055
            double gapX = originX - sceneX;
1056
            double gapY = originY - sceneY;
1057

    
1058
            // SPPID Symbol과 ID2 심볼의 크기 차이
1059
            double sizeWidth = 0;
1060
            double sizeHeight = 0;
1061
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1062
            if (sizeWidth == 0 || sizeHeight == 0)
1063
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1064

    
1065
            double percentX = (x2 - x1) / sizeWidth;
1066
            double percentY = (y2 - y1) / sizeHeight;
1067

    
1068
            double SPPIDgapX = gapX * percentX;
1069
            double SPPIDgapY = gapY * percentY;
1070

    
1071
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1072
            double distance = double.MaxValue;
1073
            double[] resultPoint;
1074
            foreach (var point in points)
1075
            {
1076
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1077
                if (distance > result)
1078
                {
1079
                    distance = result;
1080
                    resultPoint = point;
1081
                    x = point[0];
1082
                    y = point[1];
1083
                }
1084
            }
1085

    
1086
            ReleaseCOMObjects(_TargetItem);
1087
        }
1088

    
1089
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1090
        {
1091
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1092
            if (index == 0)
1093
            {
1094
                x = targetLine.SPPID.START_X;
1095
                y = targetLine.SPPID.START_Y;
1096
            }
1097
            else
1098
            {
1099
                x = targetLine.SPPID.END_X;
1100
                y = targetLine.SPPID.END_Y;
1101
            }
1102
        }
1103

    
1104
        /// <summary>
1105
        /// SPPID Symbol의 Range를 구한다.
1106
        /// </summary>
1107
        /// <param name="symbol"></param>
1108
        /// <param name="range"></param>
1109
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1110
        {
1111
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1112
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1113
            double x1 = 0;
1114
            double y1 = 0;
1115
            double x2 = 0;
1116
            double y2 = 0;
1117
            symbol2d.Range(out x1, out y1, out x2, out y2);
1118
            range = new double[] { x1, y1, x2, y2 };
1119

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

    
1130
            foreach (var childSymbol in symbol.ChildSymbols)
1131
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1132

    
1133
            ReleaseCOMObjects(_TargetItem);
1134
        }
1135

    
1136
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range)
1137
        {
1138
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1139
            if (_TargetItem != null)
1140
            {
1141
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1142
                double x1 = 0;
1143
                double y1 = 0;
1144
                double x2 = 0;
1145
                double y2 = 0;
1146
                symbol2d.Range(out x1, out y1, out x2, out y2);
1147
                range = new double[] { x1, y1, x2, y2 };
1148

    
1149
                foreach (var childSymbol in symbol.ChildSymbols)
1150
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1151

    
1152
                ReleaseCOMObjects(_TargetItem);
1153
            }
1154
        }
1155

    
1156
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1157
        {
1158
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1159
            foreach (var symbol in symbols)
1160
            {
1161
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1162
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1163
                double x1 = 0;
1164
                double y1 = 0;
1165
                double x2 = 0;
1166
                double y2 = 0;
1167
                symbol2d.Range(out x1, out y1, out x2, out y2);
1168

    
1169
                tempRange[0] = Math.Min(tempRange[0], x1);
1170
                tempRange[1] = Math.Min(tempRange[1], y1);
1171
                tempRange[2] = Math.Max(tempRange[2], x2);
1172
                tempRange[3] = Math.Max(tempRange[3], y2);
1173

    
1174
                foreach (var childSymbol in symbol.ChildSymbols)
1175
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1176

    
1177
                ReleaseCOMObjects(_TargetItem);
1178
            }
1179

    
1180
            range = tempRange;
1181
        }
1182

    
1183
        /// <summary>
1184
        /// Child Modeling 된 Symbol의 Range를 구한다.
1185
        /// </summary>
1186
        /// <param name="childSymbol"></param>
1187
        /// <param name="range"></param>
1188
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1189
        {
1190
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1191
            if (_ChildSymbol != null)
1192
            {
1193
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1194
                double x1 = 0;
1195
                double y1 = 0;
1196
                double x2 = 0;
1197
                double y2 = 0;
1198
                symbol2d.Range(out x1, out y1, out x2, out y2);
1199
                range[0] = Math.Min(range[0], x1);
1200
                range[1] = Math.Min(range[1], y1);
1201
                range[2] = Math.Max(range[2], x2);
1202
                range[3] = Math.Max(range[3], y2);
1203

    
1204
                for (int i = 1; i < int.MaxValue; i++)
1205
                {
1206
                    double connX = 0;
1207
                    double connY = 0;
1208
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1209
                        points.Add(new double[] { connX, connY });
1210
                    else
1211
                        break;
1212
                }
1213

    
1214
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1215
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1216

    
1217
                ReleaseCOMObjects(_ChildSymbol);
1218
            }
1219
        }
1220

    
1221
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1222
        {
1223
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1224
            if (_ChildSymbol != null)
1225
            {
1226
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1227
                double x1 = 0;
1228
                double y1 = 0;
1229
                double x2 = 0;
1230
                double y2 = 0;
1231
                symbol2d.Range(out x1, out y1, out x2, out y2);
1232
                range[0] = Math.Min(range[0], x1);
1233
                range[1] = Math.Min(range[1], y1);
1234
                range[2] = Math.Max(range[2], x2);
1235
                range[3] = Math.Max(range[3], y2);
1236

    
1237
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1238
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1239
                ReleaseCOMObjects(_ChildSymbol);
1240
            }
1241
        }
1242

    
1243
        /// <summary>
1244
        /// Label Symbol Modeling
1245
        /// </summary>
1246
        /// <param name="symbol"></param>
1247
        private void LabelSymbolModeling(Symbol symbol)
1248
        {
1249
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1250
            {
1251
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1252
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1253
                    return;
1254
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1255

    
1256
                string symbolUID = itemAttribute.VALUE;
1257
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1258
                if (targetItem != null &&
1259
                    (targetItem.GetType() == typeof(Symbol) ||
1260
                    targetItem.GetType() == typeof(Equipment)))
1261
                {
1262
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1263
                    string sRep = null;
1264
                    if (targetItem.GetType() == typeof(Symbol))
1265
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1266
                    else if (targetItem.GetType() == typeof(Equipment))
1267
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1268
                    if (!string.IsNullOrEmpty(sRep))
1269
                    {
1270
                        // LEADER Line 검사
1271
                        bool leaderLine = false;
1272
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1273
                        if (symbolMapping != null)
1274
                            leaderLine = symbolMapping.LEADERLINE;
1275

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

    
1280
                        //Leader 선 센터로
1281
                        if (_LMLabelPresist != null)
1282
                        {
1283
                            // Target Item에 Label의 Attribute Input
1284
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1285

    
1286
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1287
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1288
                            if (dependency != null)
1289
                            {
1290
                                bool result = false;
1291
                                foreach (var attributes in dependency.AttributeSets)
1292
                                {
1293
                                    foreach (var attribute in attributes)
1294
                                    {
1295
                                        string name = attribute.Name;
1296
                                        string value = attribute.GetValue().ToString();
1297
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1298
                                        {
1299
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1300
                                            {
1301
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1302
                                                {
1303
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1304
                                                    double prevX = _TargetItem.get_XCoordinate();
1305
                                                    double prevY = _TargetItem.get_YCoordinate();
1306
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1307
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1308
                                                    result = true;
1309
                                                    break;
1310
                                                }
1311
                                            }
1312
                                        }
1313

    
1314
                                        if (result)
1315
                                            break;
1316
                                    }
1317

    
1318
                                    if (result)
1319
                                        break;
1320
                                }
1321
                            }
1322

    
1323
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1324
                            _LMLabelPresist.Commit();
1325
                            ReleaseCOMObjects(_LMLabelPresist);
1326
                        }
1327

    
1328
                        ReleaseCOMObjects(_TargetItem);
1329
                    }
1330
                }
1331
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1332
                {
1333
                    Line targetLine = targetItem as Line;
1334
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1335
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1336
                    if (connectedLMConnector != null)
1337
                    {
1338
                        // LEADER Line 검사
1339
                        bool leaderLine = false;
1340
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1341
                        if (symbolMapping != null)
1342
                            leaderLine = symbolMapping.LEADERLINE;
1343

    
1344
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1345
                        if (_LMLabelPresist != null)
1346
                        {
1347
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1348
                            _LMLabelPresist.Commit();
1349
                            ReleaseCOMObjects(_LMLabelPresist);
1350
                        }
1351
                        ReleaseCOMObjects(connectedLMConnector);
1352
                    }
1353

    
1354
                    foreach (var item in connectorVertices)
1355
                        if (item.Key != null)
1356
                            ReleaseCOMObjects(item.Key);
1357
                }
1358
            }
1359
        }
1360

    
1361
        /// <summary>
1362
        /// Equipment를 실제로 Modeling 메서드
1363
        /// </summary>
1364
        /// <param name="equipment"></param>
1365
        private void EquipmentModeling(Equipment equipment)
1366
        {
1367
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1368
                return;
1369

    
1370
            LMSymbol _LMSymbol = null;
1371
            LMSymbol targetItem = null;
1372
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1373
            double x = equipment.SPPID.ORIGINAL_X;
1374
            double y = equipment.SPPID.ORIGINAL_Y;
1375
            int mirror = 0;
1376
            double angle = equipment.ANGLE;
1377

    
1378
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1379

    
1380
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1381
            if (connector != null)
1382
            {
1383
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1384
                if (connEquipment != null)
1385
                {
1386
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1387
                        EquipmentModeling(connEquipment);
1388

    
1389
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1390
                    {
1391
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1392
                        if (targetItem != null)
1393
                        {
1394
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1395
                        }
1396
                        else
1397
                        {
1398
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1399
                        }
1400
                    }
1401
                    else
1402
                    {
1403
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1404
                    }
1405
                }
1406
                else
1407
                {
1408
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1409
                }
1410
            }
1411
            else
1412
            {
1413
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1414
            }
1415

    
1416
            if (_LMSymbol != null)
1417
            {
1418
                _LMSymbol.Commit();
1419
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1420
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1421
                ReleaseCOMObjects(_LMSymbol);
1422
            }
1423

    
1424
            if (targetItem != null)
1425
            {
1426
                ReleaseCOMObjects(targetItem);
1427
            }
1428

    
1429
            ReleaseCOMObjects(_LMSymbol);
1430
        }
1431

    
1432
        /// <summary>
1433
        /// 첫 진입점
1434
        /// </summary>
1435
        /// <param name="symbol"></param>
1436
        private void SymbolModelingBySymbol(Symbol symbol)
1437
        {
1438
            SymbolModeling(symbol, null);
1439
            List<object> endObjects = new List<object>();
1440
            endObjects.Add(symbol);
1441

    
1442
            foreach (var connector in symbol.CONNECTORS)
1443
            {
1444
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1445
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1446
                {
1447
                    endObjects.Add(connItem);
1448
                    if (connItem.GetType() == typeof(Symbol))
1449
                    {
1450
                        Symbol connSymbol = connItem as Symbol;
1451
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1452
                        {
1453
                            SymbolModeling(connSymbol, symbol);
1454
                        }
1455
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1456
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1457
                    }
1458
                    else if (connItem.GetType() == typeof(Line))
1459
                    {
1460
                        Line connLine = connItem as Line;
1461
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1462
                    }
1463
                }
1464
            }
1465
        }
1466

    
1467
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1468
        {
1469
            foreach (var connector in symbol.CONNECTORS)
1470
            {
1471
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1472
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1473
                {
1474
                    if (!endObjects.Contains(connItem))
1475
                    {
1476
                        endObjects.Add(connItem);
1477
                        if (connItem.GetType() == typeof(Symbol))
1478
                        {
1479
                            Symbol connSymbol = connItem as Symbol;
1480
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1481
                            {
1482
                                SymbolModeling(connSymbol, symbol);
1483
                            }
1484
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1485
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1486
                        }
1487
                        else if (connItem.GetType() == typeof(Line))
1488
                        {
1489
                            Line connLine = connItem as Line;
1490
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1491
                        }
1492
                    }
1493
                }
1494
            }
1495
        }
1496

    
1497
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1498
        {
1499
            foreach (var connector in line.CONNECTORS)
1500
            {
1501
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1502
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1503
                {
1504
                    if (!endObjects.Contains(connItem))
1505
                    {
1506
                        endObjects.Add(connItem);
1507
                        if (connItem.GetType() == typeof(Symbol))
1508
                        {
1509
                            Symbol connSymbol = connItem as Symbol;
1510
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1511
                            {
1512
                                List<Symbol> group = new List<Symbol>();
1513
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1514
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1515
                                List<Symbol> endModelingGroup = new List<Symbol>();
1516
                                if (priority != null)
1517
                                {
1518
                                    SymbolGroupModeling(priority, group);
1519

    
1520
                                    // Range 겹치는지 확인해야함
1521
                                    double[] prevRange = null;
1522
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1523
                                    double[] groupRange = null;
1524
                                    GetSPPIDSymbolRange(group, ref groupRange);
1525

    
1526
                                    double distanceX = 0;
1527
                                    double distanceY = 0;
1528
                                    bool overlapX = false;
1529
                                    bool overlapY = false;
1530
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1531
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1532
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1533
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1534
                                    {
1535
                                        RemoveSymbol(group);
1536
                                        foreach (var _temp in group)
1537
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1538

    
1539
                                        SymbolGroupModeling(priority, group);
1540
                                    }
1541
                                }
1542
                                else
1543
                                {
1544
                                    SymbolModeling(connSymbol, null);
1545
                                    // Range 겹치는지 확인해야함
1546
                                    double[] prevRange = null;
1547
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1548
                                    double[] connRange = null;
1549
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1550

    
1551
                                    double distanceX = 0;
1552
                                    double distanceY = 0;
1553
                                    bool overlapX = false;
1554
                                    bool overlapY = false;
1555
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1556
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1557
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1558
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1559
                                    {
1560
                                        RemoveSymbol(connSymbol);
1561
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1562

    
1563
                                        SymbolModeling(connSymbol, null);
1564
                                    }
1565
                                }
1566
                            }
1567
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1568
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1569
                        }
1570
                        else if (connItem.GetType() == typeof(Line))
1571
                        {
1572
                            Line connLine = connItem as Line;
1573
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1574
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1575
                        }
1576
                    }
1577
                }
1578
            }
1579
        }
1580

    
1581
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1582
        {
1583
            List<Symbol> endModelingGroup = new List<Symbol>();
1584
            SymbolModeling(firstSymbol, null);
1585
            endModelingGroup.Add(firstSymbol);
1586
            while (endModelingGroup.Count != group.Count)
1587
            {
1588
                foreach (var _symbol in group)
1589
                {
1590
                    if (!endModelingGroup.Contains(_symbol))
1591
                    {
1592
                        foreach (var _connector in _symbol.CONNECTORS)
1593
                        {
1594
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1595
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1596
                            {
1597
                                SymbolModeling(_symbol, _connSymbol);
1598
                                endModelingGroup.Add(_symbol);
1599
                                break;
1600
                            }
1601
                        }
1602
                    }
1603
                }
1604
            }
1605
        }
1606

    
1607
        /// <summary>
1608
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1609
        /// </summary>
1610
        /// <param name="childSymbol"></param>
1611
        /// <param name="parentSymbol"></param>
1612
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1613
        {
1614
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1615
            double x1 = 0;
1616
            double x2 = 0;
1617
            double y1 = 0;
1618
            double y2 = 0;
1619
            symbol2d.Range(out x1, out y1, out x2, out y2);
1620

    
1621
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1622
            if (_LMSymbol != null)
1623
            {
1624
                _LMSymbol.Commit();
1625
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1626
                foreach (var item in childSymbol.ChildSymbols)
1627
                    CreateChildSymbol(item, _LMSymbol, parent);
1628
            }
1629

    
1630

    
1631
            ReleaseCOMObjects(_LMSymbol);
1632
        }
1633
        double index = 0;
1634
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1635
        {
1636
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1637
                return;
1638

    
1639
            List<Line> group = new List<Line>();
1640
            GetConnectedLineGroup(line, group);
1641
            LineCoordinateCorrection(group);
1642

    
1643
            foreach (var groupLine in group)
1644
            {
1645
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1646
                {
1647
                    BranchLines.Add(groupLine);
1648
                    continue;
1649
                }
1650

    
1651
                bool diagonal = false;
1652
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1653
                    diagonal = true;
1654
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1655
                LMSymbol _LMSymbolStart = null;
1656
                LMSymbol _LMSymbolEnd = null;
1657
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1658
                foreach (var connector in groupLine.CONNECTORS)
1659
                {
1660
                    double x = 0;
1661
                    double y = 0;
1662
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1663
                    if (connector.ConnectedObject == null)
1664
                    {
1665
                        placeRunInputs.AddPoint(x, y);
1666
                    }
1667
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1668
                    {
1669
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1670
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1671
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1672
                        {
1673
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1674
                            if (_LMSymbolStart != null)
1675
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1676
                            else
1677
                                placeRunInputs.AddPoint(x, y);
1678
                        }
1679
                        else
1680
                        {
1681
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1682
                            if (_LMSymbolEnd != null)
1683
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1684
                            else
1685
                                placeRunInputs.AddPoint(x, y);
1686
                        }
1687
                    }
1688
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1689
                    {
1690
                        Line targetLine = connector.ConnectedObject as Line;
1691
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1692
                        {
1693
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1694
                            if (targetConnector != null)
1695
                            {
1696
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1697
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1698
                            }
1699
                            else
1700
                            {
1701
                                placeRunInputs.AddPoint( x, y);
1702
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1703
                            }
1704
                        }
1705
                        else
1706
                        {
1707
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1708
                            {
1709
                                index += 0.01;
1710
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1711
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1712
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1713
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1714
                                else
1715
                                {
1716
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
1717
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1718
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1719
                                    else
1720
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1721
                                }
1722
                            }
1723

    
1724
                            placeRunInputs.AddPoint(x, y);
1725

    
1726
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1727
                            {
1728
                                index += 0.01;
1729
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1730
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1731
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1732
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1733
                                else
1734
                                {
1735
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
1736
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1737
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1738
                                    else
1739
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1740
                                }
1741
                            }
1742
                        }
1743
                    }
1744
                }
1745

    
1746
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1747
                if (_lMConnector != null)
1748
                {
1749
                    _lMConnector.Commit();
1750
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1751
                    bool bRemodelingStart = false;
1752
                    if (_LMSymbolStart != null)
1753
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1754
                    bool bRemodelingEnd = false;
1755
                    if (_LMSymbolEnd != null)
1756
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1757

    
1758
                    if (bRemodelingStart || bRemodelingEnd)
1759
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1760

    
1761
                    FlowMarkModeling(groupLine);
1762
                    LineNumberModelingOnlyOne(groupLine);
1763

    
1764
                    ReleaseCOMObjects(_lMConnector);
1765
                }
1766
                else if (!isBranchModeling)
1767
                {
1768
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1769
                }
1770

    
1771
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1772
                x.ConnectedObject != null &&
1773
                x.ConnectedObject.GetType() == typeof(Line) &&
1774
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1775
                .Select(x => x.ConnectedObject)
1776
                .ToList();
1777

    
1778
                foreach (var item in removeLines)
1779
                    RemoveLineForModeling(item as Line);
1780

    
1781
                if (_LMAItem != null)
1782
                    ReleaseCOMObjects(_LMAItem);
1783
                if (placeRunInputs != null)
1784
                    ReleaseCOMObjects(placeRunInputs);
1785
                if (_LMSymbolStart != null)
1786
                    ReleaseCOMObjects(_LMSymbolStart);
1787
                if (_LMSymbolEnd != null)
1788
                    ReleaseCOMObjects(_LMSymbolEnd);
1789

    
1790
                if (isBranchModeling && BranchLines.Contains(groupLine))
1791
                    BranchLines.Remove(groupLine);
1792
            }
1793
        }
1794

    
1795
        private void RemoveLineForModeling(Line line)
1796
        {
1797
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1798
            if (modelItem != null)
1799
            {
1800
                foreach (LMRepresentation rep in modelItem.Representations)
1801
                {
1802
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1803
                    {
1804
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1805
                        dynamic OID = rep.get_GraphicOID().ToString();
1806
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1807
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1808
                        int verticesCount = lineStringGeometry.VertexCount;
1809
                        double[] vertices = null;
1810
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1811
                        for (int i = 0; i < verticesCount; i++)
1812
                        {
1813
                            double x = 0;
1814
                            double y = 0;
1815
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1816
                            if (verticesCount == 2 && (x < 0 || y < 0))
1817
                                _placement.PIDRemovePlacement(rep);
1818
                        }
1819
                        ReleaseCOMObjects(_LMConnector);
1820
                    }
1821
                }
1822

    
1823
                ReleaseCOMObjects(modelItem);
1824
            }
1825
        }
1826

    
1827
        private void GetConnectedLineGroup(Line line, List<Line> group)
1828
        {
1829
            if (!group.Contains(line))
1830
                group.Add(line);
1831
            foreach (var connector in line.CONNECTORS)
1832
            {
1833
                if (connector.ConnectedObject != null &&
1834
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1835
                    !group.Contains(connector.ConnectedObject) &&
1836
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1837
                {
1838
                    Line connLine = connector.ConnectedObject as Line;
1839
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1840
                    {
1841
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1842
                            group.Insert(0, connLine);
1843
                        else
1844
                            group.Add(connLine);
1845
                        GetConnectedLineGroup(connLine, group);
1846
                    }
1847
                }
1848
            }
1849
        }
1850

    
1851
        private void LineCoordinateCorrection(List<Line> group)
1852
        {
1853
            // 순서대로 전 Item 기준 정렬
1854
            LineCoordinateCorrectionByStart(group);
1855

    
1856
            // 역으로 심볼이 있을 경우 좌표 보정
1857
            LineCoordinateCorrectionForLastLine(group);
1858
        }
1859

    
1860
        private void LineCoordinateCorrectionByStart(List<Line> group)
1861
        {
1862
            for (int i = 0; i < group.Count; i++)
1863
            {
1864
                Line line = group[i];
1865
                if (i == 0)
1866
                {
1867
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1868
                    if (symbolConnector != null)
1869
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1870
                }
1871
                else if (i != 0)
1872
                {
1873
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1874
                }
1875
            }
1876
        }
1877

    
1878
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1879
        {
1880
            Line checkLine = group[group.Count - 1];
1881
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1882
            if (lastSymbolConnector != null)
1883
            {
1884
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1885
                for (int i = group.Count - 2; i >= 0; i--)
1886
                {
1887
                    Line line = group[i + 1];
1888
                    Line prevLine = group[i];
1889

    
1890
                    // 같으면 보정
1891
                    if (line.SlopeType == prevLine.SlopeType)
1892
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1893
                    else
1894
                    {
1895
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1896
                        {
1897
                            double prevX = 0;
1898
                            double prevY = 0;
1899
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1900
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1901

    
1902
                            double x = 0;
1903
                            double y = 0;
1904
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1905
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1906
                        }
1907
                        else if (line.SlopeType == SlopeType.VERTICAL)
1908
                        {
1909
                            double prevX = 0;
1910
                            double prevY = 0;
1911
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1912
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1913

    
1914
                            double x = 0;
1915
                            double y = 0;
1916
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1917
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1918
                        }
1919
                        break;
1920
                    }
1921
                }
1922
            }
1923
        }
1924

    
1925
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1926
        {
1927
            double x = 0;
1928
            double y = 0;
1929
            if (connItem.GetType() == typeof(Symbol))
1930
            {
1931
                Symbol targetSymbol = connItem as Symbol;
1932
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1933
                if (targetConnector != null)
1934
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
1935
                else
1936
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
1937
            }
1938
            else if (connItem.GetType() == typeof(Line))
1939
            {
1940
                Line targetLine = connItem as Line;
1941
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
1942
            }
1943

    
1944
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
1945
        }
1946

    
1947
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
1948
        {
1949
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1950
            int index = line.CONNECTORS.IndexOf(connector);
1951
            if (index == 0)
1952
            {
1953
                line.SPPID.START_X = x;
1954
                line.SPPID.START_Y = y;
1955
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1956
                    line.SPPID.END_Y = y;
1957
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1958
                    line.SPPID.END_X = x;
1959
            }
1960
            else
1961
            {
1962
                line.SPPID.END_X = x;
1963
                line.SPPID.END_Y = y;
1964
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1965
                    line.SPPID.START_Y = y;
1966
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1967
                    line.SPPID.START_X = x;
1968
            }
1969
        }
1970

    
1971
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
1972
        {
1973
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1974
            int index = line.CONNECTORS.IndexOf(connector);
1975
            if (index == 0)
1976
            {
1977
                line.SPPID.START_X = x;
1978
                if (line.SlopeType == SlopeType.VERTICAL)
1979
                    line.SPPID.END_X = x;
1980
            }
1981
            else
1982
            {
1983
                line.SPPID.END_X = x;
1984
                if (line.SlopeType == SlopeType.VERTICAL)
1985
                    line.SPPID.START_X = x;
1986
            }
1987
        }
1988

    
1989
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
1990
        {
1991
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1992
            int index = line.CONNECTORS.IndexOf(connector);
1993
            if (index == 0)
1994
            {
1995
                line.SPPID.START_Y = y;
1996
                if (line.SlopeType == SlopeType.HORIZONTAL)
1997
                    line.SPPID.END_Y = y;
1998
            }
1999
            else
2000
            {
2001
                line.SPPID.END_Y = y;
2002
                if (line.SlopeType == SlopeType.HORIZONTAL)
2003
                    line.SPPID.START_Y = y;
2004
            }
2005
        }
2006

    
2007
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2008
        {
2009
            if (symbol != null)
2010
            {
2011
                string repID = symbol.AsLMRepresentation().Id;
2012
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2013
                string lineUID = line.UID;
2014

    
2015
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2016
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2017
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2018

    
2019
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2020
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2021
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2022

    
2023
                if (startSpecBreak != null || startEndBreak != null)
2024
                    result = true;
2025
            }
2026
        }
2027

    
2028
        /// <summary>
2029
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2030
        /// </summary>
2031
        /// <param name="lines"></param>
2032
        /// <param name="prevLMConnector"></param>
2033
        /// <param name="startSymbol"></param>
2034
        /// <param name="endSymbol"></param>
2035
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2036
        {
2037
            string symbolPath = string.Empty;
2038
            #region get symbol path
2039
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2040
            symbolPath = GetSPPIDFileName(modelItem);
2041
            ReleaseCOMObjects(modelItem);
2042
            #endregion
2043
            bool diagonal = false;
2044
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2045
                diagonal = true;
2046
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2047
            LMConnector newConnector = null;
2048
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2049
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2050
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2051
            int verticesCount = lineStringGeometry.VertexCount;
2052
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2053

    
2054
            List<double[]> vertices = new List<double[]>();
2055
            for (int i = 1; i <= verticesCount; i++)
2056
            {
2057
                double x = 0;
2058
                double y = 0;
2059
                lineStringGeometry.GetVertex(i, ref x, ref y);
2060
                vertices.Add(new double[] { x, y });
2061
            }
2062

    
2063
            for (int i = 0; i < vertices.Count; i++)
2064
            {
2065
                double[] points = vertices[i];
2066
                // 시작 심볼이 있고 첫번째 좌표일 때
2067
                if (startSymbol != null && i == 0)
2068
                {
2069
                    if (bStart)
2070
                    {
2071
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2072
                        if (slopeType == SlopeType.HORIZONTAL)
2073
                            placeRunInputs.AddPoint(points[0], -0.1);
2074
                        else if (slopeType == SlopeType.VERTICAL)
2075
                            placeRunInputs.AddPoint(-0.1, points[1]);
2076
                        else
2077
                            placeRunInputs.AddPoint(points[0], -0.1);
2078

    
2079
                        placeRunInputs.AddPoint(points[0], points[1]);
2080
                    }
2081
                    else
2082
                    {
2083
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2084
                    }
2085
                }
2086
                // 마지막 심볼이 있고 마지막 좌표일 때
2087
                else if (endSymbol != null && i == vertices.Count - 1)
2088
                {
2089
                    if (bEnd)
2090
                    {
2091
                        placeRunInputs.AddPoint(points[0], points[1]);
2092

    
2093
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2094
                        if (slopeType == SlopeType.HORIZONTAL)
2095
                            placeRunInputs.AddPoint(points[0], -0.1);
2096
                        else if (slopeType == SlopeType.VERTICAL)
2097
                            placeRunInputs.AddPoint(-0.1, points[1]);
2098
                        else
2099
                            placeRunInputs.AddPoint(points[0], -0.1);
2100
                    }
2101
                    else
2102
                    {
2103
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2104
                    }
2105
                }
2106
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2107
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2108
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2109
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2110
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2111
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2112
                else
2113
                    placeRunInputs.AddPoint(points[0], points[1]);
2114
            }
2115

    
2116
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2117
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2118

    
2119
            ReleaseCOMObjects(placeRunInputs);
2120
            ReleaseCOMObjects(_LMAItem);
2121
            ReleaseCOMObjects(modelItem);
2122

    
2123
            if (newConnector != null)
2124
            {
2125
                newConnector.Commit();
2126
                if (startSymbol != null && bStart)
2127
                {
2128
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2129
                    placeRunInputs = new PlaceRunInputs();
2130
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2131
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2132
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2133
                    if (_LMConnector != null)
2134
                    {
2135
                        _LMConnector.Commit();
2136
                        RemoveConnectorForReModelingLine(newConnector);
2137
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2138
                        ReleaseCOMObjects(_LMConnector);
2139
                    }
2140
                    ReleaseCOMObjects(placeRunInputs);
2141
                    ReleaseCOMObjects(_LMAItem);
2142
                }
2143

    
2144
                if (endSymbol != null && bEnd)
2145
                {
2146
                    if (startSymbol != null)
2147
                    {
2148
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2149
                        newConnector = dicVertices.First().Key;
2150
                    }
2151

    
2152
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2153
                    placeRunInputs = new PlaceRunInputs();
2154
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2155
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2156
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2157
                    if (_LMConnector != null)
2158
                    {
2159
                        _LMConnector.Commit();
2160
                        RemoveConnectorForReModelingLine(newConnector);
2161
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2162
                        ReleaseCOMObjects(_LMConnector);
2163
                    }
2164
                    ReleaseCOMObjects(placeRunInputs);
2165
                    ReleaseCOMObjects(_LMAItem);
2166
                }
2167

    
2168
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2169
                ReleaseCOMObjects(newConnector);
2170
            }
2171

    
2172
            ReleaseCOMObjects(modelItem);
2173
        }
2174

    
2175
        /// <summary>
2176
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2177
        /// </summary>
2178
        /// <param name="connector"></param>
2179
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2180
        {
2181
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2182
            foreach (var item in dicVertices)
2183
            {
2184
                if (item.Value.Count == 2)
2185
                {
2186
                    bool result = false;
2187
                    foreach (var point in item.Value)
2188
                    {
2189
                        if (point[0] < 0 || point[1] < 0)
2190
                        {
2191
                            result = true;
2192
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2193
                            break;
2194
                        }
2195
                    }
2196

    
2197
                    if (result)
2198
                        break;
2199
                }
2200
            }
2201
            foreach (var item in dicVertices)
2202
                ReleaseCOMObjects(item.Key);
2203
        }
2204

    
2205
        /// <summary>
2206
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2207
        /// </summary>
2208
        /// <param name="symbol"></param>
2209
        /// <param name="line"></param>
2210
        /// <returns></returns>
2211
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2212
        {
2213
            LMSymbol _LMSymbol = null;
2214
            foreach (var connector in symbol.CONNECTORS)
2215
            {
2216
                if (connector.CONNECTEDITEM == line.UID)
2217
                {
2218
                    if (connector.Index == 0)
2219
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2220
                    else
2221
                    {
2222
                        ChildSymbol child = null;
2223
                        foreach (var childSymbol in symbol.ChildSymbols)
2224
                        {
2225
                            if (childSymbol.Connectors.Contains(connector))
2226
                                child = childSymbol;
2227
                            else
2228
                                child = GetChildSymbolByConnector(childSymbol, connector);
2229

    
2230
                            if (child != null)
2231
                                break;
2232
                        }
2233

    
2234
                        if (child != null)
2235
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2236
                    }
2237

    
2238
                    break;
2239
                }
2240
            }
2241

    
2242
            return _LMSymbol;
2243
        }
2244

    
2245
        /// <summary>
2246
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2247
        /// </summary>
2248
        /// <param name="item"></param>
2249
        /// <param name="connector"></param>
2250
        /// <returns></returns>
2251
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2252
        {
2253
            foreach (var childSymbol in item.ChildSymbols)
2254
            {
2255
                if (childSymbol.Connectors.Contains(connector))
2256
                    return childSymbol;
2257
                else
2258
                    return GetChildSymbolByConnector(childSymbol, connector);
2259
            }
2260

    
2261
            return null;
2262
        }
2263

    
2264
        /// <summary>
2265
        /// EndBreak 모델링 메서드
2266
        /// </summary>
2267
        /// <param name="endBreak"></param>
2268
        private void EndBreakModeling(EndBreak endBreak)
2269
        {
2270
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2271
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2272
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2273

    
2274
            if (targetLMConnector != null)
2275
            {
2276
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2277
                Array array = null;
2278
                if (point != null)
2279
                    array = new double[] { 0, point[0], point[1] };
2280
                else
2281
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2282
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2283
                if (_LmLabelPersist != null)
2284
                {
2285
                    _LmLabelPersist.Commit();
2286
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2287
                    if (_LmLabelPersist.ModelItemObject != null)
2288
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2289
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2290
                    ReleaseCOMObjects(_LmLabelPersist);
2291
                }
2292
                ReleaseCOMObjects(targetLMConnector);
2293
            }
2294
        }
2295

    
2296
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2297
        {
2298
            string symbolPath = string.Empty;
2299
            #region get symbol path
2300
            if (string.IsNullOrEmpty(changeSymbolPath))
2301
            {
2302
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2303
                symbolPath = GetSPPIDFileName(modelItem);
2304
                ReleaseCOMObjects(modelItem);
2305
            }
2306
            else
2307
                symbolPath = changeSymbolPath;
2308
            
2309
            #endregion
2310

    
2311
            LMConnector newConnector = null;
2312
            dynamic OID = connector.get_GraphicOID().ToString();
2313
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2314
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2315
            int verticesCount = lineStringGeometry.VertexCount;
2316
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2317
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2318

    
2319
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2320
            {
2321
                double[] vertices = null;
2322
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2323
                double x = 0;
2324
                double y = 0;
2325
                lineStringGeometry.GetVertex(1, ref x, ref y);
2326

    
2327
                string flowDirection = string.Empty;
2328
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2329
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2330
                    flowDirection = flowAttribute.get_Value().ToString();
2331

    
2332
                if (flowDirection == "End 1 is downstream (Outlet)")
2333
                {
2334
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2335
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2336
                    flowDirection = "End 1 is upstream (Inlet)";
2337
                }
2338
                else
2339
                {
2340
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2341
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2342
                }
2343

    
2344
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2345
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2346
                newConnector.Commit();
2347
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2348
                if (!string.IsNullOrEmpty(flowDirection))
2349
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2350
            }
2351
            else
2352
            {
2353
                List<double[]> vertices = new List<double[]>();
2354
                for (int i = 1; i <= verticesCount; i++)
2355
                {
2356
                    double x = 0;
2357
                    double y = 0;
2358
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2359
                    vertices.Add(new double[] { x, y });
2360
                }
2361

    
2362
                for (int i = 0; i < vertices.Count; i++)
2363
                {
2364
                    double[] points = vertices[i];
2365
                    if (i == 0)
2366
                    {
2367
                        if (connector.ConnectItem1SymbolObject != null)
2368
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2369
                        else
2370
                            placeRunInputs.AddPoint(points[0], points[1]);
2371
                    }
2372
                    else if (i == vertices.Count - 1)
2373
                    {
2374
                        if (connector.ConnectItem2SymbolObject != null)
2375
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2376
                        else
2377
                            placeRunInputs.AddPoint(points[0], points[1]);
2378
                    }
2379
                    else
2380
                        placeRunInputs.AddPoint(points[0], points[1]);
2381
                }
2382

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

    
2385
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2386
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2387
                newConnector.Commit();
2388
                foreach (var line in lines)
2389
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2390
            }
2391

    
2392

    
2393
            return newConnector;
2394
        }
2395

    
2396
        /// <summary>
2397
        /// SpecBreak Modeling 메서드
2398
        /// </summary>
2399
        /// <param name="specBreak"></param>
2400
        private void SpecBreakModeling(SpecBreak specBreak)
2401
        {
2402
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2403
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2404

    
2405
            if (upStreamObj != null &&
2406
                downStreamObj != null)
2407
            {
2408
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2409

    
2410
                if (targetLMConnector != null)
2411
                {
2412
                    foreach (var attribute in specBreak.ATTRIBUTES)
2413
                    {
2414
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2415
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2416
                        {
2417
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2418
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2419
                            Array array = null;
2420
                            if (point != null)
2421
                                array = new double[] { 0, point[0], point[1] };
2422
                            else
2423
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2424
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2425

    
2426
                            if (_LmLabelPersist != null)
2427
                            {
2428
                                _LmLabelPersist.Commit();
2429
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2430
                                if (_LmLabelPersist.ModelItemObject != null)
2431
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2432
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2433
                                ReleaseCOMObjects(_LmLabelPersist);
2434
                            }
2435
                        }
2436
                    }
2437
                    ReleaseCOMObjects(targetLMConnector);
2438
                }
2439
            }
2440
        }
2441

    
2442
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2443
        {
2444
            LMConnector targetConnector = null;
2445
            Symbol targetSymbol = targetObj as Symbol;
2446
            Symbol connectedSymbol = connectedObj as Symbol;
2447
            Line targetLine = targetObj as Line;
2448
            Line connectedLine = connectedObj as Line;
2449
            if (targetSymbol != null && connectedSymbol != null)
2450
            {
2451
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2452
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2453

    
2454
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2455
                {
2456
                    if (connector.get_ItemStatus() != "Active")
2457
                        continue;
2458

    
2459
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2460
                    {
2461
                        targetConnector = connector;
2462
                        break;
2463
                    }
2464
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2465
                    {
2466
                        targetConnector = connector;
2467
                        break;
2468
                    }
2469
                }
2470

    
2471
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2472
                {
2473
                    if (connector.get_ItemStatus() != "Active")
2474
                        continue;
2475

    
2476
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2477
                    {
2478
                        targetConnector = connector;
2479
                        break;
2480
                    }
2481
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2482
                    {
2483
                        targetConnector = connector;
2484
                        break;
2485
                    }
2486
                }
2487

    
2488
                ReleaseCOMObjects(targetLMSymbol);
2489
                ReleaseCOMObjects(connectedLMSymbol);
2490
            }
2491
            else if (targetLine != null && connectedLine != null)
2492
            {
2493
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2494
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2495

    
2496
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2497
                {
2498
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2499
                    {
2500
                        if (targetConnector != null)
2501
                            break;
2502

    
2503
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2504
                        {
2505
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2506

    
2507
                            if (IsConnected(_LMConnector, connectedModelItem))
2508
                                targetConnector = _LMConnector;
2509
                            else
2510
                                ReleaseCOMObjects(_LMConnector);
2511
                        }
2512
                    }
2513

    
2514
                    ReleaseCOMObjects(targetModelItem);
2515
                }
2516
            }
2517
            else
2518
            {
2519
                LMSymbol connectedLMSymbol = null;
2520
                if (connectedSymbol != null)
2521
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2522
                else if (targetSymbol != null)
2523
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2524
                else
2525
                {
2526

    
2527
                }
2528
                LMModelItem targetModelItem = null;
2529
                if (targetLine != null)
2530
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2531
                else if (connectedLine != null)
2532
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2533
                else
2534
                {
2535

    
2536
                }
2537
                if (connectedLMSymbol != null && targetModelItem != null)
2538
                {
2539
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2540
                    {
2541
                        if (connector.get_ItemStatus() != "Active")
2542
                            continue;
2543

    
2544
                        if (IsConnected(connector, targetModelItem))
2545
                        {
2546
                            targetConnector = connector;
2547
                            break;
2548
                        }
2549
                    }
2550

    
2551
                    if (targetConnector == null)
2552
                    {
2553
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2554
                        {
2555
                            if (connector.get_ItemStatus() != "Active")
2556
                                continue;
2557

    
2558
                            if (IsConnected(connector, targetModelItem))
2559
                            {
2560
                                targetConnector = connector;
2561
                                break;
2562
                            }
2563
                        }
2564
                    }
2565
                }
2566

    
2567
            }
2568

    
2569
            return targetConnector;
2570
        }
2571

    
2572
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2573
        {
2574
            double[] result = null;
2575
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2576
            {
2577
                return GetConnectorVertices(targetConnector)[0];
2578
            }
2579
            else
2580
            {
2581
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
2582
                {
2583
                    Line line = connObj as Line;
2584
                    LMConnector connectedConnector = null;
2585
                    int connIndex = 0;
2586
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2587
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
2588

    
2589
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2590

    
2591
                    ReleaseCOMObjects(modelItem);
2592
                    ReleaseCOMObjects(connectedConnector);
2593

    
2594
                    if (vertices.Count > 0)
2595
                    {
2596
                        if (connIndex == 1)
2597
                            return vertices[0];
2598
                        else if (connIndex == 2)
2599
                            return vertices[vertices.Count - 1];
2600
                    }
2601
                }
2602
                else
2603
                {
2604
                    Log.Write("error in GetSegemtPoint");
2605
                }
2606
            }
2607

    
2608
            return result;
2609
        }
2610

    
2611
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2612
        {
2613
            bool result = false;
2614

    
2615
            foreach (LMRepresentation rep in modelItem.Representations)
2616
            {
2617
                if (result)
2618
                    break;
2619

    
2620
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2621
                {
2622
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2623

    
2624
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2625
                        connector.ConnectItem1SymbolObject != null &&
2626
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2627
                    {
2628
                        result = true;
2629
                        ReleaseCOMObjects(_LMConnector);
2630
                        break;
2631
                    }
2632
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2633
                        connector.ConnectItem2SymbolObject != null &&
2634
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2635
                    {
2636
                        result = true;
2637
                        ReleaseCOMObjects(_LMConnector);
2638
                        break;
2639
                    }
2640
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2641
                        connector.ConnectItem1SymbolObject != null &&
2642
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2643
                    {
2644
                        result = true;
2645
                        ReleaseCOMObjects(_LMConnector);
2646
                        break;
2647
                    }
2648
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2649
                        connector.ConnectItem2SymbolObject != null &&
2650
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2651
                    {
2652
                        result = true;
2653
                        ReleaseCOMObjects(_LMConnector);
2654
                        break;
2655
                    }
2656

    
2657
                    ReleaseCOMObjects(_LMConnector);
2658
                }
2659
            }
2660

    
2661

    
2662
            return result;
2663
        }
2664

    
2665
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2666
        {
2667
            foreach (LMRepresentation rep in modelItem.Representations)
2668
            {
2669
                if (connectedConnector != null)
2670
                    break;
2671

    
2672
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2673
                {
2674
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2675

    
2676
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2677
                        connector.ConnectItem1SymbolObject != null &&
2678
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2679
                    {
2680
                        connectedConnector = _LMConnector;
2681
                        connectorIndex = 1;
2682
                        break;
2683
                    }
2684
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2685
                        connector.ConnectItem2SymbolObject != null &&
2686
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2687
                    {
2688
                        connectedConnector = _LMConnector;
2689
                        connectorIndex = 2;
2690
                        break;
2691
                    }
2692
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2693
                        connector.ConnectItem1SymbolObject != null &&
2694
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2695
                    {
2696
                        connectedConnector = _LMConnector;
2697
                        connectorIndex = 1;
2698
                        break;
2699
                    }
2700
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2701
                        connector.ConnectItem2SymbolObject != null &&
2702
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2703
                    {
2704
                        connectedConnector = _LMConnector;
2705
                        connectorIndex = 2;
2706
                        break;
2707
                    }
2708

    
2709
                    if (connectedConnector == null)
2710
                        ReleaseCOMObjects(_LMConnector);
2711
                }
2712
            }
2713
        }
2714

    
2715
        /// <summary>
2716
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2717
        /// </summary>
2718
        /// <param name="modelItemID1"></param>
2719
        /// <param name="modelItemID2"></param>
2720
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2721
        {
2722
            try
2723
            {
2724
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2725
                _LMAItem item1 = modelItem1.AsLMAItem();
2726
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2727
                _LMAItem item2 = modelItem2.AsLMAItem();
2728

    
2729
                // item2가 item1으로 조인
2730
                _placement.PIDJoinRuns(ref item1, ref item2);
2731
                item1.Commit();
2732
                item2.Commit();
2733

    
2734
                string beforeID = string.Empty;
2735
                string afterID = string.Empty;
2736

    
2737
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2738
                {
2739
                    beforeID = modelItem2.Id;
2740
                    afterID = modelItem1.Id;
2741
                    survivorId = afterID;
2742
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
2743
                    if (attribute != null)
2744
                        attribute.set_Value("End 1 is upstream (Inlet)");
2745
                }
2746
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2747
                {
2748
                    beforeID = modelItem1.Id;
2749
                    afterID = modelItem2.Id;
2750
                    survivorId = afterID;
2751
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
2752
                    if (attribute != null)
2753
                        attribute.set_Value("End 1 is upstream (Inlet)");
2754
                }
2755
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2756
                    survivorId = null;
2757
                else
2758
                {
2759
                    Log.Write("잘못된 경우");
2760
                    survivorId = null;
2761
                }
2762

    
2763
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2764
                {
2765
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2766
                    foreach (var line in lines)
2767
                        line.SPPID.ModelItemId = afterID;
2768
                }
2769

    
2770
                ReleaseCOMObjects(modelItem1);
2771
                ReleaseCOMObjects(item1);
2772
                ReleaseCOMObjects(modelItem2);
2773
                ReleaseCOMObjects(item2);
2774
            }
2775
            catch (Exception ex)
2776
            {
2777
                Log.Write("Join Error");
2778
                Log.Write(ex.Message);
2779
            }
2780
        }
2781

    
2782
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2783
        {
2784
            List<string> modelItemIDs = new List<string>();
2785
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2786
            {
2787
                LMModelItem modelItem = connector.ModelItemObject;
2788
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2789
                    modelItemIDs.Add(modelItem.Id);
2790
                ReleaseCOMObjects(modelItem);
2791
                ReleaseCOMObjects(connector);
2792
            }
2793

    
2794
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2795
            {
2796
                LMModelItem modelItem = connector.ModelItemObject;
2797
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2798
                    modelItemIDs.Add(modelItem.Id);
2799
                ReleaseCOMObjects(modelItem);
2800
                ReleaseCOMObjects(connector);
2801
            }
2802

    
2803

    
2804
            List<string> result = new List<string>();
2805
            modelItemIDs = modelItemIDs.Distinct().ToList();
2806
            string originalName = GetSPPIDFileName(modelId);
2807
            foreach (var item in modelItemIDs)
2808
            {
2809
                string fileName = GetSPPIDFileName(item);
2810
                if (originalName == fileName)
2811
                    result.Add(item);
2812
                else
2813
                {
2814
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2815
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()))
2816
                    {
2817
                        result.Add(item);
2818
                        ReleaseCOMObjects(connector);
2819
                    }
2820
                }
2821
            }
2822
            
2823
            return result;
2824
        }
2825

    
2826
        /// <summary>
2827
        /// PipeRun의 좌표를 가져오는 메서드
2828
        /// </summary>
2829
        /// <param name="modelId"></param>
2830
        /// <returns></returns>
2831
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2832
        {
2833
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2834
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2835

    
2836
            if (modelItem != null)
2837
            {
2838
                foreach (LMRepresentation rep in modelItem.Representations)
2839
                {
2840
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2841
                    {
2842
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2843
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2844
                        dynamic OID = rep.get_GraphicOID().ToString();
2845
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2846
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2847
                        int verticesCount = lineStringGeometry.VertexCount;
2848
                        double[] vertices = null;
2849
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2850
                        for (int i = 0; i < verticesCount; i++)
2851
                        {
2852
                            double x = 0;
2853
                            double y = 0;
2854
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2855
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
2856
                        }
2857
                    }
2858
                }
2859

    
2860
                ReleaseCOMObjects(modelItem);
2861
            }
2862

    
2863
            return connectorVertices;
2864
        }
2865

    
2866
        private List<double[]> GetConnectorVertices(LMConnector connector)
2867
        {
2868
            List<double[]> vertices = new List<double[]>();
2869
            if (connector != null)
2870
            {
2871
                dynamic OID = connector.get_GraphicOID().ToString();
2872
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2873
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2874
                int verticesCount = lineStringGeometry.VertexCount;
2875
                double[] value = null;
2876
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
2877
                for (int i = 0; i < verticesCount; i++)
2878
                {
2879
                    double x = 0;
2880
                    double y = 0;
2881
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2882
                    vertices.Add(new double[] { x, y });
2883
                }
2884
            }
2885
            return vertices;
2886
        }
2887

    
2888
        /// <summary>
2889
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
2890
        /// </summary>
2891
        /// <param name="connectorVertices"></param>
2892
        /// <param name="connX"></param>
2893
        /// <param name="connY"></param>
2894
        /// <returns></returns>
2895
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
2896
        {
2897
            double length = double.MaxValue;
2898
            LMConnector targetConnector = null;
2899
            foreach (var item in connectorVertices)
2900
            {
2901
                List<double[]> points = item.Value;
2902
                for (int i = 0; i < points.Count - 1; i++)
2903
                {
2904
                    double[] point1 = points[i];
2905
                    double[] point2 = points[i + 1];
2906
                    double x1 = Math.Min(point1[0], point2[0]);
2907
                    double y1 = Math.Min(point1[1], point2[1]);
2908
                    double x2 = Math.Max(point1[0], point2[0]);
2909
                    double y2 = Math.Max(point1[1], point2[1]);
2910

    
2911
                    if ((x1 <= connX && x2 >= connX) ||
2912
                        (y1 <= connY && y2 >= connY))
2913
                    {
2914
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
2915
                        if (length >= distance)
2916
                        {
2917
                            targetConnector = item.Key;
2918
                            length = distance;
2919
                        }
2920

    
2921
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
2922
                        if (length >= distance)
2923
                        {
2924
                            targetConnector = item.Key;
2925
                            length = distance;
2926
                        }
2927
                    }
2928
                }
2929
            }
2930

    
2931
            // 못찾았을때.
2932
            length = double.MaxValue;
2933
            if (targetConnector == null)
2934
            {
2935
                foreach (var item in connectorVertices)
2936
                {
2937
                    List<double[]> points = item.Value;
2938

    
2939
                    foreach (double[] point in points)
2940
                    {
2941
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
2942
                        if (length >= distance)
2943
                        {
2944
                            targetConnector = item.Key;
2945
                            length = distance;
2946
                        }
2947
                    }
2948
                }
2949
            }
2950

    
2951
            return targetConnector;
2952
        }
2953

    
2954
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
2955
        {
2956
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2957
            if (vertices.Count == 0)
2958
                return null;
2959

    
2960
            double length = double.MaxValue;
2961
            LMConnector targetConnector = null;
2962
            double[] resultPoint = null;
2963
            List<double[]> targetVertices = null;
2964

    
2965
            // Vertices 포인트에 제일 가까운곳
2966
            foreach (var item in vertices)
2967
            {
2968
                List<double[]> points = item.Value;
2969
                for (int i = 0; i < points.Count; i++)
2970
                {
2971
                    double[] point = points[i];
2972
                    double tempX = point[0];
2973
                    double tempY = point[1];
2974

    
2975
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
2976
                    if (length >= distance)
2977
                    {
2978
                        targetConnector = item.Key;
2979
                        length = distance;
2980
                        resultPoint = point;
2981
                        targetVertices = item.Value;
2982
                    }
2983
                }
2984
            }
2985

    
2986
            // Vertices Cross에 제일 가까운곳
2987
            foreach (var item in vertices)
2988
            {
2989
                List<double[]> points = item.Value;
2990
                for (int i = 0; i < points.Count - 1; i++)
2991
                {
2992
                    double[] point1 = points[i];
2993
                    double[] point2 = points[i + 1];
2994

    
2995
                    double maxLineX = Math.Max(point1[0], point2[0]);
2996
                    double minLineX = Math.Min(point1[0], point2[0]);
2997
                    double maxLineY = Math.Max(point1[1], point2[1]);
2998
                    double minLineY = Math.Min(point1[1], point2[1]);
2999

    
3000
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3001

    
3002
                    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]);
3003
                    if (crossingPoint != null)
3004
                    {
3005
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3006
                        if (length >= distance)
3007
                        {
3008
                            if (slope == SlopeType.Slope &&
3009
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3010
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3011
                            {
3012
                                targetConnector = item.Key;
3013
                                length = distance;
3014
                                resultPoint = crossingPoint;
3015
                                targetVertices = item.Value;
3016
                            }
3017
                            else if (slope == SlopeType.HORIZONTAL &&
3018
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3019
                            {
3020
                                targetConnector = item.Key;
3021
                                length = distance;
3022
                                resultPoint = crossingPoint;
3023
                                targetVertices = item.Value;
3024
                            }
3025
                            else if (slope == SlopeType.VERTICAL &&
3026
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3027
                            {
3028
                                targetConnector = item.Key;
3029
                                length = distance;
3030
                                resultPoint = crossingPoint;
3031
                                targetVertices = item.Value;
3032
                            }
3033
                        }
3034
                    }
3035
                }
3036
            }
3037

    
3038
            foreach (var item in vertices)
3039
                if (item.Key != null && item.Key != targetConnector)
3040
                    ReleaseCOMObjects(item.Key);
3041

    
3042
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3043
            {
3044
                double tempResultX = resultPoint[0];
3045
                double tempResultY = resultPoint[1];
3046
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3047

    
3048
                GridSetting gridSetting = GridSetting.GetInstance();
3049

    
3050
                for (int i = 0; i < targetVertices.Count; i++)
3051
                {
3052
                    double[] point = targetVertices[i];
3053
                    double tempX = targetVertices[i][0];
3054
                    double tempY = targetVertices[i][1];
3055
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3056
                    if (tempX == tempResultX && tempY == tempResultY)
3057
                    {
3058
                        if (i == 0)
3059
                        {
3060
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3061
                            bool containZeroLength = false;
3062
                            if (connSymbol != null)
3063
                            {
3064
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3065
                                {
3066
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3067
                                        containZeroLength = true;
3068
                                }
3069
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3070
                                {
3071
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3072
                                        containZeroLength = true;
3073
                                }
3074
                            }
3075

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

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

    
3111
                                if (bCalcY)
3112
                                {
3113
                                    double nextY = targetVertices[i + 1][1];
3114
                                    double newY = 0;
3115
                                    if (nextY > tempY)
3116
                                    {
3117
                                        newY = tempY + gridSetting.Length;
3118
                                        if (newY > nextY)
3119
                                            newY = (point[1] + nextY) / 2;
3120
                                    }
3121
                                    else
3122
                                    {
3123
                                        newY = tempY - gridSetting.Length;
3124
                                        if (newY < nextY)
3125
                                            newY = (point[1] + nextY) / 2;
3126
                                    }
3127
                                    resultPoint = new double[] { resultPoint[0], newY };
3128
                                }
3129
                            }
3130
                        }
3131
                        else if (i == targetVertices.Count - 1)
3132
                        {
3133
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3134
                            bool containZeroLength = false;
3135
                            if (connSymbol != null)
3136
                            {
3137
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3138
                                {
3139
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3140
                                        containZeroLength = true;
3141
                                }
3142
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3143
                                {
3144
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3145
                                        containZeroLength = true;
3146
                                }
3147
                            }
3148

    
3149
                            if (connSymbol == null ||
3150
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3151
                                containZeroLength)
3152
                            {
3153
                                bool bCalcX = false;
3154
                                bool bCalcY = false;
3155
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3156
                                    bCalcX = true;
3157
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3158
                                    bCalcY = true;
3159
                                else
3160
                                {
3161
                                    bCalcX = true;
3162
                                    bCalcY = true;
3163
                                }
3164

    
3165
                                if (bCalcX)
3166
                                {
3167
                                    double nextX = targetVertices[i - 1][0];
3168
                                    double newX = 0;
3169
                                    if (nextX > tempX)
3170
                                    {
3171
                                        newX = tempX + gridSetting.Length;
3172
                                        if (newX > nextX)
3173
                                            newX = (point[0] + nextX) / 2;
3174
                                    }
3175
                                    else
3176
                                    {
3177
                                        newX = tempX - gridSetting.Length;
3178
                                        if (newX < nextX)
3179
                                            newX = (point[0] + nextX) / 2;
3180
                                    }
3181
                                    resultPoint = new double[] { newX, resultPoint[1] };
3182
                                }
3183

    
3184
                                if (bCalcY)
3185
                                {
3186
                                    double nextY = targetVertices[i - 1][1];
3187
                                    double newY = 0;
3188
                                    if (nextY > tempY)
3189
                                    {
3190
                                        newY = tempY + gridSetting.Length;
3191
                                        if (newY > nextY)
3192
                                            newY = (point[1] + nextY) / 2;
3193
                                    }
3194
                                    else
3195
                                    {
3196
                                        newY = tempY - gridSetting.Length;
3197
                                        if (newY < nextY)
3198
                                            newY = (point[1] + nextY) / 2;
3199
                                    }
3200
                                    resultPoint = new double[] { resultPoint[0], newY };
3201
                                }
3202
                            }
3203
                        }
3204
                        break;
3205
                    }
3206
                }
3207
            }
3208

    
3209
            x = resultPoint[0];
3210
            y = resultPoint[1];
3211

    
3212
            return targetConnector;
3213
        }
3214

    
3215
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3216
        {
3217
            LMConnector result = null;
3218
            List<LMConnector> connectors = new List<LMConnector>();
3219
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3220

    
3221
            if (modelItem != null)
3222
            {
3223
                foreach (LMRepresentation rep in modelItem.Representations)
3224
                {
3225
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3226
                        connectors.Add(dataSource.GetConnector(rep.Id));
3227
                }
3228

    
3229
                ReleaseCOMObjects(modelItem);
3230
            }
3231

    
3232
            if (connectors.Count == 1)
3233
                result = connectors[0];
3234
            else
3235
                foreach (var item in connectors)
3236
                    ReleaseCOMObjects(item);
3237

    
3238
            return result;
3239
        }
3240

    
3241
        /// <summary>
3242
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3243
        /// </summary>
3244
        /// <param name="lineNumber"></param>
3245
        private void LineNumberModelingOnlyOne(Line line)
3246
        {
3247
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3248
            if (lineNumber != null)
3249
            {
3250
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3251
                if (connectedLMConnector != null)
3252
                {
3253
                    double x = 0;
3254
                    double y = 0;
3255
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3256

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

    
3260
                    if (_LmLabelPresist != null)
3261
                    {
3262
                        _LmLabelPresist.Commit();
3263
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3264
                        ReleaseCOMObjects(_LmLabelPresist);
3265
                    }
3266
                }
3267
            }
3268
        }
3269

    
3270
        private void LineNumberModeling(LineNumber lineNumber)
3271
        {
3272
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3273
            if (line != null)
3274
            {
3275
                double x = 0;
3276
                double y = 0;
3277
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3278

    
3279
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3280
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3281
                if (connectedLMConnector != null)
3282
                {
3283
                    Array points = new double[] { 0, x, y };
3284
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3285

    
3286
                    if (_LmLabelPresist != null)
3287
                    {
3288
                        _LmLabelPresist.Commit();
3289
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3290
                        ReleaseCOMObjects(_LmLabelPresist);
3291
                    }
3292
                }
3293

    
3294
                foreach (var item in connectorVertices)
3295
                    ReleaseCOMObjects(item.Key);
3296
            }
3297
        }
3298
        /// <summary>
3299
        /// Flow Mark Modeling
3300
        /// </summary>
3301
        /// <param name="line"></param>
3302
        private void FlowMarkModeling(Line line)
3303
        {
3304
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3305
            {
3306
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3307
                if (connector != null)
3308
                {
3309
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3310
                    List<double[]> vertices = GetConnectorVertices(connector);
3311
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3312
                    double[] point = vertices[vertices.Count - 1];
3313
                    Array array = new double[] { 0, point[0], point[1] };
3314
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3315
                    if (_LMLabelPersist != null)
3316
                    {
3317
                        _LMLabelPersist.Commit();
3318
                        ReleaseCOMObjects(_LMLabelPersist);
3319
                    }
3320
                        
3321
                }
3322
            }
3323
        }
3324

    
3325
        /// <summary>
3326
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3327
        /// </summary>
3328
        /// <param name="lineNumber"></param>
3329
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3330
        {
3331
            foreach (LineRun run in lineNumber.RUNS)
3332
            {
3333
                foreach (var item in run.RUNITEMS)
3334
                {
3335
                    if (item.GetType() == typeof(Symbol))
3336
                    {
3337
                        Symbol symbol = item as Symbol;
3338
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3339
                        if (_LMSymbol != null)
3340
                        {
3341
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3342

    
3343
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3344
                            {
3345
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3346
                                {
3347
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3348
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3349
                                    {
3350
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3351
                                        if (_LMAAttribute != null)
3352
                                        {
3353
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3354
                                                _LMAAttribute.set_Value(attribute.VALUE);
3355
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3356
                                                _LMAAttribute.set_Value(attribute.VALUE);
3357
                                        }
3358
                                    }
3359
                                }
3360
                                _LMModelItem.Commit();
3361
                            }
3362
                            if (_LMModelItem != null)
3363
                                ReleaseCOMObjects(_LMModelItem);
3364
                        }
3365
                        if (_LMSymbol != null)
3366
                            ReleaseCOMObjects(_LMSymbol);
3367
                    }
3368
                    else if (item.GetType() == typeof(Line))
3369
                    {
3370
                        Line line = item as Line;
3371
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3372
                        {
3373
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3374
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3375
                            {
3376
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3377
                                {
3378
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3379
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3380
                                    {
3381
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3382
                                        if (_LMAAttribute != null)
3383
                                        {
3384
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3385
                                                _LMAAttribute.set_Value(attribute.VALUE);
3386
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3387
                                                _LMAAttribute.set_Value(attribute.VALUE);
3388

    
3389
                                        }
3390
                                    }
3391
                                }
3392
                                _LMModelItem.Commit();
3393
                            }
3394
                            if (_LMModelItem != null)
3395
                                ReleaseCOMObjects(_LMModelItem);
3396
                            endLine.Add(line.SPPID.ModelItemId);
3397
                        }
3398
                    }
3399
                }
3400
            }
3401
        }
3402

    
3403
        /// <summary>
3404
        /// Symbol Attribute 입력 메서드
3405
        /// </summary>
3406
        /// <param name="item"></param>
3407
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3408
        {
3409
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3410
            string sRep = null;
3411
            if (targetItem.GetType() == typeof(Symbol))
3412
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3413
            else if (targetItem.GetType() == typeof(Equipment))
3414
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3415

    
3416
            if (!string.IsNullOrEmpty(sRep))
3417
            {
3418
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3419
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3420
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3421
                
3422
                foreach (var item in targetAttributes)
3423
                {
3424
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3425
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3426
                    {
3427
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3428
                        if (_Attribute != null)
3429
                        {
3430
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3431
                            if (associItem != null)
3432
                            {
3433
                                if (associItem.GetType() == typeof(Text))
3434
                                {
3435
                                    Text text = associItem as Text;
3436
                                    text.SPPID.RepresentationId = "Attribute";
3437
                                }
3438
                                else if (associItem.GetType() == typeof(Note))
3439
                                {
3440
                                    Note note = associItem as Note;
3441
                                    note.SPPID.RepresentationId = "Attribute";
3442
                                }
3443
                            }
3444
                            _Attribute.set_Value(item.VALUE);
3445
                        }
3446
                            
3447
                    }
3448
                }
3449
                _LMModelItem.Commit();
3450

    
3451
                ReleaseCOMObjects(_Attributes);
3452
                ReleaseCOMObjects(_LMModelItem);
3453
                ReleaseCOMObjects(_LMSymbol);
3454
            }
3455
        }
3456

    
3457
        /// <summary>
3458
        /// Input SpecBreak Attribute
3459
        /// </summary>
3460
        /// <param name="specBreak"></param>
3461
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3462
        {
3463
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3464
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3465

    
3466
            if (upStreamObj != null &&
3467
                downStreamObj != null)
3468
            {
3469
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3470

    
3471
                if (targetLMConnector != null)
3472
                {
3473
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3474
                    {
3475
                        string symbolPath = _LMLabelPersist.get_FileName();
3476
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3477
                        if (mapping != null)
3478
                        {
3479
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3480
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3481
                            {
3482
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3483
                                if (values.Length == 2)
3484
                                {
3485
                                    string upStreamValue = values[0];
3486
                                    string downStreamValue = values[1];
3487

    
3488
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3489
                                }
3490
                            }
3491
                        }
3492
                    }
3493

    
3494
                    ReleaseCOMObjects(targetLMConnector);
3495
                }
3496
            }
3497

    
3498

    
3499
            #region 내부에서만 쓰는 메서드
3500
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3501
            {
3502
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3503
                Line upStreamLine = _upStreamObj as Line;
3504
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3505
                Line downStreamLine = _downStreamObj as Line;
3506
                // 둘다 Line일 경우
3507
                if (upStreamLine != null && downStreamLine != null)
3508
                {
3509
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3510
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3511
                }
3512
                // 둘다 Symbol일 경우
3513
                else if (upStreamSymbol != null && downStreamSymbol != null)
3514
                {
3515
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3516
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3517
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3518

    
3519
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3520
                    {
3521
                        if (connector.get_ItemStatus() != "Active")
3522
                            continue;
3523

    
3524
                        if (connector.Id != zeroLenthConnector.Id)
3525
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3526
                    }
3527

    
3528
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3529
                    {
3530
                        if (connector.get_ItemStatus() != "Active")
3531
                            continue;
3532

    
3533
                        if (connector.Id != zeroLenthConnector.Id)
3534
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3535
                    }
3536

    
3537
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3538
                    {
3539
                        if (connector.get_ItemStatus() != "Active")
3540
                            continue;
3541

    
3542
                        if (connector.Id != zeroLenthConnector.Id)
3543
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3544
                    }
3545

    
3546
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3547
                    {
3548
                        if (connector.get_ItemStatus() != "Active")
3549
                            continue;
3550

    
3551
                        if (connector.Id != zeroLenthConnector.Id)
3552
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3553
                    }
3554

    
3555
                    ReleaseCOMObjects(zeroLenthConnector);
3556
                    ReleaseCOMObjects(upStreamLMSymbol);
3557
                    ReleaseCOMObjects(downStreamLMSymbol);
3558
                }
3559
                else if (upStreamSymbol != null && downStreamLine != null)
3560
                {
3561
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3562
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3563
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3564

    
3565
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3566
                    {
3567
                        if (connector.get_ItemStatus() != "Active")
3568
                            continue;
3569

    
3570
                        if (connector.Id == zeroLenthConnector.Id)
3571
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3572
                    }
3573

    
3574
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3575
                    {
3576
                        if (connector.get_ItemStatus() != "Active")
3577
                            continue;
3578

    
3579
                        if (connector.Id == zeroLenthConnector.Id)
3580
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3581
                    }
3582

    
3583
                    ReleaseCOMObjects(zeroLenthConnector);
3584
                    ReleaseCOMObjects(upStreamLMSymbol);
3585
                }
3586
                else if (upStreamLine != null && downStreamSymbol != null)
3587
                {
3588
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3589
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3590
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3591

    
3592
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3593
                    {
3594
                        if (connector.get_ItemStatus() != "Active")
3595
                            continue;
3596

    
3597
                        if (connector.Id == zeroLenthConnector.Id)
3598
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3599
                    }
3600

    
3601
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3602
                    {
3603
                        if (connector.get_ItemStatus() != "Active")
3604
                            continue;
3605

    
3606
                        if (connector.Id == zeroLenthConnector.Id)
3607
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3608
                    }
3609

    
3610
                    ReleaseCOMObjects(zeroLenthConnector);
3611
                    ReleaseCOMObjects(downStreamLMSymbol);
3612
                }
3613
            }
3614

    
3615
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3616
            {
3617
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3618
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3619
                {
3620
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3621
                    if (_LMAAttribute != null)
3622
                    {
3623
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3624
                            _LMAAttribute.set_Value(value);
3625
                        else if (_LMAAttribute.get_Value() != value)
3626
                            _LMAAttribute.set_Value(value);
3627
                    }
3628

    
3629
                    _LMModelItem.Commit();
3630
                }
3631
                if (_LMModelItem != null)
3632
                    ReleaseCOMObjects(_LMModelItem);
3633
            }
3634

    
3635
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3636
            {
3637
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3638
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3639
                {
3640
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3641
                    if (_LMAAttribute != null)
3642
                    {
3643
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3644
                            _LMAAttribute.set_Value(value);
3645
                        else if (_LMAAttribute.get_Value() != value)
3646
                            _LMAAttribute.set_Value(value);
3647
                    }
3648

    
3649
                    _LMModelItem.Commit();
3650
                }
3651
                if (_LMModelItem != null)
3652
                    ReleaseCOMObjects(_LMModelItem);
3653
            }
3654
            #endregion
3655
        }
3656

    
3657
        /// <summary>
3658
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3659
        /// </summary>
3660
        /// <param name="text"></param>
3661
        private void TextModeling(Text text)
3662
        {
3663
            LMSymbol _LMSymbol = null;
3664
            LMConnector connectedLMConnector = null;
3665
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3666
            if (text.ASSOCIATION)
3667
            {
3668
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3669
                if (owner != null && owner.GetType() == typeof(Symbol))
3670
                {
3671
                    Symbol symbol = owner as Symbol;
3672
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3673
                    if (_LMSymbol != null)
3674
                    {
3675
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3676
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3677
                        {
3678
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3679

    
3680
                            if (mapping != null)
3681
                            {
3682
                                double x = 0;
3683
                                double y = 0;
3684

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

    
3688
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3689
                                if (_LMLabelPersist != null)
3690
                                {
3691
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3692
                                    _LMLabelPersist.Commit();
3693
                                    ReleaseCOMObjects(_LMLabelPersist);
3694
                                }
3695
                            }
3696
                        }
3697
                    }
3698
                }
3699
                else if (owner != null && owner.GetType() == typeof(Line))
3700
                {
3701
                    Line line = owner as Line;
3702
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3703
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3704

    
3705
                    if (connectedLMConnector != null)
3706
                    {
3707
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3708
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3709
                        {
3710
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3711

    
3712
                            if (mapping != null)
3713
                            {
3714
                                double x = 0;
3715
                                double y = 0;
3716

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

    
3720
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3721
                                if (_LMLabelPersist != null)
3722
                                {
3723
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3724
                                    _LMLabelPersist.Commit();
3725
                                    ReleaseCOMObjects(_LMLabelPersist);
3726
                                }
3727
                            }
3728
                        }
3729
                    }
3730
                }
3731
            }
3732
            else
3733
            {
3734
                LMItemNote _LMItemNote = null;
3735
                LMAAttribute _LMAAttribute = null;
3736

    
3737
                double x = 0;
3738
                double y = 0;
3739
                double angle = text.ANGLE;
3740
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3741

    
3742
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3743
                if (_LMSymbol != null)
3744
                {
3745
                    _LMSymbol.Commit();
3746
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3747
                    if (_LMItemNote != null)
3748
                    {
3749
                        _LMItemNote.Commit();
3750
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3751
                        if (_LMAAttribute != null)
3752
                        {
3753
                            _LMAAttribute.set_Value(text.VALUE);
3754
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3755
                            _LMItemNote.Commit();
3756

    
3757
                            if (_LMAAttribute != null)
3758
                                ReleaseCOMObjects(_LMAAttribute);
3759
                            if (_LMItemNote != null)
3760
                                ReleaseCOMObjects(_LMItemNote);
3761
                        }
3762
                    }
3763
                }
3764
            }
3765
            if (_LMSymbol != null)
3766
                ReleaseCOMObjects(_LMSymbol);
3767
        }
3768

    
3769
        /// <summary>
3770
        /// Note Modeling
3771
        /// </summary>
3772
        /// <param name="note"></param>
3773
        private void NoteModeling(Note note)
3774
        {
3775
            LMSymbol _LMSymbol = null;
3776
            LMItemNote _LMItemNote = null;
3777
            LMAAttribute _LMAAttribute = null;
3778

    
3779
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3780
            {
3781
                double x = 0;
3782
                double y = 0;
3783

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

    
3786
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
3787
                if (_LMSymbol != null)
3788
                {
3789
                    _LMSymbol.Commit();
3790
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3791
                    if (_LMItemNote != null)
3792
                    {
3793
                        _LMItemNote.Commit();
3794
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3795
                        if (_LMAAttribute != null)
3796
                        {
3797
                            _LMAAttribute.set_Value(note.VALUE);
3798
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3799
                            _LMItemNote.Commit();
3800
                        }
3801
                    }
3802
                }
3803
            }
3804

    
3805
            if (_LMAAttribute != null)
3806
                ReleaseCOMObjects(_LMAAttribute);
3807
            if (_LMItemNote != null)
3808
                ReleaseCOMObjects(_LMItemNote);
3809
            if (_LMSymbol != null)
3810
                ReleaseCOMObjects(_LMSymbol);
3811
        }
3812

    
3813
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
3814
        {
3815
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
3816
            if (modelItem != null)
3817
            {
3818
                foreach (LMRepresentation rep in modelItem.Representations)
3819
                {
3820
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3821
                    {
3822
                        LMConnector connector = dataSource.GetConnector(rep.Id);
3823
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
3824
                        {
3825
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
3826
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3827
                            if (modelItemIds.Count == 1)
3828
                            {
3829
                                string joinModelItemId = modelItemIds[0];
3830
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3831
                                if (survivorId != null)
3832
                                    break;
3833
                            }
3834
                        }
3835
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
3836
                        {
3837
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
3838
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3839
                            if (modelItemIds.Count == 1)
3840
                            {
3841
                                string joinModelItemId = modelItemIds[0];
3842
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3843
                                if (survivorId != null)
3844
                                    break;
3845
                            }
3846
                        }
3847
                    }
3848
                }
3849
            }
3850
        }
3851

    
3852
        /// <summary>
3853
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
3854
        /// </summary>
3855
        /// <param name="x"></param>
3856
        /// <param name="y"></param>
3857
        /// <param name="originX"></param>
3858
        /// <param name="originY"></param>
3859
        /// <param name="SPPIDLabelLocation"></param>
3860
        /// <param name="location"></param>
3861
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
3862
        {
3863
            if (location == Location.None)
3864
            {
3865
                x = originX;
3866
                y = originY;
3867
            }
3868
            else
3869
            {
3870
                if (location.HasFlag(Location.Center))
3871
                {
3872
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
3873
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
3874
                }
3875

    
3876
                if (location.HasFlag(Location.Left))
3877
                    x = SPPIDLabelLocation.X1;
3878
                else if (location.HasFlag(Location.Right))
3879
                    x = SPPIDLabelLocation.X2;
3880

    
3881
                if (location.HasFlag(Location.Down))
3882
                    y = SPPIDLabelLocation.Y1;
3883
                else if (location.HasFlag(Location.Up))
3884
                    y = SPPIDLabelLocation.Y2;
3885
            }
3886
        }
3887

    
3888
        /// <summary>
3889
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
3890
        /// 1. Angle Valve
3891
        /// 2. 3개로 이루어진 Symbol Group
3892
        /// </summary>
3893
        /// <returns></returns>
3894
        private List<Symbol> GetPrioritySymbol()
3895
        {
3896
            DataTable symbolTable = document.SymbolTable;
3897
            // List에 순서대로 쌓는다.
3898
            List<Symbol> symbols = new List<Symbol>();
3899

    
3900
            // Angle Valve 부터
3901
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
3902
            {
3903
                if (!symbols.Contains(symbol))
3904
                {
3905
                    double originX = 0;
3906
                    double originY = 0;
3907

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

    
3912
                    SlopeType slopeType1 = SlopeType.None;
3913
                    SlopeType slopeType2 = SlopeType.None;
3914
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
3915
                    {
3916
                        double connectorX = 0;
3917
                        double connectorY = 0;
3918
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
3919
                        if (slopeType1 == SlopeType.None)
3920
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3921
                        else
3922
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3923
                    }
3924

    
3925
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
3926
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
3927
                        symbols.Add(symbol);
3928
                }
3929
            }
3930

    
3931
            List<Symbol> tempSymbols = new List<Symbol>();
3932
            // Conn 갯수 기준
3933
            foreach (var item in document.SYMBOLS)
3934
            {
3935
                if (!symbols.Contains(item))
3936
                    tempSymbols.Add(item);
3937
            }
3938
            tempSymbols.Sort(SortSymbolPriority);
3939
            symbols.AddRange(tempSymbols);
3940

    
3941
            return symbols;
3942
        }
3943

    
3944
        private void SetPriorityLine(List<Line> lines)
3945
        {
3946
            lines.Sort(SortLinePriority);
3947

    
3948
            int SortLinePriority(Line a, Line b)
3949
            {
3950
                // Branch 없는것부터
3951
                int branchRetval = CompareBranchLine(a, b);
3952
                if (branchRetval != 0)
3953
                {
3954
                    return branchRetval;
3955
                }
3956
                else
3957
                {
3958
                    // Symbol 연결 갯수
3959
                    int connSymbolRetval = CompareConnSymbol(a, b);
3960
                    if (connSymbolRetval != 0)
3961
                    {
3962
                        return connSymbolRetval;
3963
                    }
3964
                    else
3965
                    {
3966
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
3967
                        int connItemRetval = CompareConnItem(a, b);
3968
                        if (connItemRetval != 0)
3969
                        {
3970
                            return connItemRetval;
3971
                        }
3972
                        else
3973
                        {
3974
                            // ConnectedItem이 없는것
3975
                            int noneConnRetval = CompareNoneConn(a, b);
3976
                            if (noneConnRetval != 0)
3977
                            {
3978
                                return noneConnRetval;
3979
                            }
3980
                            else
3981
                            {
3982

    
3983
                            }
3984
                        }
3985
                    }
3986
                }
3987

    
3988
                return 0;
3989
            }
3990

    
3991
            int CompareNotSegmentLine(Line a, Line b)
3992
            {
3993
                List<Connector> connectorsA = a.CONNECTORS
3994
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3995
                    .ToList();
3996

    
3997
                List<Connector> connectorsB = b.CONNECTORS
3998
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3999
                    .ToList();
4000

    
4001
                // 오름차순
4002
                return connectorsB.Count.CompareTo(connectorsA.Count);
4003
            }
4004

    
4005
            int CompareConnSymbol(Line a, Line b)
4006
            {
4007
                List<Connector> connectorsA = a.CONNECTORS
4008
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4009
                    .ToList();
4010

    
4011
                List<Connector> connectorsB = b.CONNECTORS
4012
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4013
                    .ToList();
4014

    
4015
                // 오름차순
4016
                return connectorsB.Count.CompareTo(connectorsA.Count);
4017
            }
4018

    
4019
            int CompareConnItem(Line a, Line b)
4020
            {
4021
                List<Connector> connectorsA = a.CONNECTORS
4022
                    .Where(conn => conn.ConnectedObject != null && 
4023
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
4024
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
4025
                    .ToList();
4026

    
4027
                List<Connector> connectorsB = b.CONNECTORS
4028
                    .Where(conn => conn.ConnectedObject != null &&
4029
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4030
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4031
                    .ToList();
4032

    
4033
                // 오름차순
4034
                return connectorsB.Count.CompareTo(connectorsA.Count);
4035
            }
4036

    
4037
            int CompareBranchLine(Line a, Line b)
4038
            {
4039
                List<Connector> connectorsA = a.CONNECTORS
4040
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
4041
                    .ToList();
4042
                List<Connector> connectorsB = b.CONNECTORS
4043
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
4044
                    .ToList();
4045

    
4046
                // 내림차순
4047
                return connectorsA.Count.CompareTo(connectorsB.Count);
4048
            }
4049

    
4050
            int CompareNoneConn(Line a, Line b)
4051
            {
4052
                List<Connector> connectorsA = a.CONNECTORS
4053
                    .Where(conn => conn.ConnectedObject == null)
4054
                    .ToList();
4055

    
4056
                List<Connector> connectorsB = b.CONNECTORS
4057
                    .Where(conn => conn.ConnectedObject == null)
4058
                    .ToList();
4059

    
4060
                // 오름차순
4061
                return connectorsB.Count.CompareTo(connectorsA.Count);
4062
            }
4063
        }
4064

    
4065
        private void SortBranchLines()
4066
        {
4067
            BranchLines.Sort(SortBranchLine);
4068
            int SortBranchLine(Line a, Line b)
4069
            {
4070
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4071
                 x.ConnectedObject.GetType() == typeof(Line) &&
4072
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
4073
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4074

    
4075
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4076
                 x.ConnectedObject.GetType() == typeof(Line) &&
4077
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4078
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4079

    
4080
                // 내림차순
4081
                return countA.CompareTo(countB);
4082
            }
4083
        }
4084

    
4085
        private static int SortSymbolPriority(Symbol a, Symbol b)
4086
        {
4087
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4088
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4089
            int retval = countB.CompareTo(countA);
4090
            if (retval != 0)
4091
                return retval;
4092
            else
4093
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
4094
        }
4095

    
4096
        private string GetSPPIDFileName(LMModelItem modelItem)
4097
        {
4098
            string symbolPath = null;
4099
            foreach (LMRepresentation rep in modelItem.Representations)
4100
            {
4101
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4102
                {
4103
                    symbolPath = rep.get_FileName();
4104
                    break;
4105
                }
4106
            }
4107
            return symbolPath;
4108
        }
4109

    
4110
        private string GetSPPIDFileName(string modelItemId)
4111
        {
4112
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4113
            string symbolPath = null;
4114
            foreach (LMRepresentation rep in modelItem.Representations)
4115
            {
4116
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4117
                {
4118
                    symbolPath = rep.get_FileName();
4119
                    break;
4120
                }
4121
            }
4122
            ReleaseCOMObjects(modelItem);
4123
            return symbolPath;
4124
        }
4125

    
4126
        /// <summary>
4127
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
4128
        /// </summary>
4129
        /// <param name="graphicOID"></param>
4130
        /// <param name="milliseconds"></param>
4131
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
4132
        {
4133
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
4134
            {
4135
                double minX = 0;
4136
                double minY = 0;
4137
                double maxX = 0;
4138
                double maxY = 0;
4139
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
4140
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
4141

    
4142
                Thread.Sleep(milliseconds);
4143
            }
4144
        }
4145

    
4146
        /// <summary>
4147
        /// ComObject를 Release
4148
        /// </summary>
4149
        /// <param name="objVars"></param>
4150
        public void ReleaseCOMObjects(params object[] objVars)
4151
        {
4152
            if (objVars != null)
4153
            {
4154
                int intNewRefCount = 0;
4155
                foreach (object obj in objVars)
4156
                {
4157
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
4158
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
4159
                }
4160
            }
4161
        }
4162
    }
4163
}
클립보드 이미지 추가 (최대 크기: 500 MB)