프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 28d05cc2

이력 | 보기 | 이력해설 | 다운로드 (212 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 : IDisposable
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
                _placement = new Placement();
84
                dataSource = _placement.PIDDataSource;
85

    
86
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
87
                {
88
                    Log.Write("Start Modeling");
89
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
90
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
91
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 20);
92
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
93

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

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

    
152
                Log.Write("End Modeling");
153
                radApp.ActiveWindow.Fit();
154

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

    
172
                ReleaseCOMObjects(dataSource);
173
                dataSource = null;
174
                ReleaseCOMObjects(_placement);
175
                _placement = null;
176

    
177
                Thread.Sleep(1000);
178
            }
179
        }
180

    
181
        private void RunEquipmentModeling()
182
        {
183
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
184
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
185
            foreach (Equipment item in document.Equipments)
186
            {
187
                try
188
                {
189
                    EquipmentModeling(item);
190
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
191
                }
192
                catch (Exception ex)
193
                {
194
                    Log.Write("Error in EquipmentModeling");
195
                    Log.Write("UID : " + item.UID);
196
                    Log.Write(ex.Message);
197
                    Log.Write(ex.StackTrace);
198
                }
199
            }
200
        }
201

    
202
        private void RunSymbolModeling()
203
        {
204
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
205
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
206
            prioritySymbols = GetPrioritySymbol();
207
            foreach (var item in prioritySymbols)
208
            {
209
                try
210
                {
211
                    SymbolModelingBySymbol(item);
212
                }
213
                catch (Exception ex)
214
                {
215
                    Log.Write("Error in SymbolModelingByPriority");
216
                    Log.Write("UID : " + item.UID);
217
                    Log.Write(ex.Message);
218
                    Log.Write(ex.StackTrace);
219
                }
220
            }
221
        }
222
        private void RunLineModeling()
223
        {
224
            List<Line> AllLine = document.LINES.ToList();
225
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
226
            !SPPIDUtil.IsBranchedLine(document, x));
227
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
228

    
229
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
230
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
231

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

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

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

    
304
                LMRelationships relationships = new LMRelationships();
305
                relationships.Collect(dataSource, Filter: filter);
306

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

    
515
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
516

    
517
                        ReleaseCOMObjects(modelItem);
518
                        modelItem = null;
519
                    }
520
                }
521

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

    
534
                SetFlowDirectionByLine(modelId);
535

    
536
                ReleaseCOMObjects(zeroLengthModelItem);
537
                zeroLengthModelItem = null;
538

    
539
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
540
            }
541
            foreach (var modelId in ZeroLengthModelItemIDReverse)
542
            {
543
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
544
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
545
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
546
                {
547
                    attribute.set_Value("End 1 is downstream (Outlet)");
548
                    zeroLengthModelItem.Commit();
549
                }
550

    
551
                SetFlowDirectionByLine(modelId);
552

    
553
                ReleaseCOMObjects(zeroLengthModelItem);
554
                zeroLengthModelItem = null;
555

    
556
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
557
            }
558
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
559
            {
560
                SetFlowDirectionByLine(modelId);
561
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
562
            }
563

    
564
            void SetFlowDirectionByLine(string lineModelItemID)
565
            {
566
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
567
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
568
                {
569
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
570
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
571
                    {
572
                        string sFlowDirection = attribute.get_Value().ToString();
573
                        foreach (LMRepresentation rep in modelItem.Representations)
574
                        {
575
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
576
                            {
577
                                LMConnector connector = dataSource.GetConnector(rep.Id);
578

    
579
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
580
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
581
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
582
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
583

    
584
                                ReleaseCOMObjects(connector);
585
                            }
586
                        }
587
                    }
588
                    ReleaseCOMObjects(modelItem);
589
                    modelItem = null;
590
                }
591

    
592
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
593
                {
594
                    // Item2가 Symbol
595
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
596
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
597
                    {
598
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
599
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
600
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
601

    
602
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
603

    
604
                        symbolModelItem.Commit();
605
                        ReleaseCOMObjects(symbolModelItem);
606
                        symbolModelItem = null;
607
                    }
608
                    // Item1이 Symbol
609
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
610
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
611
                    {
612
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
613
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
614
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
615

    
616
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
617

    
618
                        symbolModelItem.Commit();
619
                        ReleaseCOMObjects(symbolModelItem);
620
                        symbolModelItem = null;
621
                    }
622
                }
623

    
624
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
625
                {
626
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
627
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
628
                    if (attribute != null)
629
                    {
630
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
631
                            attribute.set_Value("End 1 is downstream (Outlet)");
632
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
633
                            attribute.set_Value("End 1 is upstream (Inlet)");
634
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
635
                            attribute.set_Value("End 1 is upstream (Inlet)");
636
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
637
                            attribute.set_Value("End 1 is downstream (Outlet)");
638
                    }
639
                }
640
            }
641
        }
642
        private void RunNoteModeling()
643
        {
644
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
645
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
646
            List<Note> correctList = new List<Note>();
647
            foreach (var item in document.NOTES)
648
                try
649
                {
650
                    NoteModeling(item, correctList);
651
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
652
                }
653
                catch (Exception ex)
654
                {
655
                    Log.Write("Error in NoteModeling");
656
                    Log.Write("UID : " + item.UID);
657
                    Log.Write(ex.Message);
658
                    Log.Write(ex.StackTrace);
659
                }
660

    
661
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
662
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
663
            SortNote(correctList);
664
            List<Note> endList = new List<Note>();
665
            if (correctList.Count > 0)
666
                endList.Add(correctList[0]);
667
            foreach (var item in document.NOTES)
668
                try
669
                {
670
                    if (!endList.Contains(item))
671
                        NoteCorrectModeling(item, endList);
672
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
673
                }
674
                catch (Exception ex)
675
                {
676
                    Log.Write("Error in NoteModeling");
677
                    Log.Write("UID : " + item.UID);
678
                    Log.Write(ex.Message);
679
                    Log.Write(ex.StackTrace);
680
                }
681
        }
682
        private void RunTextModeling()
683
        {
684
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
685
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
686
            List<Text> correctList = new List<Text>();
687
            foreach (var item in document.TEXTINFOS)
688
                try
689
                {
690
                    TextModeling(item, correctList);
691
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
692
                }
693
                catch (Exception ex)
694
                {
695
                    Log.Write("Error in TextModeling");
696
                    Log.Write("UID : " + item.UID);
697
                    Log.Write(ex.Message);
698
                    Log.Write(ex.StackTrace);
699
                }
700

    
701
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
702
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Text");
703
            SortText(correctList);
704
            List<Text> endList = new List<Text>();
705
            if (correctList.Count > 0)
706
                endList.Add(correctList[0]);
707
            foreach (var item in correctList)
708
                try
709
                {
710
                    if (!endList.Contains(item))
711
                        TextCorrectModeling(item, endList);
712
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
713
                }
714
                catch (Exception ex)
715
                {
716
                    Log.Write("Error in TextModeling");
717
                    Log.Write("UID : " + item.UID);
718
                    Log.Write(ex.Message);
719
                    Log.Write(ex.StackTrace);
720
                }
721
        }
722
        private void RunInputLineNumberAttribute()
723
        {
724
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
725
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
726
            List<string> endLine = new List<string>();
727
            foreach (var item in document.LINENUMBERS)
728
                try
729
                {
730
                    InputLineNumberAttribute(item, endLine);
731
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
732
                }
733
                catch (Exception ex)
734
                {
735
                    Log.Write("Error in InputLineNumberAttribute");
736
                    Log.Write("UID : " + item.UID);
737
                    Log.Write(ex.Message);
738
                    Log.Write(ex.StackTrace);
739
                }
740
        }
741
        private void RunInputSymbolAttribute()
742
        {
743
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
744
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
745
            foreach (var item in document.SYMBOLS)
746
                try
747
                {
748
                    InputSymbolAttribute(item, item.ATTRIBUTES);
749
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
750
                }
751
                catch (Exception ex)
752
                {
753
                    Log.Write("Error in InputSymbolAttribute");
754
                    Log.Write("UID : " + item.UID);
755
                    Log.Write(ex.Message);
756
                    Log.Write(ex.StackTrace);
757
                }
758
        }
759
        private void RunInputSpecBreakAttribute()
760
        {
761
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
762
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
763
            foreach (var item in document.SpecBreaks)
764
                try
765
                {
766
                    InputSpecBreakAttribute(item);
767
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
768
                }
769
                catch (Exception ex)
770
                {
771
                    Log.Write("Error in InputSpecBreakAttribute");
772
                    Log.Write("UID : " + item.UID);
773
                    Log.Write(ex.Message);
774
                    Log.Write(ex.StackTrace);
775
                }
776
        }
777
        private void RunLabelSymbolModeling()
778
        {
779
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
780
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
781
            foreach (var item in document.SYMBOLS)
782
                try
783
                {
784
                    LabelSymbolModeling(item);
785
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
786
                }
787
                catch (Exception ex)
788
                {
789
                    Log.Write("Error in LabelSymbolModeling");
790
                    Log.Write("UID : " + item.UID);
791
                    Log.Write(ex.Message);
792
                    Log.Write(ex.StackTrace);
793
                }
794
        }
795
        
796
        /// <summary>
797
        /// 도면 생성 메서드
798
        /// </summary>
799
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
800
        {
801
            Log.Write("------------------ Start create document ------------------");
802
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
803
            Log.Write("Drawing name : " + drawingName);
804
            Log.Write("Drawing number : " + drawingNumber);
805
            Thread.Sleep(1000);
806
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
807
            if (newDrawing != null)
808
            {
809
                document.SPPID_DrawingNumber = drawingNumber;
810
                document.SPPID_DrawingName = drawingName;
811
                Thread.Sleep(1000);
812
                radApp.ActiveWindow.Fit();
813
                Thread.Sleep(1000);
814
                radApp.ActiveWindow.Zoom = 2000;
815
                Thread.Sleep(2000);
816

    
817
                //current LMDrawing 가져오기
818
                LMAFilter filter = new LMAFilter();
819
                LMACriterion criterion = new LMACriterion();
820
                filter.ItemType = "Drawing";
821
                criterion.SourceAttributeName = "Name";
822
                criterion.Operator = "=";
823
                criterion.set_ValueAttribute(drawingName);
824
                filter.get_Criteria().Add(criterion);
825

    
826
                LMDrawings drawings = new LMDrawings();
827
                drawings.Collect(dataSource, Filter: filter);
828

    
829
                drawingID = ((dynamic)drawings).Nth(1).Id;
830
                ReleaseCOMObjects(filter);
831
                ReleaseCOMObjects(criterion);
832
                ReleaseCOMObjects(drawings);
833
                filter = null;
834
                criterion = null;
835
                drawings = null;
836
            }
837
            else
838
                Log.Write("Fail Create Drawing");
839

    
840
            if (newDrawing != null)
841
                return true;
842
            else
843
                return false;
844
        }
845

    
846
        /// <summary>
847
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
848
        /// </summary>
849
        /// <param name="drawingName"></param>
850
        /// <param name="drawingNumber"></param>
851
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
852
        {
853
            LMDrawings drawings = new LMDrawings();
854
            drawings.Collect(dataSource);
855

    
856
            List<string> drawingNameList = new List<string>();
857
            List<string> drawingNumberList = new List<string>();
858

    
859
            foreach (LMDrawing item in drawings)
860
            {
861
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
862
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
863
            }
864

    
865
            int nameLength = drawingName.Length;
866
            while (drawingNameList.Contains(drawingName))
867
            {
868
                if (nameLength == drawingName.Length)
869
                    drawingName += "-1";
870
                else
871
                {
872
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
873
                    drawingName = drawingName.Substring(0, nameLength + 1);
874
                    drawingName += ++index;
875
                }
876
            }
877

    
878
            int numberLength = drawingNumber.Length;
879
            while (drawingNameList.Contains(drawingNumber))
880
            {
881
                if (numberLength == drawingNumber.Length)
882
                    drawingNumber += "-1";
883
                else
884
                {
885
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
886
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
887
                    drawingNumber += ++index;
888
                }
889
            }
890
            ReleaseCOMObjects(drawings);
891
            drawings = null;
892
        }
893

    
894
        /// <summary>
895
        /// 도면 크기 구하는 메서드
896
        /// </summary>
897
        /// <returns></returns>
898
        private bool DocumentCoordinateCorrection()
899
        {
900
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
901
            {
902
                Log.Write("Setting Drawing X, Drawing Y");
903
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
904
                Log.Write("Start coordinate correction");
905
                document.CoordinateCorrection();
906
                return true;
907
            }
908
            else
909
            {
910
                Log.Write("Need Drawing X, Y");
911
                return false;
912
            }
913
        }
914

    
915
        /// <summary>
916
        /// 심볼을 실제로 Modeling 메서드
917
        /// </summary>
918
        /// <param name="symbol">생성할 심볼</param>
919
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
920
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
921
        {
922
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
923
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
924
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
925
                return;
926
            // 이미 모델링 됐을 경우
927
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
928
                return;
929

    
930
            LMSymbol _LMSymbol = null;
931

    
932
            string mappingPath = symbol.SPPID.MAPPINGNAME;
933
            double x = symbol.SPPID.ORIGINAL_X;
934
            double y = symbol.SPPID.ORIGINAL_Y;
935
            int mirror = 0;
936
            double angle = symbol.ANGLE;
937

    
938
            // OPC 일경우 180도 일때 Mirror
939
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
940
                mirror = 1;
941

    
942
            // Mirror 계산
943
            if (symbol.FLIP == 1)
944
            {
945
                mirror = 1;
946
                angle += Math.PI;
947
            }
948

    
949
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
950
            {
951
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
952
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
953
                if (connector != null)
954
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
955

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

    
958
                if (_LMSymbol != null && _TargetItem != null)
959
                {
960
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
961

    
962
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
963
                    {
964
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
965
                        if (reModelingConnector != null)
966
                            ReModelingLMConnector(reModelingConnector);
967
                    }
968
                }
969

    
970
                ReleaseCOMObjects(_TargetItem);
971
            }
972
            else
973
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
974

    
975
            if (_LMSymbol != null)
976
            {
977
                _LMSymbol.Commit();
978

    
979
                // ConnCheck
980
                List<string> ids = new List<string>();
981
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
982
                {
983
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
984
                        ids.Add(item.Id);
985
                    ReleaseCOMObjects(item);
986
                }
987
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
988
                {
989
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
990
                        ids.Add(item.Id);
991
                    ReleaseCOMObjects(item);
992
                }
993

    
994
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
995
                if (targetSymbol == null && ids.Count != createdSymbolCount)
996
                {
997
                    double currentX = _LMSymbol.get_XCoordinate();
998
                    double currentY = _LMSymbol.get_YCoordinate();
999

    
1000

    
1001
                }
1002

    
1003
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1004
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1005
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1006

    
1007
                foreach (var item in symbol.ChildSymbols)
1008
                    CreateChildSymbol(item, _LMSymbol, symbol);
1009

    
1010
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1011
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1012

    
1013
                double[] range = null;
1014
                GetSPPIDSymbolRange(symbol, ref range);
1015
                symbol.SPPID.SPPID_Min_X = range[0];
1016
                symbol.SPPID.SPPID_Min_Y = range[1];
1017
                symbol.SPPID.SPPID_Max_X = range[2];
1018
                symbol.SPPID.SPPID_Max_Y = range[3];
1019

    
1020
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1021
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1022
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1023
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1024

    
1025
                ReleaseCOMObjects(_LMSymbol);
1026
            }
1027
        }
1028

    
1029
        private void RemoveSymbol(Symbol symbol)
1030
        {
1031
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1032
            {
1033
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1034
                if (_LMSymbol != null)
1035
                {
1036
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1037
                    ReleaseCOMObjects(_LMSymbol);
1038
                }
1039
            }
1040

    
1041
            symbol.SPPID.RepresentationId = string.Empty;
1042
            symbol.SPPID.ModelItemID = string.Empty;
1043
            symbol.SPPID.SPPID_X = double.NaN;
1044
            symbol.SPPID.SPPID_Y = double.NaN;
1045
            symbol.SPPID.SPPID_Min_X = double.NaN;
1046
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1047
            symbol.SPPID.SPPID_Max_X = double.NaN;
1048
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1049
        }
1050

    
1051
        private void RemoveSymbol(List<Symbol> symbols)
1052
        {
1053
            foreach (var symbol in symbols)
1054
            {
1055
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1056
                {
1057
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1058
                    if (_LMSymbol != null)
1059
                    {
1060
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1061
                        ReleaseCOMObjects(_LMSymbol);
1062
                    }
1063
                }
1064

    
1065
                symbol.SPPID.RepresentationId = string.Empty;
1066
                symbol.SPPID.ModelItemID = string.Empty;
1067
                symbol.SPPID.SPPID_X = double.NaN;
1068
                symbol.SPPID.SPPID_Y = double.NaN;
1069
                symbol.SPPID.SPPID_Min_X = double.NaN;
1070
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1071
                symbol.SPPID.SPPID_Max_X = double.NaN;
1072
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1073
            }
1074
        }
1075

    
1076
        /// <summary>
1077
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1078
        /// </summary>
1079
        /// <param name="targetConnector"></param>
1080
        /// <param name="targetSymbol"></param>
1081
        /// <param name="x"></param>
1082
        /// <param name="y"></param>
1083
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1084
        {
1085
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1086

    
1087
            double[] range = null;
1088
            List<double[]> points = new List<double[]>();
1089
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1090
            double x1 = range[0];
1091
            double y1 = range[1];
1092
            double x2 = range[2];
1093
            double y2 = range[3];
1094

    
1095
            // Origin 기준 Connector의 위치차이
1096
            double sceneX = 0;
1097
            double sceneY = 0;
1098
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1099
            double originX = 0;
1100
            double originY = 0;
1101
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1102
            double gapX = originX - sceneX;
1103
            double gapY = originY - sceneY;
1104

    
1105
            // SPPID Symbol과 ID2 심볼의 크기 차이
1106
            double sizeWidth = 0;
1107
            double sizeHeight = 0;
1108
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1109
            if (sizeWidth == 0 || sizeHeight == 0)
1110
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1111

    
1112
            double percentX = (x2 - x1) / sizeWidth;
1113
            double percentY = (y2 - y1) / sizeHeight;
1114

    
1115
            double SPPIDgapX = gapX * percentX;
1116
            double SPPIDgapY = gapY * percentY;
1117

    
1118
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1119
            double distance = double.MaxValue;
1120
            double[] resultPoint;
1121
            foreach (var point in points)
1122
            {
1123
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1124
                if (distance > result)
1125
                {
1126
                    distance = result;
1127
                    resultPoint = point;
1128
                    x = point[0];
1129
                    y = point[1];
1130
                }
1131
            }
1132

    
1133
            ReleaseCOMObjects(_TargetItem);
1134
        }
1135

    
1136
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1137
        {
1138
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1139
            if (index == 0)
1140
            {
1141
                x = targetLine.SPPID.START_X;
1142
                y = targetLine.SPPID.START_Y;
1143
            }
1144
            else
1145
            {
1146
                x = targetLine.SPPID.END_X;
1147
                y = targetLine.SPPID.END_Y;
1148
            }
1149
        }
1150

    
1151
        /// <summary>
1152
        /// SPPID Symbol의 Range를 구한다.
1153
        /// </summary>
1154
        /// <param name="symbol"></param>
1155
        /// <param name="range"></param>
1156
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1157
        {
1158
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1159
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1160
            double x1 = 0;
1161
            double y1 = 0;
1162
            double x2 = 0;
1163
            double y2 = 0;
1164
            symbol2d.Range(out x1, out y1, out x2, out y2);
1165
            range = new double[] { x1, y1, x2, y2 };
1166

    
1167
            for (int i = 1; i < int.MaxValue; i++)
1168
            {
1169
                double connX = 0;
1170
                double connY = 0;
1171
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1172
                    points.Add(new double[] { connX, connY });
1173
                else
1174
                    break;
1175
            }
1176

    
1177
            foreach (var childSymbol in symbol.ChildSymbols)
1178
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1179

    
1180
            ReleaseCOMObjects(_TargetItem);
1181
        }
1182

    
1183
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range)
1184
        {
1185
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1186
            if (_TargetItem != null)
1187
            {
1188
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1189
                double x1 = 0;
1190
                double y1 = 0;
1191
                double x2 = 0;
1192
                double y2 = 0;
1193
                symbol2d.Range(out x1, out y1, out x2, out y2);
1194
                range = new double[] { x1, y1, x2, y2 };
1195

    
1196
                foreach (var childSymbol in symbol.ChildSymbols)
1197
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1198

    
1199
                ReleaseCOMObjects(_TargetItem);
1200
            }
1201
        }
1202

    
1203
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1204
        {
1205
            if (labelPersist != null)
1206
            {
1207
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1208
                if (dependency != null)
1209
                {
1210
                    double x1 = 0;
1211
                    double y1 = 0;
1212
                    double x2 = 0;
1213
                    double y2 = 0;
1214
                    dependency.Range(out x1, out y1, out x2, out y2);
1215
                    range = new double[] { x1, y1, x2, y2 };
1216
                }
1217
            }
1218
        }
1219

    
1220
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1221
        {
1222
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1223
            foreach (var symbol in symbols)
1224
            {
1225
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1226
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.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

    
1233
                tempRange[0] = Math.Min(tempRange[0], x1);
1234
                tempRange[1] = Math.Min(tempRange[1], y1);
1235
                tempRange[2] = Math.Max(tempRange[2], x2);
1236
                tempRange[3] = Math.Max(tempRange[3], y2);
1237

    
1238
                foreach (var childSymbol in symbol.ChildSymbols)
1239
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1240

    
1241
                ReleaseCOMObjects(_TargetItem);
1242
            }
1243

    
1244
            range = tempRange;
1245
        }
1246

    
1247
        /// <summary>
1248
        /// Child Modeling 된 Symbol의 Range를 구한다.
1249
        /// </summary>
1250
        /// <param name="childSymbol"></param>
1251
        /// <param name="range"></param>
1252
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1253
        {
1254
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1255
            if (_ChildSymbol != null)
1256
            {
1257
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1258
                double x1 = 0;
1259
                double y1 = 0;
1260
                double x2 = 0;
1261
                double y2 = 0;
1262
                symbol2d.Range(out x1, out y1, out x2, out y2);
1263
                range[0] = Math.Min(range[0], x1);
1264
                range[1] = Math.Min(range[1], y1);
1265
                range[2] = Math.Max(range[2], x2);
1266
                range[3] = Math.Max(range[3], y2);
1267

    
1268
                for (int i = 1; i < int.MaxValue; i++)
1269
                {
1270
                    double connX = 0;
1271
                    double connY = 0;
1272
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1273
                        points.Add(new double[] { connX, connY });
1274
                    else
1275
                        break;
1276
                }
1277

    
1278
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1279
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1280

    
1281
                ReleaseCOMObjects(_ChildSymbol);
1282
            }
1283
        }
1284

    
1285
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1286
        {
1287
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1288
            if (_ChildSymbol != null)
1289
            {
1290
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1291
                double x1 = 0;
1292
                double y1 = 0;
1293
                double x2 = 0;
1294
                double y2 = 0;
1295
                symbol2d.Range(out x1, out y1, out x2, out y2);
1296
                range[0] = Math.Min(range[0], x1);
1297
                range[1] = Math.Min(range[1], y1);
1298
                range[2] = Math.Max(range[2], x2);
1299
                range[3] = Math.Max(range[3], y2);
1300

    
1301
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1302
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1303
                ReleaseCOMObjects(_ChildSymbol);
1304
            }
1305
        }
1306

    
1307
        /// <summary>
1308
        /// Label Symbol Modeling
1309
        /// </summary>
1310
        /// <param name="symbol"></param>
1311
        private void LabelSymbolModeling(Symbol symbol)
1312
        {
1313
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1314
            {
1315
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1316
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1317
                    return;
1318
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1319

    
1320
                string symbolUID = itemAttribute.VALUE;
1321
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1322
                if (targetItem != null &&
1323
                    (targetItem.GetType() == typeof(Symbol) ||
1324
                    targetItem.GetType() == typeof(Equipment)))
1325
                {
1326
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1327
                    string sRep = null;
1328
                    if (targetItem.GetType() == typeof(Symbol))
1329
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1330
                    else if (targetItem.GetType() == typeof(Equipment))
1331
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1332
                    if (!string.IsNullOrEmpty(sRep))
1333
                    {
1334
                        // LEADER Line 검사
1335
                        bool leaderLine = false;
1336
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1337
                        if (symbolMapping != null)
1338
                            leaderLine = symbolMapping.LEADERLINE;
1339

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

    
1344
                        //Leader 선 센터로
1345
                        if (_LMLabelPresist != null)
1346
                        {
1347
                            // Target Item에 Label의 Attribute Input
1348
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1349

    
1350
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1351
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1352
                            if (dependency != null)
1353
                            {
1354
                                bool result = false;
1355
                                foreach (var attributes in dependency.AttributeSets)
1356
                                {
1357
                                    foreach (var attribute in attributes)
1358
                                    {
1359
                                        string name = attribute.Name;
1360
                                        string value = attribute.GetValue().ToString();
1361
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1362
                                        {
1363
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1364
                                            {
1365
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1366
                                                {
1367
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1368
                                                    double prevX = _TargetItem.get_XCoordinate();
1369
                                                    double prevY = _TargetItem.get_YCoordinate();
1370
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1371
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1372
                                                    result = true;
1373
                                                    break;
1374
                                                }
1375
                                            }
1376
                                        }
1377

    
1378
                                        if (result)
1379
                                            break;
1380
                                    }
1381

    
1382
                                    if (result)
1383
                                        break;
1384
                                }
1385
                            }
1386

    
1387
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1388
                            _LMLabelPresist.Commit();
1389
                            ReleaseCOMObjects(_LMLabelPresist);
1390
                        }
1391

    
1392
                        ReleaseCOMObjects(_TargetItem);
1393
                    }
1394
                }
1395
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1396
                {
1397
                    Line targetLine = targetItem as Line;
1398
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1399
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1400
                    if (connectedLMConnector != null)
1401
                    {
1402
                        // LEADER Line 검사
1403
                        bool leaderLine = false;
1404
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1405
                        if (symbolMapping != null)
1406
                            leaderLine = symbolMapping.LEADERLINE;
1407

    
1408
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1409
                        if (_LMLabelPresist != null)
1410
                        {
1411
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1412
                            _LMLabelPresist.Commit();
1413
                            ReleaseCOMObjects(_LMLabelPresist);
1414
                        }
1415
                        ReleaseCOMObjects(connectedLMConnector);
1416
                    }
1417

    
1418
                    foreach (var item in connectorVertices)
1419
                        if (item.Key != null)
1420
                            ReleaseCOMObjects(item.Key);
1421
                }
1422
            }
1423
        }
1424

    
1425
        /// <summary>
1426
        /// Equipment를 실제로 Modeling 메서드
1427
        /// </summary>
1428
        /// <param name="equipment"></param>
1429
        private void EquipmentModeling(Equipment equipment)
1430
        {
1431
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1432
                return;
1433

    
1434
            LMSymbol _LMSymbol = null;
1435
            LMSymbol targetItem = null;
1436
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1437
            double x = equipment.SPPID.ORIGINAL_X;
1438
            double y = equipment.SPPID.ORIGINAL_Y;
1439
            int mirror = 0;
1440
            double angle = equipment.ANGLE;
1441

    
1442
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1443

    
1444
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1445
            if (connector != null)
1446
            {
1447
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1448
                if (connEquipment != null)
1449
                {
1450
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1451
                        EquipmentModeling(connEquipment);
1452

    
1453
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1454
                    {
1455
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1456
                        if (targetItem != null)
1457
                        {
1458
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1459
                        }
1460
                        else
1461
                        {
1462
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1463
                        }
1464
                    }
1465
                    else
1466
                    {
1467
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1468
                    }
1469
                }
1470
                else
1471
                {
1472
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1473
                }
1474
            }
1475
            else
1476
            {
1477
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1478
            }
1479

    
1480
            if (_LMSymbol != null)
1481
            {
1482
                _LMSymbol.Commit();
1483
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1484
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1485
                ReleaseCOMObjects(_LMSymbol);
1486
            }
1487

    
1488
            if (targetItem != null)
1489
            {
1490
                ReleaseCOMObjects(targetItem);
1491
            }
1492

    
1493
            ReleaseCOMObjects(_LMSymbol);
1494
        }
1495

    
1496
        /// <summary>
1497
        /// 첫 진입점
1498
        /// </summary>
1499
        /// <param name="symbol"></param>
1500
        private void SymbolModelingBySymbol(Symbol symbol)
1501
        {
1502
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1503
            List<object> endObjects = new List<object>();
1504
            endObjects.Add(symbol);
1505

    
1506
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1507
            foreach (var connector in symbol.CONNECTORS)
1508
            {
1509
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1510
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1511
                {
1512
                    endObjects.Add(connItem);
1513
                    if (connItem.GetType() == typeof(Symbol))
1514
                    {
1515
                        Symbol connSymbol = connItem as Symbol;
1516
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1517
                        {
1518
                            SymbolModeling(connSymbol, symbol);
1519
                        }
1520
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1521
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1522
                    }
1523
                    else if (connItem.GetType() == typeof(Line))
1524
                    {
1525
                        Line connLine = connItem as Line;
1526
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1527
                    }
1528
                }
1529
            }
1530
        }
1531

    
1532
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1533
        {
1534
            foreach (var connector in symbol.CONNECTORS)
1535
            {
1536
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1537
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1538
                {
1539
                    if (!endObjects.Contains(connItem))
1540
                    {
1541
                        endObjects.Add(connItem);
1542
                        if (connItem.GetType() == typeof(Symbol))
1543
                        {
1544
                            Symbol connSymbol = connItem as Symbol;
1545
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1546
                            {
1547
                                SymbolModeling(connSymbol, symbol);
1548
                            }
1549
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1550
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1551
                        }
1552
                        else if (connItem.GetType() == typeof(Line))
1553
                        {
1554
                            Line connLine = connItem as Line;
1555
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1556
                        }
1557
                    }
1558
                }
1559
            }
1560
        }
1561

    
1562
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1563
        {
1564
            foreach (var connector in line.CONNECTORS)
1565
            {
1566
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1567
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1568
                {
1569
                    if (!endObjects.Contains(connItem))
1570
                    {
1571
                        endObjects.Add(connItem);
1572
                        if (connItem.GetType() == typeof(Symbol))
1573
                        {
1574
                            Symbol connSymbol = connItem as Symbol;
1575
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1576
                            {
1577
                                List<Symbol> group = new List<Symbol>();
1578
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1579
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1580
                                List<Symbol> endModelingGroup = new List<Symbol>();
1581
                                if (priority != null)
1582
                                {
1583
                                    SymbolGroupModeling(priority, group);
1584

    
1585
                                    // Range 겹치는지 확인해야함
1586
                                    double[] prevRange = null;
1587
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1588
                                    double[] groupRange = null;
1589
                                    GetSPPIDSymbolRange(group, ref groupRange);
1590

    
1591
                                    double distanceX = 0;
1592
                                    double distanceY = 0;
1593
                                    bool overlapX = false;
1594
                                    bool overlapY = false;
1595
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1596
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1597
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1598
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1599
                                    {
1600
                                        RemoveSymbol(group);
1601
                                        foreach (var _temp in group)
1602
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1603

    
1604
                                        SymbolGroupModeling(priority, group);
1605
                                    }
1606
                                }
1607
                                else
1608
                                {
1609
                                    SymbolModeling(connSymbol, null);
1610
                                    // Range 겹치는지 확인해야함
1611
                                    double[] prevRange = null;
1612
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1613
                                    double[] connRange = null;
1614
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1615

    
1616
                                    double distanceX = 0;
1617
                                    double distanceY = 0;
1618
                                    bool overlapX = false;
1619
                                    bool overlapY = false;
1620
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1621
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1622
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1623
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1624
                                    {
1625
                                        RemoveSymbol(connSymbol);
1626
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1627

    
1628
                                        SymbolModeling(connSymbol, null);
1629
                                    }
1630
                                }
1631
                            }
1632
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1633
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1634
                        }
1635
                        else if (connItem.GetType() == typeof(Line))
1636
                        {
1637
                            Line connLine = connItem as Line;
1638
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1639
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1640
                        }
1641
                    }
1642
                }
1643
            }
1644
        }
1645

    
1646
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1647
        {
1648
            List<Symbol> endModelingGroup = new List<Symbol>();
1649
            SymbolModeling(firstSymbol, null);
1650
            endModelingGroup.Add(firstSymbol);
1651
            while (endModelingGroup.Count != group.Count)
1652
            {
1653
                foreach (var _symbol in group)
1654
                {
1655
                    if (!endModelingGroup.Contains(_symbol))
1656
                    {
1657
                        foreach (var _connector in _symbol.CONNECTORS)
1658
                        {
1659
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1660
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1661
                            {
1662
                                SymbolModeling(_symbol, _connSymbol);
1663
                                endModelingGroup.Add(_symbol);
1664
                                break;
1665
                            }
1666
                        }
1667
                    }
1668
                }
1669
            }
1670
        }
1671

    
1672
        /// <summary>
1673
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1674
        /// </summary>
1675
        /// <param name="childSymbol"></param>
1676
        /// <param name="parentSymbol"></param>
1677
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1678
        {
1679
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1680
            double x1 = 0;
1681
            double x2 = 0;
1682
            double y1 = 0;
1683
            double y2 = 0;
1684
            symbol2d.Range(out x1, out y1, out x2, out y2);
1685

    
1686
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1687
            if (_LMSymbol != null)
1688
            {
1689
                _LMSymbol.Commit();
1690
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1691
                foreach (var item in childSymbol.ChildSymbols)
1692
                    CreateChildSymbol(item, _LMSymbol, parent);
1693
            }
1694

    
1695

    
1696
            ReleaseCOMObjects(_LMSymbol);
1697
        }
1698
        double index = 0;
1699
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1700
        {
1701
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1702
                return;
1703

    
1704
            List<Line> group = new List<Line>();
1705
            GetConnectedLineGroup(line, group);
1706
            LineCoordinateCorrection(group);
1707

    
1708
            foreach (var groupLine in group)
1709
            {
1710
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1711
                {
1712
                    BranchLines.Add(groupLine);
1713
                    continue;
1714
                }
1715

    
1716
                bool diagonal = false;
1717
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1718
                    diagonal = true;
1719
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1720
                LMSymbol _LMSymbolStart = null;
1721
                LMSymbol _LMSymbolEnd = null;
1722
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1723
                foreach (var connector in groupLine.CONNECTORS)
1724
                {
1725
                    double x = 0;
1726
                    double y = 0;
1727
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1728
                    if (connector.ConnectedObject == null)
1729
                    {
1730
                        placeRunInputs.AddPoint(x, y);
1731
                    }
1732
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1733
                    {
1734
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1735
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1736
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1737
                        {
1738
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1739
                            if (_LMSymbolStart != null)
1740
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1741
                            else
1742
                                placeRunInputs.AddPoint(x, y);
1743
                        }
1744
                        else
1745
                        {
1746
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1747
                            if (_LMSymbolEnd != null)
1748
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1749
                            else
1750
                                placeRunInputs.AddPoint(x, y);
1751
                        }
1752
                    }
1753
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1754
                    {
1755
                        Line targetLine = connector.ConnectedObject as Line;
1756
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1757
                        {
1758
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1759
                            if (targetConnector != null)
1760
                            {
1761
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1762
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1763
                            }
1764
                            else
1765
                            {
1766
                                placeRunInputs.AddPoint( x, y);
1767
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1768
                            }
1769
                        }
1770
                        else
1771
                        {
1772
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1773
                            {
1774
                                index += 0.01;
1775
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1776
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1777
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1778
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1779
                                else
1780
                                {
1781
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
1782
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1783
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1784
                                    else
1785
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1786
                                }
1787
                            }
1788

    
1789
                            placeRunInputs.AddPoint(x, y);
1790

    
1791
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1792
                            {
1793
                                index += 0.01;
1794
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1795
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1796
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1797
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1798
                                else
1799
                                {
1800
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
1801
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1802
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1803
                                    else
1804
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1805
                                }
1806
                            }
1807
                        }
1808
                    }
1809
                }
1810

    
1811
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1812
                if (_lMConnector != null)
1813
                {
1814
                    _lMConnector.Commit();
1815
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1816
                    bool bRemodelingStart = false;
1817
                    if (_LMSymbolStart != null)
1818
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1819
                    bool bRemodelingEnd = false;
1820
                    if (_LMSymbolEnd != null)
1821
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1822

    
1823
                    if (bRemodelingStart || bRemodelingEnd)
1824
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1825

    
1826
                    FlowMarkModeling(groupLine);
1827
                    LineNumberModelingOnlyOne(groupLine);
1828

    
1829
                    ReleaseCOMObjects(_lMConnector);
1830
                }
1831
                else if (!isBranchModeling)
1832
                {
1833
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1834
                }
1835

    
1836
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1837
                x.ConnectedObject != null &&
1838
                x.ConnectedObject.GetType() == typeof(Line) &&
1839
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1840
                .Select(x => x.ConnectedObject)
1841
                .ToList();
1842

    
1843
                foreach (var item in removeLines)
1844
                    RemoveLineForModeling(item as Line);
1845

    
1846
                if (_LMAItem != null)
1847
                    ReleaseCOMObjects(_LMAItem);
1848
                if (placeRunInputs != null)
1849
                    ReleaseCOMObjects(placeRunInputs);
1850
                if (_LMSymbolStart != null)
1851
                    ReleaseCOMObjects(_LMSymbolStart);
1852
                if (_LMSymbolEnd != null)
1853
                    ReleaseCOMObjects(_LMSymbolEnd);
1854

    
1855
                if (isBranchModeling && BranchLines.Contains(groupLine))
1856
                    BranchLines.Remove(groupLine);
1857
            }
1858
        }
1859

    
1860
        private void RemoveLineForModeling(Line line)
1861
        {
1862
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1863
            if (modelItem != null)
1864
            {
1865
                foreach (LMRepresentation rep in modelItem.Representations)
1866
                {
1867
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1868
                    {
1869
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1870
                        dynamic OID = rep.get_GraphicOID().ToString();
1871
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1872
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1873
                        int verticesCount = lineStringGeometry.VertexCount;
1874
                        double[] vertices = null;
1875
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1876
                        for (int i = 0; i < verticesCount; i++)
1877
                        {
1878
                            double x = 0;
1879
                            double y = 0;
1880
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1881
                            if (verticesCount == 2 && (x < 0 || y < 0))
1882
                                _placement.PIDRemovePlacement(rep);
1883
                        }
1884
                        ReleaseCOMObjects(_LMConnector);
1885
                    }
1886
                }
1887

    
1888
                ReleaseCOMObjects(modelItem);
1889
            }
1890
        }
1891

    
1892
        private void GetConnectedLineGroup(Line line, List<Line> group)
1893
        {
1894
            if (!group.Contains(line))
1895
                group.Add(line);
1896
            foreach (var connector in line.CONNECTORS)
1897
            {
1898
                if (connector.ConnectedObject != null &&
1899
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1900
                    !group.Contains(connector.ConnectedObject) &&
1901
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1902
                {
1903
                    Line connLine = connector.ConnectedObject as Line;
1904
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1905
                    {
1906
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1907
                            group.Insert(0, connLine);
1908
                        else
1909
                            group.Add(connLine);
1910
                        GetConnectedLineGroup(connLine, group);
1911
                    }
1912
                }
1913
            }
1914
        }
1915

    
1916
        private void LineCoordinateCorrection(List<Line> group)
1917
        {
1918
            // 순서대로 전 Item 기준 정렬
1919
            LineCoordinateCorrectionByStart(group);
1920

    
1921
            // 역으로 심볼이 있을 경우 좌표 보정
1922
            LineCoordinateCorrectionForLastLine(group);
1923
        }
1924

    
1925
        private void LineCoordinateCorrectionByStart(List<Line> group)
1926
        {
1927
            for (int i = 0; i < group.Count; i++)
1928
            {
1929
                Line line = group[i];
1930
                if (i == 0)
1931
                {
1932
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1933
                    if (symbolConnector != null)
1934
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1935
                }
1936
                else if (i != 0)
1937
                {
1938
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1939
                }
1940
            }
1941
        }
1942

    
1943
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1944
        {
1945
            Line checkLine = group[group.Count - 1];
1946
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1947
            if (lastSymbolConnector != null)
1948
            {
1949
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1950
                for (int i = group.Count - 2; i >= 0; i--)
1951
                {
1952
                    Line line = group[i + 1];
1953
                    Line prevLine = group[i];
1954

    
1955
                    // 같으면 보정
1956
                    if (line.SlopeType == prevLine.SlopeType)
1957
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1958
                    else
1959
                    {
1960
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1961
                        {
1962
                            double prevX = 0;
1963
                            double prevY = 0;
1964
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1965
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1966

    
1967
                            double x = 0;
1968
                            double y = 0;
1969
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1970
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1971
                        }
1972
                        else if (line.SlopeType == SlopeType.VERTICAL)
1973
                        {
1974
                            double prevX = 0;
1975
                            double prevY = 0;
1976
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1977
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1978

    
1979
                            double x = 0;
1980
                            double y = 0;
1981
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1982
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1983
                        }
1984
                        break;
1985
                    }
1986
                }
1987
            }
1988
        }
1989

    
1990
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1991
        {
1992
            double x = 0;
1993
            double y = 0;
1994
            if (connItem.GetType() == typeof(Symbol))
1995
            {
1996
                Symbol targetSymbol = connItem as Symbol;
1997
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1998
                if (targetConnector != null)
1999
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2000
                else
2001
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2002
            }
2003
            else if (connItem.GetType() == typeof(Line))
2004
            {
2005
                Line targetLine = connItem as Line;
2006
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2007
            }
2008

    
2009
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2010
        }
2011

    
2012
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2013
        {
2014
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2015
            int index = line.CONNECTORS.IndexOf(connector);
2016
            if (index == 0)
2017
            {
2018
                line.SPPID.START_X = x;
2019
                line.SPPID.START_Y = y;
2020
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2021
                    line.SPPID.END_Y = y;
2022
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2023
                    line.SPPID.END_X = x;
2024
            }
2025
            else
2026
            {
2027
                line.SPPID.END_X = x;
2028
                line.SPPID.END_Y = y;
2029
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2030
                    line.SPPID.START_Y = y;
2031
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2032
                    line.SPPID.START_X = x;
2033
            }
2034
        }
2035

    
2036
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2037
        {
2038
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2039
            int index = line.CONNECTORS.IndexOf(connector);
2040
            if (index == 0)
2041
            {
2042
                line.SPPID.START_X = x;
2043
                if (line.SlopeType == SlopeType.VERTICAL)
2044
                    line.SPPID.END_X = x;
2045
            }
2046
            else
2047
            {
2048
                line.SPPID.END_X = x;
2049
                if (line.SlopeType == SlopeType.VERTICAL)
2050
                    line.SPPID.START_X = x;
2051
            }
2052
        }
2053

    
2054
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2055
        {
2056
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2057
            int index = line.CONNECTORS.IndexOf(connector);
2058
            if (index == 0)
2059
            {
2060
                line.SPPID.START_Y = y;
2061
                if (line.SlopeType == SlopeType.HORIZONTAL)
2062
                    line.SPPID.END_Y = y;
2063
            }
2064
            else
2065
            {
2066
                line.SPPID.END_Y = y;
2067
                if (line.SlopeType == SlopeType.HORIZONTAL)
2068
                    line.SPPID.START_Y = y;
2069
            }
2070
        }
2071

    
2072
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2073
        {
2074
            if (symbol != null)
2075
            {
2076
                string repID = symbol.AsLMRepresentation().Id;
2077
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2078
                string lineUID = line.UID;
2079

    
2080
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2081
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2082
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2083

    
2084
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2085
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2086
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2087

    
2088
                if (startSpecBreak != null || startEndBreak != null)
2089
                    result = true;
2090
            }
2091
        }
2092

    
2093
        /// <summary>
2094
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2095
        /// </summary>
2096
        /// <param name="lines"></param>
2097
        /// <param name="prevLMConnector"></param>
2098
        /// <param name="startSymbol"></param>
2099
        /// <param name="endSymbol"></param>
2100
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2101
        {
2102
            string symbolPath = string.Empty;
2103
            #region get symbol path
2104
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2105
            symbolPath = GetSPPIDFileName(modelItem);
2106
            ReleaseCOMObjects(modelItem);
2107
            #endregion
2108
            bool diagonal = false;
2109
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2110
                diagonal = true;
2111
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2112
            LMConnector newConnector = null;
2113
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2114
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2115
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2116
            int verticesCount = lineStringGeometry.VertexCount;
2117
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2118

    
2119
            List<double[]> vertices = new List<double[]>();
2120
            for (int i = 1; i <= verticesCount; i++)
2121
            {
2122
                double x = 0;
2123
                double y = 0;
2124
                lineStringGeometry.GetVertex(i, ref x, ref y);
2125
                vertices.Add(new double[] { x, y });
2126
            }
2127

    
2128
            for (int i = 0; i < vertices.Count; i++)
2129
            {
2130
                double[] points = vertices[i];
2131
                // 시작 심볼이 있고 첫번째 좌표일 때
2132
                if (startSymbol != null && i == 0)
2133
                {
2134
                    if (bStart)
2135
                    {
2136
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2137
                        if (slopeType == SlopeType.HORIZONTAL)
2138
                            placeRunInputs.AddPoint(points[0], -0.1);
2139
                        else if (slopeType == SlopeType.VERTICAL)
2140
                            placeRunInputs.AddPoint(-0.1, points[1]);
2141
                        else
2142
                            placeRunInputs.AddPoint(points[0], -0.1);
2143

    
2144
                        placeRunInputs.AddPoint(points[0], points[1]);
2145
                    }
2146
                    else
2147
                    {
2148
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2149
                    }
2150
                }
2151
                // 마지막 심볼이 있고 마지막 좌표일 때
2152
                else if (endSymbol != null && i == vertices.Count - 1)
2153
                {
2154
                    if (bEnd)
2155
                    {
2156
                        placeRunInputs.AddPoint(points[0], points[1]);
2157

    
2158
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2159
                        if (slopeType == SlopeType.HORIZONTAL)
2160
                            placeRunInputs.AddPoint(points[0], -0.1);
2161
                        else if (slopeType == SlopeType.VERTICAL)
2162
                            placeRunInputs.AddPoint(-0.1, points[1]);
2163
                        else
2164
                            placeRunInputs.AddPoint(points[0], -0.1);
2165
                    }
2166
                    else
2167
                    {
2168
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2169
                    }
2170
                }
2171
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2172
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2173
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2174
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2175
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2176
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2177
                else
2178
                    placeRunInputs.AddPoint(points[0], points[1]);
2179
            }
2180

    
2181
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2182
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2183

    
2184
            ReleaseCOMObjects(placeRunInputs);
2185
            ReleaseCOMObjects(_LMAItem);
2186
            ReleaseCOMObjects(modelItem);
2187

    
2188
            if (newConnector != null)
2189
            {
2190
                newConnector.Commit();
2191
                if (startSymbol != null && bStart)
2192
                {
2193
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2194
                    placeRunInputs = new PlaceRunInputs();
2195
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2196
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2197
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2198
                    if (_LMConnector != null)
2199
                    {
2200
                        _LMConnector.Commit();
2201
                        RemoveConnectorForReModelingLine(newConnector);
2202
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2203
                        ReleaseCOMObjects(_LMConnector);
2204
                    }
2205
                    ReleaseCOMObjects(placeRunInputs);
2206
                    ReleaseCOMObjects(_LMAItem);
2207
                }
2208

    
2209
                if (endSymbol != null && bEnd)
2210
                {
2211
                    if (startSymbol != null)
2212
                    {
2213
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2214
                        newConnector = dicVertices.First().Key;
2215
                    }
2216

    
2217
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2218
                    placeRunInputs = new PlaceRunInputs();
2219
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2220
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2221
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2222
                    if (_LMConnector != null)
2223
                    {
2224
                        _LMConnector.Commit();
2225
                        RemoveConnectorForReModelingLine(newConnector);
2226
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2227
                        ReleaseCOMObjects(_LMConnector);
2228
                    }
2229
                    ReleaseCOMObjects(placeRunInputs);
2230
                    ReleaseCOMObjects(_LMAItem);
2231
                }
2232

    
2233
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2234
                ReleaseCOMObjects(newConnector);
2235
            }
2236

    
2237
            ReleaseCOMObjects(modelItem);
2238
        }
2239

    
2240
        /// <summary>
2241
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2242
        /// </summary>
2243
        /// <param name="connector"></param>
2244
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2245
        {
2246
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2247
            foreach (var item in dicVertices)
2248
            {
2249
                if (item.Value.Count == 2)
2250
                {
2251
                    bool result = false;
2252
                    foreach (var point in item.Value)
2253
                    {
2254
                        if (point[0] < 0 || point[1] < 0)
2255
                        {
2256
                            result = true;
2257
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2258
                            break;
2259
                        }
2260
                    }
2261

    
2262
                    if (result)
2263
                        break;
2264
                }
2265
            }
2266
            foreach (var item in dicVertices)
2267
                ReleaseCOMObjects(item.Key);
2268
        }
2269

    
2270
        /// <summary>
2271
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2272
        /// </summary>
2273
        /// <param name="symbol"></param>
2274
        /// <param name="line"></param>
2275
        /// <returns></returns>
2276
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2277
        {
2278
            LMSymbol _LMSymbol = null;
2279
            foreach (var connector in symbol.CONNECTORS)
2280
            {
2281
                if (connector.CONNECTEDITEM == line.UID)
2282
                {
2283
                    if (connector.Index == 0)
2284
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2285
                    else
2286
                    {
2287
                        ChildSymbol child = null;
2288
                        foreach (var childSymbol in symbol.ChildSymbols)
2289
                        {
2290
                            if (childSymbol.Connectors.Contains(connector))
2291
                                child = childSymbol;
2292
                            else
2293
                                child = GetChildSymbolByConnector(childSymbol, connector);
2294

    
2295
                            if (child != null)
2296
                                break;
2297
                        }
2298

    
2299
                        if (child != null)
2300
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2301
                    }
2302

    
2303
                    break;
2304
                }
2305
            }
2306

    
2307
            return _LMSymbol;
2308
        }
2309

    
2310
        /// <summary>
2311
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2312
        /// </summary>
2313
        /// <param name="item"></param>
2314
        /// <param name="connector"></param>
2315
        /// <returns></returns>
2316
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2317
        {
2318
            foreach (var childSymbol in item.ChildSymbols)
2319
            {
2320
                if (childSymbol.Connectors.Contains(connector))
2321
                    return childSymbol;
2322
                else
2323
                    return GetChildSymbolByConnector(childSymbol, connector);
2324
            }
2325

    
2326
            return null;
2327
        }
2328

    
2329
        /// <summary>
2330
        /// EndBreak 모델링 메서드
2331
        /// </summary>
2332
        /// <param name="endBreak"></param>
2333
        private void EndBreakModeling(EndBreak endBreak)
2334
        {
2335
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2336
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2337
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2338

    
2339
            if (targetLMConnector != null)
2340
            {
2341
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2342
                Array array = null;
2343
                if (point != null)
2344
                    array = new double[] { 0, point[0], point[1] };
2345
                else
2346
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2347
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2348
                if (_LmLabelPersist != null)
2349
                {
2350
                    _LmLabelPersist.Commit();
2351
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2352
                    if (_LmLabelPersist.ModelItemObject != null)
2353
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2354
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2355
                    ReleaseCOMObjects(_LmLabelPersist);
2356
                }
2357
                ReleaseCOMObjects(targetLMConnector);
2358
            }
2359
        }
2360

    
2361
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2362
        {
2363
            string symbolPath = string.Empty;
2364
            #region get symbol path
2365
            if (string.IsNullOrEmpty(changeSymbolPath))
2366
            {
2367
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2368
                symbolPath = GetSPPIDFileName(modelItem);
2369
                ReleaseCOMObjects(modelItem);
2370
            }
2371
            else
2372
                symbolPath = changeSymbolPath;
2373
            
2374
            #endregion
2375

    
2376
            LMConnector newConnector = null;
2377
            dynamic OID = connector.get_GraphicOID().ToString();
2378
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2379
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2380
            int verticesCount = lineStringGeometry.VertexCount;
2381
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2382
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2383

    
2384
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2385
            {
2386
                double[] vertices = null;
2387
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2388
                double x = 0;
2389
                double y = 0;
2390
                lineStringGeometry.GetVertex(1, ref x, ref y);
2391

    
2392
                string flowDirection = string.Empty;
2393
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2394
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2395
                    flowDirection = flowAttribute.get_Value().ToString();
2396

    
2397
                if (flowDirection == "End 1 is downstream (Outlet)")
2398
                {
2399
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2400
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2401
                    flowDirection = "End 1 is upstream (Inlet)";
2402
                }
2403
                else
2404
                {
2405
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2406
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2407
                }
2408

    
2409
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2410
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2411
                newConnector.Commit();
2412
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2413
                if (!string.IsNullOrEmpty(flowDirection))
2414
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2415
            }
2416
            else
2417
            {
2418
                List<double[]> vertices = new List<double[]>();
2419
                for (int i = 1; i <= verticesCount; i++)
2420
                {
2421
                    double x = 0;
2422
                    double y = 0;
2423
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2424
                    vertices.Add(new double[] { x, y });
2425
                }
2426

    
2427
                for (int i = 0; i < vertices.Count; i++)
2428
                {
2429
                    double[] points = vertices[i];
2430
                    if (i == 0)
2431
                    {
2432
                        if (connector.ConnectItem1SymbolObject != null)
2433
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2434
                        else
2435
                            placeRunInputs.AddPoint(points[0], points[1]);
2436
                    }
2437
                    else if (i == vertices.Count - 1)
2438
                    {
2439
                        if (connector.ConnectItem2SymbolObject != null)
2440
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2441
                        else
2442
                            placeRunInputs.AddPoint(points[0], points[1]);
2443
                    }
2444
                    else
2445
                        placeRunInputs.AddPoint(points[0], points[1]);
2446
                }
2447

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

    
2450
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2451
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2452
                newConnector.Commit();
2453
                foreach (var line in lines)
2454
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2455
            }
2456

    
2457

    
2458
            return newConnector;
2459
        }
2460

    
2461
        /// <summary>
2462
        /// SpecBreak Modeling 메서드
2463
        /// </summary>
2464
        /// <param name="specBreak"></param>
2465
        private void SpecBreakModeling(SpecBreak specBreak)
2466
        {
2467
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2468
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2469

    
2470
            if (upStreamObj != null &&
2471
                downStreamObj != null)
2472
            {
2473
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2474
                if (targetLMConnector != null)
2475
                {
2476
                    foreach (var attribute in specBreak.ATTRIBUTES)
2477
                    {
2478
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2479
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2480
                        {
2481
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2482
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2483
                            Array array = null;
2484
                            if (point != null)
2485
                                array = new double[] { 0, point[0], point[1] };
2486
                            else
2487
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2488
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2489

    
2490
                            if (_LmLabelPersist != null)
2491
                            {
2492
                                _LmLabelPersist.Commit();
2493
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2494
                                if (_LmLabelPersist.ModelItemObject != null)
2495
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2496
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2497
                                ReleaseCOMObjects(_LmLabelPersist);
2498
                            }
2499
                        }
2500
                    }
2501
                    ReleaseCOMObjects(targetLMConnector);
2502
                }
2503
            }
2504
        }
2505

    
2506
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2507
        {
2508
            LMConnector targetConnector = null;
2509
            Symbol targetSymbol = targetObj as Symbol;
2510
            Symbol connectedSymbol = connectedObj as Symbol;
2511
            Line targetLine = targetObj as Line;
2512
            Line connectedLine = connectedObj as Line;
2513
            if (targetSymbol != null && connectedSymbol != null)
2514
            {
2515
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2516
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2517

    
2518
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2519
                {
2520
                    if (connector.get_ItemStatus() != "Active")
2521
                        continue;
2522

    
2523
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2524
                    {
2525
                        targetConnector = connector;
2526
                        break;
2527
                    }
2528
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2529
                    {
2530
                        targetConnector = connector;
2531
                        break;
2532
                    }
2533
                }
2534

    
2535
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2536
                {
2537
                    if (connector.get_ItemStatus() != "Active")
2538
                        continue;
2539

    
2540
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2541
                    {
2542
                        targetConnector = connector;
2543
                        break;
2544
                    }
2545
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2546
                    {
2547
                        targetConnector = connector;
2548
                        break;
2549
                    }
2550
                }
2551

    
2552
                ReleaseCOMObjects(targetLMSymbol);
2553
                ReleaseCOMObjects(connectedLMSymbol);
2554
            }
2555
            else if (targetLine != null && connectedLine != null)
2556
            {
2557
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2558
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2559

    
2560
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2561
                {
2562
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2563
                    {
2564
                        if (targetConnector != null)
2565
                            break;
2566

    
2567
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2568
                        {
2569
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2570

    
2571
                            if (IsConnected(_LMConnector, connectedModelItem))
2572
                                targetConnector = _LMConnector;
2573
                            else
2574
                                ReleaseCOMObjects(_LMConnector);
2575
                        }
2576
                    }
2577

    
2578
                    ReleaseCOMObjects(targetModelItem);
2579
                }
2580
            }
2581
            else
2582
            {
2583
                LMSymbol connectedLMSymbol = null;
2584
                if (connectedSymbol != null)
2585
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2586
                else if (targetSymbol != null)
2587
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2588
                else
2589
                {
2590

    
2591
                }
2592
                LMModelItem targetModelItem = null;
2593
                if (targetLine != null)
2594
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2595
                else if (connectedLine != null)
2596
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2597
                else
2598
                {
2599

    
2600
                }
2601
                if (connectedLMSymbol != null && targetModelItem != null)
2602
                {
2603
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2604
                    {
2605
                        if (connector.get_ItemStatus() != "Active")
2606
                            continue;
2607

    
2608
                        if (IsConnected(connector, targetModelItem))
2609
                        {
2610
                            targetConnector = connector;
2611
                            break;
2612
                        }
2613
                    }
2614

    
2615
                    if (targetConnector == null)
2616
                    {
2617
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2618
                        {
2619
                            if (connector.get_ItemStatus() != "Active")
2620
                                continue;
2621

    
2622
                            if (IsConnected(connector, targetModelItem))
2623
                            {
2624
                                targetConnector = connector;
2625
                                break;
2626
                            }
2627
                        }
2628
                    }
2629
                }
2630

    
2631
            }
2632

    
2633
            return targetConnector;
2634
        }
2635

    
2636
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2637
        {
2638
            double[] result = null;
2639
            Line targetLine = targetObj as Line;
2640
            Symbol targetSymbol = targetObj as Symbol;
2641
            Line connLine = connObj as Line;
2642
            Symbol connSymbol = connObj as Symbol;
2643

    
2644
            double move = GridSetting.GetInstance().Length * 3;
2645
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2646
            {
2647
                result = GetConnectorVertices(targetConnector)[0];
2648
                if (targetSymbol != null && connSymbol != null)
2649
                {
2650
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
2651
                    if (slopeType == SlopeType.HORIZONTAL)
2652
                        result = new double[] { result[0], result[1] - move };
2653
                    else if (slopeType == SlopeType.VERTICAL)
2654
                        result = new double[] { result[0] - move, result[1] };
2655
                }
2656
                else if (targetLine != null)
2657
                {
2658
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
2659
                        result = new double[] { result[0], result[1] - move };
2660
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
2661
                        result = new double[] { result[0] - move, result[1] };
2662
                }
2663
                else if (connLine != null)
2664
                {
2665
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
2666
                        result = new double[] { result[0], result[1] - move };
2667
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
2668
                        result = new double[] { result[0] - move, result[1] };
2669
                }
2670
            }
2671
            else
2672
            {
2673
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
2674
                {
2675
                    Line line = connObj as Line;
2676
                    LMConnector connectedConnector = null;
2677
                    int connIndex = 0;
2678
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2679
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
2680

    
2681
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2682

    
2683
                    ReleaseCOMObjects(modelItem);
2684
                    ReleaseCOMObjects(connectedConnector);
2685

    
2686
                    if (vertices.Count > 0)
2687
                    {
2688
                        if (connIndex == 1)
2689
                            result = vertices[0];
2690
                        else if (connIndex == 2)
2691
                            result = vertices[vertices.Count - 1];
2692

    
2693
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
2694
                        {
2695
                            result = new double[] { result[0], result[1] - move };
2696
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
2697
                            {
2698
                                result = new double[] { result[0] + move, result[1] };
2699
                            }
2700
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
2701
                            {
2702
                                result = new double[] { result[0] - move, result[1] };
2703
                            }
2704
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
2705
                            {
2706
                                result = new double[] { result[0] - move, result[1] };
2707
                            }
2708
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
2709
                            {
2710
                                result = new double[] { result[0] + move, result[1] };
2711
                            }
2712
                        }
2713
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
2714
                        {
2715
                            result = new double[] { result[0] - move, result[1] };
2716
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
2717
                            {
2718
                                result = new double[] { result[0], result[1] + move };
2719
                            }
2720
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
2721
                            {
2722
                                result = new double[] { result[0], result[1] - move };
2723
                            }
2724
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
2725
                            {
2726
                                result = new double[] { result[0], result[1] - move };
2727
                            }
2728
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
2729
                            {
2730
                                result = new double[] { result[0], result[1] + move };
2731
                            }
2732
                        }
2733
                            
2734
                    }
2735
                }
2736
                else
2737
                {
2738
                    Log.Write("error in GetSegemtPoint");
2739
                }
2740
            }
2741

    
2742
            return result;
2743
        }
2744

    
2745
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2746
        {
2747
            bool result = false;
2748

    
2749
            foreach (LMRepresentation rep in modelItem.Representations)
2750
            {
2751
                if (result)
2752
                    break;
2753

    
2754
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2755
                {
2756
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2757

    
2758
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2759
                        connector.ConnectItem1SymbolObject != null &&
2760
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2761
                    {
2762
                        result = true;
2763
                        ReleaseCOMObjects(_LMConnector);
2764
                        break;
2765
                    }
2766
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2767
                        connector.ConnectItem2SymbolObject != null &&
2768
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2769
                    {
2770
                        result = true;
2771
                        ReleaseCOMObjects(_LMConnector);
2772
                        break;
2773
                    }
2774
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2775
                        connector.ConnectItem1SymbolObject != null &&
2776
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2777
                    {
2778
                        result = true;
2779
                        ReleaseCOMObjects(_LMConnector);
2780
                        break;
2781
                    }
2782
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2783
                        connector.ConnectItem2SymbolObject != null &&
2784
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2785
                    {
2786
                        result = true;
2787
                        ReleaseCOMObjects(_LMConnector);
2788
                        break;
2789
                    }
2790

    
2791
                    ReleaseCOMObjects(_LMConnector);
2792
                }
2793
            }
2794

    
2795

    
2796
            return result;
2797
        }
2798

    
2799
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2800
        {
2801
            foreach (LMRepresentation rep in modelItem.Representations)
2802
            {
2803
                if (connectedConnector != null)
2804
                    break;
2805

    
2806
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2807
                {
2808
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2809

    
2810
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2811
                        connector.ConnectItem1SymbolObject != null &&
2812
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2813
                    {
2814
                        connectedConnector = _LMConnector;
2815
                        connectorIndex = 1;
2816
                        break;
2817
                    }
2818
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2819
                        connector.ConnectItem2SymbolObject != null &&
2820
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2821
                    {
2822
                        connectedConnector = _LMConnector;
2823
                        connectorIndex = 2;
2824
                        break;
2825
                    }
2826
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2827
                        connector.ConnectItem1SymbolObject != null &&
2828
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2829
                    {
2830
                        connectedConnector = _LMConnector;
2831
                        connectorIndex = 1;
2832
                        break;
2833
                    }
2834
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2835
                        connector.ConnectItem2SymbolObject != null &&
2836
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2837
                    {
2838
                        connectedConnector = _LMConnector;
2839
                        connectorIndex = 2;
2840
                        break;
2841
                    }
2842

    
2843
                    if (connectedConnector == null)
2844
                        ReleaseCOMObjects(_LMConnector);
2845
                }
2846
            }
2847
        }
2848

    
2849
        /// <summary>
2850
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2851
        /// </summary>
2852
        /// <param name="modelItemID1"></param>
2853
        /// <param name="modelItemID2"></param>
2854
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2855
        {
2856
            try
2857
            {
2858
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2859
                _LMAItem item1 = modelItem1.AsLMAItem();
2860
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2861
                _LMAItem item2 = modelItem2.AsLMAItem();
2862

    
2863
                // item2가 item1으로 조인
2864
                _placement.PIDJoinRuns(ref item1, ref item2);
2865
                item1.Commit();
2866
                item2.Commit();
2867

    
2868
                string beforeID = string.Empty;
2869
                string afterID = string.Empty;
2870

    
2871
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2872
                {
2873
                    beforeID = modelItem2.Id;
2874
                    afterID = modelItem1.Id;
2875
                    survivorId = afterID;
2876
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
2877
                    if (attribute != null)
2878
                        attribute.set_Value("End 1 is upstream (Inlet)");
2879
                }
2880
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2881
                {
2882
                    beforeID = modelItem1.Id;
2883
                    afterID = modelItem2.Id;
2884
                    survivorId = afterID;
2885
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
2886
                    if (attribute != null)
2887
                        attribute.set_Value("End 1 is upstream (Inlet)");
2888
                }
2889
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2890
                    survivorId = null;
2891
                else
2892
                {
2893
                    Log.Write("잘못된 경우");
2894
                    survivorId = null;
2895
                }
2896

    
2897
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2898
                {
2899
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2900
                    foreach (var line in lines)
2901
                        line.SPPID.ModelItemId = afterID;
2902
                }
2903

    
2904
                ReleaseCOMObjects(modelItem1);
2905
                ReleaseCOMObjects(item1);
2906
                ReleaseCOMObjects(modelItem2);
2907
                ReleaseCOMObjects(item2);
2908
            }
2909
            catch (Exception ex)
2910
            {
2911
                Log.Write("Join Error");
2912
                Log.Write(ex.Message);
2913
            }
2914
        }
2915

    
2916
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2917
        {
2918
            List<string> modelItemIDs = new List<string>();
2919
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2920
            {
2921
                LMModelItem modelItem = connector.ModelItemObject;
2922
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2923
                    modelItemIDs.Add(modelItem.Id);
2924
                ReleaseCOMObjects(modelItem);
2925
                ReleaseCOMObjects(connector);
2926
            }
2927

    
2928
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2929
            {
2930
                LMModelItem modelItem = connector.ModelItemObject;
2931
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2932
                    modelItemIDs.Add(modelItem.Id);
2933
                ReleaseCOMObjects(modelItem);
2934
                ReleaseCOMObjects(connector);
2935
            }
2936

    
2937

    
2938
            List<string> result = new List<string>();
2939
            modelItemIDs = modelItemIDs.Distinct().ToList();
2940
            string originalName = GetSPPIDFileName(modelId);
2941
            bool existZeroLength = false;
2942
            foreach (var item in modelItemIDs)
2943
            {
2944
                string fileName = GetSPPIDFileName(item);
2945
                if (originalName == fileName)
2946
                    result.Add(item);
2947
                else
2948
                {
2949
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2950
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()) && connector.LabelPersists.Count == 0)
2951
                    {
2952
                        result.Add(item);
2953
                        ReleaseCOMObjects(connector);
2954
                        existZeroLength = true;
2955
                    }
2956
                }
2957
            }
2958

    
2959
            if (result.Count == 1 && existZeroLength)
2960
            {
2961
                LMConnector connector = GetLMConnectorOnlyOne(result[0]);
2962
                LMConnector newConnector = ReModelingLMConnector(connector, originalName);
2963
                result.Clear();
2964
                if (newConnector != null)
2965
                    result.Add(newConnector.ModelItemID);
2966

    
2967
                ReleaseCOMObjects(connector);
2968
                connector = null;
2969
                ReleaseCOMObjects(newConnector);
2970
                newConnector = null;
2971
            }
2972
            
2973
            return result;
2974
        }
2975

    
2976
        /// <summary>
2977
        /// PipeRun의 좌표를 가져오는 메서드
2978
        /// </summary>
2979
        /// <param name="modelId"></param>
2980
        /// <returns></returns>
2981
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2982
        {
2983
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2984
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2985

    
2986
            if (modelItem != null)
2987
            {
2988
                foreach (LMRepresentation rep in modelItem.Representations)
2989
                {
2990
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2991
                    {
2992
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2993
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2994
                        dynamic OID = rep.get_GraphicOID().ToString();
2995
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2996
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2997
                        int verticesCount = lineStringGeometry.VertexCount;
2998
                        double[] vertices = null;
2999
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3000
                        for (int i = 0; i < verticesCount; i++)
3001
                        {
3002
                            double x = 0;
3003
                            double y = 0;
3004
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3005
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3006
                        }
3007
                    }
3008
                }
3009

    
3010
                ReleaseCOMObjects(modelItem);
3011
            }
3012

    
3013
            return connectorVertices;
3014
        }
3015

    
3016
        private List<double[]> GetConnectorVertices(LMConnector connector)
3017
        {
3018
            List<double[]> vertices = new List<double[]>();
3019
            if (connector != null)
3020
            {
3021
                dynamic OID = connector.get_GraphicOID().ToString();
3022
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3023
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3024
                int verticesCount = lineStringGeometry.VertexCount;
3025
                double[] value = null;
3026
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3027
                for (int i = 0; i < verticesCount; i++)
3028
                {
3029
                    double x = 0;
3030
                    double y = 0;
3031
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3032
                    vertices.Add(new double[] { x, y });
3033
                }
3034
            }
3035
            return vertices;
3036
        }
3037

    
3038
        /// <summary>
3039
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3040
        /// </summary>
3041
        /// <param name="connectorVertices"></param>
3042
        /// <param name="connX"></param>
3043
        /// <param name="connY"></param>
3044
        /// <returns></returns>
3045
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3046
        {
3047
            double length = double.MaxValue;
3048
            LMConnector targetConnector = null;
3049
            foreach (var item in connectorVertices)
3050
            {
3051
                List<double[]> points = item.Value;
3052
                for (int i = 0; i < points.Count - 1; i++)
3053
                {
3054
                    double[] point1 = points[i];
3055
                    double[] point2 = points[i + 1];
3056
                    double x1 = Math.Min(point1[0], point2[0]);
3057
                    double y1 = Math.Min(point1[1], point2[1]);
3058
                    double x2 = Math.Max(point1[0], point2[0]);
3059
                    double y2 = Math.Max(point1[1], point2[1]);
3060

    
3061
                    if ((x1 <= connX && x2 >= connX) ||
3062
                        (y1 <= connY && y2 >= connY))
3063
                    {
3064
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3065
                        if (length >= distance)
3066
                        {
3067
                            targetConnector = item.Key;
3068
                            length = distance;
3069
                        }
3070

    
3071
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3072
                        if (length >= distance)
3073
                        {
3074
                            targetConnector = item.Key;
3075
                            length = distance;
3076
                        }
3077
                    }
3078
                }
3079
            }
3080

    
3081
            // 못찾았을때.
3082
            length = double.MaxValue;
3083
            if (targetConnector == null)
3084
            {
3085
                foreach (var item in connectorVertices)
3086
                {
3087
                    List<double[]> points = item.Value;
3088

    
3089
                    foreach (double[] point in points)
3090
                    {
3091
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3092
                        if (length >= distance)
3093
                        {
3094
                            targetConnector = item.Key;
3095
                            length = distance;
3096
                        }
3097
                    }
3098
                }
3099
            }
3100

    
3101
            return targetConnector;
3102
        }
3103

    
3104
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3105
        {
3106
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3107
            if (vertices.Count == 0)
3108
                return null;
3109

    
3110
            double length = double.MaxValue;
3111
            LMConnector targetConnector = null;
3112
            double[] resultPoint = null;
3113
            List<double[]> targetVertices = null;
3114

    
3115
            // Vertices 포인트에 제일 가까운곳
3116
            foreach (var item in vertices)
3117
            {
3118
                List<double[]> points = item.Value;
3119
                for (int i = 0; i < points.Count; i++)
3120
                {
3121
                    double[] point = points[i];
3122
                    double tempX = point[0];
3123
                    double tempY = point[1];
3124

    
3125
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3126
                    if (length >= distance)
3127
                    {
3128
                        targetConnector = item.Key;
3129
                        length = distance;
3130
                        resultPoint = point;
3131
                        targetVertices = item.Value;
3132
                    }
3133
                }
3134
            }
3135

    
3136
            // Vertices Cross에 제일 가까운곳
3137
            foreach (var item in vertices)
3138
            {
3139
                List<double[]> points = item.Value;
3140
                for (int i = 0; i < points.Count - 1; i++)
3141
                {
3142
                    double[] point1 = points[i];
3143
                    double[] point2 = points[i + 1];
3144

    
3145
                    double maxLineX = Math.Max(point1[0], point2[0]);
3146
                    double minLineX = Math.Min(point1[0], point2[0]);
3147
                    double maxLineY = Math.Max(point1[1], point2[1]);
3148
                    double minLineY = Math.Min(point1[1], point2[1]);
3149

    
3150
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3151

    
3152
                    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]);
3153
                    if (crossingPoint != null)
3154
                    {
3155
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3156
                        if (length >= distance)
3157
                        {
3158
                            if (slope == SlopeType.Slope &&
3159
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3160
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3161
                            {
3162
                                targetConnector = item.Key;
3163
                                length = distance;
3164
                                resultPoint = crossingPoint;
3165
                                targetVertices = item.Value;
3166
                            }
3167
                            else if (slope == SlopeType.HORIZONTAL &&
3168
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3169
                            {
3170
                                targetConnector = item.Key;
3171
                                length = distance;
3172
                                resultPoint = crossingPoint;
3173
                                targetVertices = item.Value;
3174
                            }
3175
                            else if (slope == SlopeType.VERTICAL &&
3176
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3177
                            {
3178
                                targetConnector = item.Key;
3179
                                length = distance;
3180
                                resultPoint = crossingPoint;
3181
                                targetVertices = item.Value;
3182
                            }
3183
                        }
3184
                    }
3185
                }
3186
            }
3187

    
3188
            foreach (var item in vertices)
3189
                if (item.Key != null && item.Key != targetConnector)
3190
                    ReleaseCOMObjects(item.Key);
3191

    
3192
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3193
            {
3194
                double tempResultX = resultPoint[0];
3195
                double tempResultY = resultPoint[1];
3196
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3197

    
3198
                GridSetting gridSetting = GridSetting.GetInstance();
3199

    
3200
                for (int i = 0; i < targetVertices.Count; i++)
3201
                {
3202
                    double[] point = targetVertices[i];
3203
                    double tempX = targetVertices[i][0];
3204
                    double tempY = targetVertices[i][1];
3205
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3206
                    if (tempX == tempResultX && tempY == tempResultY)
3207
                    {
3208
                        if (i == 0)
3209
                        {
3210
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3211
                            bool containZeroLength = false;
3212
                            if (connSymbol != null)
3213
                            {
3214
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3215
                                {
3216
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3217
                                        containZeroLength = true;
3218
                                }
3219
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3220
                                {
3221
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3222
                                        containZeroLength = true;
3223
                                }
3224
                            }
3225

    
3226
                            if (connSymbol == null ||
3227
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3228
                                containZeroLength)
3229
                            {
3230
                                bool bCalcX = false;
3231
                                bool bCalcY = false;
3232
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3233
                                    bCalcX = true;
3234
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3235
                                    bCalcY = true;
3236
                                else
3237
                                {
3238
                                    bCalcX = true;
3239
                                    bCalcY = true;
3240
                                }
3241

    
3242
                                if (bCalcX)
3243
                                {
3244
                                    double nextX = targetVertices[i + 1][0];
3245
                                    double newX = 0;
3246
                                    if (nextX > tempX)
3247
                                    {
3248
                                        newX = tempX + gridSetting.Length;
3249
                                        if (newX > nextX)
3250
                                            newX = (point[0] + nextX) / 2;
3251
                                    }
3252
                                    else
3253
                                    {
3254
                                        newX = tempX - gridSetting.Length;
3255
                                        if (newX < nextX)
3256
                                            newX = (point[0] + nextX) / 2;
3257
                                    }
3258
                                    resultPoint = new double[] { newX, resultPoint[1] };
3259
                                }
3260

    
3261
                                if (bCalcY)
3262
                                {
3263
                                    double nextY = targetVertices[i + 1][1];
3264
                                    double newY = 0;
3265
                                    if (nextY > tempY)
3266
                                    {
3267
                                        newY = tempY + gridSetting.Length;
3268
                                        if (newY > nextY)
3269
                                            newY = (point[1] + nextY) / 2;
3270
                                    }
3271
                                    else
3272
                                    {
3273
                                        newY = tempY - gridSetting.Length;
3274
                                        if (newY < nextY)
3275
                                            newY = (point[1] + nextY) / 2;
3276
                                    }
3277
                                    resultPoint = new double[] { resultPoint[0], newY };
3278
                                }
3279
                            }
3280
                        }
3281
                        else if (i == targetVertices.Count - 1)
3282
                        {
3283
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3284
                            bool containZeroLength = false;
3285
                            if (connSymbol != null)
3286
                            {
3287
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3288
                                {
3289
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3290
                                        containZeroLength = true;
3291
                                }
3292
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3293
                                {
3294
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3295
                                        containZeroLength = true;
3296
                                }
3297
                            }
3298

    
3299
                            if (connSymbol == null ||
3300
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3301
                                containZeroLength)
3302
                            {
3303
                                bool bCalcX = false;
3304
                                bool bCalcY = false;
3305
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3306
                                    bCalcX = true;
3307
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3308
                                    bCalcY = true;
3309
                                else
3310
                                {
3311
                                    bCalcX = true;
3312
                                    bCalcY = true;
3313
                                }
3314

    
3315
                                if (bCalcX)
3316
                                {
3317
                                    double nextX = targetVertices[i - 1][0];
3318
                                    double newX = 0;
3319
                                    if (nextX > tempX)
3320
                                    {
3321
                                        newX = tempX + gridSetting.Length;
3322
                                        if (newX > nextX)
3323
                                            newX = (point[0] + nextX) / 2;
3324
                                    }
3325
                                    else
3326
                                    {
3327
                                        newX = tempX - gridSetting.Length;
3328
                                        if (newX < nextX)
3329
                                            newX = (point[0] + nextX) / 2;
3330
                                    }
3331
                                    resultPoint = new double[] { newX, resultPoint[1] };
3332
                                }
3333

    
3334
                                if (bCalcY)
3335
                                {
3336
                                    double nextY = targetVertices[i - 1][1];
3337
                                    double newY = 0;
3338
                                    if (nextY > tempY)
3339
                                    {
3340
                                        newY = tempY + gridSetting.Length;
3341
                                        if (newY > nextY)
3342
                                            newY = (point[1] + nextY) / 2;
3343
                                    }
3344
                                    else
3345
                                    {
3346
                                        newY = tempY - gridSetting.Length;
3347
                                        if (newY < nextY)
3348
                                            newY = (point[1] + nextY) / 2;
3349
                                    }
3350
                                    resultPoint = new double[] { resultPoint[0], newY };
3351
                                }
3352
                            }
3353
                        }
3354
                        break;
3355
                    }
3356
                }
3357
            }
3358

    
3359
            x = resultPoint[0];
3360
            y = resultPoint[1];
3361

    
3362
            return targetConnector;
3363
        }
3364

    
3365
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3366
        {
3367
            LMConnector result = null;
3368
            List<LMConnector> connectors = new List<LMConnector>();
3369
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3370

    
3371
            if (modelItem != null)
3372
            {
3373
                foreach (LMRepresentation rep in modelItem.Representations)
3374
                {
3375
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3376
                        connectors.Add(dataSource.GetConnector(rep.Id));
3377
                }
3378

    
3379
                ReleaseCOMObjects(modelItem);
3380
            }
3381

    
3382
            if (connectors.Count == 1)
3383
                result = connectors[0];
3384
            else
3385
                foreach (var item in connectors)
3386
                    ReleaseCOMObjects(item);
3387

    
3388
            return result;
3389
        }
3390

    
3391
        /// <summary>
3392
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3393
        /// </summary>
3394
        /// <param name="lineNumber"></param>
3395
        private void LineNumberModelingOnlyOne(Line line)
3396
        {
3397
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3398
            if (lineNumber != null)
3399
            {
3400
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3401
                if (connectedLMConnector != null)
3402
                {
3403
                    double x = 0;
3404
                    double y = 0;
3405
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3406

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

    
3410
                    if (_LmLabelPresist != null)
3411
                    {
3412
                        _LmLabelPresist.Commit();
3413
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3414
                        ReleaseCOMObjects(_LmLabelPresist);
3415
                    }
3416
                }
3417
            }
3418
        }
3419

    
3420
        private void LineNumberModeling(LineNumber lineNumber)
3421
        {
3422
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3423
            if (line != null)
3424
            {
3425
                double x = 0;
3426
                double y = 0;
3427
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3428

    
3429
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3430
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3431
                if (connectedLMConnector != null)
3432
                {
3433
                    Array points = new double[] { 0, x, y };
3434
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3435

    
3436
                    if (_LmLabelPresist != null)
3437
                    {
3438
                        _LmLabelPresist.Commit();
3439
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3440
                        ReleaseCOMObjects(_LmLabelPresist);
3441
                    }
3442
                }
3443

    
3444
                foreach (var item in connectorVertices)
3445
                    ReleaseCOMObjects(item.Key);
3446
            }
3447
        }
3448
        /// <summary>
3449
        /// Flow Mark Modeling
3450
        /// </summary>
3451
        /// <param name="line"></param>
3452
        private void FlowMarkModeling(Line line)
3453
        {
3454
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3455
            {
3456
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3457
                if (connector != null)
3458
                {
3459
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3460
                    List<double[]> vertices = GetConnectorVertices(connector);
3461
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3462
                    double[] point = vertices[vertices.Count - 1];
3463
                    Array array = new double[] { 0, point[0], point[1] };
3464
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3465
                    if (_LMLabelPersist != null)
3466
                    {
3467
                        _LMLabelPersist.Commit();
3468
                        ReleaseCOMObjects(_LMLabelPersist);
3469
                    }
3470
                        
3471
                }
3472
            }
3473
        }
3474

    
3475
        /// <summary>
3476
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3477
        /// </summary>
3478
        /// <param name="lineNumber"></param>
3479
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3480
        {
3481
            foreach (LineRun run in lineNumber.RUNS)
3482
            {
3483
                foreach (var item in run.RUNITEMS)
3484
                {
3485
                    if (item.GetType() == typeof(Symbol))
3486
                    {
3487
                        Symbol symbol = item as Symbol;
3488
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3489
                        if (_LMSymbol != null)
3490
                        {
3491
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3492

    
3493
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3494
                            {
3495
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3496
                                {
3497
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3498
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3499
                                    {
3500
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3501
                                        if (_LMAAttribute != null)
3502
                                        {
3503
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3504
                                                _LMAAttribute.set_Value(attribute.VALUE);
3505
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3506
                                                _LMAAttribute.set_Value(attribute.VALUE);
3507
                                        }
3508
                                    }
3509
                                }
3510
                                _LMModelItem.Commit();
3511
                            }
3512
                            if (_LMModelItem != null)
3513
                                ReleaseCOMObjects(_LMModelItem);
3514
                        }
3515
                        if (_LMSymbol != null)
3516
                            ReleaseCOMObjects(_LMSymbol);
3517
                    }
3518
                    else if (item.GetType() == typeof(Line))
3519
                    {
3520
                        Line line = item as Line;
3521
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3522
                        {
3523
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3524
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3525
                            {
3526
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3527
                                {
3528
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3529
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3530
                                    {
3531
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3532
                                        if (_LMAAttribute != null)
3533
                                        {
3534
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3535
                                                _LMAAttribute.set_Value(attribute.VALUE);
3536
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3537
                                                _LMAAttribute.set_Value(attribute.VALUE);
3538

    
3539
                                        }
3540
                                    }
3541
                                }
3542
                                _LMModelItem.Commit();
3543
                            }
3544
                            if (_LMModelItem != null)
3545
                                ReleaseCOMObjects(_LMModelItem);
3546
                            endLine.Add(line.SPPID.ModelItemId);
3547
                        }
3548
                    }
3549
                }
3550
            }
3551
        }
3552

    
3553
        /// <summary>
3554
        /// Symbol Attribute 입력 메서드
3555
        /// </summary>
3556
        /// <param name="item"></param>
3557
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3558
        {
3559
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3560
            string sRep = null;
3561
            if (targetItem.GetType() == typeof(Symbol))
3562
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3563
            else if (targetItem.GetType() == typeof(Equipment))
3564
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3565

    
3566
            if (!string.IsNullOrEmpty(sRep))
3567
            {
3568
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3569
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3570
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3571
                
3572
                foreach (var item in targetAttributes)
3573
                {
3574
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3575
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3576
                    {
3577
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3578
                        if (_Attribute != null)
3579
                        {
3580
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3581
                            if (associItem != null)
3582
                            {
3583
                                if (associItem.GetType() == typeof(Text))
3584
                                {
3585
                                    Text text = associItem as Text;
3586
                                    text.SPPID.RepresentationId = "Attribute";
3587
                                }
3588
                                else if (associItem.GetType() == typeof(Note))
3589
                                {
3590
                                    Note note = associItem as Note;
3591
                                    note.SPPID.RepresentationId = "Attribute";
3592
                                }
3593
                            }
3594
                            _Attribute.set_Value(item.VALUE);
3595
                            // OPC 일경우 Attribute 저장
3596
                            if (targetItem.GetType() == typeof(Symbol))
3597
                            {
3598
                                Symbol symbol = targetItem as Symbol;
3599
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
3600
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
3601
                            }
3602
                        }
3603
                    }
3604
                }
3605
                _LMModelItem.Commit();
3606

    
3607
                ReleaseCOMObjects(_Attributes);
3608
                ReleaseCOMObjects(_LMModelItem);
3609
                ReleaseCOMObjects(_LMSymbol);
3610
            }
3611
        }
3612

    
3613
        /// <summary>
3614
        /// Input SpecBreak Attribute
3615
        /// </summary>
3616
        /// <param name="specBreak"></param>
3617
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3618
        {
3619
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3620
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3621

    
3622
            if (upStreamObj != null &&
3623
                downStreamObj != null)
3624
            {
3625
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3626

    
3627
                if (targetLMConnector != null)
3628
                {
3629
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3630
                    {
3631
                        string symbolPath = _LMLabelPersist.get_FileName();
3632
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3633
                        if (mapping != null)
3634
                        {
3635
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3636
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3637
                            {
3638
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3639
                                if (values.Length == 2)
3640
                                {
3641
                                    string upStreamValue = values[0];
3642
                                    string downStreamValue = values[1];
3643

    
3644
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3645
                                }
3646
                            }
3647
                        }
3648
                    }
3649

    
3650
                    ReleaseCOMObjects(targetLMConnector);
3651
                }
3652
            }
3653

    
3654

    
3655
            #region 내부에서만 쓰는 메서드
3656
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3657
            {
3658
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3659
                Line upStreamLine = _upStreamObj as Line;
3660
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3661
                Line downStreamLine = _downStreamObj as Line;
3662
                // 둘다 Line일 경우
3663
                if (upStreamLine != null && downStreamLine != null)
3664
                {
3665
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3666
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3667
                }
3668
                // 둘다 Symbol일 경우
3669
                else if (upStreamSymbol != null && downStreamSymbol != null)
3670
                {
3671
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3672
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3673
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3674

    
3675
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3676
                    {
3677
                        if (connector.get_ItemStatus() != "Active")
3678
                            continue;
3679

    
3680
                        if (connector.Id != zeroLenthConnector.Id)
3681
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3682
                    }
3683

    
3684
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3685
                    {
3686
                        if (connector.get_ItemStatus() != "Active")
3687
                            continue;
3688

    
3689
                        if (connector.Id != zeroLenthConnector.Id)
3690
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3691
                    }
3692

    
3693
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3694
                    {
3695
                        if (connector.get_ItemStatus() != "Active")
3696
                            continue;
3697

    
3698
                        if (connector.Id != zeroLenthConnector.Id)
3699
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3700
                    }
3701

    
3702
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3703
                    {
3704
                        if (connector.get_ItemStatus() != "Active")
3705
                            continue;
3706

    
3707
                        if (connector.Id != zeroLenthConnector.Id)
3708
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3709
                    }
3710

    
3711
                    ReleaseCOMObjects(zeroLenthConnector);
3712
                    ReleaseCOMObjects(upStreamLMSymbol);
3713
                    ReleaseCOMObjects(downStreamLMSymbol);
3714
                }
3715
                else if (upStreamSymbol != null && downStreamLine != null)
3716
                {
3717
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3718
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3719
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3720

    
3721
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3722
                    {
3723
                        if (connector.get_ItemStatus() != "Active")
3724
                            continue;
3725

    
3726
                        if (connector.Id == zeroLenthConnector.Id)
3727
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3728
                    }
3729

    
3730
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3731
                    {
3732
                        if (connector.get_ItemStatus() != "Active")
3733
                            continue;
3734

    
3735
                        if (connector.Id == zeroLenthConnector.Id)
3736
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3737
                    }
3738

    
3739
                    ReleaseCOMObjects(zeroLenthConnector);
3740
                    ReleaseCOMObjects(upStreamLMSymbol);
3741
                }
3742
                else if (upStreamLine != null && downStreamSymbol != null)
3743
                {
3744
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3745
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3746
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3747

    
3748
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3749
                    {
3750
                        if (connector.get_ItemStatus() != "Active")
3751
                            continue;
3752

    
3753
                        if (connector.Id == zeroLenthConnector.Id)
3754
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3755
                    }
3756

    
3757
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3758
                    {
3759
                        if (connector.get_ItemStatus() != "Active")
3760
                            continue;
3761

    
3762
                        if (connector.Id == zeroLenthConnector.Id)
3763
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3764
                    }
3765

    
3766
                    ReleaseCOMObjects(zeroLenthConnector);
3767
                    ReleaseCOMObjects(downStreamLMSymbol);
3768
                }
3769
            }
3770

    
3771
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3772
            {
3773
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3774
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3775
                {
3776
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3777
                    if (_LMAAttribute != null)
3778
                    {
3779
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3780
                            _LMAAttribute.set_Value(value);
3781
                        else if (_LMAAttribute.get_Value() != value)
3782
                            _LMAAttribute.set_Value(value);
3783
                    }
3784

    
3785
                    _LMModelItem.Commit();
3786
                }
3787
                if (_LMModelItem != null)
3788
                    ReleaseCOMObjects(_LMModelItem);
3789
            }
3790

    
3791
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3792
            {
3793
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3794
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3795
                {
3796
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3797
                    if (_LMAAttribute != null)
3798
                    {
3799
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3800
                            _LMAAttribute.set_Value(value);
3801
                        else if (_LMAAttribute.get_Value() != value)
3802
                            _LMAAttribute.set_Value(value);
3803
                    }
3804

    
3805
                    _LMModelItem.Commit();
3806
                }
3807
                if (_LMModelItem != null)
3808
                    ReleaseCOMObjects(_LMModelItem);
3809
            }
3810
            #endregion
3811
        }
3812

    
3813
        /// <summary>
3814
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3815
        /// </summary>
3816
        /// <param name="text"></param>
3817
        private void TextModeling(Text text, List<Text> correctList)
3818
        {
3819
            LMSymbol _LMSymbol = null;
3820
            LMConnector connectedLMConnector = null;
3821
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3822
            if (text.ASSOCIATION)
3823
            {
3824
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3825
                if (owner != null && owner.GetType() == typeof(Symbol))
3826
                {
3827
                    Symbol symbol = owner as Symbol;
3828
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3829
                    if (_LMSymbol != null)
3830
                    {
3831
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3832
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3833
                        {
3834
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3835

    
3836
                            if (mapping != null)
3837
                            {
3838
                                double x = 0;
3839
                                double y = 0;
3840

    
3841
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3842
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3843
                                Array array = new double[] { 0, x, y };
3844
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3845
                                if (_LMLabelPersist != null)
3846
                                {
3847
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3848
                                    _LMLabelPersist.Commit();
3849
                                    ReleaseCOMObjects(_LMLabelPersist);
3850
                                }
3851
                            }
3852
                        }
3853
                    }
3854
                }
3855
                else if (owner != null && owner.GetType() == typeof(Line))
3856
                {
3857
                    Line line = owner as Line;
3858
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3859
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3860

    
3861
                    if (connectedLMConnector != null)
3862
                    {
3863
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3864
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3865
                        {
3866
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3867

    
3868
                            if (mapping != null)
3869
                            {
3870
                                double x = 0;
3871
                                double y = 0;
3872
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3873
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3874
                                Array array = new double[] { 0, x, y };
3875

    
3876
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3877
                                if (_LMLabelPersist != null)
3878
                                {
3879
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3880
                                    _LMLabelPersist.Commit();
3881
                                    ReleaseCOMObjects(_LMLabelPersist);
3882
                                }
3883
                            }
3884
                        }
3885
                    }
3886
                }
3887
            }
3888
            else
3889
            {
3890
                LMItemNote _LMItemNote = null;
3891
                LMAAttribute _LMAAttribute = null;
3892

    
3893
                double x = 0;
3894
                double y = 0;
3895
                double angle = text.ANGLE;
3896
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3897

    
3898
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3899
                text.SPPID.SPPID_X = x;
3900
                text.SPPID.SPPID_Y = y;
3901

    
3902
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3903
                if (_LMSymbol != null)
3904
                {
3905
                    _LMSymbol.Commit();
3906
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3907
                    if (_LMItemNote != null)
3908
                    {
3909
                        _LMItemNote.Commit();
3910
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3911
                        if (_LMAAttribute != null)
3912
                        {
3913
                            _LMAAttribute.set_Value(text.VALUE);
3914
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3915
                            _LMItemNote.Commit();
3916

    
3917

    
3918
                            double[] range = null;
3919
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
3920
                            {
3921
                                double[] temp = null;
3922
                                GetSPPIDSymbolRange(labelPersist, ref temp);
3923
                                if (temp != null)
3924
                                {
3925
                                    if (range == null)
3926
                                        range = temp;
3927
                                    else
3928
                                    {
3929
                                        range = new double[] {
3930
                                            Math.Min(range[0], temp[0]),
3931
                                            Math.Min(range[1], temp[1]),
3932
                                            Math.Max(range[2], temp[2]),
3933
                                            Math.Max(range[3], temp[3])
3934
                                        };
3935
                                    }
3936
                                }
3937
                            }
3938
                            if (range != null)
3939
                                correctList.Add(text);
3940
                            text.SPPID.Range = range;
3941

    
3942

    
3943
                            if (_LMAAttribute != null)
3944
                                ReleaseCOMObjects(_LMAAttribute);
3945
                            if (_LMItemNote != null)
3946
                                ReleaseCOMObjects(_LMItemNote);
3947
                        }
3948
                    }
3949
                }
3950
            }
3951
            if (_LMSymbol != null)
3952
                ReleaseCOMObjects(_LMSymbol);
3953
        }
3954

    
3955
        private void TextCorrectModeling(Text text, List<Text> endList)
3956
        {
3957
            bool needRemodeling = false;
3958
            bool loop = true;
3959
            GridSetting gridSetting = GridSetting.GetInstance();
3960
            while (loop)
3961
            {
3962
                loop = false;
3963
                foreach (var overlapText in endList)
3964
                {
3965
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
3966
                    {
3967
                        double tempX = 0;
3968
                        double tempY = 0;
3969
                        bool overlapX = false;
3970
                        bool overlapY = false;
3971
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
3972
                        double angle = SPPIDUtil.CalcAngle(text.LOCATION_X, text.LOCATION_Y, overlapText.LOCATION_X, overlapText.LOCATION_Y);
3973
                        if (overlapY && angle >= 45)
3974
                        {
3975
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
3976
                            double move = gridSetting.Length * count;
3977
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
3978
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
3979
                            needRemodeling = true;
3980
                            loop = true;
3981
                        }
3982
                        if (overlapX && angle <= 45)
3983
                        {
3984
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
3985
                            double move = gridSetting.Length * count;
3986
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
3987
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
3988
                            needRemodeling = true;
3989
                            loop = true;
3990
                        }
3991
                    }
3992
                }
3993
            }
3994
            
3995

    
3996
            if (needRemodeling)
3997
            {
3998
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
3999
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4000
                text.SPPID.RepresentationId = null;
4001

    
4002
                LMItemNote _LMItemNote = null;
4003
                LMAAttribute _LMAAttribute = null;
4004
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
4005
                if (_LMSymbol != null)
4006
                {
4007
                    _LMSymbol.Commit();
4008
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4009
                    if (_LMItemNote != null)
4010
                    {
4011
                        _LMItemNote.Commit();
4012
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4013
                        if (_LMAAttribute != null)
4014
                        {
4015
                            _LMAAttribute.set_Value(text.VALUE);
4016
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4017
                            _LMItemNote.Commit();
4018

    
4019
                            ReleaseCOMObjects(_LMAAttribute);
4020
                            ReleaseCOMObjects(_LMItemNote);
4021
                        }
4022
                    }
4023
                }
4024

    
4025
                ReleaseCOMObjects(symbol);
4026
                symbol = null;
4027
                ReleaseCOMObjects(_LMItemNote);
4028
                _LMItemNote = null;
4029
                ReleaseCOMObjects(_LMAAttribute);
4030
                _LMAAttribute = null;
4031
                ReleaseCOMObjects(_LMSymbol);
4032
                _LMSymbol = null;
4033
            }
4034

    
4035
            endList.Add(text);
4036
        }
4037

    
4038
        /// <summary>
4039
        /// Note Modeling
4040
        /// </summary>
4041
        /// <param name="note"></param>
4042
        private void NoteModeling(Note note, List<Note> correctList)
4043
        {
4044
            LMSymbol _LMSymbol = null;
4045
            LMItemNote _LMItemNote = null;
4046
            LMAAttribute _LMAAttribute = null;
4047

    
4048
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
4049
            {
4050
                double x = 0;
4051
                double y = 0;
4052

    
4053
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
4054
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
4055
                note.SPPID.SPPID_X = x;
4056
                note.SPPID.SPPID_Y = y;
4057

    
4058
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
4059
                if (_LMSymbol != null)
4060
                {
4061
                    _LMSymbol.Commit();
4062
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4063
                    if (_LMItemNote != null)
4064
                    {
4065
                        _LMItemNote.Commit();
4066
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4067
                        if (_LMAAttribute != null)
4068
                        {
4069
                            _LMAAttribute.set_Value(note.VALUE);
4070
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4071

    
4072
                            double[] range = null;
4073
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4074
                            {
4075
                                double[] temp = null;
4076
                                GetSPPIDSymbolRange(labelPersist, ref temp);
4077
                                if (temp != null)
4078
                                {
4079
                                    if (range == null)
4080
                                        range = temp;
4081
                                    else
4082
                                    {
4083
                                        range = new double[] {
4084
                                            Math.Min(range[0], temp[0]),
4085
                                            Math.Min(range[1], temp[1]),
4086
                                            Math.Max(range[2], temp[2]),
4087
                                            Math.Max(range[3], temp[3])
4088
                                        };
4089
                                    }
4090
                                }
4091
                            }
4092
                            if (range != null)
4093
                                correctList.Add(note);
4094
                            note.SPPID.Range = range;
4095

    
4096

    
4097
                            _LMItemNote.Commit();
4098
                        }
4099
                    }
4100
                }
4101
            }
4102

    
4103
            if (_LMAAttribute != null)
4104
                ReleaseCOMObjects(_LMAAttribute);
4105
            if (_LMItemNote != null)
4106
                ReleaseCOMObjects(_LMItemNote);
4107
            if (_LMSymbol != null)
4108
                ReleaseCOMObjects(_LMSymbol);
4109
        }
4110

    
4111
        private void NoteCorrectModeling(Note note, List<Note> endList)
4112
        {
4113
            bool needRemodeling = false;
4114
            bool loop = true;
4115
            GridSetting gridSetting = GridSetting.GetInstance();
4116
            while (loop)
4117
            {
4118
                loop = false;
4119
                foreach (var overlap in endList)
4120
                {
4121
                    if (overlap.SPPID.Range != null && note.SPPID.Range !=null)
4122
                    {
4123
                        if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
4124
                        {
4125
                            double tempX = 0;
4126
                            double tempY = 0;
4127
                            bool overlapX = false;
4128
                            bool overlapY = false;
4129
                            SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4130
                            double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
4131
                            if (overlapY && angle >= 45)
4132
                            {
4133
                                int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4134
                                double move = gridSetting.Length * count;
4135
                                note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
4136
                                note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
4137
                                needRemodeling = true;
4138
                                loop = true;
4139
                            }
4140
                            if (overlapX && angle <= 45)
4141
                            {
4142
                                int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4143
                                double move = gridSetting.Length * count;
4144
                                note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
4145
                                note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
4146
                                needRemodeling = true;
4147
                                loop = true;
4148
                            }
4149
                        }
4150
                    }
4151
                    else
4152
                    {
4153

    
4154
                    }
4155
                   
4156
                }
4157
            }
4158

    
4159

    
4160
            if (needRemodeling)
4161
            {
4162
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
4163
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4164
                note.SPPID.RepresentationId = null;
4165

    
4166
                LMItemNote _LMItemNote = null;
4167
                LMAAttribute _LMAAttribute = null;
4168
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
4169
                if (_LMSymbol != null)
4170
                {
4171
                    _LMSymbol.Commit();
4172
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4173
                    if (_LMItemNote != null)
4174
                    {
4175
                        _LMItemNote.Commit();
4176
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4177
                        if (_LMAAttribute != null)
4178
                        {
4179
                            _LMAAttribute.set_Value(note.VALUE);
4180
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4181
                            _LMItemNote.Commit();
4182

    
4183
                            ReleaseCOMObjects(_LMAAttribute);
4184
                            ReleaseCOMObjects(_LMItemNote);
4185
                        }
4186
                    }
4187
                }
4188

    
4189
                ReleaseCOMObjects(symbol);
4190
                symbol = null;
4191
                ReleaseCOMObjects(_LMItemNote);
4192
                _LMItemNote = null;
4193
                ReleaseCOMObjects(_LMAAttribute);
4194
                _LMAAttribute = null;
4195
                ReleaseCOMObjects(_LMSymbol);
4196
                _LMSymbol = null;
4197
            }
4198

    
4199
            endList.Add(note);
4200
        }
4201

    
4202
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
4203
        {
4204
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4205
            if (modelItem != null)
4206
            {
4207
                foreach (LMRepresentation rep in modelItem.Representations)
4208
                {
4209
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4210
                    {
4211
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4212
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4213
                        {
4214
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
4215
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4216
                            if (modelItemIds.Count == 1)
4217
                            {
4218
                                string joinModelItemId = modelItemIds[0];
4219
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4220
                                if (survivorId != null)
4221
                                    break;
4222
                            }
4223
                        }
4224
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4225
                        {
4226
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
4227
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4228
                            if (modelItemIds.Count == 1)
4229
                            {
4230
                                string joinModelItemId = modelItemIds[0];
4231
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4232
                                if (survivorId != null)
4233
                                    break;
4234
                            }
4235
                        }
4236
                    }
4237
                }
4238
            }
4239
        }
4240

    
4241
        /// <summary>
4242
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
4243
        /// </summary>
4244
        /// <param name="x"></param>
4245
        /// <param name="y"></param>
4246
        /// <param name="originX"></param>
4247
        /// <param name="originY"></param>
4248
        /// <param name="SPPIDLabelLocation"></param>
4249
        /// <param name="location"></param>
4250
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
4251
        {
4252
            if (location == Location.None)
4253
            {
4254
                x = originX;
4255
                y = originY;
4256
            }
4257
            else
4258
            {
4259
                if (location.HasFlag(Location.Center))
4260
                {
4261
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
4262
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
4263
                }
4264

    
4265
                if (location.HasFlag(Location.Left))
4266
                    x = SPPIDLabelLocation.X1;
4267
                else if (location.HasFlag(Location.Right))
4268
                    x = SPPIDLabelLocation.X2;
4269

    
4270
                if (location.HasFlag(Location.Down))
4271
                    y = SPPIDLabelLocation.Y1;
4272
                else if (location.HasFlag(Location.Up))
4273
                    y = SPPIDLabelLocation.Y2;
4274
            }
4275
        }
4276

    
4277
        /// <summary>
4278
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
4279
        /// 1. Angle Valve
4280
        /// 2. 3개로 이루어진 Symbol Group
4281
        /// </summary>
4282
        /// <returns></returns>
4283
        private List<Symbol> GetPrioritySymbol()
4284
        {
4285
            DataTable symbolTable = document.SymbolTable;
4286
            // List에 순서대로 쌓는다.
4287
            List<Symbol> symbols = new List<Symbol>();
4288

    
4289
            // Angle Valve 부터
4290
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
4291
            {
4292
                if (!symbols.Contains(symbol))
4293
                {
4294
                    double originX = 0;
4295
                    double originY = 0;
4296

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

    
4301
                    SlopeType slopeType1 = SlopeType.None;
4302
                    SlopeType slopeType2 = SlopeType.None;
4303
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
4304
                    {
4305
                        double connectorX = 0;
4306
                        double connectorY = 0;
4307
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
4308
                        if (slopeType1 == SlopeType.None)
4309
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
4310
                        else
4311
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
4312
                    }
4313

    
4314
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
4315
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
4316
                        symbols.Add(symbol);
4317
                }
4318
            }
4319

    
4320
            List<Symbol> tempSymbols = new List<Symbol>();
4321
            // Conn 갯수 기준
4322
            foreach (var item in document.SYMBOLS)
4323
            {
4324
                if (!symbols.Contains(item))
4325
                    tempSymbols.Add(item);
4326
            }
4327
            tempSymbols.Sort(SortSymbolPriority);
4328
            symbols.AddRange(tempSymbols);
4329

    
4330
            return symbols;
4331
        }
4332

    
4333
        private void SetPriorityLine(List<Line> lines)
4334
        {
4335
            lines.Sort(SortLinePriority);
4336

    
4337
            int SortLinePriority(Line a, Line b)
4338
            {
4339
                // Branch 없는것부터
4340
                int branchRetval = CompareBranchLine(a, b);
4341
                if (branchRetval != 0)
4342
                {
4343
                    return branchRetval;
4344
                }
4345
                else
4346
                {
4347
                    // Symbol 연결 갯수
4348
                    int connSymbolRetval = CompareConnSymbol(a, b);
4349
                    if (connSymbolRetval != 0)
4350
                    {
4351
                        return connSymbolRetval;
4352
                    }
4353
                    else
4354
                    {
4355
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
4356
                        int connItemRetval = CompareConnItem(a, b);
4357
                        if (connItemRetval != 0)
4358
                        {
4359
                            return connItemRetval;
4360
                        }
4361
                        else
4362
                        {
4363
                            // ConnectedItem이 없는것
4364
                            int noneConnRetval = CompareNoneConn(a, b);
4365
                            if (noneConnRetval != 0)
4366
                            {
4367
                                return noneConnRetval;
4368
                            }
4369
                            else
4370
                            {
4371

    
4372
                            }
4373
                        }
4374
                    }
4375
                }
4376

    
4377
                return 0;
4378
            }
4379

    
4380
            int CompareNotSegmentLine(Line a, Line b)
4381
            {
4382
                List<Connector> connectorsA = a.CONNECTORS
4383
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4384
                    .ToList();
4385

    
4386
                List<Connector> connectorsB = b.CONNECTORS
4387
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4388
                    .ToList();
4389

    
4390
                // 오름차순
4391
                return connectorsB.Count.CompareTo(connectorsA.Count);
4392
            }
4393

    
4394
            int CompareConnSymbol(Line a, Line b)
4395
            {
4396
                List<Connector> connectorsA = a.CONNECTORS
4397
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4398
                    .ToList();
4399

    
4400
                List<Connector> connectorsB = b.CONNECTORS
4401
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4402
                    .ToList();
4403

    
4404
                // 오름차순
4405
                return connectorsB.Count.CompareTo(connectorsA.Count);
4406
            }
4407

    
4408
            int CompareConnItem(Line a, Line b)
4409
            {
4410
                List<Connector> connectorsA = a.CONNECTORS
4411
                    .Where(conn => conn.ConnectedObject != null && 
4412
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
4413
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
4414
                    .ToList();
4415

    
4416
                List<Connector> connectorsB = b.CONNECTORS
4417
                    .Where(conn => conn.ConnectedObject != null &&
4418
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4419
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4420
                    .ToList();
4421

    
4422
                // 오름차순
4423
                return connectorsB.Count.CompareTo(connectorsA.Count);
4424
            }
4425

    
4426
            int CompareBranchLine(Line a, Line b)
4427
            {
4428
                List<Connector> connectorsA = a.CONNECTORS
4429
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
4430
                    .ToList();
4431
                List<Connector> connectorsB = b.CONNECTORS
4432
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
4433
                    .ToList();
4434

    
4435
                // 내림차순
4436
                return connectorsA.Count.CompareTo(connectorsB.Count);
4437
            }
4438

    
4439
            int CompareNoneConn(Line a, Line b)
4440
            {
4441
                List<Connector> connectorsA = a.CONNECTORS
4442
                    .Where(conn => conn.ConnectedObject == null)
4443
                    .ToList();
4444

    
4445
                List<Connector> connectorsB = b.CONNECTORS
4446
                    .Where(conn => conn.ConnectedObject == null)
4447
                    .ToList();
4448

    
4449
                // 오름차순
4450
                return connectorsB.Count.CompareTo(connectorsA.Count);
4451
            }
4452
        }
4453

    
4454
        private void SortText(List<Text> texts)
4455
        {
4456
            texts.Sort(Sort);
4457

    
4458
            int Sort(Text a, Text b)
4459
            {
4460
                int yRetval = CompareY(a, b);
4461
                if (yRetval != 0)
4462
                {
4463
                    return yRetval;
4464
                }
4465
                else
4466
                {
4467
                    return CompareX(a, b);
4468
                }
4469
            }
4470

    
4471
            int CompareY(Text a, Text b)
4472
            {
4473
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
4474
            }
4475

    
4476
            int CompareX(Text a, Text b)
4477
            {
4478
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
4479
            }
4480
        }
4481
        private void SortNote(List<Note> notes)
4482
        {
4483
            notes.Sort(Sort);
4484

    
4485
            int Sort(Note a, Note b)
4486
            {
4487
                int yRetval = CompareY(a, b);
4488
                if (yRetval != 0)
4489
                {
4490
                    return yRetval;
4491
                }
4492
                else
4493
                {
4494
                    return CompareX(a, b);
4495
                }
4496
            }
4497

    
4498
            int CompareY(Note a, Note b)
4499
            {
4500
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
4501
            }
4502

    
4503
            int CompareX(Note a, Note b)
4504
            {
4505
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
4506
            }
4507
        }
4508

    
4509
        private void SortBranchLines()
4510
        {
4511
            BranchLines.Sort(SortBranchLine);
4512
            int SortBranchLine(Line a, Line b)
4513
            {
4514
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4515
                 x.ConnectedObject.GetType() == typeof(Line) &&
4516
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
4517
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4518

    
4519
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4520
                 x.ConnectedObject.GetType() == typeof(Line) &&
4521
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4522
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4523

    
4524
                // 내림차순
4525
                return countA.CompareTo(countB);
4526
            }
4527
        }
4528

    
4529
        private static int SortSymbolPriority(Symbol a, Symbol b)
4530
        {
4531
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4532
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4533
            int retval = countB.CompareTo(countA);
4534
            if (retval != 0)
4535
                return retval;
4536
            else
4537
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
4538
        }
4539

    
4540
        private string GetSPPIDFileName(LMModelItem modelItem)
4541
        {
4542
            string symbolPath = null;
4543
            foreach (LMRepresentation rep in modelItem.Representations)
4544
            {
4545
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4546
                {
4547
                    symbolPath = rep.get_FileName();
4548
                    break;
4549
                }
4550
            }
4551
            return symbolPath;
4552
        }
4553

    
4554
        private string GetSPPIDFileName(string modelItemId)
4555
        {
4556
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4557
            string symbolPath = null;
4558
            foreach (LMRepresentation rep in modelItem.Representations)
4559
            {
4560
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4561
                {
4562
                    symbolPath = rep.get_FileName();
4563
                    break;
4564
                }
4565
            }
4566
            ReleaseCOMObjects(modelItem);
4567
            return symbolPath;
4568
        }
4569

    
4570
        /// <summary>
4571
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
4572
        /// </summary>
4573
        /// <param name="graphicOID"></param>
4574
        /// <param name="milliseconds"></param>
4575
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
4576
        {
4577
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
4578
            {
4579
                double minX = 0;
4580
                double minY = 0;
4581
                double maxX = 0;
4582
                double maxY = 0;
4583
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
4584
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
4585

    
4586
                Thread.Sleep(milliseconds);
4587
            }
4588
        }
4589

    
4590
        /// <summary>
4591
        /// ComObject를 Release
4592
        /// </summary>
4593
        /// <param name="objVars"></param>
4594
        public void ReleaseCOMObjects(params object[] objVars)
4595
        {
4596
            if (objVars != null)
4597
            {
4598
                int intNewRefCount = 0;
4599
                foreach (object obj in objVars)
4600
                {
4601
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
4602
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
4603
                }
4604
            }
4605
        }
4606

    
4607
        /// IDisposable 구현
4608
        ~AutoModeling()
4609
        {
4610
            this.Dispose(false);
4611
        }
4612

    
4613
        private bool disposed;
4614
        public void Dispose()
4615
        {
4616
            this.Dispose(true);
4617
            GC.SuppressFinalize(this);
4618
        }
4619

    
4620
        protected virtual void Dispose(bool disposing)
4621
        {
4622
            if (this.disposed) return;
4623
            if (disposing)
4624
            {
4625
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
4626
            }
4627
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
4628
            this.disposed = true;
4629
        }
4630
    }
4631
}