프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ e27329d6

이력 | 보기 | 이력해설 | 다운로드 (247 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, 21);
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
                    RunClearNominalDiameter();
102
                    // Join SameConnector
103
                    RunJoinRunForSameConnector();
104
                    // Join Run
105
                    RunJoinRun();
106
                    // Check FlowDirection
107
                    RunFlowDirection();
108
                    // EndBreak Modeling
109
                    RunEndBreakModeling();
110
                    // SpecBreak Modeling
111
                    RunSpecBreakModeling();
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
                    // Correct Text
127
                    RunCorrectAssociationText();
128

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

    
154
                Log.Write("End Modeling");
155
                radApp.ActiveWindow.Fit();
156

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

    
174
                ReleaseCOMObjects(dataSource);
175
                dataSource = null;
176
                ReleaseCOMObjects(_placement);
177
                _placement = null;
178

    
179
                Thread.Sleep(1000);
180
            }
181
        }
182

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

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

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

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

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

    
273
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
274
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
275
            foreach (var item in stepLast_Line)
276
            {
277
                try
278
                {
279
                    NewLineModeling(item);
280
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
281
                }
282
                catch (Exception ex)
283
                {
284
                    Log.Write("Error in NewLineModeling");
285
                    Log.Write("UID : " + item.UID);
286
                    Log.Write(ex.Message);
287
                    Log.Write(ex.StackTrace);
288
                }
289
            }
290
        }
291
        private void RunClearNominalDiameter()
292
        {
293
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
294
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
295
            List<string> endClearModelItemID = new List<string>();
296
            for (int i = 0; i < document.LINES.Count; i++)
297
            {
298
                Line item = document.LINES[i];
299
                string modelItemID = item.SPPID.ModelItemId;
300
                if (!string.IsNullOrEmpty(modelItemID))
301
                {
302
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
303
                    if (modelItem != null)
304
                    {
305
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
306
                        if (attribute != null)
307
                            attribute.set_Value(DBNull.Value);
308

    
309
                        modelItem.Commit();
310
                        ReleaseCOMObjects(modelItem);
311
                        modelItem = null;
312
                    }
313
                }
314
                if (!endClearModelItemID.Contains(modelItemID))
315
                    endClearModelItemID.Add(modelItemID);
316
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
317
            }
318
            for (int i = 0; i < document.SYMBOLS.Count; i++)
319
            {
320
                Symbol item = document.SYMBOLS[i];
321
                string repID = item.SPPID.RepresentationId;
322
                string modelItemID = item.SPPID.ModelItemID;
323
                if (!string.IsNullOrEmpty(modelItemID))
324
                {
325
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
326
                    if (modelItem != null)
327
                    {
328
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
329
                        if (attribute != null)
330
                            attribute.set_Value(DBNull.Value);
331
                        int index = 1;
332
                        while (true)
333
                        {
334
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
335
                            if (attribute != null)
336
                                attribute.set_Value(DBNull.Value);
337
                            else
338
                                break;
339
                            index++;
340
                        }
341
                        modelItem.Commit();
342
                        ReleaseCOMObjects(modelItem);
343
                        modelItem = null;
344
                    }
345
                }
346
                if (!string.IsNullOrEmpty(repID))
347
                {
348
                    LMSymbol symbol = dataSource.GetSymbol(repID);
349
                    if (symbol != null)
350
                    {
351
                        foreach (LMConnector connector in symbol.Connect1Connectors)
352
                        {
353
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
354
                            {
355
                                endClearModelItemID.Add(connector.ModelItemID);
356
                                LMModelItem modelItem = connector.ModelItemObject;
357
                                if (modelItem != null)
358
                                {
359
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
360
                                    if (attribute != null)
361
                                        attribute.set_Value(DBNull.Value);
362

    
363
                                    modelItem.Commit();
364
                                    ReleaseCOMObjects(modelItem);
365
                                    modelItem = null;
366
                                }
367
                            }
368
                        }
369
                        foreach (LMConnector connector in symbol.Connect2Connectors)
370
                        {
371
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
372
                            {
373
                                endClearModelItemID.Add(connector.ModelItemID);
374
                                LMModelItem modelItem = connector.ModelItemObject;
375
                                if (modelItem != null)
376
                                {
377
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
378
                                    if (attribute != null)
379
                                        attribute.set_Value(DBNull.Value);
380

    
381
                                    modelItem.Commit();
382
                                    ReleaseCOMObjects(modelItem);
383
                                    modelItem = null;
384
                                }
385
                            }
386
                        }
387
                    }
388
                    ReleaseCOMObjects(symbol);
389
                    symbol = null;
390
                }
391
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
392
            }
393
        }
394
        private void RunClearValueInconsistancy()
395
        {
396
            int count = 1;
397
            bool loop = true;
398
            while (loop)
399
            {
400
                loop = false;
401
                LMAFilter filter = new LMAFilter();
402
                LMACriterion criterion = new LMACriterion();
403
                filter.ItemType = "Relationship";
404
                criterion.SourceAttributeName = "SP_DRAWINGID";
405
                criterion.Operator = "=";
406
                criterion.set_ValueAttribute(drawingID);
407
                filter.get_Criteria().Add(criterion);
408

    
409
                LMRelationships relationships = new LMRelationships();
410
                relationships.Collect(dataSource, Filter: filter);
411

    
412
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
413
                if (count > 1)
414
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
415
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
416
                foreach (LMRelationship relationship in relationships)
417
                {
418
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
419
                    {
420
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
421
                        {
422
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
423
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
424
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
425
                            if (modelItem1 != null)
426
                            {
427
                                string attrName = array[0];
428
                                if (attrName.Contains("PipingPoint"))
429
                                {
430
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
431
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
432
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
433
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
434
                                    {
435
                                        loop = true;
436
                                        attribute1.set_Value(DBNull.Value);
437
                                    }
438
                                    attribute1 = null;
439
                                }
440
                                else
441
                                {
442
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
443
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
444
                                    {
445
                                        loop = true;
446
                                        attribute1.set_Value(DBNull.Value);
447
                                    }
448
                                    attribute1 = null;
449
                                }
450
                                modelItem1.Commit();
451
                            }
452
                            if (modelItem2 != null)
453
                            {
454
                                string attrName = array[1];
455
                                if (attrName.Contains("PipingPoint"))
456
                                {
457
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
458
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
459
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
460
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
461
                                    {
462
                                        attribute2.set_Value(DBNull.Value);
463
                                        loop = true;
464
                                    }
465
                                    attribute2 = null;
466
                                }
467
                                else
468
                                {
469
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
470
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
471
                                    {
472
                                        attribute2.set_Value(DBNull.Value);
473
                                        loop = true;
474
                                    }
475
                                    attribute2 = null;
476
                                }
477
                                modelItem2.Commit();
478
                            }
479
                            ReleaseCOMObjects(modelItem1);
480
                            modelItem1 = null;
481
                            ReleaseCOMObjects(modelItem2);
482
                            modelItem2 = null;
483
                            inconsistency.Commit();
484
                        }
485
                        ReleaseCOMObjects(inconsistency);
486
                    }
487
                    relationship.Commit();
488
                    ReleaseCOMObjects(relationship);
489
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
490
                }
491
                ReleaseCOMObjects(filter);
492
                filter = null;
493
                ReleaseCOMObjects(criterion);
494
                criterion = null;
495
                ReleaseCOMObjects(relationships);
496
                relationships = null;
497
                count++;
498
            }
499
        }
500
        private void RunEndBreakModeling()
501
        {
502
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
503
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
504
            foreach (var item in document.EndBreaks)
505
                try
506
                {
507
                    EndBreakModeling(item);
508
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
509
                }
510
                catch (Exception ex)
511
                {
512
                    Log.Write("Error in EndBreakModeling");
513
                    Log.Write("UID : " + item.UID);
514
                    Log.Write(ex.Message);
515
                    Log.Write(ex.StackTrace);
516
                }
517
        }
518
        private void RunSpecBreakModeling()
519
        {
520
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
521
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
522
            foreach (var item in document.SpecBreaks)
523
                try
524
                {
525
                    SpecBreakModeling(item);
526
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
527
                }
528
                catch (Exception ex)
529
                {
530
                    Log.Write("Error in SpecBreakModeling");
531
                    Log.Write("UID : " + item.UID);
532
                    Log.Write(ex.Message);
533
                    Log.Write(ex.StackTrace);
534
                }
535
        }
536
        private void RunJoinRunForSameConnector()
537
        {
538
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
539
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
540
            foreach (var line in document.LINES)
541
            {
542
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
543
                List<List<double[]>> result = new List<List<double[]>>();
544
                foreach (var item in vertices)
545
                {
546
                    ReleaseCOMObjects(item.Key);
547
                    result.Add(item.Value);
548
                }
549
                line.SPPID.Vertices = result;
550
                vertices = null;
551
            }
552

    
553
            foreach (var line in document.LINES)
554
            {
555
                foreach (var connector in line.CONNECTORS)
556
                {
557
                    if (connector.ConnectedObject != null &&
558
                        connector.ConnectedObject.GetType() == typeof(Line) &&
559
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
560
                    {
561
                        Line connLine = connector.ConnectedObject as Line;
562
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
563
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
564
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
565
                            !SPPIDUtil.IsSegment(document, line, connLine))
566
                        {
567
                            string survivorId = string.Empty;
568
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
569
                        }
570

    
571
                    }
572
                }
573
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
574
            }
575

    
576
            foreach (var line in document.LINES)
577
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
578
        }
579
        private void RunJoinRun()
580
        {
581
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
582
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
583
            List<string> endModelID = new List<string>();
584
            foreach (var line in document.LINES)
585
            {
586
                if (!endModelID.Contains(line.SPPID.ModelItemId))
587
                {
588
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
589
                    {
590
                        string survivorId = string.Empty;
591
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
592
                        if (string.IsNullOrEmpty(survivorId))
593
                        {
594
                            endModelID.Add(line.SPPID.ModelItemId);
595
                        }
596
                    }
597
                }
598
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
599
            }
600
        }
601
        private void RunLineNumberModeling()
602
        {
603
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
604
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
605
            foreach (var item in document.LINENUMBERS)
606
            {
607
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
608
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
609
                {
610
                    ReleaseCOMObjects(label);
611
                    item.SPPID.RepresentationId = null;
612
                    LineNumberModeling(item);
613
                }
614
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
615
            }
616
        }
617
        private void RunFlowDirection()
618
        {
619
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 
620
                document.LINES.Count + ZeroLengthModelItemID.Count + ZeroLengthModelItemIDReverse.Count + ZeroLengthSymbolToSymbolModelItemID.Count);
621
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Check Flow Direction");
622
            foreach (var line in document.LINES)
623
            {
624
                if (!string.IsNullOrEmpty(line.SPPID.ModelItemId))
625
                {
626
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
627
                    if (modelItem != null && modelItem.get_ItemStatus() == "Active")
628
                    {
629
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
630
                        if (attribute != null)
631
                        {
632
                            attribute.set_Value("End 1 is upstream (Inlet)");
633
                            modelItem.Commit();
634
                        }
635

    
636
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
637

    
638
                        ReleaseCOMObjects(modelItem);
639
                        modelItem = null;
640
                    }
641
                }
642

    
643
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
644
            }
645
            foreach (var modelId in ZeroLengthModelItemID)
646
            {
647
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
648
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
649
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
650
                {
651
                    attribute.set_Value("End 1 is upstream (Inlet)");
652
                    zeroLengthModelItem.Commit();
653
                }
654

    
655
                SetFlowDirectionByLine(modelId);
656

    
657
                ReleaseCOMObjects(zeroLengthModelItem);
658
                zeroLengthModelItem = null;
659

    
660
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
661
            }
662
            foreach (var modelId in ZeroLengthModelItemIDReverse)
663
            {
664
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
665
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
666
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
667
                {
668
                    attribute.set_Value("End 1 is downstream (Outlet)");
669
                    zeroLengthModelItem.Commit();
670
                }
671

    
672
                SetFlowDirectionByLine(modelId);
673

    
674
                ReleaseCOMObjects(zeroLengthModelItem);
675
                zeroLengthModelItem = null;
676

    
677
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
678
            }
679
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
680
            {
681
                SetFlowDirectionByLine(modelId);
682
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
683
            }
684

    
685
            void SetFlowDirectionByLine(string lineModelItemID)
686
            {
687
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
688
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
689
                {
690
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
691
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
692
                    {
693
                        string sFlowDirection = attribute.get_Value().ToString();
694
                        foreach (LMRepresentation rep in modelItem.Representations)
695
                        {
696
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
697
                            {
698
                                LMConnector connector = dataSource.GetConnector(rep.Id);
699

    
700
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
701
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
702
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
703
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
704

    
705
                                ReleaseCOMObjects(connector);
706
                            }
707
                        }
708
                    }
709
                    ReleaseCOMObjects(modelItem);
710
                    modelItem = null;
711
                }
712

    
713
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
714
                {
715
                    // Item2가 Symbol
716
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
717
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
718
                    {
719
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
720
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
721
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
722

    
723
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
724

    
725
                        symbolModelItem.Commit();
726
                        ReleaseCOMObjects(symbolModelItem);
727
                        symbolModelItem = null;
728
                    }
729
                    // Item1이 Symbol
730
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
731
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
732
                    {
733
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
734
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
735
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
736

    
737
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
738

    
739
                        symbolModelItem.Commit();
740
                        ReleaseCOMObjects(symbolModelItem);
741
                        symbolModelItem = null;
742
                    }
743
                }
744

    
745
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
746
                {
747
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
748
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
749
                    if (attribute != null)
750
                    {
751
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
752
                            attribute.set_Value("End 1 is downstream (Outlet)");
753
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
754
                            attribute.set_Value("End 1 is upstream (Inlet)");
755
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
756
                            attribute.set_Value("End 1 is upstream (Inlet)");
757
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
758
                            attribute.set_Value("End 1 is downstream (Outlet)");
759
                    }
760
                }
761
            }
762
        }
763
        private void RunNoteModeling()
764
        {
765
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
766
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
767
            List<Note> correctList = new List<Note>();
768
            foreach (var item in document.NOTES)
769
                try
770
                {
771
                    NoteModeling(item, correctList);
772
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
773
                }
774
                catch (Exception ex)
775
                {
776
                    Log.Write("Error in NoteModeling");
777
                    Log.Write("UID : " + item.UID);
778
                    Log.Write(ex.Message);
779
                    Log.Write(ex.StackTrace);
780
                }
781

    
782
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
783
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
784
            SortNote(correctList);
785
            List<Note> endList = new List<Note>();
786
            if (correctList.Count > 0)
787
                endList.Add(correctList[0]);
788
            foreach (var item in correctList)
789
                try
790
                {
791
                    if (!endList.Contains(item))
792
                        NoteCorrectModeling(item, endList);
793
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
794
                }
795
                catch (Exception ex)
796
                {
797
                    Log.Write("Error in NoteModeling");
798
                    Log.Write("UID : " + item.UID);
799
                    Log.Write(ex.Message);
800
                    Log.Write(ex.StackTrace);
801
                }
802
        }
803
        private void RunTextModeling()
804
        {
805
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
806
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
807
            SortText(document.TEXTINFOS);
808
            foreach (var item in document.TEXTINFOS)
809
                try
810
                {
811
                    if (item.ASSOCIATION)
812
                        AssociationTextModeling(item);
813
                    else
814
                        NormalTextModeling(item);
815
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
816
                }
817
                catch (Exception ex)
818
                {
819
                    Log.Write("Error in TextModeling");
820
                    Log.Write("UID : " + item.UID);
821
                    Log.Write(ex.Message);
822
                    Log.Write(ex.StackTrace);
823
                }
824
        }
825
        private void RunInputLineNumberAttribute()
826
        {
827
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
828
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
829
            List<string> endLine = new List<string>();
830
            foreach (var item in document.LINENUMBERS)
831
                try
832
                {
833
                    InputLineNumberAttribute(item, endLine);
834
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
835
                }
836
                catch (Exception ex)
837
                {
838
                    Log.Write("Error in InputLineNumberAttribute");
839
                    Log.Write("UID : " + item.UID);
840
                    Log.Write(ex.Message);
841
                    Log.Write(ex.StackTrace);
842
                }
843
        }
844
        private void RunInputSymbolAttribute()
845
        {
846
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
847
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
848
            foreach (var item in document.SYMBOLS)
849
                try
850
                {
851
                    InputSymbolAttribute(item, item.ATTRIBUTES);
852
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
853
                }
854
                catch (Exception ex)
855
                {
856
                    Log.Write("Error in InputSymbolAttribute");
857
                    Log.Write("UID : " + item.UID);
858
                    Log.Write(ex.Message);
859
                    Log.Write(ex.StackTrace);
860
                }
861
        }
862
        private void RunInputSpecBreakAttribute()
863
        {
864
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
865
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
866
            foreach (var item in document.SpecBreaks)
867
                try
868
                {
869
                    InputSpecBreakAttribute(item);
870
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
871
                }
872
                catch (Exception ex)
873
                {
874
                    Log.Write("Error in InputSpecBreakAttribute");
875
                    Log.Write("UID : " + item.UID);
876
                    Log.Write(ex.Message);
877
                    Log.Write(ex.StackTrace);
878
                }
879
        }
880
        private void RunLabelSymbolModeling()
881
        {
882
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
883
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
884
            foreach (var item in document.SYMBOLS)
885
                try
886
                {
887
                    LabelSymbolModeling(item);
888
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
889
                }
890
                catch (Exception ex)
891
                {
892
                    Log.Write("Error in LabelSymbolModeling");
893
                    Log.Write("UID : " + item.UID);
894
                    Log.Write(ex.Message);
895
                    Log.Write(ex.StackTrace);
896
                }
897
        }
898
        private void RunCorrectAssociationText()
899
        {
900
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
901
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
902
            List<Text> endTexts = new List<Text>();
903
            foreach (var item in document.TEXTINFOS)
904
            {
905
                try
906
                {
907
                    if (item.ASSOCIATION && !endTexts.Contains(item))
908
                        AssociationTextCorrectModeling(item, endTexts);
909
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
910
                }
911
                catch (Exception ex)
912
                {
913
                    Log.Write("Error in RunCorrectAssociationText");
914
                    Log.Write("UID : " + item.UID);
915
                    Log.Write(ex.Message);
916
                    Log.Write(ex.StackTrace);
917
                }
918
                
919
            }
920

    
921
            foreach (var item in document.LINENUMBERS)
922
            {
923
                try
924
                {
925
                    LineNumberCorrectModeling(item);
926
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
927
                }
928
                catch (Exception ex)
929
                {
930
                    Log.Write("Error in RunCorrectAssociationText");
931
                    Log.Write("UID : " + item.UID);
932
                    Log.Write(ex.Message);
933
                    Log.Write(ex.StackTrace);
934
                }
935
            }
936
        }
937
        /// <summary>
938
        /// 도면 생성 메서드
939
        /// </summary>
940
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
941
        {
942
            Log.Write("------------------ Start create document ------------------");
943
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
944
            Log.Write("Drawing name : " + drawingName);
945
            Log.Write("Drawing number : " + drawingNumber);
946
            Thread.Sleep(1000);
947
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
948
            if (newDrawing != null)
949
            {
950
                document.SPPID_DrawingNumber = drawingNumber;
951
                document.SPPID_DrawingName = drawingName;
952
                Thread.Sleep(1000);
953
                radApp.ActiveWindow.Fit();
954
                Thread.Sleep(1000);
955
                radApp.ActiveWindow.Zoom = 2000;
956
                Thread.Sleep(2000);
957

    
958
                //current LMDrawing 가져오기
959
                LMAFilter filter = new LMAFilter();
960
                LMACriterion criterion = new LMACriterion();
961
                filter.ItemType = "Drawing";
962
                criterion.SourceAttributeName = "Name";
963
                criterion.Operator = "=";
964
                criterion.set_ValueAttribute(drawingName);
965
                filter.get_Criteria().Add(criterion);
966

    
967
                LMDrawings drawings = new LMDrawings();
968
                drawings.Collect(dataSource, Filter: filter);
969

    
970
                drawingID = ((dynamic)drawings).Nth(1).Id;
971
                ReleaseCOMObjects(filter);
972
                ReleaseCOMObjects(criterion);
973
                ReleaseCOMObjects(drawings);
974
                filter = null;
975
                criterion = null;
976
                drawings = null;
977
            }
978
            else
979
                Log.Write("Fail Create Drawing");
980

    
981
            if (newDrawing != null)
982
                return true;
983
            else
984
                return false;
985
        }
986

    
987
        /// <summary>
988
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
989
        /// </summary>
990
        /// <param name="drawingName"></param>
991
        /// <param name="drawingNumber"></param>
992
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
993
        {
994
            LMDrawings drawings = new LMDrawings();
995
            drawings.Collect(dataSource);
996

    
997
            List<string> drawingNameList = new List<string>();
998
            List<string> drawingNumberList = new List<string>();
999

    
1000
            foreach (LMDrawing item in drawings)
1001
            {
1002
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1003
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1004
            }
1005

    
1006
            int nameLength = drawingName.Length;
1007
            while (drawingNameList.Contains(drawingName))
1008
            {
1009
                if (nameLength == drawingName.Length)
1010
                    drawingName += "-1";
1011
                else
1012
                {
1013
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1014
                    drawingName = drawingName.Substring(0, nameLength + 1);
1015
                    drawingName += ++index;
1016
                }
1017
            }
1018

    
1019
            int numberLength = drawingNumber.Length;
1020
            while (drawingNameList.Contains(drawingNumber))
1021
            {
1022
                if (numberLength == drawingNumber.Length)
1023
                    drawingNumber += "-1";
1024
                else
1025
                {
1026
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1027
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1028
                    drawingNumber += ++index;
1029
                }
1030
            }
1031
            ReleaseCOMObjects(drawings);
1032
            drawings = null;
1033
        }
1034

    
1035
        /// <summary>
1036
        /// 도면 크기 구하는 메서드
1037
        /// </summary>
1038
        /// <returns></returns>
1039
        private bool DocumentCoordinateCorrection()
1040
        {
1041
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1042
            {
1043
                Log.Write("Setting Drawing X, Drawing Y");
1044
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1045
                Log.Write("Start coordinate correction");
1046
                document.CoordinateCorrection();
1047
                return true;
1048
            }
1049
            else
1050
            {
1051
                Log.Write("Need Drawing X, Y");
1052
                return false;
1053
            }
1054
        }
1055

    
1056
        /// <summary>
1057
        /// 심볼을 실제로 Modeling 메서드
1058
        /// </summary>
1059
        /// <param name="symbol">생성할 심볼</param>
1060
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1061
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1062
        {
1063
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1064
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1065
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1066
                return;
1067
            // 이미 모델링 됐을 경우
1068
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1069
                return;
1070

    
1071
            LMSymbol _LMSymbol = null;
1072

    
1073
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1074
            double x = symbol.SPPID.ORIGINAL_X;
1075
            double y = symbol.SPPID.ORIGINAL_Y;
1076
            int mirror = 0;
1077
            double angle = symbol.ANGLE;
1078

    
1079
            // OPC 일경우 180도 일때 Mirror
1080
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1081
                mirror = 1;
1082

    
1083
            // Mirror 계산
1084
            if (symbol.FLIP == 1)
1085
            {
1086
                mirror = 1;
1087
                angle += Math.PI;
1088
            }
1089

    
1090
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1091
            {
1092
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1093
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1094
                if (connector != null)
1095
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1096

    
1097
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1098
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1099
                if (temp != null)
1100
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1101
                ReleaseCOMObjects(temp);
1102
                temp = null;
1103

    
1104
                if (_LMSymbol != null && _TargetItem != null)
1105
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1106

    
1107
                ReleaseCOMObjects(_TargetItem);
1108
            }
1109
            else
1110
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1111

    
1112
            if (_LMSymbol != null)
1113
            {
1114
                _LMSymbol.Commit();
1115

    
1116
                // ConnCheck
1117
                List<string> ids = new List<string>();
1118
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1119
                {
1120
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1121
                        ids.Add(item.Id);
1122
                    ReleaseCOMObjects(item);
1123
                }
1124
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1125
                {
1126
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1127
                        ids.Add(item.Id);
1128
                    ReleaseCOMObjects(item);
1129
                }
1130

    
1131
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1132
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1133
                {
1134
                    double currentX = _LMSymbol.get_XCoordinate();
1135
                    double currentY = _LMSymbol.get_YCoordinate();
1136

    
1137

    
1138
                }
1139

    
1140
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1141
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1142
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1143

    
1144
                foreach (var item in symbol.ChildSymbols)
1145
                    CreateChildSymbol(item, _LMSymbol, symbol);
1146

    
1147
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1148
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1149

    
1150
                double[] range = null;
1151
                GetSPPIDSymbolRange(symbol, ref range);
1152
                symbol.SPPID.SPPID_Min_X = range[0];
1153
                symbol.SPPID.SPPID_Min_Y = range[1];
1154
                symbol.SPPID.SPPID_Max_X = range[2];
1155
                symbol.SPPID.SPPID_Max_Y = range[3];
1156

    
1157
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1158
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1159
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1160
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1161

    
1162
                ReleaseCOMObjects(_LMSymbol);
1163
            }
1164
        }
1165
        /// <summary>
1166
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1167
        /// Signal Point는 고려하지 않음
1168
        /// </summary>
1169
        /// <param name="symbol"></param>
1170
        /// <param name="_TargetItem"></param>
1171
        /// <param name="targetX"></param>
1172
        /// <param name="targetY"></param>
1173
        /// <returns></returns>
1174
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1175
        {
1176
            LMConnector tempConnector = null;
1177

    
1178
            List<Symbol> group = new List<Symbol>();
1179
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1180
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1181
            {
1182
                List<Connector> connectors = new List<Connector>();
1183
                foreach (var item in group)
1184
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1185
                /// Primary or Secondary Type Line만 고려
1186
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1187
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1188
                if (_connector != null)
1189
                {
1190
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1191
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1192
                    /// PipingPoint가 2개 이상만
1193
                    if (pointInfos.Count >= 2)
1194
                    {
1195
                        double lineX = 0;
1196
                        double lineY = 0;
1197
                        double length = 0;
1198
                        foreach (var item in pointInfos)
1199
                        {
1200
                            double tempX = item[1];
1201
                            double tempY = item[2];
1202

    
1203
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1204
                            if (calcDistance > length)
1205
                            {
1206
                                lineX = tempX;
1207
                                lineY = tempY;
1208
                            }
1209
                        }
1210

    
1211
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1212
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1213
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1214
                        placeRunInputs.AddPoint(-1, -1);
1215
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1216
                        if (tempConnector != null)
1217
                            tempConnector.Commit();
1218
                        ReleaseCOMObjects(_LMAItem);
1219
                        _LMAItem = null;
1220
                        ReleaseCOMObjects(placeRunInputs);
1221
                        placeRunInputs = null;
1222
                    }
1223
                }
1224
            }
1225

    
1226
            return tempConnector;
1227
        }
1228
        /// <summary>
1229
        /// Symbol의 PipingPoints를 구함
1230
        /// SignalPoint는 고려하지 않음
1231
        /// </summary>
1232
        /// <param name="symbol"></param>
1233
        /// <returns></returns>
1234
        private List<double[]> getPipingPoints(LMSymbol symbol)
1235
        {
1236
            LMModelItem modelItem = symbol.ModelItemObject;
1237
            LMPipingPoints pipingPoints = null;
1238
            if (modelItem.get_ItemTypeName() == "PipingComp")
1239
            {
1240
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1241
                pipingPoints = pipingComp.PipingPoints;
1242
                ReleaseCOMObjects(pipingComp);
1243
                pipingComp = null;
1244
            }
1245
            else if (modelItem.get_ItemTypeName() == "Instrument")
1246
            {
1247
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1248
                pipingPoints = instrument.PipingPoints;
1249
                ReleaseCOMObjects(instrument);
1250
                instrument = null;
1251
            }
1252
            else
1253
                Log.Write("다른 Type");
1254

    
1255
            List<double[]> info = new List<double[]>();
1256
            if (pipingPoints != null)
1257
            {
1258
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1259
                {
1260
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1261
                    {
1262
                        if (attribute.Name == "PipingPointNumber")
1263
                        {
1264
                            int index = Convert.ToInt32(attribute.get_Value());
1265
                            if (info.Find(loopX => loopX[0] == index) == null)
1266
                            {
1267
                                double x = 0;
1268
                                double y = 0;
1269
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1270
                                    info.Add(new double[] { index, x, y });
1271
                            }
1272
                        }
1273
                    }
1274
                }
1275
            }
1276
            ReleaseCOMObjects(modelItem);
1277
            modelItem = null;
1278
            ReleaseCOMObjects(pipingPoints);
1279
            pipingPoints = null;
1280

    
1281
            return info;
1282
        }
1283

    
1284
        private void RemoveSymbol(Symbol symbol)
1285
        {
1286
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1287
            {
1288
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1289
                if (_LMSymbol != null)
1290
                {
1291
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1292
                    ReleaseCOMObjects(_LMSymbol);
1293
                }
1294
            }
1295

    
1296
            symbol.SPPID.RepresentationId = string.Empty;
1297
            symbol.SPPID.ModelItemID = string.Empty;
1298
            symbol.SPPID.SPPID_X = double.NaN;
1299
            symbol.SPPID.SPPID_Y = double.NaN;
1300
            symbol.SPPID.SPPID_Min_X = double.NaN;
1301
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1302
            symbol.SPPID.SPPID_Max_X = double.NaN;
1303
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1304
        }
1305

    
1306
        private void RemoveSymbol(List<Symbol> symbols)
1307
        {
1308
            foreach (var symbol in symbols)
1309
            {
1310
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1311
                {
1312
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1313
                    if (_LMSymbol != null)
1314
                    {
1315
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1316
                        ReleaseCOMObjects(_LMSymbol);
1317
                    }
1318
                }
1319

    
1320
                symbol.SPPID.RepresentationId = string.Empty;
1321
                symbol.SPPID.ModelItemID = string.Empty;
1322
                symbol.SPPID.SPPID_X = double.NaN;
1323
                symbol.SPPID.SPPID_Y = double.NaN;
1324
                symbol.SPPID.SPPID_Min_X = double.NaN;
1325
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1326
                symbol.SPPID.SPPID_Max_X = double.NaN;
1327
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1328
            }
1329
        }
1330

    
1331
        /// <summary>
1332
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1333
        /// </summary>
1334
        /// <param name="targetConnector"></param>
1335
        /// <param name="targetSymbol"></param>
1336
        /// <param name="x"></param>
1337
        /// <param name="y"></param>
1338
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1339
        {
1340
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1341

    
1342
            double[] range = null;
1343
            List<double[]> points = new List<double[]>();
1344
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1345
            double x1 = range[0];
1346
            double y1 = range[1];
1347
            double x2 = range[2];
1348
            double y2 = range[3];
1349

    
1350
            // Origin 기준 Connector의 위치차이
1351
            double sceneX = 0;
1352
            double sceneY = 0;
1353
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1354
            double originX = 0;
1355
            double originY = 0;
1356
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1357
            double gapX = originX - sceneX;
1358
            double gapY = originY - sceneY;
1359

    
1360
            // SPPID Symbol과 ID2 심볼의 크기 차이
1361
            double sizeWidth = 0;
1362
            double sizeHeight = 0;
1363
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1364
            if (sizeWidth == 0 || sizeHeight == 0)
1365
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1366

    
1367
            double percentX = (x2 - x1) / sizeWidth;
1368
            double percentY = (y2 - y1) / sizeHeight;
1369

    
1370
            double SPPIDgapX = gapX * percentX;
1371
            double SPPIDgapY = gapY * percentY;
1372

    
1373
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1374
            double distance = double.MaxValue;
1375
            double[] resultPoint;
1376
            foreach (var point in points)
1377
            {
1378
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1379
                if (distance > result)
1380
                {
1381
                    distance = result;
1382
                    resultPoint = point;
1383
                    x = point[0];
1384
                    y = point[1];
1385
                }
1386
            }
1387

    
1388
            ReleaseCOMObjects(_TargetItem);
1389
        }
1390

    
1391
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1392
        {
1393
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1394
            if (index == 0)
1395
            {
1396
                x = targetLine.SPPID.START_X;
1397
                y = targetLine.SPPID.START_Y;
1398
            }
1399
            else
1400
            {
1401
                x = targetLine.SPPID.END_X;
1402
                y = targetLine.SPPID.END_Y;
1403
            }
1404
        }
1405

    
1406
        /// <summary>
1407
        /// SPPID Symbol의 Range를 구한다.
1408
        /// </summary>
1409
        /// <param name="symbol"></param>
1410
        /// <param name="range"></param>
1411
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1412
        {
1413
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1414
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1415
            double x1 = 0;
1416
            double y1 = 0;
1417
            double x2 = 0;
1418
            double y2 = 0;
1419
            symbol2d.Range(out x1, out y1, out x2, out y2);
1420
            range = new double[] { x1, y1, x2, y2 };
1421

    
1422
            for (int i = 1; i < int.MaxValue; i++)
1423
            {
1424
                double connX = 0;
1425
                double connY = 0;
1426
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1427
                    points.Add(new double[] { connX, connY });
1428
                else
1429
                    break;
1430
            }
1431

    
1432
            foreach (var childSymbol in symbol.ChildSymbols)
1433
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1434

    
1435
            ReleaseCOMObjects(_TargetItem);
1436
        }
1437

    
1438
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1439
        {
1440
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1441
            if (_TargetItem != null)
1442
            {
1443
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1444
                double x1 = 0;
1445
                double y1 = 0;
1446
                double x2 = 0;
1447
                double y2 = 0;
1448
                if (!bForGraphic)
1449
                {
1450
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1451
                    range = new double[] { x1, y1, x2, y2 };
1452
                }
1453
                else
1454
                {
1455
                    x1 = double.MaxValue;
1456
                    y1 = double.MaxValue;
1457
                    x2 = double.MinValue;
1458
                    y2 = double.MinValue;
1459
                    range = new double[] { x1, y1, x2, y2 };
1460

    
1461
                    foreach (var item in symbol2d.DrawingObjects)
1462
                    {
1463
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1464
                        {
1465
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1466
                            if (rangeObject.Layer == "Default")
1467
                            {
1468
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1469
                                range = new double[] {
1470
                                Math.Min(x1, range[0]),
1471
                                Math.Min(y1, range[1]),
1472
                                Math.Max(x2, range[2]),
1473
                                Math.Max(y2, range[3])
1474
                            };
1475
                            }
1476
                        }
1477
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1478
                        {
1479
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1480
                            if (rangeObject.Layer == "Default")
1481
                            {
1482
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1483
                                range = new double[] {
1484
                                Math.Min(x1, range[0]),
1485
                                Math.Min(y1, range[1]),
1486
                                Math.Max(x2, range[2]),
1487
                                Math.Max(y2, range[3])
1488
                            };
1489
                            }
1490
                        }
1491
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1492
                        {
1493
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1494
                            if (rangeObject.Layer == "Default")
1495
                            {
1496
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1497
                                range = new double[] {
1498
                                Math.Min(x1, range[0]),
1499
                                Math.Min(y1, range[1]),
1500
                                Math.Max(x2, range[2]),
1501
                                Math.Max(y2, range[3])
1502
                            };
1503
                            }
1504
                        }
1505
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1506
                        {
1507
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1508
                            if (rangeObject.Layer == "Default")
1509
                            {
1510
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1511
                                range = new double[] {
1512
                                Math.Min(x1, range[0]),
1513
                                Math.Min(y1, range[1]),
1514
                                Math.Max(x2, range[2]),
1515
                                Math.Max(y2, range[3])
1516
                            };
1517
                            }
1518
                        }
1519
                    }
1520
                }
1521

    
1522
                if (!bOnlySymbol)
1523
                {
1524
                    foreach (var childSymbol in symbol.ChildSymbols)
1525
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1526
                }
1527
                ReleaseCOMObjects(_TargetItem);
1528
            }
1529
        }
1530

    
1531
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1532
        {
1533
            if (labelPersist != null)
1534
            {
1535
                double x1 = double.MaxValue;
1536
                double y1 = double.MaxValue;
1537
                double x2 = double.MinValue;
1538
                double y2 = double.MinValue;
1539
                range = new double[] { x1, y1, x2, y2 };
1540

    
1541
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1542
                foreach (var item in dependency.DrawingObjects)
1543
                {
1544
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1545
                    if (textBox != null)
1546
                    {
1547
                        if (dependency != null)
1548
                        {
1549
                            double tempX1;
1550
                            double tempY1;
1551
                            double tempX2;
1552
                            double tempY2;
1553
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1554
                            x1 = Math.Min(x1, tempX1);
1555
                            y1 = Math.Min(y1, tempY1);
1556
                            x2 = Math.Max(x2, tempX2);
1557
                            y2 = Math.Max(y2, tempY2);
1558

    
1559
                            range = new double[] { x1, y1, x2, y2 };
1560
                        }
1561
                    }
1562
                }
1563
                
1564
            }
1565
        }
1566

    
1567
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1568
        {
1569
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1570
            foreach (var symbol in symbols)
1571
            {
1572
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1573
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1574
                double x1 = 0;
1575
                double y1 = 0;
1576
                double x2 = 0;
1577
                double y2 = 0;
1578
                symbol2d.Range(out x1, out y1, out x2, out y2);
1579

    
1580
                tempRange[0] = Math.Min(tempRange[0], x1);
1581
                tempRange[1] = Math.Min(tempRange[1], y1);
1582
                tempRange[2] = Math.Max(tempRange[2], x2);
1583
                tempRange[3] = Math.Max(tempRange[3], y2);
1584

    
1585
                foreach (var childSymbol in symbol.ChildSymbols)
1586
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1587

    
1588
                ReleaseCOMObjects(_TargetItem);
1589
            }
1590

    
1591
            range = tempRange;
1592
        }
1593

    
1594
        /// <summary>
1595
        /// Child Modeling 된 Symbol의 Range를 구한다.
1596
        /// </summary>
1597
        /// <param name="childSymbol"></param>
1598
        /// <param name="range"></param>
1599
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1600
        {
1601
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1602
            if (_ChildSymbol != null)
1603
            {
1604
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1605
                double x1 = 0;
1606
                double y1 = 0;
1607
                double x2 = 0;
1608
                double y2 = 0;
1609
                symbol2d.Range(out x1, out y1, out x2, out y2);
1610
                range[0] = Math.Min(range[0], x1);
1611
                range[1] = Math.Min(range[1], y1);
1612
                range[2] = Math.Max(range[2], x2);
1613
                range[3] = Math.Max(range[3], y2);
1614

    
1615
                for (int i = 1; i < int.MaxValue; i++)
1616
                {
1617
                    double connX = 0;
1618
                    double connY = 0;
1619
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1620
                        points.Add(new double[] { connX, connY });
1621
                    else
1622
                        break;
1623
                }
1624

    
1625
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1626
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1627

    
1628
                ReleaseCOMObjects(_ChildSymbol);
1629
            }
1630
        }
1631

    
1632
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1633
        {
1634
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1635
            if (_ChildSymbol != null)
1636
            {
1637
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1638
                double x1 = 0;
1639
                double y1 = 0;
1640
                double x2 = 0;
1641
                double y2 = 0;
1642
                symbol2d.Range(out x1, out y1, out x2, out y2);
1643
                range[0] = Math.Min(range[0], x1);
1644
                range[1] = Math.Min(range[1], y1);
1645
                range[2] = Math.Max(range[2], x2);
1646
                range[3] = Math.Max(range[3], y2);
1647

    
1648
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1649
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1650
                ReleaseCOMObjects(_ChildSymbol);
1651
            }
1652
        }
1653

    
1654
        /// <summary>
1655
        /// Label Symbol Modeling
1656
        /// </summary>
1657
        /// <param name="symbol"></param>
1658
        private void LabelSymbolModeling(Symbol symbol)
1659
        {
1660
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1661
            {
1662
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1663
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1664
                    return;
1665
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1666

    
1667
                string symbolUID = itemAttribute.VALUE;
1668
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1669
                if (targetItem != null &&
1670
                    (targetItem.GetType() == typeof(Symbol) ||
1671
                    targetItem.GetType() == typeof(Equipment)))
1672
                {
1673
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1674
                    string sRep = null;
1675
                    if (targetItem.GetType() == typeof(Symbol))
1676
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1677
                    else if (targetItem.GetType() == typeof(Equipment))
1678
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1679
                    if (!string.IsNullOrEmpty(sRep))
1680
                    {
1681
                        // LEADER Line 검사
1682
                        bool leaderLine = false;
1683
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1684
                        if (symbolMapping != null)
1685
                            leaderLine = symbolMapping.LEADERLINE;
1686

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

    
1691
                        //Leader 선 센터로
1692
                        if (_LMLabelPresist != null)
1693
                        {
1694
                            // Target Item에 Label의 Attribute Input
1695
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1696

    
1697
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1698
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1699
                            if (dependency != null)
1700
                            {
1701
                                bool result = false;
1702
                                foreach (var attributes in dependency.AttributeSets)
1703
                                {
1704
                                    foreach (var attribute in attributes)
1705
                                    {
1706
                                        string name = attribute.Name;
1707
                                        string value = attribute.GetValue().ToString();
1708
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1709
                                        {
1710
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1711
                                            {
1712
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1713
                                                {
1714
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1715
                                                    double prevX = _TargetItem.get_XCoordinate();
1716
                                                    double prevY = _TargetItem.get_YCoordinate();
1717
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1718
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1719
                                                    result = true;
1720
                                                    break;
1721
                                                }
1722
                                            }
1723
                                        }
1724

    
1725
                                        if (result)
1726
                                            break;
1727
                                    }
1728

    
1729
                                    if (result)
1730
                                        break;
1731
                                }
1732
                            }
1733

    
1734
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1735
                            _LMLabelPresist.Commit();
1736
                            ReleaseCOMObjects(_LMLabelPresist);
1737
                        }
1738

    
1739
                        ReleaseCOMObjects(_TargetItem);
1740
                    }
1741
                }
1742
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1743
                {
1744
                    Line targetLine = targetItem as Line;
1745
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1746
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1747
                    if (connectedLMConnector != null)
1748
                    {
1749
                        // LEADER Line 검사
1750
                        bool leaderLine = false;
1751
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1752
                        if (symbolMapping != null)
1753
                            leaderLine = symbolMapping.LEADERLINE;
1754

    
1755
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1756
                        if (_LMLabelPresist != null)
1757
                        {
1758
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1759
                            _LMLabelPresist.Commit();
1760
                            ReleaseCOMObjects(_LMLabelPresist);
1761
                        }
1762
                        ReleaseCOMObjects(connectedLMConnector);
1763
                    }
1764

    
1765
                    foreach (var item in connectorVertices)
1766
                        if (item.Key != null)
1767
                            ReleaseCOMObjects(item.Key);
1768
                }
1769
            }
1770
        }
1771

    
1772
        /// <summary>
1773
        /// Equipment를 실제로 Modeling 메서드
1774
        /// </summary>
1775
        /// <param name="equipment"></param>
1776
        private void EquipmentModeling(Equipment equipment)
1777
        {
1778
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1779
                return;
1780

    
1781
            LMSymbol _LMSymbol = null;
1782
            LMSymbol targetItem = null;
1783
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1784
            double x = equipment.SPPID.ORIGINAL_X;
1785
            double y = equipment.SPPID.ORIGINAL_Y;
1786
            int mirror = 0;
1787
            double angle = equipment.ANGLE;
1788

    
1789
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1790

    
1791
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1792
            if (connector != null)
1793
            {
1794
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1795
                if (connEquipment != null)
1796
                {
1797
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1798
                        EquipmentModeling(connEquipment);
1799

    
1800
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1801
                    {
1802
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1803
                        if (targetItem != null)
1804
                        {
1805
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1806
                        }
1807
                        else
1808
                        {
1809
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1810
                        }
1811
                    }
1812
                    else
1813
                    {
1814
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1815
                    }
1816
                }
1817
                else
1818
                {
1819
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1820
                }
1821
            }
1822
            else
1823
            {
1824
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1825
            }
1826

    
1827
            if (_LMSymbol != null)
1828
            {
1829
                _LMSymbol.Commit();
1830
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1831
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1832
                ReleaseCOMObjects(_LMSymbol);
1833
            }
1834

    
1835
            if (targetItem != null)
1836
            {
1837
                ReleaseCOMObjects(targetItem);
1838
            }
1839

    
1840
            ReleaseCOMObjects(_LMSymbol);
1841
        }
1842

    
1843
        /// <summary>
1844
        /// 첫 진입점
1845
        /// </summary>
1846
        /// <param name="symbol"></param>
1847
        private void SymbolModelingBySymbol(Symbol symbol)
1848
        {
1849
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1850
            List<object> endObjects = new List<object>();
1851
            endObjects.Add(symbol);
1852

    
1853
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1854
            foreach (var connector in symbol.CONNECTORS)
1855
            {
1856
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1857
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1858
                {
1859
                    endObjects.Add(connItem);
1860
                    if (connItem.GetType() == typeof(Symbol))
1861
                    {
1862
                        Symbol connSymbol = connItem as Symbol;
1863
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1864
                        {
1865
                            SymbolModeling(connSymbol, symbol);
1866
                        }
1867
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1868
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1869
                    }
1870
                    else if (connItem.GetType() == typeof(Line))
1871
                    {
1872
                        Line connLine = connItem as Line;
1873
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1874
                    }
1875
                }
1876
            }
1877
        }
1878

    
1879
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1880
        {
1881
            foreach (var connector in symbol.CONNECTORS)
1882
            {
1883
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1884
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1885
                {
1886
                    if (!endObjects.Contains(connItem))
1887
                    {
1888
                        endObjects.Add(connItem);
1889
                        if (connItem.GetType() == typeof(Symbol))
1890
                        {
1891
                            Symbol connSymbol = connItem as Symbol;
1892
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1893
                            {
1894
                                SymbolModeling(connSymbol, symbol);
1895
                            }
1896
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1897
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1898
                        }
1899
                        else if (connItem.GetType() == typeof(Line))
1900
                        {
1901
                            Line connLine = connItem as Line;
1902
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1903
                        }
1904
                    }
1905
                }
1906
            }
1907
        }
1908

    
1909
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1910
        {
1911
            foreach (var connector in line.CONNECTORS)
1912
            {
1913
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1914
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1915
                {
1916
                    if (!endObjects.Contains(connItem))
1917
                    {
1918
                        endObjects.Add(connItem);
1919
                        if (connItem.GetType() == typeof(Symbol))
1920
                        {
1921
                            Symbol connSymbol = connItem as Symbol;
1922
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1923
                            {
1924
                                List<Symbol> group = new List<Symbol>();
1925
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1926
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1927
                                List<Symbol> endModelingGroup = new List<Symbol>();
1928
                                if (priority != null)
1929
                                {
1930
                                    SymbolGroupModeling(priority, group);
1931

    
1932
                                    // Range 겹치는지 확인해야함
1933
                                    double[] prevRange = null;
1934
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1935
                                    double[] groupRange = null;
1936
                                    GetSPPIDSymbolRange(group, ref groupRange);
1937

    
1938
                                    double distanceX = 0;
1939
                                    double distanceY = 0;
1940
                                    bool overlapX = false;
1941
                                    bool overlapY = false;
1942
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1943
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1944
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1945
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1946
                                    {
1947
                                        RemoveSymbol(group);
1948
                                        foreach (var _temp in group)
1949
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1950

    
1951
                                        SymbolGroupModeling(priority, group);
1952
                                    }
1953
                                }
1954
                                else
1955
                                {
1956
                                    SymbolModeling(connSymbol, null);
1957
                                    // Range 겹치는지 확인해야함
1958
                                    double[] prevRange = null;
1959
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1960
                                    double[] connRange = null;
1961
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1962

    
1963
                                    double distanceX = 0;
1964
                                    double distanceY = 0;
1965
                                    bool overlapX = false;
1966
                                    bool overlapY = false;
1967
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1968
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1969
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1970
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1971
                                    {
1972
                                        RemoveSymbol(connSymbol);
1973
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1974

    
1975
                                        SymbolModeling(connSymbol, null);
1976
                                    }
1977
                                }
1978
                            }
1979
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1980
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1981
                        }
1982
                        else if (connItem.GetType() == typeof(Line))
1983
                        {
1984
                            Line connLine = connItem as Line;
1985
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1986
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1987
                        }
1988
                    }
1989
                }
1990
            }
1991
        }
1992

    
1993
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1994
        {
1995
            List<Symbol> endModelingGroup = new List<Symbol>();
1996
            SymbolModeling(firstSymbol, null);
1997
            endModelingGroup.Add(firstSymbol);
1998
            while (endModelingGroup.Count != group.Count)
1999
            {
2000
                foreach (var _symbol in group)
2001
                {
2002
                    if (!endModelingGroup.Contains(_symbol))
2003
                    {
2004
                        foreach (var _connector in _symbol.CONNECTORS)
2005
                        {
2006
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2007
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2008
                            {
2009
                                SymbolModeling(_symbol, _connSymbol);
2010
                                endModelingGroup.Add(_symbol);
2011
                                break;
2012
                            }
2013
                        }
2014
                    }
2015
                }
2016
            }
2017
        }
2018

    
2019
        /// <summary>
2020
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2021
        /// </summary>
2022
        /// <param name="childSymbol"></param>
2023
        /// <param name="parentSymbol"></param>
2024
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2025
        {
2026
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2027
            double x1 = 0;
2028
            double x2 = 0;
2029
            double y1 = 0;
2030
            double y2 = 0;
2031
            symbol2d.Range(out x1, out y1, out x2, out y2);
2032

    
2033
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2034
            if (_LMSymbol != null)
2035
            {
2036
                _LMSymbol.Commit();
2037
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2038
                foreach (var item in childSymbol.ChildSymbols)
2039
                    CreateChildSymbol(item, _LMSymbol, parent);
2040
            }
2041

    
2042

    
2043
            ReleaseCOMObjects(_LMSymbol);
2044
        }
2045
        double index = 0;
2046
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2047
        {
2048
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2049
                return;
2050

    
2051
            List<Line> group = new List<Line>();
2052
            GetConnectedLineGroup(line, group);
2053
            LineCoordinateCorrection(group);
2054

    
2055
            foreach (var groupLine in group)
2056
            {
2057
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2058
                {
2059
                    BranchLines.Add(groupLine);
2060
                    continue;
2061
                }
2062

    
2063
                bool diagonal = false;
2064
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2065
                    diagonal = true;
2066
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2067
                LMSymbol _LMSymbolStart = null;
2068
                LMSymbol _LMSymbolEnd = null;
2069
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2070
                foreach (var connector in groupLine.CONNECTORS)
2071
                {
2072
                    double x = 0;
2073
                    double y = 0;
2074
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2075
                    if (connector.ConnectedObject == null)
2076
                    {
2077
                        placeRunInputs.AddPoint(x, y);
2078
                    }
2079
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2080
                    {
2081
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2082
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2083
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2084
                        {
2085
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2086
                            if (_LMSymbolStart != null)
2087
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2088
                            else
2089
                                placeRunInputs.AddPoint(x, y);
2090
                        }
2091
                        else
2092
                        {
2093
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2094
                            if (_LMSymbolEnd != null)
2095
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2096
                            else
2097
                                placeRunInputs.AddPoint(x, y);
2098
                        }
2099
                    }
2100
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2101
                    {
2102
                        Line targetLine = connector.ConnectedObject as Line;
2103
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2104
                        {
2105
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2106
                            if (targetConnector != null)
2107
                            {
2108
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2109
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2110
                            }
2111
                            else
2112
                            {
2113
                                placeRunInputs.AddPoint( x, y);
2114
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2115
                            }
2116
                        }
2117
                        else
2118
                        {
2119
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2120
                            {
2121
                                index += 0.01;
2122
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2123
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2124
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2125
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2126
                                else
2127
                                {
2128
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2129
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2130
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2131
                                    else
2132
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2133
                                }
2134
                            }
2135

    
2136
                            placeRunInputs.AddPoint(x, y);
2137

    
2138
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2139
                            {
2140
                                index += 0.01;
2141
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2142
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2143
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2144
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2145
                                else
2146
                                {
2147
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2148
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2149
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2150
                                    else
2151
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2152
                                }
2153
                            }
2154
                        }
2155
                    }
2156
                }
2157

    
2158
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2159
                if (_lMConnector != null)
2160
                {
2161
                    _lMConnector.Commit();
2162
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2163

    
2164
                    bool bRemodelingStart = false;
2165
                    if (_LMSymbolStart != null)
2166
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2167
                    bool bRemodelingEnd = false;
2168
                    if (_LMSymbolEnd != null)
2169
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2170

    
2171
                    if (bRemodelingStart || bRemodelingEnd)
2172
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2173

    
2174
                    FlowMarkModeling(groupLine);
2175
                    LineNumberModelingOnlyOne(groupLine);
2176

    
2177
                    ReleaseCOMObjects(_lMConnector);
2178
                }
2179
                else if (!isBranchModeling)
2180
                {
2181
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2182
                }
2183

    
2184
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2185
                x.ConnectedObject != null &&
2186
                x.ConnectedObject.GetType() == typeof(Line) &&
2187
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2188
                .Select(x => x.ConnectedObject)
2189
                .ToList();
2190

    
2191
                foreach (var item in removeLines)
2192
                    RemoveLineForModeling(item as Line);
2193

    
2194
                if (_LMAItem != null)
2195
                    ReleaseCOMObjects(_LMAItem);
2196
                if (placeRunInputs != null)
2197
                    ReleaseCOMObjects(placeRunInputs);
2198
                if (_LMSymbolStart != null)
2199
                    ReleaseCOMObjects(_LMSymbolStart);
2200
                if (_LMSymbolEnd != null)
2201
                    ReleaseCOMObjects(_LMSymbolEnd);
2202

    
2203
                if (isBranchModeling && BranchLines.Contains(groupLine))
2204
                    BranchLines.Remove(groupLine);
2205
            }
2206
        }
2207

    
2208
        private void RemoveLineForModeling(Line line)
2209
        {
2210
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2211
            if (modelItem != null)
2212
            {
2213
                foreach (LMRepresentation rep in modelItem.Representations)
2214
                {
2215
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2216
                    {
2217
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2218
                        dynamic OID = rep.get_GraphicOID().ToString();
2219
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2220
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2221
                        int verticesCount = lineStringGeometry.VertexCount;
2222
                        double[] vertices = null;
2223
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2224
                        for (int i = 0; i < verticesCount; i++)
2225
                        {
2226
                            double x = 0;
2227
                            double y = 0;
2228
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2229
                            if (verticesCount == 2 && (x < 0 || y < 0))
2230
                                _placement.PIDRemovePlacement(rep);
2231
                        }
2232
                        ReleaseCOMObjects(_LMConnector);
2233
                    }
2234
                }
2235

    
2236
                ReleaseCOMObjects(modelItem);
2237
            }
2238
        }
2239

    
2240
        private void GetConnectedLineGroup(Line line, List<Line> group)
2241
        {
2242
            if (!group.Contains(line))
2243
                group.Add(line);
2244
            foreach (var connector in line.CONNECTORS)
2245
            {
2246
                if (connector.ConnectedObject != null &&
2247
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2248
                    !group.Contains(connector.ConnectedObject) &&
2249
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2250
                {
2251
                    Line connLine = connector.ConnectedObject as Line;
2252
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2253
                    {
2254
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2255
                            group.Insert(0, connLine);
2256
                        else
2257
                            group.Add(connLine);
2258
                        GetConnectedLineGroup(connLine, group);
2259
                    }
2260
                }
2261
            }
2262
        }
2263

    
2264
        private void LineCoordinateCorrection(List<Line> group)
2265
        {
2266
            // 순서대로 전 Item 기준 정렬
2267
            LineCoordinateCorrectionByStart(group);
2268

    
2269
            // 역으로 심볼이 있을 경우 좌표 보정
2270
            LineCoordinateCorrectionForLastLine(group);
2271
        }
2272

    
2273
        private void LineCoordinateCorrectionByStart(List<Line> group)
2274
        {
2275
            for (int i = 0; i < group.Count; i++)
2276
            {
2277
                Line line = group[i];
2278
                if (i == 0)
2279
                {
2280
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2281
                    if (symbolConnector != null)
2282
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2283
                }
2284
                else if (i != 0)
2285
                {
2286
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2287
                }
2288
            }
2289
        }
2290

    
2291
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2292
        {
2293
            Line checkLine = group[group.Count - 1];
2294
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2295
            if (lastSymbolConnector != null)
2296
            {
2297
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2298
                for (int i = group.Count - 2; i >= 0; i--)
2299
                {
2300
                    Line line = group[i + 1];
2301
                    Line prevLine = group[i];
2302

    
2303
                    // 같으면 보정
2304
                    if (line.SlopeType == prevLine.SlopeType)
2305
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2306
                    else
2307
                    {
2308
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2309
                        {
2310
                            double prevX = 0;
2311
                            double prevY = 0;
2312
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2313
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2314

    
2315
                            double x = 0;
2316
                            double y = 0;
2317
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2318
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2319
                        }
2320
                        else if (line.SlopeType == SlopeType.VERTICAL)
2321
                        {
2322
                            double prevX = 0;
2323
                            double prevY = 0;
2324
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2325
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2326

    
2327
                            double x = 0;
2328
                            double y = 0;
2329
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2330
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2331
                        }
2332
                        break;
2333
                    }
2334
                }
2335
            }
2336
        }
2337

    
2338
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2339
        {
2340
            double x = 0;
2341
            double y = 0;
2342
            if (connItem.GetType() == typeof(Symbol))
2343
            {
2344
                Symbol targetSymbol = connItem as Symbol;
2345
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2346
                if (targetConnector != null)
2347
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2348
                else
2349
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2350
            }
2351
            else if (connItem.GetType() == typeof(Line))
2352
            {
2353
                Line targetLine = connItem as Line;
2354
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2355
            }
2356

    
2357
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2358
        }
2359

    
2360
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2361
        {
2362
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2363
            int index = line.CONNECTORS.IndexOf(connector);
2364
            if (index == 0)
2365
            {
2366
                line.SPPID.START_X = x;
2367
                line.SPPID.START_Y = y;
2368
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2369
                    line.SPPID.END_Y = y;
2370
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2371
                    line.SPPID.END_X = x;
2372
            }
2373
            else
2374
            {
2375
                line.SPPID.END_X = x;
2376
                line.SPPID.END_Y = y;
2377
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2378
                    line.SPPID.START_Y = y;
2379
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2380
                    line.SPPID.START_X = x;
2381
            }
2382
        }
2383

    
2384
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2385
        {
2386
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2387
            int index = line.CONNECTORS.IndexOf(connector);
2388
            if (index == 0)
2389
            {
2390
                line.SPPID.START_X = x;
2391
                if (line.SlopeType == SlopeType.VERTICAL)
2392
                    line.SPPID.END_X = x;
2393
            }
2394
            else
2395
            {
2396
                line.SPPID.END_X = x;
2397
                if (line.SlopeType == SlopeType.VERTICAL)
2398
                    line.SPPID.START_X = x;
2399
            }
2400
        }
2401

    
2402
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2403
        {
2404
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2405
            int index = line.CONNECTORS.IndexOf(connector);
2406
            if (index == 0)
2407
            {
2408
                line.SPPID.START_Y = y;
2409
                if (line.SlopeType == SlopeType.HORIZONTAL)
2410
                    line.SPPID.END_Y = y;
2411
            }
2412
            else
2413
            {
2414
                line.SPPID.END_Y = y;
2415
                if (line.SlopeType == SlopeType.HORIZONTAL)
2416
                    line.SPPID.START_Y = y;
2417
            }
2418
        }
2419

    
2420
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2421
        {
2422
            if (symbol != null)
2423
            {
2424
                string repID = symbol.AsLMRepresentation().Id;
2425
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2426
                string lineUID = line.UID;
2427

    
2428
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2429
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2430
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2431

    
2432
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2433
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2434
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2435

    
2436
                if (startSpecBreak != null || startEndBreak != null)
2437
                    result = true;
2438
            }
2439
        }
2440

    
2441
        /// <summary>
2442
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2443
        /// </summary>
2444
        /// <param name="lines"></param>
2445
        /// <param name="prevLMConnector"></param>
2446
        /// <param name="startSymbol"></param>
2447
        /// <param name="endSymbol"></param>
2448
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2449
        {
2450
            string symbolPath = string.Empty;
2451
            #region get symbol path
2452
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2453
            symbolPath = GetSPPIDFileName(modelItem);
2454
            ReleaseCOMObjects(modelItem);
2455
            #endregion
2456
            bool diagonal = false;
2457
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2458
                diagonal = true;
2459
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2460
            LMConnector newConnector = null;
2461
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2462
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2463
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2464
            int verticesCount = lineStringGeometry.VertexCount;
2465
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2466

    
2467
            List<double[]> vertices = new List<double[]>();
2468
            for (int i = 1; i <= verticesCount; i++)
2469
            {
2470
                double x = 0;
2471
                double y = 0;
2472
                lineStringGeometry.GetVertex(i, ref x, ref y);
2473
                vertices.Add(new double[] { x, y });
2474
            }
2475

    
2476
            for (int i = 0; i < vertices.Count; i++)
2477
            {
2478
                double[] points = vertices[i];
2479
                // 시작 심볼이 있고 첫번째 좌표일 때
2480
                if (startSymbol != null && i == 0)
2481
                {
2482
                    if (bStart)
2483
                    {
2484
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2485
                        if (slopeType == SlopeType.HORIZONTAL)
2486
                            placeRunInputs.AddPoint(points[0], -0.1);
2487
                        else if (slopeType == SlopeType.VERTICAL)
2488
                            placeRunInputs.AddPoint(-0.1, points[1]);
2489
                        else
2490
                            placeRunInputs.AddPoint(points[0], -0.1);
2491

    
2492
                        placeRunInputs.AddPoint(points[0], points[1]);
2493
                    }
2494
                    else
2495
                    {
2496
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2497
                    }
2498
                }
2499
                // 마지막 심볼이 있고 마지막 좌표일 때
2500
                else if (endSymbol != null && i == vertices.Count - 1)
2501
                {
2502
                    if (bEnd)
2503
                    {
2504
                        placeRunInputs.AddPoint(points[0], points[1]);
2505

    
2506
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2507
                        if (slopeType == SlopeType.HORIZONTAL)
2508
                            placeRunInputs.AddPoint(points[0], -0.1);
2509
                        else if (slopeType == SlopeType.VERTICAL)
2510
                            placeRunInputs.AddPoint(-0.1, points[1]);
2511
                        else
2512
                            placeRunInputs.AddPoint(points[0], -0.1);
2513
                    }
2514
                    else
2515
                    {
2516
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2517
                    }
2518
                }
2519
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2520
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2521
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2522
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2523
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2524
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2525
                else
2526
                    placeRunInputs.AddPoint(points[0], points[1]);
2527
            }
2528

    
2529
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2530
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2531

    
2532
            ReleaseCOMObjects(placeRunInputs);
2533
            ReleaseCOMObjects(_LMAItem);
2534
            ReleaseCOMObjects(modelItem);
2535

    
2536
            if (newConnector != null)
2537
            {
2538
                newConnector.Commit();
2539
                if (startSymbol != null && bStart)
2540
                {
2541
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2542
                    placeRunInputs = new PlaceRunInputs();
2543
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2544
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2545
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2546
                    if (_LMConnector != null)
2547
                    {
2548
                        _LMConnector.Commit();
2549
                        RemoveConnectorForReModelingLine(newConnector);
2550
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2551
                        ReleaseCOMObjects(_LMConnector);
2552
                    }
2553
                    ReleaseCOMObjects(placeRunInputs);
2554
                    ReleaseCOMObjects(_LMAItem);
2555
                }
2556

    
2557
                if (endSymbol != null && bEnd)
2558
                {
2559
                    if (startSymbol != null)
2560
                    {
2561
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2562
                        newConnector = dicVertices.First().Key;
2563
                    }
2564

    
2565
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2566
                    placeRunInputs = new PlaceRunInputs();
2567
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2568
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2569
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2570
                    if (_LMConnector != null)
2571
                    {
2572
                        _LMConnector.Commit();
2573
                        RemoveConnectorForReModelingLine(newConnector);
2574
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2575
                        ReleaseCOMObjects(_LMConnector);
2576
                    }
2577
                    ReleaseCOMObjects(placeRunInputs);
2578
                    ReleaseCOMObjects(_LMAItem);
2579
                }
2580

    
2581
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2582
                ReleaseCOMObjects(newConnector);
2583
            }
2584

    
2585
            ReleaseCOMObjects(modelItem);
2586
        }
2587

    
2588
        /// <summary>
2589
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2590
        /// </summary>
2591
        /// <param name="connector"></param>
2592
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2593
        {
2594
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2595
            foreach (var item in dicVertices)
2596
            {
2597
                if (item.Value.Count == 2)
2598
                {
2599
                    bool result = false;
2600
                    foreach (var point in item.Value)
2601
                    {
2602
                        if (point[0] < 0 || point[1] < 0)
2603
                        {
2604
                            result = true;
2605
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2606
                            break;
2607
                        }
2608
                    }
2609

    
2610
                    if (result)
2611
                        break;
2612
                }
2613
            }
2614
            foreach (var item in dicVertices)
2615
                ReleaseCOMObjects(item.Key);
2616
        }
2617

    
2618
        /// <summary>
2619
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2620
        /// </summary>
2621
        /// <param name="symbol"></param>
2622
        /// <param name="line"></param>
2623
        /// <returns></returns>
2624
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2625
        {
2626
            LMSymbol _LMSymbol = null;
2627
            foreach (var connector in symbol.CONNECTORS)
2628
            {
2629
                if (connector.CONNECTEDITEM == line.UID)
2630
                {
2631
                    if (connector.Index == 0)
2632
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2633
                    else
2634
                    {
2635
                        ChildSymbol child = null;
2636
                        foreach (var childSymbol in symbol.ChildSymbols)
2637
                        {
2638
                            if (childSymbol.Connectors.Contains(connector))
2639
                                child = childSymbol;
2640
                            else
2641
                                child = GetChildSymbolByConnector(childSymbol, connector);
2642

    
2643
                            if (child != null)
2644
                                break;
2645
                        }
2646

    
2647
                        if (child != null)
2648
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2649
                    }
2650

    
2651
                    break;
2652
                }
2653
            }
2654

    
2655
            return _LMSymbol;
2656
        }
2657

    
2658
        /// <summary>
2659
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2660
        /// </summary>
2661
        /// <param name="item"></param>
2662
        /// <param name="connector"></param>
2663
        /// <returns></returns>
2664
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2665
        {
2666
            foreach (var childSymbol in item.ChildSymbols)
2667
            {
2668
                if (childSymbol.Connectors.Contains(connector))
2669
                    return childSymbol;
2670
                else
2671
                    return GetChildSymbolByConnector(childSymbol, connector);
2672
            }
2673

    
2674
            return null;
2675
        }
2676

    
2677
        /// <summary>
2678
        /// EndBreak 모델링 메서드
2679
        /// </summary>
2680
        /// <param name="endBreak"></param>
2681
        private void EndBreakModeling(EndBreak endBreak)
2682
        {
2683
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2684
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2685

    
2686
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2687
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2688
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2689

    
2690
            if (targetLMConnector != null)
2691
            {
2692
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2693
                Array array = null;
2694
                if (point != null)
2695
                    array = new double[] { 0, point[0], point[1] };
2696
                else
2697
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2698
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2699
                if (_LmLabelPersist != null)
2700
                {
2701
                    _LmLabelPersist.Commit();
2702
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2703
                    if (_LmLabelPersist.ModelItemObject != null)
2704
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2705
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2706
                    ReleaseCOMObjects(_LmLabelPersist);
2707
                }
2708
                ReleaseCOMObjects(targetLMConnector);
2709
            }
2710
            else
2711
            {
2712
                Log.Write("End Break UID : " + endBreak.UID);
2713
                Log.Write("Can't find targetLMConnector");
2714
            }
2715
        }
2716

    
2717
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2718
        {
2719
            string symbolPath = string.Empty;
2720
            #region get symbol path
2721
            if (string.IsNullOrEmpty(changeSymbolPath))
2722
            {
2723
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2724
                symbolPath = GetSPPIDFileName(modelItem);
2725
                ReleaseCOMObjects(modelItem);
2726
            }
2727
            else
2728
                symbolPath = changeSymbolPath;
2729
            
2730
            #endregion
2731

    
2732
            LMConnector newConnector = null;
2733
            dynamic OID = connector.get_GraphicOID().ToString();
2734
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2735
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2736
            int verticesCount = lineStringGeometry.VertexCount;
2737
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2738
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2739

    
2740
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2741
            {
2742
                double[] vertices = null;
2743
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2744
                double x = 0;
2745
                double y = 0;
2746
                lineStringGeometry.GetVertex(1, ref x, ref y);
2747

    
2748
                string flowDirection = string.Empty;
2749
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2750
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2751
                    flowDirection = flowAttribute.get_Value().ToString();
2752

    
2753
                if (flowDirection == "End 1 is downstream (Outlet)")
2754
                {
2755
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2756
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2757
                    flowDirection = "End 1 is upstream (Inlet)";
2758
                }
2759
                else
2760
                {
2761
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2762
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2763
                }
2764
                string oldModelItemId = connector.ModelItemID;
2765
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2766
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2767
                newConnector.Commit();
2768
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2769
                if (!string.IsNullOrEmpty(flowDirection))
2770
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2771
                ReleaseCOMObjects(connector);
2772

    
2773
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
2774
                {
2775
                    foreach (var repId in line.SPPID.Representations)
2776
                    {
2777
                        LMConnector _connector = dataSource.GetConnector(repId);
2778
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
2779
                        {
2780
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
2781
                            {
2782
                                line.SPPID.ModelItemId = _connector.ModelItemID;
2783
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
2784
                            }
2785
                        }
2786
                        ReleaseCOMObjects(_connector);
2787
                        _connector = null;
2788
                    }
2789
                }
2790
            }
2791

    
2792
            return newConnector;
2793
        }
2794

    
2795
        /// <summary>
2796
        /// SpecBreak Modeling 메서드
2797
        /// </summary>
2798
        /// <param name="specBreak"></param>
2799
        private void SpecBreakModeling(SpecBreak specBreak)
2800
        {
2801
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2802
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2803

    
2804
            if (upStreamObj != null &&
2805
                downStreamObj != null)
2806
            {
2807
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2808
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && targetLMConnector != null)
2809
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2810

    
2811
                if (targetLMConnector != null)
2812
                {
2813
                    foreach (var attribute in specBreak.ATTRIBUTES)
2814
                    {
2815
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2816
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2817
                        {
2818
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2819
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2820
                            Array array = null;
2821
                            if (point != null)
2822
                                array = new double[] { 0, point[0], point[1] };
2823
                            else
2824
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2825
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2826

    
2827
                            if (_LmLabelPersist != null)
2828
                            {
2829
                                _LmLabelPersist.Commit();
2830
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2831
                                if (_LmLabelPersist.ModelItemObject != null)
2832
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2833
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2834
                                ReleaseCOMObjects(_LmLabelPersist);
2835
                            }
2836
                        }
2837
                    }
2838
                    ReleaseCOMObjects(targetLMConnector);
2839
                }
2840
                else
2841
                {
2842
                    Log.Write("Spec Break UID : " + specBreak.UID);
2843
                    Log.Write("Can't find targetLMConnector");
2844
                }
2845
            }
2846
        }
2847

    
2848
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2849
        {
2850
            LMConnector targetConnector = null;
2851
            Symbol targetSymbol = targetObj as Symbol;
2852
            Symbol connectedSymbol = connectedObj as Symbol;
2853
            Line targetLine = targetObj as Line;
2854
            Line connectedLine = connectedObj as Line;
2855
            if (targetSymbol != null && connectedSymbol != null)
2856
            {
2857
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2858
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2859

    
2860
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2861
                {
2862
                    if (connector.get_ItemStatus() != "Active")
2863
                        continue;
2864

    
2865
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2866
                    {
2867
                        targetConnector = connector;
2868
                        break;
2869
                    }
2870
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2871
                    {
2872
                        targetConnector = connector;
2873
                        break;
2874
                    }
2875
                }
2876

    
2877
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2878
                {
2879
                    if (connector.get_ItemStatus() != "Active")
2880
                        continue;
2881

    
2882
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2883
                    {
2884
                        targetConnector = connector;
2885
                        break;
2886
                    }
2887
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2888
                    {
2889
                        targetConnector = connector;
2890
                        break;
2891
                    }
2892
                }
2893

    
2894
                ReleaseCOMObjects(targetLMSymbol);
2895
                ReleaseCOMObjects(connectedLMSymbol);
2896
            }
2897
            else if (targetLine != null && connectedLine != null)
2898
            {
2899
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2900
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2901

    
2902
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2903
                {
2904
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2905
                    {
2906
                        if (targetConnector != null)
2907
                            break;
2908

    
2909
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2910
                        {
2911
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2912

    
2913
                            if (IsConnected(_LMConnector, connectedModelItem))
2914
                                targetConnector = _LMConnector;
2915
                            else
2916
                                ReleaseCOMObjects(_LMConnector);
2917
                        }
2918
                    }
2919

    
2920
                    ReleaseCOMObjects(targetModelItem);
2921
                }
2922
            }
2923
            else
2924
            {
2925
                LMSymbol connectedLMSymbol = null;
2926
                if (connectedSymbol != null)
2927
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2928
                else if (targetSymbol != null)
2929
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2930
                else
2931
                {
2932

    
2933
                }
2934
                LMModelItem targetModelItem = null;
2935
                if (targetLine != null)
2936
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2937
                else if (connectedLine != null)
2938
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2939
                else
2940
                {
2941

    
2942
                }
2943
                if (connectedLMSymbol != null && targetModelItem != null)
2944
                {
2945
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2946
                    {
2947
                        if (connector.get_ItemStatus() != "Active")
2948
                            continue;
2949

    
2950
                        if (IsConnected(connector, targetModelItem))
2951
                        {
2952
                            targetConnector = connector;
2953
                            break;
2954
                        }
2955
                    }
2956

    
2957
                    if (targetConnector == null)
2958
                    {
2959
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2960
                        {
2961
                            if (connector.get_ItemStatus() != "Active")
2962
                                continue;
2963

    
2964
                            if (IsConnected(connector, targetModelItem))
2965
                            {
2966
                                targetConnector = connector;
2967
                                break;
2968
                            }
2969
                        }
2970
                    }
2971
                }
2972

    
2973
            }
2974

    
2975
            return targetConnector;
2976
        }
2977

    
2978
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2979
        {
2980
            double[] result = null;
2981
            Line targetLine = targetObj as Line;
2982
            Symbol targetSymbol = targetObj as Symbol;
2983
            Line connLine = connObj as Line;
2984
            Symbol connSymbol = connObj as Symbol;
2985

    
2986
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
2987
            double lineMove = GridSetting.GetInstance().Length * 3;
2988
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2989
            {
2990
                result = GetConnectorVertices(targetConnector)[0];
2991
                if (targetSymbol != null && connSymbol != null)
2992
                {
2993
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
2994
                    if (slopeType == SlopeType.HORIZONTAL)
2995
                        result = new double[] { result[0], result[1] - zeroLengthMove };
2996
                    else if (slopeType == SlopeType.VERTICAL)
2997
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
2998
                }
2999
                else if (targetLine != null)
3000
                {
3001
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3002
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3003
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3004
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3005
                }
3006
                else if (connLine != null)
3007
                {
3008
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3009
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3010
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3011
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3012
                }
3013
            }
3014
            else
3015
            {
3016
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3017
                {
3018
                    Line line = connObj as Line;
3019
                    LMConnector connectedConnector = null;
3020
                    int connIndex = 0;
3021
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3022
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3023

    
3024
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3025

    
3026
                    ReleaseCOMObjects(modelItem);
3027
                    ReleaseCOMObjects(connectedConnector);
3028

    
3029
                    if (vertices.Count > 0)
3030
                    {
3031
                        if (connIndex == 1)
3032
                            result = vertices[0];
3033
                        else if (connIndex == 2)
3034
                            result = vertices[vertices.Count - 1];
3035

    
3036
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3037
                        {
3038
                            result = new double[] { result[0], result[1] - lineMove };
3039
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3040
                            {
3041
                                result = new double[] { result[0] - lineMove, result[1] };
3042
                            }
3043
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3044
                            {
3045
                                result = new double[] { result[0] + lineMove, result[1] };
3046
                            }
3047
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3048
                            {
3049
                                result = new double[] { result[0] + lineMove, result[1] };
3050
                            }
3051
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3052
                            {
3053
                                result = new double[] { result[0] - lineMove, result[1] };
3054
                            }
3055
                        }
3056
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3057
                        {
3058
                            result = new double[] { result[0] - lineMove, result[1] };
3059
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3060
                            {
3061
                                result = new double[] { result[0], result[1] - lineMove };
3062
                            }
3063
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3064
                            {
3065
                                result = new double[] { result[0], result[1] + lineMove };
3066
                            }
3067
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3068
                            {
3069
                                result = new double[] { result[0], result[1] + lineMove };
3070
                            }
3071
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3072
                            {
3073
                                result = new double[] { result[0], result[1] - lineMove };
3074
                            }
3075
                        }
3076
                            
3077
                    }
3078
                }
3079
                else
3080
                {
3081
                    Log.Write("error in GetSegemtPoint");
3082
                }
3083
            }
3084

    
3085
            return result;
3086
        }
3087

    
3088
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3089
        {
3090
            bool result = false;
3091

    
3092
            foreach (LMRepresentation rep in modelItem.Representations)
3093
            {
3094
                if (result)
3095
                    break;
3096

    
3097
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3098
                {
3099
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3100

    
3101
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3102
                        connector.ConnectItem1SymbolObject != null &&
3103
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3104
                    {
3105
                        result = true;
3106
                        ReleaseCOMObjects(_LMConnector);
3107
                        break;
3108
                    }
3109
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3110
                        connector.ConnectItem2SymbolObject != null &&
3111
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3112
                    {
3113
                        result = true;
3114
                        ReleaseCOMObjects(_LMConnector);
3115
                        break;
3116
                    }
3117
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3118
                        connector.ConnectItem1SymbolObject != null &&
3119
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3120
                    {
3121
                        result = true;
3122
                        ReleaseCOMObjects(_LMConnector);
3123
                        break;
3124
                    }
3125
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3126
                        connector.ConnectItem2SymbolObject != null &&
3127
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3128
                    {
3129
                        result = true;
3130
                        ReleaseCOMObjects(_LMConnector);
3131
                        break;
3132
                    }
3133

    
3134
                    ReleaseCOMObjects(_LMConnector);
3135
                }
3136
            }
3137

    
3138

    
3139
            return result;
3140
        }
3141

    
3142
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3143
        {
3144
            foreach (LMRepresentation rep in modelItem.Representations)
3145
            {
3146
                if (connectedConnector != null)
3147
                    break;
3148

    
3149
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3150
                {
3151
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3152

    
3153
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3154
                        connector.ConnectItem1SymbolObject != null &&
3155
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3156
                    {
3157
                        connectedConnector = _LMConnector;
3158
                        connectorIndex = 1;
3159
                        break;
3160
                    }
3161
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3162
                        connector.ConnectItem2SymbolObject != null &&
3163
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3164
                    {
3165
                        connectedConnector = _LMConnector;
3166
                        connectorIndex = 2;
3167
                        break;
3168
                    }
3169
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3170
                        connector.ConnectItem1SymbolObject != null &&
3171
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3172
                    {
3173
                        connectedConnector = _LMConnector;
3174
                        connectorIndex = 1;
3175
                        break;
3176
                    }
3177
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3178
                        connector.ConnectItem2SymbolObject != null &&
3179
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3180
                    {
3181
                        connectedConnector = _LMConnector;
3182
                        connectorIndex = 2;
3183
                        break;
3184
                    }
3185

    
3186
                    if (connectedConnector == null)
3187
                        ReleaseCOMObjects(_LMConnector);
3188
                }
3189
            }
3190
        }
3191

    
3192
        /// <summary>
3193
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3194
        /// </summary>
3195
        /// <param name="modelItemID1"></param>
3196
        /// <param name="modelItemID2"></param>
3197
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
3198
        {
3199
            try
3200
            {
3201
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3202
                _LMAItem item1 = modelItem1.AsLMAItem();
3203
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3204
                _LMAItem item2 = modelItem2.AsLMAItem();
3205

    
3206
                // item2가 item1으로 조인
3207
                _placement.PIDJoinRuns(ref item1, ref item2);
3208
                item1.Commit();
3209
                item2.Commit();
3210

    
3211
                string beforeID = string.Empty;
3212
                string afterID = string.Empty;
3213

    
3214
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3215
                {
3216
                    beforeID = modelItem2.Id;
3217
                    afterID = modelItem1.Id;
3218
                    survivorId = afterID;
3219
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
3220
                    if (attribute != null)
3221
                        attribute.set_Value("End 1 is upstream (Inlet)");
3222
                }
3223
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3224
                {
3225
                    beforeID = modelItem1.Id;
3226
                    afterID = modelItem2.Id;
3227
                    survivorId = afterID;
3228
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
3229
                    if (attribute != null)
3230
                        attribute.set_Value("End 1 is upstream (Inlet)");
3231
                }
3232
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3233
                    survivorId = null;
3234
                else
3235
                {
3236
                    Log.Write("잘못된 경우");
3237
                    survivorId = null;
3238
                }
3239

    
3240
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3241
                {
3242
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3243
                    foreach (var line in lines)
3244
                        line.SPPID.ModelItemId = afterID;
3245
                }
3246

    
3247
                ReleaseCOMObjects(modelItem1);
3248
                ReleaseCOMObjects(item1);
3249
                ReleaseCOMObjects(modelItem2);
3250
                ReleaseCOMObjects(item2);
3251
            }
3252
            catch (Exception ex)
3253
            {
3254
                Log.Write("Join Error");
3255
                Log.Write(ex.Message);
3256
            }
3257
        }
3258

    
3259
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3260
        {
3261
            List<string> temp = new List<string>();
3262
            List<LMConnector> connectors = new List<LMConnector>();
3263
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3264
            {
3265
                if (connector.get_ItemStatus() != "Active")
3266
                    continue;
3267

    
3268
                LMModelItem modelItem = connector.ModelItemObject;
3269
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3270
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3271
                    temp.Add(modelItem.Id);
3272

    
3273
                if (temp.Contains(modelItem.Id) &&
3274
                    connOtherSymbol != null &&
3275
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3276
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3277
                    temp.Remove(modelItem.Id);
3278

    
3279

    
3280
                if (temp.Contains(modelItem.Id))
3281
                    connectors.Add(connector);
3282
                ReleaseCOMObjects(connOtherSymbol);
3283
                connOtherSymbol = null;
3284
                ReleaseCOMObjects(modelItem);
3285
                modelItem = null;
3286
            }
3287

    
3288
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3289
            {
3290
                if (connector.get_ItemStatus() != "Active")
3291
                    continue;
3292

    
3293
                LMModelItem modelItem = connector.ModelItemObject;
3294
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3295
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3296
                    temp.Add(modelItem.Id);
3297

    
3298
                if (temp.Contains(modelItem.Id) &&
3299
                    connOtherSymbol != null &&
3300
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3301
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3302
                    temp.Remove(modelItem.Id);
3303

    
3304
                if (temp.Contains(modelItem.Id))
3305
                    connectors.Add(connector);
3306
                ReleaseCOMObjects(connOtherSymbol);
3307
                connOtherSymbol = null;
3308
                ReleaseCOMObjects(modelItem);
3309
                modelItem = null;
3310
            }
3311

    
3312

    
3313
            List<string> result = new List<string>();
3314
            string originalName = GetSPPIDFileName(modelId);
3315
            foreach (var connector in connectors)
3316
            {
3317
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3318
                if (originalName == fileName)
3319
                    result.Add(connector.ModelItemID);
3320
                else
3321
                {
3322
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3323
                        result.Add(connector.ModelItemID);
3324
                    else
3325
                    {
3326
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3327
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3328
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3329
                            result.Add(connector.ModelItemID);
3330
                    }
3331
                }
3332
            }
3333

    
3334
            foreach (var connector in connectors)
3335
                ReleaseCOMObjects(connector);
3336
            
3337
            return result;
3338

    
3339

    
3340
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3341
            {
3342
                LMSymbol findResult = null;
3343
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3344
                    findResult = connector.ConnectItem1SymbolObject;
3345
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3346
                    findResult = connector.ConnectItem2SymbolObject;
3347

    
3348
                return findResult;
3349
            }
3350
        }
3351

    
3352
        /// <summary>
3353
        /// PipeRun의 좌표를 가져오는 메서드
3354
        /// </summary>
3355
        /// <param name="modelId"></param>
3356
        /// <returns></returns>
3357
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3358
        {
3359
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3360
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3361

    
3362
            if (modelItem != null)
3363
            {
3364
                foreach (LMRepresentation rep in modelItem.Representations)
3365
                {
3366
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3367
                    {
3368
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3369
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3370
                        {
3371
                            ReleaseCOMObjects(_LMConnector);
3372
                            _LMConnector = null;
3373
                            continue;
3374
                        }
3375
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3376
                        dynamic OID = rep.get_GraphicOID().ToString();
3377
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3378
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3379
                        int verticesCount = lineStringGeometry.VertexCount;
3380
                        double[] vertices = null;
3381
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3382
                        for (int i = 0; i < verticesCount; i++)
3383
                        {
3384
                            double x = 0;
3385
                            double y = 0;
3386
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3387
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3388
                        }
3389
                    }
3390
                }
3391

    
3392
                ReleaseCOMObjects(modelItem);
3393
            }
3394

    
3395
            return connectorVertices;
3396
        }
3397

    
3398
        private List<double[]> GetConnectorVertices(LMConnector connector)
3399
        {
3400
            List<double[]> vertices = new List<double[]>();
3401
            if (connector != null)
3402
            {
3403
                dynamic OID = connector.get_GraphicOID().ToString();
3404
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3405
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3406
                int verticesCount = lineStringGeometry.VertexCount;
3407
                double[] value = null;
3408
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3409
                for (int i = 0; i < verticesCount; i++)
3410
                {
3411
                    double x = 0;
3412
                    double y = 0;
3413
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3414
                    vertices.Add(new double[] { x, y });
3415
                }
3416
            }
3417
            return vertices;
3418
        }
3419

    
3420
        /// <summary>
3421
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3422
        /// </summary>
3423
        /// <param name="connectorVertices"></param>
3424
        /// <param name="connX"></param>
3425
        /// <param name="connY"></param>
3426
        /// <returns></returns>
3427
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3428
        {
3429
            double length = double.MaxValue;
3430
            LMConnector targetConnector = null;
3431
            foreach (var item in connectorVertices)
3432
            {
3433
                List<double[]> points = item.Value;
3434
                for (int i = 0; i < points.Count - 1; i++)
3435
                {
3436
                    double[] point1 = points[i];
3437
                    double[] point2 = points[i + 1];
3438
                    double x1 = Math.Min(point1[0], point2[0]);
3439
                    double y1 = Math.Min(point1[1], point2[1]);
3440
                    double x2 = Math.Max(point1[0], point2[0]);
3441
                    double y2 = Math.Max(point1[1], point2[1]);
3442

    
3443
                    if ((x1 <= connX && x2 >= connX) ||
3444
                        (y1 <= connY && y2 >= connY))
3445
                    {
3446
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3447
                        if (length >= distance)
3448
                        {
3449
                            targetConnector = item.Key;
3450
                            length = distance;
3451
                        }
3452

    
3453
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3454
                        if (length >= distance)
3455
                        {
3456
                            targetConnector = item.Key;
3457
                            length = distance;
3458
                        }
3459
                    }
3460
                }
3461
            }
3462

    
3463
            // 못찾았을때.
3464
            length = double.MaxValue;
3465
            if (targetConnector == null)
3466
            {
3467
                foreach (var item in connectorVertices)
3468
                {
3469
                    List<double[]> points = item.Value;
3470

    
3471
                    foreach (double[] point in points)
3472
                    {
3473
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3474
                        if (length >= distance)
3475
                        {
3476
                            targetConnector = item.Key;
3477
                            length = distance;
3478
                        }
3479
                    }
3480
                }
3481
            }
3482

    
3483
            return targetConnector;
3484
        }
3485

    
3486
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3487
        {
3488
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3489
            if (vertices.Count == 0)
3490
                return null;
3491

    
3492
            double length = double.MaxValue;
3493
            LMConnector targetConnector = null;
3494
            double[] resultPoint = null;
3495
            List<double[]> targetVertices = null;
3496

    
3497
            // Vertices 포인트에 제일 가까운곳
3498
            foreach (var item in vertices)
3499
            {
3500
                List<double[]> points = item.Value;
3501
                for (int i = 0; i < points.Count; i++)
3502
                {
3503
                    double[] point = points[i];
3504
                    double tempX = point[0];
3505
                    double tempY = point[1];
3506

    
3507
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3508
                    if (length >= distance)
3509
                    {
3510
                        targetConnector = item.Key;
3511
                        length = distance;
3512
                        resultPoint = point;
3513
                        targetVertices = item.Value;
3514
                    }
3515
                }
3516
            }
3517

    
3518
            // Vertices Cross에 제일 가까운곳
3519
            foreach (var item in vertices)
3520
            {
3521
                List<double[]> points = item.Value;
3522
                for (int i = 0; i < points.Count - 1; i++)
3523
                {
3524
                    double[] point1 = points[i];
3525
                    double[] point2 = points[i + 1];
3526

    
3527
                    double maxLineX = Math.Max(point1[0], point2[0]);
3528
                    double minLineX = Math.Min(point1[0], point2[0]);
3529
                    double maxLineY = Math.Max(point1[1], point2[1]);
3530
                    double minLineY = Math.Min(point1[1], point2[1]);
3531

    
3532
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3533

    
3534
                    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]);
3535
                    if (crossingPoint != null)
3536
                    {
3537
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3538
                        if (length >= distance)
3539
                        {
3540
                            if (slope == SlopeType.Slope &&
3541
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3542
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3543
                            {
3544
                                targetConnector = item.Key;
3545
                                length = distance;
3546
                                resultPoint = crossingPoint;
3547
                                targetVertices = item.Value;
3548
                            }
3549
                            else if (slope == SlopeType.HORIZONTAL &&
3550
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3551
                            {
3552
                                targetConnector = item.Key;
3553
                                length = distance;
3554
                                resultPoint = crossingPoint;
3555
                                targetVertices = item.Value;
3556
                            }
3557
                            else if (slope == SlopeType.VERTICAL &&
3558
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3559
                            {
3560
                                targetConnector = item.Key;
3561
                                length = distance;
3562
                                resultPoint = crossingPoint;
3563
                                targetVertices = item.Value;
3564
                            }
3565
                        }
3566
                    }
3567
                }
3568
            }
3569

    
3570
            foreach (var item in vertices)
3571
                if (item.Key != null && item.Key != targetConnector)
3572
                    ReleaseCOMObjects(item.Key);
3573

    
3574
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3575
            {
3576
                double tempResultX = resultPoint[0];
3577
                double tempResultY = resultPoint[1];
3578
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3579

    
3580
                GridSetting gridSetting = GridSetting.GetInstance();
3581

    
3582
                for (int i = 0; i < targetVertices.Count; i++)
3583
                {
3584
                    double[] point = targetVertices[i];
3585
                    double tempX = targetVertices[i][0];
3586
                    double tempY = targetVertices[i][1];
3587
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3588
                    if (tempX == tempResultX && tempY == tempResultY)
3589
                    {
3590
                        if (i == 0)
3591
                        {
3592
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3593
                            bool containZeroLength = false;
3594
                            if (connSymbol != null)
3595
                            {
3596
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3597
                                {
3598
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3599
                                        containZeroLength = true;
3600
                                }
3601
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3602
                                {
3603
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3604
                                        containZeroLength = true;
3605
                                }
3606
                            }
3607

    
3608
                            if (connSymbol == null ||
3609
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3610
                                containZeroLength)
3611
                            {
3612
                                bool bCalcX = false;
3613
                                bool bCalcY = false;
3614
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3615
                                    bCalcX = true;
3616
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3617
                                    bCalcY = true;
3618
                                else
3619
                                {
3620
                                    bCalcX = true;
3621
                                    bCalcY = true;
3622
                                }
3623

    
3624
                                if (bCalcX)
3625
                                {
3626
                                    double nextX = targetVertices[i + 1][0];
3627
                                    double newX = 0;
3628
                                    if (nextX > tempX)
3629
                                    {
3630
                                        newX = tempX + gridSetting.Length;
3631
                                        if (newX > nextX)
3632
                                            newX = (point[0] + nextX) / 2;
3633
                                    }
3634
                                    else
3635
                                    {
3636
                                        newX = tempX - gridSetting.Length;
3637
                                        if (newX < nextX)
3638
                                            newX = (point[0] + nextX) / 2;
3639
                                    }
3640
                                    resultPoint = new double[] { newX, resultPoint[1] };
3641
                                }
3642

    
3643
                                if (bCalcY)
3644
                                {
3645
                                    double nextY = targetVertices[i + 1][1];
3646
                                    double newY = 0;
3647
                                    if (nextY > tempY)
3648
                                    {
3649
                                        newY = tempY + gridSetting.Length;
3650
                                        if (newY > nextY)
3651
                                            newY = (point[1] + nextY) / 2;
3652
                                    }
3653
                                    else
3654
                                    {
3655
                                        newY = tempY - gridSetting.Length;
3656
                                        if (newY < nextY)
3657
                                            newY = (point[1] + nextY) / 2;
3658
                                    }
3659
                                    resultPoint = new double[] { resultPoint[0], newY };
3660
                                }
3661
                            }
3662
                        }
3663
                        else if (i == targetVertices.Count - 1)
3664
                        {
3665
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3666
                            bool containZeroLength = false;
3667
                            if (connSymbol != null)
3668
                            {
3669
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3670
                                {
3671
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3672
                                        containZeroLength = true;
3673
                                }
3674
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3675
                                {
3676
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3677
                                        containZeroLength = true;
3678
                                }
3679
                            }
3680

    
3681
                            if (connSymbol == null ||
3682
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3683
                                containZeroLength)
3684
                            {
3685
                                bool bCalcX = false;
3686
                                bool bCalcY = false;
3687
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3688
                                    bCalcX = true;
3689
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3690
                                    bCalcY = true;
3691
                                else
3692
                                {
3693
                                    bCalcX = true;
3694
                                    bCalcY = true;
3695
                                }
3696

    
3697
                                if (bCalcX)
3698
                                {
3699
                                    double nextX = targetVertices[i - 1][0];
3700
                                    double newX = 0;
3701
                                    if (nextX > tempX)
3702
                                    {
3703
                                        newX = tempX + gridSetting.Length;
3704
                                        if (newX > nextX)
3705
                                            newX = (point[0] + nextX) / 2;
3706
                                    }
3707
                                    else
3708
                                    {
3709
                                        newX = tempX - gridSetting.Length;
3710
                                        if (newX < nextX)
3711
                                            newX = (point[0] + nextX) / 2;
3712
                                    }
3713
                                    resultPoint = new double[] { newX, resultPoint[1] };
3714
                                }
3715

    
3716
                                if (bCalcY)
3717
                                {
3718
                                    double nextY = targetVertices[i - 1][1];
3719
                                    double newY = 0;
3720
                                    if (nextY > tempY)
3721
                                    {
3722
                                        newY = tempY + gridSetting.Length;
3723
                                        if (newY > nextY)
3724
                                            newY = (point[1] + nextY) / 2;
3725
                                    }
3726
                                    else
3727
                                    {
3728
                                        newY = tempY - gridSetting.Length;
3729
                                        if (newY < nextY)
3730
                                            newY = (point[1] + nextY) / 2;
3731
                                    }
3732
                                    resultPoint = new double[] { resultPoint[0], newY };
3733
                                }
3734
                            }
3735
                        }
3736
                        break;
3737
                    }
3738
                }
3739
            }
3740

    
3741
            x = resultPoint[0];
3742
            y = resultPoint[1];
3743

    
3744
            return targetConnector;
3745
        }
3746

    
3747
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3748
        {
3749
            LMConnector result = null;
3750
            List<LMConnector> connectors = new List<LMConnector>();
3751
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3752

    
3753
            if (modelItem != null)
3754
            {
3755
                foreach (LMRepresentation rep in modelItem.Representations)
3756
                {
3757
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3758
                        connectors.Add(dataSource.GetConnector(rep.Id));
3759
                }
3760

    
3761
                ReleaseCOMObjects(modelItem);
3762
            }
3763

    
3764
            if (connectors.Count == 1)
3765
                result = connectors[0];
3766
            else
3767
                foreach (var item in connectors)
3768
                    ReleaseCOMObjects(item);
3769

    
3770
            return result;
3771
        }
3772

    
3773
        public List<string> GetRepresentations(string modelItemID)
3774
        {
3775
            List<string> result = new List<string>(); ;
3776
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3777
            if (modelItem != null)
3778
            {
3779
                foreach (LMRepresentation rep in modelItem.Representations)
3780
                {
3781
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3782
                        result.Add(rep.Id);
3783
                }
3784
                ReleaseCOMObjects(modelItem);
3785
            }
3786

    
3787
            return result;
3788
        }
3789

    
3790
        /// <summary>
3791
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3792
        /// </summary>
3793
        /// <param name="lineNumber"></param>
3794
        private void LineNumberModelingOnlyOne(Line line)
3795
        {
3796
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3797
            if (lineNumber != null)
3798
            {
3799
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3800
                if (connectedLMConnector != null)
3801
                {
3802
                    double x = 0;
3803
                    double y = 0;
3804
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3805

    
3806
                    Array points = new double[] { 0, x, y };
3807
                    lineNumber.SPPID.SPPID_X = x;
3808
                    lineNumber.SPPID.SPPID_Y = y;
3809
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3810

    
3811
                    if (_LmLabelPresist != null)
3812
                    {
3813
                        _LmLabelPresist.Commit();
3814
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3815
                        ReleaseCOMObjects(_LmLabelPresist);
3816
                    }
3817
                }
3818
            }
3819
        }
3820

    
3821
        private void LineNumberModeling(LineNumber lineNumber)
3822
        {
3823
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3824
            if (line != null)
3825
            {
3826
                double x = 0;
3827
                double y = 0;
3828
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3829

    
3830
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3831
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3832
                if (connectedLMConnector != null)
3833
                {
3834
                    Array points = new double[] { 0, x, y };
3835
                    lineNumber.SPPID.SPPID_X = x;
3836
                    lineNumber.SPPID.SPPID_Y = y;
3837
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3838

    
3839
                    if (_LmLabelPresist != null)
3840
                    {
3841
                        _LmLabelPresist.Commit();
3842
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3843
                        ReleaseCOMObjects(_LmLabelPresist);
3844
                    }
3845
                }
3846

    
3847
                foreach (var item in connectorVertices)
3848
                    ReleaseCOMObjects(item.Key);
3849
            }
3850
        }
3851
        private void LineNumberCorrectModeling(LineNumber lineNumber)
3852
        {
3853
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3854
            if (line == null || line.SPPID.Vertices == null)
3855
                return;
3856

    
3857
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
3858
            {
3859
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
3860
                if (removeLabel != null)
3861
                {
3862
                    GridSetting gridSetting = GridSetting.GetInstance();
3863
                    double[] labelRange = null;
3864
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
3865
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
3866
                    List<double[]> vertices = GetConnectorVertices(connector);
3867

    
3868
                    double[] resultStart = null;
3869
                    double[] resultEnd = null;
3870
                    double distance = double.MaxValue;
3871
                    for (int i = 0; i < vertices.Count - 1; i++)
3872
                    {
3873
                        double[] startPoint = vertices[i];
3874
                        double[] endPoint = vertices[i + 1];
3875
                        foreach (var item in line.SPPID.Vertices)
3876
                        {
3877
                            double[] lineStartPoint = item[0];
3878
                            double[] lineEndPoint = item[item.Count - 1];
3879

    
3880
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
3881
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
3882
                            if (tempDistance < distance)
3883
                            {
3884
                                distance = tempDistance;
3885
                                resultStart = startPoint;
3886
                                resultEnd = endPoint;
3887
                            }
3888
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
3889
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
3890
                            if (tempDistance < distance)
3891
                            {
3892
                                distance = tempDistance;
3893
                                resultStart = startPoint;
3894
                                resultEnd = endPoint;
3895
                            }
3896
                        }
3897
                    }
3898

    
3899
                    if (resultStart != null && resultEnd != null)
3900
                    {
3901
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
3902
                        double lineStartX = 0;
3903
                        double lineStartY = 0;
3904
                        double lineEndX = 0;
3905
                        double lineEndY = 0;
3906
                        double lineNumberX = 0;
3907
                        double lineNumberY = 0;
3908
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
3909
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
3910

    
3911
                        double lineX = (lineStartX + lineEndX) / 2;
3912
                        double lineY = (lineStartY + lineEndY) / 2;
3913
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
3914
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
3915

    
3916
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
3917
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
3918
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
3919
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
3920

    
3921
                        double offsetX = 0;
3922
                        double offsetY = 0;
3923
                        if (slope == SlopeType.HORIZONTAL)
3924
                        {
3925
                            // Line Number 아래
3926
                            if (lineY < lineNumberY)
3927
                            {
3928
                                offsetX = labelCenterX - SPPIDCenterX;
3929
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
3930
                                MoveLineNumber(lineNumber, offsetX, offsetY);
3931
                            }
3932
                            // Line Number 위
3933
                            else
3934
                            {
3935
                                offsetX = labelCenterX - SPPIDCenterX;
3936
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
3937
                                MoveLineNumber(lineNumber, offsetX, offsetY);
3938
                            }
3939
                        }
3940
                        else if (slope == SlopeType.VERTICAL)
3941
                        {
3942
                            // Line Number 오르쪽
3943
                            if (lineX < lineNumberX)
3944
                            {
3945
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
3946
                                offsetY = labelCenterY - SPPIDCenterY;
3947
                                MoveLineNumber(lineNumber, offsetX, offsetY);
3948
                            }
3949
                            // Line Number 왼쪽
3950
                            else
3951
                            {
3952
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
3953
                                offsetY = labelCenterY - SPPIDCenterY;
3954
                                MoveLineNumber(lineNumber, offsetX, offsetY);
3955
                            }
3956
                        }
3957

    
3958
                        if (offsetY != 0 && offsetY != 0)
3959
                        {
3960
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
3961
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
3962
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
3963

    
3964
                            if (_LmLabelPresist != null)
3965
                            {
3966
                                _LmLabelPresist.Commit();
3967
                                lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3968
                            }
3969
                            ReleaseCOMObjects(_LmLabelPresist);
3970
                            _LmLabelPresist = null; 
3971
                        }
3972

    
3973
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
3974
                        {
3975
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
3976
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
3977
                        }
3978
                    }
3979

    
3980

    
3981
                    ReleaseCOMObjects(connector);
3982
                    connector = null;
3983
                }
3984

    
3985
                ReleaseCOMObjects(removeLabel);
3986
                removeLabel = null;
3987
            }
3988
        }
3989
        /// <summary>
3990
        /// Flow Mark Modeling
3991
        /// </summary>
3992
        /// <param name="line"></param>
3993
        private void FlowMarkModeling(Line line)
3994
        {
3995
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3996
            {
3997
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3998
                if (connector != null)
3999
                {
4000
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4001
                    List<double[]> vertices = GetConnectorVertices(connector);
4002
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4003
                    double[] point = vertices[vertices.Count - 1];
4004
                    Array array = new double[] { 0, point[0], point[1] };
4005
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4006
                    if (_LMLabelPersist != null)
4007
                    {
4008
                        _LMLabelPersist.Commit();
4009
                        ReleaseCOMObjects(_LMLabelPersist);
4010
                    }
4011
                        
4012
                }
4013
            }
4014
        }
4015

    
4016
        /// <summary>
4017
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4018
        /// </summary>
4019
        /// <param name="lineNumber"></param>
4020
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4021
        {
4022
            foreach (LineRun run in lineNumber.RUNS)
4023
            {
4024
                foreach (var item in run.RUNITEMS)
4025
                {
4026
                    if (item.GetType() == typeof(Symbol))
4027
                    {
4028
                        Symbol symbol = item as Symbol;
4029
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4030
                        if (_LMSymbol != null)
4031
                        {
4032
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4033

    
4034
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4035
                            {
4036
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4037
                                {
4038
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4039
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4040
                                    {
4041
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4042
                                        if (_LMAAttribute != null)
4043
                                        {
4044
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4045
                                                _LMAAttribute.set_Value(attribute.VALUE);
4046
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4047
                                                _LMAAttribute.set_Value(attribute.VALUE);
4048
                                        }
4049
                                    }
4050
                                }
4051
                                _LMModelItem.Commit();
4052
                            }
4053
                            if (_LMModelItem != null)
4054
                                ReleaseCOMObjects(_LMModelItem);
4055
                        }
4056
                        if (_LMSymbol != null)
4057
                            ReleaseCOMObjects(_LMSymbol);
4058
                    }
4059
                    else if (item.GetType() == typeof(Line))
4060
                    {
4061
                        Line line = item as Line;
4062
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4063
                        {
4064
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4065
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4066
                            {
4067
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4068
                                {
4069
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4070
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4071
                                    {
4072
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4073
                                        if (_LMAAttribute != null)
4074
                                        {
4075
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4076
                                                _LMAAttribute.set_Value(attribute.VALUE);
4077
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4078
                                                _LMAAttribute.set_Value(attribute.VALUE);
4079

    
4080
                                        }
4081
                                    }
4082
                                }
4083
                                _LMModelItem.Commit();
4084
                            }
4085
                            if (_LMModelItem != null)
4086
                                ReleaseCOMObjects(_LMModelItem);
4087
                            endLine.Add(line.SPPID.ModelItemId);
4088
                        }
4089
                    }
4090
                }
4091
            }
4092
        }
4093

    
4094
        /// <summary>
4095
        /// Symbol Attribute 입력 메서드
4096
        /// </summary>
4097
        /// <param name="item"></param>
4098
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4099
        {
4100
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4101
            string sRep = null;
4102
            if (targetItem.GetType() == typeof(Symbol))
4103
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4104
            else if (targetItem.GetType() == typeof(Equipment))
4105
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4106

    
4107
            if (!string.IsNullOrEmpty(sRep))
4108
            {
4109
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4110
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4111
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4112
                
4113
                foreach (var item in targetAttributes)
4114
                {
4115
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4116
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4117
                    {
4118
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4119
                        if (_Attribute != null)
4120
                        {
4121
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
4122
                            //if (associItem != null)
4123
                            //{
4124
                            //    if (associItem.GetType() == typeof(Text))
4125
                            //    {
4126
                            //        Text text = associItem as Text;
4127
                            //        text.SPPID.RepresentationId = "Attribute";
4128
                            //    }
4129
                            //    else if (associItem.GetType() == typeof(Note))
4130
                            //    {
4131
                            //        Note note = associItem as Note;
4132
                            //        note.SPPID.RepresentationId = "Attribute";
4133
                            //    }
4134
                            //}
4135
                            _Attribute.set_Value(item.VALUE);
4136
                            // OPC 일경우 Attribute 저장
4137
                            if (targetItem.GetType() == typeof(Symbol))
4138
                            {
4139
                                Symbol symbol = targetItem as Symbol;
4140
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4141
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4142
                            }
4143
                        }
4144
                    }
4145
                }
4146
                _LMModelItem.Commit();
4147

    
4148
                ReleaseCOMObjects(_Attributes);
4149
                ReleaseCOMObjects(_LMModelItem);
4150
                ReleaseCOMObjects(_LMSymbol);
4151
            }
4152
        }
4153

    
4154
        /// <summary>
4155
        /// Input SpecBreak Attribute
4156
        /// </summary>
4157
        /// <param name="specBreak"></param>
4158
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4159
        {
4160
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4161
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4162

    
4163
            if (upStreamObj != null &&
4164
                downStreamObj != null)
4165
            {
4166
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4167

    
4168
                if (targetLMConnector != null)
4169
                {
4170
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4171
                    {
4172
                        string symbolPath = _LMLabelPersist.get_FileName();
4173
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4174
                        if (mapping != null)
4175
                        {
4176
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4177
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4178
                            {
4179
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4180
                                if (values.Length == 2)
4181
                                {
4182
                                    string upStreamValue = values[0];
4183
                                    string downStreamValue = values[1];
4184

    
4185
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4186
                                }
4187
                            }
4188
                        }
4189
                    }
4190

    
4191
                    ReleaseCOMObjects(targetLMConnector);
4192
                }
4193
            }
4194

    
4195

    
4196
            #region 내부에서만 쓰는 메서드
4197
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4198
            {
4199
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4200
                Line upStreamLine = _upStreamObj as Line;
4201
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4202
                Line downStreamLine = _downStreamObj as Line;
4203
                // 둘다 Line일 경우
4204
                if (upStreamLine != null && downStreamLine != null)
4205
                {
4206
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4207
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4208
                }
4209
                // 둘다 Symbol일 경우
4210
                else if (upStreamSymbol != null && downStreamSymbol != null)
4211
                {
4212
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4213
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4214
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4215

    
4216
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4217
                    {
4218
                        if (connector.get_ItemStatus() != "Active")
4219
                            continue;
4220

    
4221
                        if (connector.Id != zeroLenthConnector.Id)
4222
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4223
                    }
4224

    
4225
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4226
                    {
4227
                        if (connector.get_ItemStatus() != "Active")
4228
                            continue;
4229

    
4230
                        if (connector.Id != zeroLenthConnector.Id)
4231
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4232
                    }
4233

    
4234
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4235
                    {
4236
                        if (connector.get_ItemStatus() != "Active")
4237
                            continue;
4238

    
4239
                        if (connector.Id != zeroLenthConnector.Id)
4240
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4241
                    }
4242

    
4243
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4244
                    {
4245
                        if (connector.get_ItemStatus() != "Active")
4246
                            continue;
4247

    
4248
                        if (connector.Id != zeroLenthConnector.Id)
4249
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4250
                    }
4251

    
4252
                    ReleaseCOMObjects(zeroLenthConnector);
4253
                    ReleaseCOMObjects(upStreamLMSymbol);
4254
                    ReleaseCOMObjects(downStreamLMSymbol);
4255
                }
4256
                else if (upStreamSymbol != null && downStreamLine != null)
4257
                {
4258
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4259
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4260
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4261

    
4262
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4263
                    {
4264
                        if (connector.get_ItemStatus() != "Active")
4265
                            continue;
4266

    
4267
                        if (connector.Id == zeroLenthConnector.Id)
4268
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4269
                    }
4270

    
4271
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4272
                    {
4273
                        if (connector.get_ItemStatus() != "Active")
4274
                            continue;
4275

    
4276
                        if (connector.Id == zeroLenthConnector.Id)
4277
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4278
                    }
4279

    
4280
                    ReleaseCOMObjects(zeroLenthConnector);
4281
                    ReleaseCOMObjects(upStreamLMSymbol);
4282
                }
4283
                else if (upStreamLine != null && downStreamSymbol != null)
4284
                {
4285
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4286
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4287
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4288

    
4289
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4290
                    {
4291
                        if (connector.get_ItemStatus() != "Active")
4292
                            continue;
4293

    
4294
                        if (connector.Id == zeroLenthConnector.Id)
4295
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4296
                    }
4297

    
4298
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4299
                    {
4300
                        if (connector.get_ItemStatus() != "Active")
4301
                            continue;
4302

    
4303
                        if (connector.Id == zeroLenthConnector.Id)
4304
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4305
                    }
4306

    
4307
                    ReleaseCOMObjects(zeroLenthConnector);
4308
                    ReleaseCOMObjects(downStreamLMSymbol);
4309
                }
4310
            }
4311

    
4312
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4313
            {
4314
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4315
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4316
                {
4317
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4318
                    if (_LMAAttribute != null)
4319
                    {
4320
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4321
                            _LMAAttribute.set_Value(value);
4322
                        else if (_LMAAttribute.get_Value() != value)
4323
                            _LMAAttribute.set_Value(value);
4324
                    }
4325

    
4326
                    _LMModelItem.Commit();
4327
                }
4328
                if (_LMModelItem != null)
4329
                    ReleaseCOMObjects(_LMModelItem);
4330
            }
4331

    
4332
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4333
            {
4334
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4335
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4336
                {
4337
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4338
                    if (_LMAAttribute != null)
4339
                    {
4340
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4341
                            _LMAAttribute.set_Value(value);
4342
                        else if (_LMAAttribute.get_Value() != value)
4343
                            _LMAAttribute.set_Value(value);
4344
                    }
4345

    
4346
                    _LMModelItem.Commit();
4347
                }
4348
                if (_LMModelItem != null)
4349
                    ReleaseCOMObjects(_LMModelItem);
4350
            }
4351
            #endregion
4352
        }
4353

    
4354
        /// <summary>
4355
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4356
        /// </summary>
4357
        /// <param name="text"></param>
4358
        private void NormalTextModeling(Text text)
4359
        {
4360
            LMSymbol _LMSymbol = null;
4361

    
4362
            LMItemNote _LMItemNote = null;
4363
            LMAAttribute _LMAAttribute = null;
4364

    
4365
            double x = 0;
4366
            double y = 0;
4367
            double angle = text.ANGLE;
4368
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
4369

    
4370
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4371
            text.SPPID.SPPID_X = x;
4372
            text.SPPID.SPPID_Y = y;
4373

    
4374
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
4375
            if (_LMSymbol != null)
4376
            {
4377
                _LMSymbol.Commit();
4378
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4379
                if (_LMItemNote != null)
4380
                {
4381
                    _LMItemNote.Commit();
4382
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4383
                    if (_LMAAttribute != null)
4384
                    {
4385
                        _LMAAttribute.set_Value(text.VALUE);
4386
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4387
                        _LMItemNote.Commit();
4388

    
4389

    
4390
                        double[] range = null;
4391
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4392
                        {
4393
                            double[] temp = null;
4394
                            GetSPPIDSymbolRange(labelPersist, ref temp);
4395
                            if (temp != null)
4396
                            {
4397
                                if (range == null)
4398
                                    range = temp;
4399
                                else
4400
                                {
4401
                                    range = new double[] {
4402
                                            Math.Min(range[0], temp[0]),
4403
                                            Math.Min(range[1], temp[1]),
4404
                                            Math.Max(range[2], temp[2]),
4405
                                            Math.Max(range[3], temp[3])
4406
                                        };
4407
                                }
4408
                            }
4409
                        }
4410
                        text.SPPID.Range = range;
4411

    
4412
                        if (_LMAAttribute != null)
4413
                            ReleaseCOMObjects(_LMAAttribute);
4414
                        if (_LMItemNote != null)
4415
                            ReleaseCOMObjects(_LMItemNote);
4416
                    }
4417

    
4418
                    TextCorrectModeling(text);
4419
                }
4420
            }
4421
            if (_LMSymbol != null)
4422
                ReleaseCOMObjects(_LMSymbol);
4423
        }
4424

    
4425
        private void AssociationTextModeling(Text text)
4426
        {
4427
            LMSymbol _LMSymbol = null;
4428
            LMConnector connectedLMConnector = null;
4429
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4430
            if (owner != null && owner.GetType() == typeof(Symbol))
4431
            {
4432
                Symbol symbol = owner as Symbol;
4433
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4434
                if (_LMSymbol != null)
4435
                {
4436
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4437
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4438
                    {
4439
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4440

    
4441
                        if (mapping != null)
4442
                        {
4443
                            double x = 0;
4444
                            double y = 0;
4445

    
4446
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4447
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4448
                            Array array = new double[] { 0, x, y };
4449
                            text.SPPID.SPPID_X = x;
4450
                            text.SPPID.SPPID_Y = y;
4451
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4452
                            if (_LMLabelPersist != null)
4453
                            {
4454
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4455
                                _LMLabelPersist.Commit();
4456
                                ReleaseCOMObjects(_LMLabelPersist);
4457
                            }
4458
                        }
4459
                    }
4460
                }
4461
            }
4462
            else if (owner != null && owner.GetType() == typeof(Line))
4463
            {
4464
                Line line = owner as Line;
4465
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4466
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
4467

    
4468
                if (connectedLMConnector != null)
4469
                {
4470
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4471
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4472
                    {
4473
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4474

    
4475
                        if (mapping != null)
4476
                        {
4477
                            double x = 0;
4478
                            double y = 0;
4479
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4480
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4481
                            Array array = new double[] { 0, x, y };
4482

    
4483
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4484
                            if (_LMLabelPersist != null)
4485
                            {
4486
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4487
                                _LMLabelPersist.Commit();
4488
                                ReleaseCOMObjects(_LMLabelPersist);
4489
                            }
4490
                        }
4491
                    }
4492
                }
4493
            }
4494
            if (_LMSymbol != null)
4495
                ReleaseCOMObjects(_LMSymbol);
4496
        }
4497

    
4498
        private void TextCorrectModeling(Text text)
4499
        {
4500
            if (text.SPPID.Range == null)
4501
                return;
4502

    
4503
            bool needRemodeling = false;
4504
            bool loop = true;
4505
            GridSetting gridSetting = GridSetting.GetInstance();
4506
            while (loop)
4507
            {
4508
                loop = false;
4509
                foreach (var overlapText in document.TEXTINFOS)
4510
                {
4511
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
4512
                        continue;
4513

    
4514
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
4515
                    {
4516
                        double percentX = 0;
4517
                        double percentY = 0;
4518
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
4519
                        {
4520
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
4521
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
4522
                        }
4523
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
4524
                        {
4525
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
4526
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
4527
                        }
4528

    
4529
                        double tempX = 0;
4530
                        double tempY = 0;
4531
                        bool overlapX = false;
4532
                        bool overlapY = false;
4533
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4534
                        if (percentX >= percentY)
4535
                        {
4536
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4537
                            double move = gridSetting.Length * count;
4538
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
4539
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
4540
                            needRemodeling = true;
4541
                            loop = true;
4542
                        }
4543
                        else
4544
                        {
4545
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4546
                            double move = gridSetting.Length * count;
4547
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
4548
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
4549
                            needRemodeling = true;
4550
                            loop = true;
4551
                        }
4552
                    }
4553
                }
4554
            }
4555
            
4556

    
4557
            if (needRemodeling)
4558
            {
4559
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
4560
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4561
                text.SPPID.RepresentationId = null;
4562

    
4563
                LMItemNote _LMItemNote = null;
4564
                LMAAttribute _LMAAttribute = null;
4565
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
4566
                if (_LMSymbol != null)
4567
                {
4568
                    _LMSymbol.Commit();
4569
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4570
                    if (_LMItemNote != null)
4571
                    {
4572
                        _LMItemNote.Commit();
4573
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4574
                        if (_LMAAttribute != null)
4575
                        {
4576
                            _LMAAttribute.set_Value(text.VALUE);
4577
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4578
                            _LMItemNote.Commit();
4579

    
4580
                            ReleaseCOMObjects(_LMAAttribute);
4581
                            ReleaseCOMObjects(_LMItemNote);
4582
                        }
4583
                    }
4584
                }
4585

    
4586
                ReleaseCOMObjects(symbol);
4587
                symbol = null;
4588
                ReleaseCOMObjects(_LMItemNote);
4589
                _LMItemNote = null;
4590
                ReleaseCOMObjects(_LMAAttribute);
4591
                _LMAAttribute = null;
4592
                ReleaseCOMObjects(_LMSymbol);
4593
                _LMSymbol = null;
4594
            }
4595
        }
4596

    
4597
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
4598
        {
4599
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
4600
            {
4601
                List<Text> texts = new List<Text>();
4602
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4603
                LMRepresentation representation = targetLabel.RepresentationObject;
4604
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
4605
                if (targetLabel.RepresentationObject != null && symbol != null)
4606
                {
4607
                    double[] symbolRange = null;
4608
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
4609
                    if (symbolRange != null)
4610
                    {
4611
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
4612
                        {
4613
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
4614
                            if (findText != null)
4615
                            {
4616
                                double[] range = null;
4617
                                GetSPPIDSymbolRange(labelPersist, ref range);
4618
                                findText.SPPID.Range = range;
4619
                                texts.Add(findText);
4620
                            }
4621

    
4622
                            ReleaseCOMObjects(labelPersist);
4623
                        }
4624

    
4625
                        if (texts.Count > 0)
4626
                        {
4627
                            #region Sort Text By Y
4628
                            texts.Sort(SortTextByY);
4629
                            int SortTextByY(Text a, Text b)
4630
                            {
4631
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
4632
                            }
4633
                            #endregion
4634

    
4635
                            #region 첫번째 Text로 기준 맞춤
4636
                            for (int i = 0; i < texts.Count; i++)
4637
                            {
4638
                                if (i != 0)
4639
                                {
4640
                                    Text currentText = texts[i];
4641
                                    Text prevText = texts[i - 1];
4642
                                    double minY = prevText.SPPID.Range[1];
4643
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
4644
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
4645
                                    double _gapX = centerX - centerPrevX;
4646
                                    double _gapY = currentText.SPPID.Range[3] - minY;
4647
                                    MoveText(currentText, _gapX, _gapY);
4648
                                }
4649
                            }
4650
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
4651
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
4652
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
4653
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
4654
                            rangeMinX.Sort();
4655
                            rangeMinY.Sort();
4656
                            rangeMaxX.Sort();
4657
                            rangeMaxY.Sort();
4658
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
4659
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
4660
                            #endregion
4661

    
4662
                            Text correctBySymbol = texts[0];
4663
                            double textCenterX = (text.X1 + text.X2) / 2;
4664
                            double textCenterY = (text.Y1 + text.Y2) / 2;
4665
                            double originX = 0;
4666
                            double originY = 0;
4667
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
4668
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
4669
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
4670
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
4671

    
4672
                            double gapX = 0;
4673
                            double gapY = 0;
4674
                            if (angle < 45)
4675
                            {
4676
                                // Text 오른쪽
4677
                                if (textCenterX > originX)
4678
                                {
4679
                                    gapX = rangeMinX[0] - symbolRange[2];
4680
                                    gapY = allTextCenterY - symbolCenterY;
4681
                                }
4682
                                // Text 왼쪽
4683
                                else
4684
                                {
4685
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
4686
                                    gapY = allTextCenterY - symbolCenterY;
4687
                                }
4688
                            }
4689
                            else
4690
                            {
4691
                                // Text 아래쪽
4692
                                if (textCenterY > originY)
4693
                                {
4694
                                    gapX = allTextCenterX - symbolCenterX;
4695
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
4696
                                }
4697
                                // Text 위쪽
4698
                                else
4699
                                {
4700
                                    gapX = allTextCenterX - symbolCenterX;
4701
                                    gapY = rangeMinY[0] - symbolRange[3];
4702
                                }
4703
                            }
4704

    
4705
                            foreach (var item in texts)
4706
                            {
4707
                                MoveText(item, gapX, gapY);
4708
                                RemodelingAssociationText(item);
4709
                            }
4710
                        }
4711
                    }
4712
                }
4713

    
4714
                void MoveText(Text moveText, double x, double y)
4715
                {
4716
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
4717
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
4718
                    moveText.SPPID.Range = new double[] {
4719
                        moveText.SPPID.Range[0] - x,
4720
                        moveText.SPPID.Range[1]- y,
4721
                        moveText.SPPID.Range[2]- x,
4722
                        moveText.SPPID.Range[3]- y
4723
                    };
4724
                }
4725

    
4726
                endTexts.AddRange(texts);
4727

    
4728
                ReleaseCOMObjects(targetLabel);
4729
                targetLabel = null;
4730
                ReleaseCOMObjects(representation);
4731
                representation = null;
4732
            }
4733
        }
4734

    
4735
        private void RemodelingAssociationText(Text text)
4736
        {
4737
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4738
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4739
            removeLabel.Commit();
4740
            ReleaseCOMObjects(removeLabel);
4741
            removeLabel = null;
4742

    
4743
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4744
            if (owner != null && owner.GetType() == typeof(Symbol))
4745
            {
4746
                Symbol symbol = owner as Symbol;
4747
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4748
                if (_LMSymbol != null)
4749
                {
4750
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4751
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4752
                    {
4753
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4754

    
4755
                        if (mapping != null)
4756
                        {
4757
                            double x = 0;
4758
                            double y = 0;
4759

    
4760
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
4761
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4762
                            if (_LMLabelPersist != null)
4763
                            {
4764
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4765
                                _LMLabelPersist.Commit();
4766
                            }
4767
                            ReleaseCOMObjects(_LMLabelPersist);
4768
                            _LMLabelPersist = null;
4769
                        }
4770
                    }
4771
                }
4772
                ReleaseCOMObjects(_LMSymbol);
4773
                _LMSymbol = null;
4774
            }
4775
        }
4776

    
4777
        /// <summary>
4778
        /// Note Modeling
4779
        /// </summary>
4780
        /// <param name="note"></param>
4781
        private void NoteModeling(Note note, List<Note> correctList)
4782
        {
4783
            LMSymbol _LMSymbol = null;
4784
            LMItemNote _LMItemNote = null;
4785
            LMAAttribute _LMAAttribute = null;
4786

    
4787
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
4788
            {
4789
                double x = 0;
4790
                double y = 0;
4791

    
4792
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
4793
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
4794
                note.SPPID.SPPID_X = x;
4795
                note.SPPID.SPPID_Y = y;
4796

    
4797
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
4798
                if (_LMSymbol != null)
4799
                {
4800
                    _LMSymbol.Commit();
4801
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4802
                    if (_LMItemNote != null)
4803
                    {
4804
                        _LMItemNote.Commit();
4805
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4806
                        if (_LMAAttribute != null)
4807
                        {
4808
                            _LMAAttribute.set_Value(note.VALUE);
4809
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4810

    
4811
                            double[] range = null;
4812
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4813
                            {
4814
                                double[] temp = null;
4815
                                GetSPPIDSymbolRange(labelPersist, ref temp);
4816
                                if (temp != null)
4817
                                {
4818
                                    if (range == null)
4819
                                        range = temp;
4820
                                    else
4821
                                    {
4822
                                        range = new double[] {
4823
                                            Math.Min(range[0], temp[0]),
4824
                                            Math.Min(range[1], temp[1]),
4825
                                            Math.Max(range[2], temp[2]),
4826
                                            Math.Max(range[3], temp[3])
4827
                                        };
4828
                                    }
4829
                                }
4830
                            }
4831
                            if (range != null)
4832
                                correctList.Add(note);
4833
                            note.SPPID.Range = range;
4834

    
4835

    
4836
                            _LMItemNote.Commit();
4837
                        }
4838
                    }
4839
                }
4840
            }
4841

    
4842
            if (_LMAAttribute != null)
4843
                ReleaseCOMObjects(_LMAAttribute);
4844
            if (_LMItemNote != null)
4845
                ReleaseCOMObjects(_LMItemNote);
4846
            if (_LMSymbol != null)
4847
                ReleaseCOMObjects(_LMSymbol);
4848
        }
4849

    
4850
        private void NoteCorrectModeling(Note note, List<Note> endList)
4851
        {
4852
            bool needRemodeling = false;
4853
            bool loop = true;
4854
            GridSetting gridSetting = GridSetting.GetInstance();
4855
            while (loop)
4856
            {
4857
                loop = false;
4858
                foreach (var overlap in endList)
4859
                {
4860
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
4861
                    {
4862
                        double tempX = 0;
4863
                        double tempY = 0;
4864
                        bool overlapX = false;
4865
                        bool overlapY = false;
4866
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4867
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
4868
                        if (overlapY && angle >= 45)
4869
                        {
4870
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4871
                            double move = gridSetting.Length * count;
4872
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
4873
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
4874
                            needRemodeling = true;
4875
                            loop = true;
4876
                        }
4877
                        if (overlapX && angle <= 45)
4878
                        {
4879
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4880
                            double move = gridSetting.Length * count;
4881
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
4882
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
4883
                            needRemodeling = true;
4884
                            loop = true;
4885
                        }
4886
                    }
4887
                }
4888
            }
4889

    
4890

    
4891
            if (needRemodeling)
4892
            {
4893
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
4894
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4895
                note.SPPID.RepresentationId = null;
4896

    
4897
                LMItemNote _LMItemNote = null;
4898
                LMAAttribute _LMAAttribute = null;
4899
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
4900
                if (_LMSymbol != null)
4901
                {
4902
                    _LMSymbol.Commit();
4903
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4904
                    if (_LMItemNote != null)
4905
                    {
4906
                        _LMItemNote.Commit();
4907
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4908
                        if (_LMAAttribute != null)
4909
                        {
4910
                            _LMAAttribute.set_Value(note.VALUE);
4911
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4912
                            _LMItemNote.Commit();
4913

    
4914
                            ReleaseCOMObjects(_LMAAttribute);
4915
                            ReleaseCOMObjects(_LMItemNote);
4916
                        }
4917
                    }
4918
                }
4919

    
4920
                ReleaseCOMObjects(symbol);
4921
                symbol = null;
4922
                ReleaseCOMObjects(_LMItemNote);
4923
                _LMItemNote = null;
4924
                ReleaseCOMObjects(_LMAAttribute);
4925
                _LMAAttribute = null;
4926
                ReleaseCOMObjects(_LMSymbol);
4927
                _LMSymbol = null;
4928
            }
4929

    
4930
            endList.Add(note);
4931
        }
4932

    
4933
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
4934
        {
4935
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4936
            if (modelItem != null)
4937
            {
4938
                foreach (LMRepresentation rep in modelItem.Representations)
4939
                {
4940
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4941
                    {
4942
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4943
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4944
                        {
4945
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
4946
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4947
                            if (modelItemIds.Count == 1)
4948
                            {
4949
                                string joinModelItemId = modelItemIds[0];
4950
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4951
                                if (survivorId != null)
4952
                                    break;
4953
                            }
4954
                        }
4955
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4956
                        {
4957
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
4958
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4959
                            if (modelItemIds.Count == 1)
4960
                            {
4961
                                string joinModelItemId = modelItemIds[0];
4962
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4963
                                if (survivorId != null)
4964
                                    break;
4965
                            }
4966
                        }
4967
                    }
4968
                }
4969
            }
4970
        }
4971

    
4972
        /// <summary>
4973
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
4974
        /// </summary>
4975
        /// <param name="x"></param>
4976
        /// <param name="y"></param>
4977
        /// <param name="originX"></param>
4978
        /// <param name="originY"></param>
4979
        /// <param name="SPPIDLabelLocation"></param>
4980
        /// <param name="location"></param>
4981
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
4982
        {
4983
            if (location == Location.None)
4984
            {
4985
                x = originX;
4986
                y = originY;
4987
            }
4988
            else
4989
            {
4990
                if (location.HasFlag(Location.Center))
4991
                {
4992
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
4993
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
4994
                }
4995

    
4996
                if (location.HasFlag(Location.Left))
4997
                    x = SPPIDLabelLocation.X1;
4998
                else if (location.HasFlag(Location.Right))
4999
                    x = SPPIDLabelLocation.X2;
5000

    
5001
                if (location.HasFlag(Location.Down))
5002
                    y = SPPIDLabelLocation.Y1;
5003
                else if (location.HasFlag(Location.Up))
5004
                    y = SPPIDLabelLocation.Y2;
5005
            }
5006
        }
5007

    
5008
        /// <summary>
5009
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5010
        /// 1. Angle Valve
5011
        /// 2. 3개로 이루어진 Symbol Group
5012
        /// </summary>
5013
        /// <returns></returns>
5014
        private List<Symbol> GetPrioritySymbol()
5015
        {
5016
            DataTable symbolTable = document.SymbolTable;
5017
            // List에 순서대로 쌓는다.
5018
            List<Symbol> symbols = new List<Symbol>();
5019

    
5020
            // Angle Valve 부터
5021
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5022
            {
5023
                if (!symbols.Contains(symbol))
5024
                {
5025
                    double originX = 0;
5026
                    double originY = 0;
5027

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

    
5032
                    SlopeType slopeType1 = SlopeType.None;
5033
                    SlopeType slopeType2 = SlopeType.None;
5034
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5035
                    {
5036
                        double connectorX = 0;
5037
                        double connectorY = 0;
5038
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5039
                        if (slopeType1 == SlopeType.None)
5040
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5041
                        else
5042
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5043
                    }
5044

    
5045
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5046
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5047
                        symbols.Add(symbol);
5048
                }
5049
            }
5050

    
5051
            List<Symbol> tempSymbols = new List<Symbol>();
5052
            // Conn 갯수 기준
5053
            foreach (var item in document.SYMBOLS)
5054
            {
5055
                if (!symbols.Contains(item))
5056
                    tempSymbols.Add(item);
5057
            }
5058
            tempSymbols.Sort(SortSymbolPriority);
5059
            symbols.AddRange(tempSymbols);
5060

    
5061
            return symbols;
5062
        }
5063

    
5064
        private void SetPriorityLine(List<Line> lines)
5065
        {
5066
            lines.Sort(SortLinePriority);
5067

    
5068
            int SortLinePriority(Line a, Line b)
5069
            {
5070
                // Branch 없는것부터
5071
                int branchRetval = CompareBranchLine(a, b);
5072
                if (branchRetval != 0)
5073
                {
5074
                    return branchRetval;
5075
                }
5076
                else
5077
                {
5078
                    // Symbol 연결 갯수
5079
                    int connSymbolRetval = CompareConnSymbol(a, b);
5080
                    if (connSymbolRetval != 0)
5081
                    {
5082
                        return connSymbolRetval;
5083
                    }
5084
                    else
5085
                    {
5086
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5087
                        int connItemRetval = CompareConnItem(a, b);
5088
                        if (connItemRetval != 0)
5089
                        {
5090
                            return connItemRetval;
5091
                        }
5092
                        else
5093
                        {
5094
                            // ConnectedItem이 없는것
5095
                            int noneConnRetval = CompareNoneConn(a, b);
5096
                            if (noneConnRetval != 0)
5097
                            {
5098
                                return noneConnRetval;
5099
                            }
5100
                            else
5101
                            {
5102

    
5103
                            }
5104
                        }
5105
                    }
5106
                }
5107

    
5108
                return 0;
5109
            }
5110

    
5111
            int CompareNotSegmentLine(Line a, Line b)
5112
            {
5113
                List<Connector> connectorsA = a.CONNECTORS
5114
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5115
                    .ToList();
5116

    
5117
                List<Connector> connectorsB = b.CONNECTORS
5118
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5119
                    .ToList();
5120

    
5121
                // 오름차순
5122
                return connectorsB.Count.CompareTo(connectorsA.Count);
5123
            }
5124

    
5125
            int CompareConnSymbol(Line a, Line b)
5126
            {
5127
                List<Connector> connectorsA = a.CONNECTORS
5128
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5129
                    .ToList();
5130

    
5131
                List<Connector> connectorsB = b.CONNECTORS
5132
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5133
                    .ToList();
5134

    
5135
                // 오름차순
5136
                return connectorsB.Count.CompareTo(connectorsA.Count);
5137
            }
5138

    
5139
            int CompareConnItem(Line a, Line b)
5140
            {
5141
                List<Connector> connectorsA = a.CONNECTORS
5142
                    .Where(conn => conn.ConnectedObject != null && 
5143
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5144
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5145
                    .ToList();
5146

    
5147
                List<Connector> connectorsB = b.CONNECTORS
5148
                    .Where(conn => conn.ConnectedObject != null &&
5149
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5150
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5151
                    .ToList();
5152

    
5153
                // 오름차순
5154
                return connectorsB.Count.CompareTo(connectorsA.Count);
5155
            }
5156

    
5157
            int CompareBranchLine(Line a, Line b)
5158
            {
5159
                List<Connector> connectorsA = a.CONNECTORS
5160
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5161
                    .ToList();
5162
                List<Connector> connectorsB = b.CONNECTORS
5163
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5164
                    .ToList();
5165

    
5166
                // 내림차순
5167
                return connectorsA.Count.CompareTo(connectorsB.Count);
5168
            }
5169

    
5170
            int CompareNoneConn(Line a, Line b)
5171
            {
5172
                List<Connector> connectorsA = a.CONNECTORS
5173
                    .Where(conn => conn.ConnectedObject == null)
5174
                    .ToList();
5175

    
5176
                List<Connector> connectorsB = b.CONNECTORS
5177
                    .Where(conn => conn.ConnectedObject == null)
5178
                    .ToList();
5179

    
5180
                // 오름차순
5181
                return connectorsB.Count.CompareTo(connectorsA.Count);
5182
            }
5183
        }
5184

    
5185
        private void SortText(List<Text> texts)
5186
        {
5187
            texts.Sort(Sort);
5188

    
5189
            int Sort(Text a, Text b)
5190
            {
5191
                int yRetval = CompareY(a, b);
5192
                if (yRetval != 0)
5193
                {
5194
                    return yRetval;
5195
                }
5196
                else
5197
                {
5198
                    return CompareX(a, b);
5199
                }
5200
            }
5201

    
5202
            int CompareY(Text a, Text b)
5203
            {
5204
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5205
            }
5206

    
5207
            int CompareX(Text a, Text b)
5208
            {
5209
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5210
            }
5211
        }
5212
        private void SortNote(List<Note> notes)
5213
        {
5214
            notes.Sort(Sort);
5215

    
5216
            int Sort(Note a, Note b)
5217
            {
5218
                int yRetval = CompareY(a, b);
5219
                if (yRetval != 0)
5220
                {
5221
                    return yRetval;
5222
                }
5223
                else
5224
                {
5225
                    return CompareX(a, b);
5226
                }
5227
            }
5228

    
5229
            int CompareY(Note a, Note b)
5230
            {
5231
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5232
            }
5233

    
5234
            int CompareX(Note a, Note b)
5235
            {
5236
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5237
            }
5238
        }
5239

    
5240
        private void SortBranchLines()
5241
        {
5242
            BranchLines.Sort(SortBranchLine);
5243
            int SortBranchLine(Line a, Line b)
5244
            {
5245
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5246
                 x.ConnectedObject.GetType() == typeof(Line) &&
5247
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5248
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5249

    
5250
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5251
                 x.ConnectedObject.GetType() == typeof(Line) &&
5252
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5253
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5254

    
5255
                // 내림차순
5256
                return countA.CompareTo(countB);
5257
            }
5258
        }
5259

    
5260
        private static int SortSymbolPriority(Symbol a, Symbol b)
5261
        {
5262
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5263
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5264
            int retval = countB.CompareTo(countA);
5265
            if (retval != 0)
5266
                return retval;
5267
            else
5268
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5269
        }
5270

    
5271
        private string GetSPPIDFileName(LMModelItem modelItem)
5272
        {
5273
            string symbolPath = null;
5274
            foreach (LMRepresentation rep in modelItem.Representations)
5275
            {
5276
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5277
                {
5278
                    symbolPath = rep.get_FileName();
5279
                    break;
5280
                }
5281
            }
5282
            return symbolPath;
5283
        }
5284

    
5285
        private string GetSPPIDFileName(string modelItemId)
5286
        {
5287
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5288
            string symbolPath = null;
5289
            foreach (LMRepresentation rep in modelItem.Representations)
5290
            {
5291
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5292
                {
5293
                    symbolPath = rep.get_FileName();
5294
                    break;
5295
                }
5296
            }
5297
            ReleaseCOMObjects(modelItem);
5298
            return symbolPath;
5299
        }
5300

    
5301
        /// <summary>
5302
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5303
        /// </summary>
5304
        /// <param name="graphicOID"></param>
5305
        /// <param name="milliseconds"></param>
5306
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5307
        {
5308
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5309
            {
5310
                double minX = 0;
5311
                double minY = 0;
5312
                double maxX = 0;
5313
                double maxY = 0;
5314
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5315
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5316

    
5317
                Thread.Sleep(milliseconds);
5318
            }
5319
        }
5320

    
5321
        /// <summary>
5322
        /// ComObject를 Release
5323
        /// </summary>
5324
        /// <param name="objVars"></param>
5325
        public void ReleaseCOMObjects(params object[] objVars)
5326
        {
5327
            if (objVars != null)
5328
            {
5329
                int intNewRefCount = 0;
5330
                foreach (object obj in objVars)
5331
                {
5332
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5333
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5334
                }
5335
            }
5336
        }
5337

    
5338
        /// IDisposable 구현
5339
        ~AutoModeling()
5340
        {
5341
            this.Dispose(false);
5342
        }
5343

    
5344
        private bool disposed;
5345
        public void Dispose()
5346
        {
5347
            this.Dispose(true);
5348
            GC.SuppressFinalize(this);
5349
        }
5350

    
5351
        protected virtual void Dispose(bool disposing)
5352
        {
5353
            if (this.disposed) return;
5354
            if (disposing)
5355
            {
5356
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5357
            }
5358
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5359
            this.disposed = true;
5360
        }
5361
    }
5362
}
클립보드 이미지 추가 (최대 크기: 500 MB)