프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 8c7fc81a

이력 | 보기 | 이력해설 | 다운로드 (287 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
        List<string> FlowMarkRepIds = new List<string>();
47

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

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

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

    
71
                }
72
            }
73
        }
74

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

    
95
                    // VendorPackage Modeling
96
                    RunVendorPackageModeling();
97
                    // Equipment Modeling
98
                    RunEquipmentModeling();
99
                    // Symbol Modeling
100
                    RunSymbolModeling();
101
                    // LineRun Line Modeling
102
                    RunLineModeling();
103
                    // Vent Drain Modeling
104
                    RunVentDrainModeling();
105
                    // Clear Attribute
106
                    RunClearNominalDiameter();
107
                    // Join SameConnector
108
                    RunJoinRunForSameConnector();
109
                    // Join Run
110
                    RunJoinRun();
111
                    // EndBreak Modeling
112
                    RunEndBreakModeling();
113
                    // SpecBreak Modeling
114
                    RunSpecBreakModeling();
115
                    //Line Number Modeling
116
                    RunLineNumberModeling();
117
                    // Note Modeling
118
                    RunNoteModeling();
119
                    // Text Modeling
120
                    RunTextModeling();
121
                    // Input LineNumber Attribute
122
                    RunInputLineNumberAttribute();
123
                    // Input Symbol Attribute
124
                    RunInputSymbolAttribute();
125
                    // Input SpecBreak Attribute
126
                    RunInputSpecBreakAttribute();
127
                    // Input EndBreak Attribute
128
                    RunInputEndBreakAttribute();
129
                    // Label Symbol Modeling
130
                    RunLabelSymbolModeling();
131
                    // Correct Text
132
                    RunCorrectAssociationText();
133
                    // ETC
134
                    RunETC();
135

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

    
161
                Log.Write("End Modeling");
162
                radApp.ActiveWindow.Fit();
163

    
164
                ReleaseCOMObjects(application);
165
                application = null;
166
                if (radApp.ActiveDocument != null)
167
                {
168
                    if (closeDocument && newDrawing != null)
169
                    {
170
                        newDrawing.Save();
171
                        newDrawing.CloseDrawing(true);
172
                        ReleaseCOMObjects(newDrawing);
173
                        newDrawing = null;
174
                    }
175
                    else if (newDrawing == null)
176
                    {
177
                        Log.Write("error document");
178
                    }
179
                }
180

    
181
                ReleaseCOMObjects(dataSource);
182
                dataSource = null;
183
                ReleaseCOMObjects(_placement);
184
                _placement = null;
185

    
186
                Thread.Sleep(1000);
187
            }
188
        }
189

    
190
        private void RunVendorPackageModeling()
191
        {
192
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VendorPackages.Count);
193
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "VendorPackages Modeling");
194
            foreach (VendorPackage item in document.VendorPackages)
195
            {
196
                try
197
                {
198
                    VendorPackageModeling(item);
199
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
200
                }
201
                catch (Exception ex)
202
                {
203
                    Log.Write("Error in RunVendorPackageModeling");
204
                    Log.Write("UID : " + item.UID);
205
                    Log.Write(ex.Message);
206
                    Log.Write(ex.StackTrace);
207
                }
208
            }
209
        }
210
        private void RunEquipmentModeling()
211
        {
212
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
213
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
214
            foreach (Equipment item in document.Equipments)
215
            {
216
                try
217
                {
218
                    EquipmentModeling(item);
219
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
220
                }
221
                catch (Exception ex)
222
                {
223
                    Log.Write("Error in EquipmentModeling");
224
                    Log.Write("UID : " + item.UID);
225
                    Log.Write(ex.Message);
226
                    Log.Write(ex.StackTrace);
227
                }
228
            }
229
        }
230
        private void RunSymbolModeling()
231
        {
232
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
233
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
234
            prioritySymbols = GetPrioritySymbol();
235
            foreach (var item in prioritySymbols)
236
            {
237
                try
238
                {
239
                    if (document.VentDrainSymbol.Contains(item))
240
                        continue;
241
                    SymbolModelingBySymbol(item);
242
                }
243
                catch (Exception ex)
244
                {
245
                    Log.Write("Error in SymbolModelingByPriority");
246
                    Log.Write("UID : " + item.UID);
247
                    Log.Write(ex.Message);
248
                    Log.Write(ex.StackTrace);
249
                }
250
            }
251
        }
252
        private void RunLineModeling()
253
        {
254
            List<Line> AllLine = document.LINES.ToList();
255
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
256
            !SPPIDUtil.IsBranchedLine(document, x));
257
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
258

    
259
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
260
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
261

    
262
            SetPriorityLine(step1_Line);
263
            foreach (var item in step1_Line)
264
            {
265
                try
266
                {
267
                    if (document.VentDrainLine.Contains(item))
268
                        continue;
269
                    NewLineModeling(item);
270
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
271
                }
272
                catch (Exception ex)
273
                {
274
                    Log.Write("Error in NewLineModeling");
275
                    Log.Write("UID : " + item.UID);
276
                    Log.Write(ex.Message);
277
                    Log.Write(ex.StackTrace);
278
                }
279
            }
280

    
281
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
282
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
283
            int branchCount = BranchLines.Count;
284
            while (BranchLines.Count > 0)
285
            {
286
                try
287
                {
288
                    SortBranchLines();
289
                    Line item = BranchLines[0];
290
                    NewLineModeling(item, true);
291
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
292
                }
293
                catch (Exception ex)
294
                {
295
                    Log.Write("Error in NewLineModeling");
296
                    Log.Write("UID : " + BranchLines[0].UID);
297
                    Log.Write(ex.Message);
298
                    Log.Write(ex.StackTrace);
299
                    BranchLines.Remove(BranchLines[0]);
300
                }
301
            }
302

    
303
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
304
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
305
            foreach (var item in stepLast_Line)
306
            {
307
                try
308
                {
309
                    if (document.VentDrainLine.Contains(item))
310
                        continue;
311
                    NewLineModeling(item);
312
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
313
                }
314
                catch (Exception ex)
315
                {
316
                    Log.Write("Error in NewLineModeling");
317
                    Log.Write("UID : " + item.UID);
318
                    Log.Write(ex.Message);
319
                    Log.Write(ex.StackTrace);
320
                }
321
            }
322
        }
323
        private void RunVentDrainModeling()
324
        {
325
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VentDrainLine.Count);
326
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Vent Drain Modeling");
327
            foreach (var item in document.VentDrainLine)
328
            {
329
                try
330
                {
331
                    Connector connector = item.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
332
                    if (connector != null)
333
                    {
334
                        SetCoordinate();
335
                        Symbol connSymbol = connector.ConnectedObject as Symbol;
336
                        SymbolModeling(connSymbol, null);
337
                        NewLineModeling(item, true);
338

    
339
                        GridSetting grid = GridSetting.GetInstance();
340
                        int count = grid.DrainValveCellCount;
341
                        double length = grid.Length;
342

    
343
                        // 길이 확인
344
                        if (!string.IsNullOrEmpty(item.SPPID.ModelItemId))
345
                        {
346
                            LMConnector _LMConnector = GetLMConnectorOnlyOne(item.SPPID.ModelItemId);
347
                            if (_LMConnector != null)
348
                            {
349
                                double[] connectorRange = GetConnectorRange(_LMConnector);
350
                                double connectorLength = double.NaN;
351
                                if (item.SlopeType == SlopeType.HORIZONTAL)
352
                                    connectorLength = connectorRange[2] - connectorRange[0];
353
                                else if (item.SlopeType == SlopeType.VERTICAL)
354
                                    connectorLength = connectorRange[3] - connectorRange[1];
355

    
356
                                if (!double.IsNaN(connectorLength) && connectorLength != count * length)
357
                                {
358
                                    double move = count * length - connectorLength;
359
                                    List<Symbol> group = new List<Symbol>();
360
                                    SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
361
                                    foreach (var symbol in group)
362
                                    {
363
                                        int connSymbolIndex = item.CONNECTORS.IndexOf(item.CONNECTORS.Find(x => x.ConnectedObject == connSymbol));
364
                                        if (item.SlopeType == SlopeType.HORIZONTAL)
365
                                        {
366
                                            if (connSymbolIndex == 0)
367
                                            {
368
                                                if (item.SPPID.START_X > item.SPPID.END_X)
369
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
370
                                                else
371
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
372
                                            }
373
                                            else
374
                                            {
375
                                                if (item.SPPID.START_X < item.SPPID.END_X)
376
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
377
                                                else
378
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
379
                                            }
380
                                        }
381
                                        else if (item.SlopeType == SlopeType.VERTICAL)
382
                                        {
383
                                            if (connSymbolIndex == 0)
384
                                            {
385
                                                if (item.SPPID.START_Y > item.SPPID.END_Y)
386
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
387
                                                else
388
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
389
                                            }
390
                                            else
391
                                            {
392
                                                if (item.SPPID.START_Y < item.SPPID.END_Y)
393
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
394
                                                else
395
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
396
                                            }
397
                                        }
398
                                    }
399

    
400
                                    // 제거
401
                                    RemoveSymbol(connSymbol);
402
                                    RemoveLine(item);
403

    
404
                                    // 재생성
405
                                    SymbolModelingBySymbol(connSymbol);
406
                                    NewLineModeling(item, true);
407
                                }
408
                            }
409

    
410
                            ReleaseCOMObjects(_LMConnector);
411
                            _LMConnector = null;
412
                        }
413
                    }
414
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
415
                }
416
                catch (Exception ex)
417
                {
418
                    Log.Write("Error in NewLineModeling");
419
                    Log.Write("UID : " + item.UID);
420
                    Log.Write(ex.Message);
421
                    Log.Write(ex.StackTrace);
422
                }
423

    
424
                void SetCoordinate()
425
                {
426
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
427
                    if (branchConnector != null)
428
                    {
429
                        Line connLine = branchConnector.ConnectedObject as Line;
430
                        double x = 0;
431
                        double y = 0;
432
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
433
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
434
                        if (targetConnector != null)
435
                        {
436
                            List<Symbol> group = new List<Symbol>();
437
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
438
                            if (item.SlopeType == SlopeType.HORIZONTAL)
439
                            {
440
                                item.SPPID.START_Y = y;
441
                                item.SPPID.END_Y = y;
442
                                foreach (var symbol in group)
443
                                {
444
                                    symbol.SPPID.ORIGINAL_Y = y;
445
                                    symbol.SPPID.SPPID_Y = y;
446
                                }
447
                            }
448
                            else if (item.SlopeType == SlopeType.VERTICAL)
449
                            {
450
                                item.SPPID.START_X = x;
451
                                item.SPPID.END_X = x;
452
                                foreach (var symbol in group)
453
                                {
454
                                    symbol.SPPID.ORIGINAL_X = x;
455
                                    symbol.SPPID.SPPID_X = x;
456
                                }
457
                            }
458
                        }
459
                        ReleaseCOMObjects(targetConnector);
460
                        targetConnector = null;
461
                    }
462
                }
463
            }
464
        }
465
        private void RunClearNominalDiameter()
466
        {
467
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
468
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
469
            return;
470

    
471
            List<string> endClearModelItemID = new List<string>();
472
            for (int i = 0; i < document.LINES.Count; i++)
473
            {
474
                Line item = document.LINES[i];
475
                string modelItemID = item.SPPID.ModelItemId;
476
                if (!string.IsNullOrEmpty(modelItemID))
477
                {
478
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
479
                    if (modelItem != null)
480
                    {
481
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
482
                        if (attribute != null)
483
                            attribute.set_Value(DBNull.Value);
484

    
485
                        modelItem.Commit();
486
                        ReleaseCOMObjects(modelItem);
487
                        modelItem = null;
488
                    }
489
                }
490
                if (!endClearModelItemID.Contains(modelItemID))
491
                    endClearModelItemID.Add(modelItemID);
492
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
493
            }
494
            for (int i = 0; i < document.SYMBOLS.Count; i++)
495
            {
496
                Symbol item = document.SYMBOLS[i];
497
                string repID = item.SPPID.RepresentationId;
498
                string modelItemID = item.SPPID.ModelItemID;
499
                if (!string.IsNullOrEmpty(modelItemID))
500
                {
501
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
502
                    if (modelItem != null)
503
                    {
504
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
505
                        if (attribute != null)
506
                            attribute.set_Value(DBNull.Value);
507
                        int index = 1;
508
                        while (true)
509
                        {
510
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
511
                            if (attribute != null)
512
                                attribute.set_Value(DBNull.Value);
513
                            else
514
                                break;
515
                            index++;
516
                        }
517
                        modelItem.Commit();
518
                        ReleaseCOMObjects(modelItem);
519
                        modelItem = null;
520
                    }
521
                }
522
                if (!string.IsNullOrEmpty(repID))
523
                {
524
                    LMSymbol symbol = dataSource.GetSymbol(repID);
525
                    if (symbol != null)
526
                    {
527
                        foreach (LMConnector connector in symbol.Connect1Connectors)
528
                        {
529
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
530
                            {
531
                                endClearModelItemID.Add(connector.ModelItemID);
532
                                LMModelItem modelItem = connector.ModelItemObject;
533
                                if (modelItem != null)
534
                                {
535
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
536
                                    if (attribute != null)
537
                                        attribute.set_Value(DBNull.Value);
538

    
539
                                    modelItem.Commit();
540
                                    ReleaseCOMObjects(modelItem);
541
                                    modelItem = null;
542
                                }
543
                            }
544
                        }
545
                        foreach (LMConnector connector in symbol.Connect2Connectors)
546
                        {
547
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
548
                            {
549
                                endClearModelItemID.Add(connector.ModelItemID);
550
                                LMModelItem modelItem = connector.ModelItemObject;
551
                                if (modelItem != null)
552
                                {
553
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
554
                                    if (attribute != null)
555
                                        attribute.set_Value(DBNull.Value);
556

    
557
                                    modelItem.Commit();
558
                                    ReleaseCOMObjects(modelItem);
559
                                    modelItem = null;
560
                                }
561
                            }
562
                        }
563
                    }
564
                    ReleaseCOMObjects(symbol);
565
                    symbol = null;
566
                }
567
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
568
            }
569
        }
570
        private void RunClearValueInconsistancy()
571
        {
572
            int count = 1;
573
            bool loop = true;
574
            while (loop)
575
            {
576
                loop = false;
577
                LMAFilter filter = new LMAFilter();
578
                LMACriterion criterion = new LMACriterion();
579
                filter.ItemType = "Relationship";
580
                criterion.SourceAttributeName = "SP_DRAWINGID";
581
                criterion.Operator = "=";
582
                criterion.set_ValueAttribute(drawingID);
583
                filter.get_Criteria().Add(criterion);
584

    
585
                LMRelationships relationships = new LMRelationships();
586
                relationships.Collect(dataSource, Filter: filter);
587

    
588
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
589
                if (count > 1)
590
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
591
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
592
                foreach (LMRelationship relationship in relationships)
593
                {
594
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
595
                    {
596
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
597
                        {
598
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
599
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
600
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
601
                            if (modelItem1 != null)
602
                            {
603
                                string attrName = array[0];
604
                                if (attrName.Contains("PipingPoint"))
605
                                {
606
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
607
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
608
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
609
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
610
                                    {
611
                                        loop = true;
612
                                        attribute1.set_Value(DBNull.Value);
613
                                    }
614
                                    attribute1 = null;
615
                                }
616
                                else
617
                                {
618
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
619
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
620
                                    {
621
                                        loop = true;
622
                                        attribute1.set_Value(DBNull.Value);
623
                                    }
624
                                    attribute1 = null;
625
                                }
626
                                modelItem1.Commit();
627
                            }
628
                            if (modelItem2 != null)
629
                            {
630
                                string attrName = array[1];
631
                                if (attrName.Contains("PipingPoint"))
632
                                {
633
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
634
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
635
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
636
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
637
                                    {
638
                                        attribute2.set_Value(DBNull.Value);
639
                                        loop = true;
640
                                    }
641
                                    attribute2 = null;
642
                                }
643
                                else
644
                                {
645
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
646
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
647
                                    {
648
                                        attribute2.set_Value(DBNull.Value);
649
                                        loop = true;
650
                                    }
651
                                    attribute2 = null;
652
                                }
653
                                modelItem2.Commit();
654
                            }
655
                            ReleaseCOMObjects(modelItem1);
656
                            modelItem1 = null;
657
                            ReleaseCOMObjects(modelItem2);
658
                            modelItem2 = null;
659
                            inconsistency.Commit();
660
                        }
661
                        ReleaseCOMObjects(inconsistency);
662
                    }
663
                    relationship.Commit();
664
                    ReleaseCOMObjects(relationship);
665
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
666
                }
667
                ReleaseCOMObjects(filter);
668
                filter = null;
669
                ReleaseCOMObjects(criterion);
670
                criterion = null;
671
                ReleaseCOMObjects(relationships);
672
                relationships = null;
673
                count++;
674
            }
675
        }
676
        private void RunEndBreakModeling()
677
        {
678
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
679
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
680
            foreach (var item in document.EndBreaks)
681
                try
682
                {
683
                    EndBreakModeling(item);
684
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
685
                }
686
                catch (Exception ex)
687
                {
688
                    Log.Write("Error in EndBreakModeling");
689
                    Log.Write("UID : " + item.UID);
690
                    Log.Write(ex.Message);
691
                    Log.Write(ex.StackTrace);
692
                }
693
        }
694
        private void RunSpecBreakModeling()
695
        {
696
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
697
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
698
            foreach (var item in document.SpecBreaks)
699
                try
700
                {
701
                    SpecBreakModeling(item);
702
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
703
                }
704
                catch (Exception ex)
705
                {
706
                    Log.Write("Error in SpecBreakModeling");
707
                    Log.Write("UID : " + item.UID);
708
                    Log.Write(ex.Message);
709
                    Log.Write(ex.StackTrace);
710
                }
711
        }
712
        private void RunJoinRunForSameConnector()
713
        {
714
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
715
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
716
            foreach (var line in document.LINES)
717
            {
718
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
719
                List<List<double[]>> result = new List<List<double[]>>();
720
                foreach (var item in vertices)
721
                {
722
                    ReleaseCOMObjects(item.Key);
723
                    result.Add(item.Value);
724
                }
725
                line.SPPID.Vertices = result;
726
                vertices = null;
727
            }
728

    
729
            foreach (var line in document.LINES)
730
            {
731
                foreach (var connector in line.CONNECTORS)
732
                {
733
                    if (connector.ConnectedObject != null &&
734
                        connector.ConnectedObject.GetType() == typeof(Line) &&
735
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
736
                    {
737
                        Line connLine = connector.ConnectedObject as Line;
738
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
739
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
740
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
741
                            !SPPIDUtil.IsSegment(document, line, connLine))
742
                        {
743
                            string survivorId = string.Empty;
744
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
745
                        }
746

    
747
                    }
748
                }
749
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
750
            }
751

    
752
            foreach (var line in document.LINES)
753
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
754
        }
755
        private void RunJoinRun()
756
        {
757
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
758
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
759
            List<string> endModelID = new List<string>();
760
            foreach (var line in document.LINES)
761
            {
762
                if (!endModelID.Contains(line.SPPID.ModelItemId))
763
                {
764
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
765
                    {
766
                        string survivorId = string.Empty;
767
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
768
                        if (string.IsNullOrEmpty(survivorId))
769
                        {
770
                            endModelID.Add(line.SPPID.ModelItemId);
771
                        }
772
                    }
773
                }
774
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
775
            }
776
        }
777
        private void RunLineNumberModeling()
778
        {
779
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
780
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
781
            foreach (var item in document.LINENUMBERS)
782
            {
783
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
784
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
785
                {
786
                    ReleaseCOMObjects(label);
787
                    item.SPPID.RepresentationId = null;
788
                    LineNumberModeling(item);
789
                }
790
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
791
            }
792
        }
793
        private void RunNoteModeling()
794
        {
795
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
796
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
797
            List<Note> correctList = new List<Note>();
798
            foreach (var item in document.NOTES)
799
                try
800
                {
801
                    NoteModeling(item, correctList);
802
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
803
                }
804
                catch (Exception ex)
805
                {
806
                    Log.Write("Error in NoteModeling");
807
                    Log.Write("UID : " + item.UID);
808
                    Log.Write(ex.Message);
809
                    Log.Write(ex.StackTrace);
810
                }
811

    
812
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
813
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
814
            SortNote(correctList);
815
            List<Note> endList = new List<Note>();
816
            if (correctList.Count > 0)
817
                endList.Add(correctList[0]);
818
            foreach (var item in correctList)
819
                try
820
                {
821
                    if (!endList.Contains(item))
822
                        NoteCorrectModeling(item, endList);
823
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
824
                }
825
                catch (Exception ex)
826
                {
827
                    Log.Write("Error in NoteModeling");
828
                    Log.Write("UID : " + item.UID);
829
                    Log.Write(ex.Message);
830
                    Log.Write(ex.StackTrace);
831
                }
832
        }
833
        private void RunTextModeling()
834
        {
835
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
836
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
837
            SortText(document.TEXTINFOS);
838
            foreach (var item in document.TEXTINFOS)
839
                try
840
                {
841
                    if (item.ASSOCIATION)
842
                        AssociationTextModeling(item);
843
                    else
844
                        NormalTextModeling(item);
845
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
846
                }
847
                catch (Exception ex)
848
                {
849
                    Log.Write("Error in TextModeling");
850
                    Log.Write("UID : " + item.UID);
851
                    Log.Write(ex.Message);
852
                    Log.Write(ex.StackTrace);
853
                }
854
        }
855
        private void RunInputLineNumberAttribute()
856
        {
857
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
858
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
859
            List<string> endLine = new List<string>();
860
            foreach (var item in document.LINENUMBERS)
861
                try
862
                {
863
                    InputLineNumberAttribute(item, endLine);
864
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
865
                }
866
                catch (Exception ex)
867
                {
868
                    Log.Write("Error in InputLineNumberAttribute");
869
                    Log.Write("UID : " + item.UID);
870
                    Log.Write(ex.Message);
871
                    Log.Write(ex.StackTrace);
872
                }
873
        }
874
        private void RunInputSymbolAttribute()
875
        {
876
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.Equipments.Count);
877
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
878
            foreach (var item in document.SYMBOLS)
879
                try
880
                {
881
                    InputSymbolAttribute(item, item.ATTRIBUTES);
882
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
883
                }
884
                catch (Exception ex)
885
                {
886
                    Log.Write("Error in InputSymbolAttribute");
887
                    Log.Write("UID : " + item.UID);
888
                    Log.Write(ex.Message);
889
                    Log.Write(ex.StackTrace);
890
                }
891

    
892
            foreach (var item in document.Equipments)
893
                try
894
                {
895
                    InputSymbolAttribute(item, item.ATTRIBUTES);
896
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
897
                }
898
                catch (Exception ex)
899
                {
900
                    Log.Write("Error in InputSymbolAttribute");
901
                    Log.Write("UID : " + item.UID);
902
                    Log.Write(ex.Message);
903
                    Log.Write(ex.StackTrace);
904
                }
905
        }
906
        private void RunInputSpecBreakAttribute()
907
        {
908
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
909
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
910
            foreach (var item in document.SpecBreaks)
911
                try
912
                {
913
                    InputSpecBreakAttribute(item);
914
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
915
                }
916
                catch (Exception ex)
917
                {
918
                    Log.Write("Error in InputSpecBreakAttribute");
919
                    Log.Write("UID : " + item.UID);
920
                    Log.Write(ex.Message);
921
                    Log.Write(ex.StackTrace);
922
                }
923
        }
924
        private void RunInputEndBreakAttribute()
925
        {
926
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
927
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
928
            foreach (var item in document.EndBreaks)
929
                try
930
                {
931
                    InputEndBreakAttribute(item);
932
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
933
                }
934
                catch (Exception ex)
935
                {
936
                    Log.Write("Error in RunInputEndBreakAttribute");
937
                    Log.Write("UID : " + item.UID);
938
                    Log.Write(ex.Message);
939
                    Log.Write(ex.StackTrace);
940
                }
941
        }
942
        private void RunLabelSymbolModeling()
943
        {
944
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
945
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
946
            foreach (var item in document.SYMBOLS)
947
                try
948
                {
949
                    LabelSymbolModeling(item);
950
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
951
                }
952
                catch (Exception ex)
953
                {
954
                    Log.Write("Error in LabelSymbolModeling");
955
                    Log.Write("UID : " + item.UID);
956
                    Log.Write(ex.Message);
957
                    Log.Write(ex.StackTrace);
958
                }
959
        }
960
        private void RunCorrectAssociationText()
961
        {
962
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
963
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
964
            List<Text> endTexts = new List<Text>();
965
            foreach (var item in document.TEXTINFOS)
966
            {
967
                try
968
                {
969
                    if (item.ASSOCIATION && !endTexts.Contains(item))
970
                        AssociationTextCorrectModeling(item, endTexts);
971
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
972
                }
973
                catch (Exception ex)
974
                {
975
                    Log.Write("Error in RunCorrectAssociationText");
976
                    Log.Write("UID : " + item.UID);
977
                    Log.Write(ex.Message);
978
                    Log.Write(ex.StackTrace);
979
                }
980
                
981
            }
982

    
983
            foreach (var item in document.LINENUMBERS)
984
            {
985
                try
986
                {
987
                    LineNumberCorrectModeling(item);
988
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
989
                }
990
                catch (Exception ex)
991
                {
992
                    Log.Write("Error in RunCorrectAssociationText");
993
                    Log.Write("UID : " + item.UID);
994
                    Log.Write(ex.Message);
995
                    Log.Write(ex.StackTrace);
996
                }
997
            }
998
        }
999
        private void RunETC()
1000
        {
1001
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, FlowMarkRepIds.Count);
1002
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "ETC");
1003
            foreach (var item in FlowMarkRepIds)
1004
            {
1005
                LMLabelPersist label = dataSource.GetLabelPersist(item);
1006
                if (label != null)
1007
                {
1008
                    label.get_GraphicOID();
1009
                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[label.get_GraphicOID().ToString()] as DependencyObject;
1010
                    if (dependency != null)
1011
                        dependency.BringToFront();
1012
                }
1013
                ReleaseCOMObjects(label);
1014
                label = null;
1015
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1016
            }
1017
        }
1018
        /// <summary>
1019
        /// 도면 생성 메서드
1020
        /// </summary>
1021
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1022
        {
1023
            Log.Write("------------------ Start create document ------------------");
1024
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1025
            Log.Write("Drawing name : " + drawingName);
1026
            Log.Write("Drawing number : " + drawingNumber);
1027
            Thread.Sleep(1000);
1028
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1029
            if (newDrawing != null)
1030
            {
1031
                document.SPPID_DrawingNumber = drawingNumber;
1032
                document.SPPID_DrawingName = drawingName;
1033
                Thread.Sleep(1000);
1034
                radApp.ActiveWindow.Fit();
1035
                Thread.Sleep(1000);
1036
                radApp.ActiveWindow.Zoom = 2000;
1037
                Thread.Sleep(2000);
1038

    
1039
                //current LMDrawing 가져오기
1040
                LMAFilter filter = new LMAFilter();
1041
                LMACriterion criterion = new LMACriterion();
1042
                filter.ItemType = "Drawing";
1043
                criterion.SourceAttributeName = "Name";
1044
                criterion.Operator = "=";
1045
                criterion.set_ValueAttribute(drawingName);
1046
                filter.get_Criteria().Add(criterion);
1047

    
1048
                LMDrawings drawings = new LMDrawings();
1049
                drawings.Collect(dataSource, Filter: filter);
1050

    
1051
                // Input Drawing Attribute
1052
                LMDrawing drawing = ((dynamic)drawings).Nth(1);
1053
                if (drawing != null)
1054
                {
1055
                    using (DataTable drawingAttributeDT = Project_DB.SelectDrawingProjectAttribute())
1056
                    {
1057
                        foreach (DataRow row in drawingAttributeDT.Rows)
1058
                        {
1059
                            string mappingName = DBNull.Value.Equals(row["SPPID_ATTRIBUTE"]) ? string.Empty : row["SPPID_ATTRIBUTE"].ToString();
1060
                            if (!string.IsNullOrEmpty(mappingName))
1061
                            {
1062
                                string uid = row["UID"].ToString();
1063
                                string name = row["NAME"].ToString();
1064
                                Text text = document.TEXTINFOS.Find(x => x.AREA == uid);
1065
                                if (text != null)
1066
                                {
1067
                                    string value = text.VALUE;
1068
                                    LMAAttribute attribute = drawing.Attributes[mappingName];
1069
                                    if (attribute != null)
1070
                                        attribute.set_Value(value);
1071
                                    ReleaseCOMObjects(attribute);
1072
                                    document.TEXTINFOS.Remove(text);
1073
                                }
1074
                            }
1075
                        }
1076

    
1077
                        drawingAttributeDT.Dispose();
1078
                    }
1079

    
1080
                    ReleaseCOMObjects(drawing);
1081
                }
1082

    
1083
                drawingID = ((dynamic)drawings).Nth(1).Id;
1084
                ReleaseCOMObjects(filter);
1085
                ReleaseCOMObjects(criterion);
1086
                ReleaseCOMObjects(drawings);
1087
                filter = null;
1088
                criterion = null;
1089
                drawings = null;
1090
            }
1091
            else
1092
                Log.Write("Fail Create Drawing");
1093

    
1094
            if (newDrawing != null)
1095
            {
1096
                SetBorderFile();
1097
                return true;
1098
            }
1099
            else
1100
                return false;
1101
        }
1102

    
1103
        private void SetBorderFile()
1104
        {
1105
            ETCSetting setting = ETCSetting.GetInstance();
1106

    
1107
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1108
            {
1109
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1110
                {
1111
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1112
                    {
1113
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1114
                        smartFrame.Update();
1115
                    }
1116
                        
1117
                }
1118
            }
1119
        }
1120

    
1121
        /// <summary>
1122
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1123
        /// </summary>
1124
        /// <param name="drawingName"></param>
1125
        /// <param name="drawingNumber"></param>
1126
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1127
        {
1128
            LMDrawings drawings = new LMDrawings();
1129
            drawings.Collect(dataSource);
1130

    
1131
            List<string> drawingNameList = new List<string>();
1132
            List<string> drawingNumberList = new List<string>();
1133

    
1134
            foreach (LMDrawing item in drawings)
1135
            {
1136
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1137
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1138
            }
1139

    
1140
            int nameLength = drawingName.Length;
1141
            while (drawingNameList.Contains(drawingName))
1142
            {
1143
                if (nameLength == drawingName.Length)
1144
                    drawingName += "-1";
1145
                else
1146
                {
1147
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1148
                    drawingName = drawingName.Substring(0, nameLength + 1);
1149
                    drawingName += ++index;
1150
                }
1151
            }
1152

    
1153
            int numberLength = drawingNumber.Length;
1154
            while (drawingNameList.Contains(drawingNumber))
1155
            {
1156
                if (numberLength == drawingNumber.Length)
1157
                    drawingNumber += "-1";
1158
                else
1159
                {
1160
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1161
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1162
                    drawingNumber += ++index;
1163
                }
1164
            }
1165
            ReleaseCOMObjects(drawings);
1166
            drawings = null;
1167
        }
1168

    
1169
        /// <summary>
1170
        /// 도면 크기 구하는 메서드
1171
        /// </summary>
1172
        /// <returns></returns>
1173
        private bool DocumentCoordinateCorrection()
1174
        {
1175
            if (radApp.ActiveDocument.ActiveSheet.SmartFrames2d.Count > 0)
1176
            {
1177
                double x = 0;
1178
                double y = 0;
1179
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1180
                {
1181
                    x = Math.Max(smartFrame.CropRight, x);
1182
                    y = Math.Max(smartFrame.CropTop, y);
1183
                }
1184
                document.SetSPPIDLocation(x, y);
1185
                document.CoordinateCorrection();
1186
                return true;
1187
            }
1188
            else
1189
            {
1190
                Log.Write("Need Border!");
1191
                return false;
1192
            }
1193
        }
1194

    
1195
        /// <summary>
1196
        /// 심볼을 실제로 Modeling 메서드
1197
        /// </summary>
1198
        /// <param name="symbol">생성할 심볼</param>
1199
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1200
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1201
        {
1202
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1203
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1204
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1205
                return;
1206
            // 이미 모델링 됐을 경우
1207
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1208
                return;
1209

    
1210
            LMSymbol _LMSymbol = null;
1211

    
1212
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1213
            double x = symbol.SPPID.ORIGINAL_X;
1214
            double y = symbol.SPPID.ORIGINAL_Y;
1215
            int mirror = 0;
1216
            double angle = symbol.ANGLE;
1217

    
1218
            // OPC 일경우 180도 일때 Mirror
1219
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1220
                mirror = 1;
1221

    
1222
            // Mirror 계산
1223
            if (symbol.FLIP == 1)
1224
            {
1225
                mirror = 1;
1226
                angle += Math.PI;
1227
            }
1228

    
1229
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1230
            {
1231
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1232
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1233
                if (connector != null)
1234
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1235

    
1236
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1237
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1238
                if (temp != null)
1239
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1240
                ReleaseCOMObjects(temp);
1241
                temp = null;
1242

    
1243
                if (_LMSymbol != null && _TargetItem != null)
1244
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1245

    
1246
                ReleaseCOMObjects(_TargetItem);
1247
            }
1248
            else
1249
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1250

    
1251
            if (_LMSymbol != null)
1252
            {
1253
                _LMSymbol.Commit();
1254

    
1255
                // ConnCheck
1256
                List<string> ids = new List<string>();
1257
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1258
                {
1259
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1260
                        ids.Add(item.Id);
1261
                    ReleaseCOMObjects(item);
1262
                }
1263
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1264
                {
1265
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1266
                        ids.Add(item.Id);
1267
                    ReleaseCOMObjects(item);
1268
                }
1269

    
1270
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1271
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1272
                {
1273
                    double currentX = _LMSymbol.get_XCoordinate();
1274
                    double currentY = _LMSymbol.get_YCoordinate();
1275

    
1276

    
1277
                }
1278

    
1279
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1280
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1281
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1282

    
1283
                foreach (var item in symbol.ChildSymbols)
1284
                    CreateChildSymbol(item, _LMSymbol, symbol);
1285

    
1286
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1287
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1288

    
1289
                double[] range = null;
1290
                GetSPPIDSymbolRange(symbol, ref range);
1291
                symbol.SPPID.SPPID_Min_X = range[0];
1292
                symbol.SPPID.SPPID_Min_Y = range[1];
1293
                symbol.SPPID.SPPID_Max_X = range[2];
1294
                symbol.SPPID.SPPID_Max_Y = range[3];
1295

    
1296
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1297
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1298
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1299
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1300

    
1301
                ReleaseCOMObjects(_LMSymbol);
1302
            }
1303
        }
1304
        /// <summary>
1305
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1306
        /// Signal Point는 고려하지 않음
1307
        /// </summary>
1308
        /// <param name="symbol"></param>
1309
        /// <param name="_TargetItem"></param>
1310
        /// <param name="targetX"></param>
1311
        /// <param name="targetY"></param>
1312
        /// <returns></returns>
1313
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1314
        {
1315
            LMConnector tempConnector = null;
1316

    
1317
            List<Symbol> group = new List<Symbol>();
1318
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1319
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1320
            {
1321
                List<Connector> connectors = new List<Connector>();
1322
                foreach (var item in group)
1323
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1324
                /// Primary or Secondary Type Line만 고려
1325
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1326
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1327
                if (_connector != null)
1328
                {
1329
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1330
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1331
                    /// PipingPoint가 2개 이상만
1332
                    if (pointInfos.Count >= 2)
1333
                    {
1334
                        double lineX = 0;
1335
                        double lineY = 0;
1336
                        double length = 0;
1337
                        foreach (var item in pointInfos)
1338
                        {
1339
                            double tempX = item[1];
1340
                            double tempY = item[2];
1341

    
1342
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1343
                            if (calcDistance > length)
1344
                            {
1345
                                lineX = tempX;
1346
                                lineY = tempY;
1347
                            }
1348
                        }
1349

    
1350
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1351
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1352
                        placeRunInputs.AddPoint(-1, -1);
1353
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1354
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1355
                        if (tempConnector != null)
1356
                            tempConnector.Commit();
1357
                        ReleaseCOMObjects(_LMAItem);
1358
                        _LMAItem = null;
1359
                        ReleaseCOMObjects(placeRunInputs);
1360
                        placeRunInputs = null;
1361
                    }
1362
                }
1363
            }
1364

    
1365
            return tempConnector;
1366
        }
1367
        /// <summary>
1368
        /// Symbol의 PipingPoints를 구함
1369
        /// SignalPoint는 고려하지 않음
1370
        /// </summary>
1371
        /// <param name="symbol"></param>
1372
        /// <returns></returns>
1373
        private List<double[]> getPipingPoints(LMSymbol symbol)
1374
        {
1375
            LMModelItem modelItem = symbol.ModelItemObject;
1376
            LMPipingPoints pipingPoints = null;
1377
            if (modelItem.get_ItemTypeName() == "PipingComp")
1378
            {
1379
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1380
                pipingPoints = pipingComp.PipingPoints;
1381
                ReleaseCOMObjects(pipingComp);
1382
                pipingComp = null;
1383
            }
1384
            else if (modelItem.get_ItemTypeName() == "Instrument")
1385
            {
1386
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1387
                pipingPoints = instrument.PipingPoints;
1388
                ReleaseCOMObjects(instrument);
1389
                instrument = null;
1390
            }
1391
            else
1392
                Log.Write("다른 Type");
1393

    
1394
            List<double[]> info = new List<double[]>();
1395
            if (pipingPoints != null)
1396
            {
1397
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1398
                {
1399
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1400
                    {
1401
                        if (attribute.Name == "PipingPointNumber")
1402
                        {
1403
                            int index = Convert.ToInt32(attribute.get_Value());
1404
                            if (info.Find(loopX => loopX[0] == index) == null)
1405
                            {
1406
                                double x = 0;
1407
                                double y = 0;
1408
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1409
                                    info.Add(new double[] { index, x, y });
1410
                            }
1411
                        }
1412
                    }
1413
                }
1414
            }
1415
            ReleaseCOMObjects(modelItem);
1416
            modelItem = null;
1417
            ReleaseCOMObjects(pipingPoints);
1418
            pipingPoints = null;
1419

    
1420
            return info;
1421
        }
1422

    
1423
        private void RemoveSymbol(Symbol symbol)
1424
        {
1425
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1426
            {
1427
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1428
                if (_LMSymbol != null)
1429
                {
1430
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1431
                    ReleaseCOMObjects(_LMSymbol);
1432
                }
1433
            }
1434

    
1435
            symbol.SPPID.RepresentationId = string.Empty;
1436
            symbol.SPPID.ModelItemID = string.Empty;
1437
            symbol.SPPID.SPPID_X = double.NaN;
1438
            symbol.SPPID.SPPID_Y = double.NaN;
1439
            symbol.SPPID.SPPID_Min_X = double.NaN;
1440
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1441
            symbol.SPPID.SPPID_Max_X = double.NaN;
1442
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1443
        }
1444

    
1445
        private void RemoveSymbol(List<Symbol> symbols)
1446
        {
1447
            foreach (var symbol in symbols)
1448
            {
1449
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1450
                {
1451
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1452
                    if (_LMSymbol != null)
1453
                    {
1454
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1455
                        ReleaseCOMObjects(_LMSymbol);
1456
                    }
1457
                }
1458

    
1459
                symbol.SPPID.RepresentationId = string.Empty;
1460
                symbol.SPPID.ModelItemID = string.Empty;
1461
                symbol.SPPID.SPPID_X = double.NaN;
1462
                symbol.SPPID.SPPID_Y = double.NaN;
1463
                symbol.SPPID.SPPID_Min_X = double.NaN;
1464
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1465
                symbol.SPPID.SPPID_Max_X = double.NaN;
1466
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1467
            }
1468
        }
1469

    
1470
        /// <summary>
1471
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1472
        /// </summary>
1473
        /// <param name="targetConnector"></param>
1474
        /// <param name="targetSymbol"></param>
1475
        /// <param name="x"></param>
1476
        /// <param name="y"></param>
1477
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1478
        {
1479
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1480

    
1481
            double[] range = null;
1482
            List<double[]> points = new List<double[]>();
1483
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1484
            double x1 = range[0];
1485
            double y1 = range[1];
1486
            double x2 = range[2];
1487
            double y2 = range[3];
1488

    
1489
            // Origin 기준 Connector의 위치차이
1490
            double sceneX = 0;
1491
            double sceneY = 0;
1492
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1493
            double originX = 0;
1494
            double originY = 0;
1495
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1496
            double gapX = originX - sceneX;
1497
            double gapY = originY - sceneY;
1498

    
1499
            // SPPID Symbol과 ID2 심볼의 크기 차이
1500
            double sizeWidth = 0;
1501
            double sizeHeight = 0;
1502
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1503
            if (sizeWidth == 0 || sizeHeight == 0)
1504
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1505

    
1506
            double percentX = (x2 - x1) / sizeWidth;
1507
            double percentY = (y2 - y1) / sizeHeight;
1508

    
1509
            double SPPIDgapX = gapX * percentX;
1510
            double SPPIDgapY = gapY * percentY;
1511

    
1512
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1513
            double distance = double.MaxValue;
1514
            double[] resultPoint;
1515
            foreach (var point in points)
1516
            {
1517
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1518
                if (distance > result)
1519
                {
1520
                    distance = result;
1521
                    resultPoint = point;
1522
                    x = point[0];
1523
                    y = point[1];
1524
                }
1525
            }
1526

    
1527
            ReleaseCOMObjects(_TargetItem);
1528
        }
1529

    
1530
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1531
        {
1532
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1533
            if (index == 0)
1534
            {
1535
                x = targetLine.SPPID.START_X;
1536
                y = targetLine.SPPID.START_Y;
1537
            }
1538
            else
1539
            {
1540
                x = targetLine.SPPID.END_X;
1541
                y = targetLine.SPPID.END_Y;
1542
            }
1543
        }
1544

    
1545
        /// <summary>
1546
        /// SPPID Symbol의 Range를 구한다.
1547
        /// </summary>
1548
        /// <param name="symbol"></param>
1549
        /// <param name="range"></param>
1550
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1551
        {
1552
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1553
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1554
            double x1 = 0;
1555
            double y1 = 0;
1556
            double x2 = 0;
1557
            double y2 = 0;
1558
            symbol2d.Range(out x1, out y1, out x2, out y2);
1559
            range = new double[] { x1, y1, x2, y2 };
1560

    
1561
            for (int i = 1; i < int.MaxValue; i++)
1562
            {
1563
                double connX = 0;
1564
                double connY = 0;
1565
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1566
                    points.Add(new double[] { connX, connY });
1567
                else
1568
                    break;
1569
            }
1570

    
1571
            foreach (var childSymbol in symbol.ChildSymbols)
1572
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1573

    
1574
            ReleaseCOMObjects(_TargetItem);
1575
        }
1576

    
1577
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1578
        {
1579
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1580
            if (_TargetItem != null)
1581
            {
1582
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1583
                double x1 = 0;
1584
                double y1 = 0;
1585
                double x2 = 0;
1586
                double y2 = 0;
1587
                if (!bForGraphic)
1588
                {
1589
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1590
                    range = new double[] { x1, y1, x2, y2 };
1591
                }
1592
                else
1593
                {
1594
                    x1 = double.MaxValue;
1595
                    y1 = double.MaxValue;
1596
                    x2 = double.MinValue;
1597
                    y2 = double.MinValue;
1598
                    range = new double[] { x1, y1, x2, y2 };
1599

    
1600
                    foreach (var item in symbol2d.DrawingObjects)
1601
                    {
1602
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1603
                        {
1604
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1605
                            if (rangeObject.Layer == "Default")
1606
                            {
1607
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1608
                                range = new double[] {
1609
                                Math.Min(x1, range[0]),
1610
                                Math.Min(y1, range[1]),
1611
                                Math.Max(x2, range[2]),
1612
                                Math.Max(y2, range[3])
1613
                            };
1614
                            }
1615
                        }
1616
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1617
                        {
1618
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1619
                            if (rangeObject.Layer == "Default")
1620
                            {
1621
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1622
                                range = new double[] {
1623
                                Math.Min(x1, range[0]),
1624
                                Math.Min(y1, range[1]),
1625
                                Math.Max(x2, range[2]),
1626
                                Math.Max(y2, range[3])
1627
                            };
1628
                            }
1629
                        }
1630
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1631
                        {
1632
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1633
                            if (rangeObject.Layer == "Default")
1634
                            {
1635
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1636
                                range = new double[] {
1637
                                Math.Min(x1, range[0]),
1638
                                Math.Min(y1, range[1]),
1639
                                Math.Max(x2, range[2]),
1640
                                Math.Max(y2, range[3])
1641
                            };
1642
                            }
1643
                        }
1644
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1645
                        {
1646
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1647
                            if (rangeObject.Layer == "Default")
1648
                            {
1649
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1650
                                range = new double[] {
1651
                                Math.Min(x1, range[0]),
1652
                                Math.Min(y1, range[1]),
1653
                                Math.Max(x2, range[2]),
1654
                                Math.Max(y2, range[3])
1655
                            };
1656
                            }
1657
                        }
1658
                    }
1659
                }
1660

    
1661
                if (!bOnlySymbol)
1662
                {
1663
                    foreach (var childSymbol in symbol.ChildSymbols)
1664
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1665
                }
1666
                ReleaseCOMObjects(_TargetItem);
1667
            }
1668
        }
1669

    
1670
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1671
        {
1672
            if (labelPersist != null)
1673
            {
1674
                double x1 = double.MaxValue;
1675
                double y1 = double.MaxValue;
1676
                double x2 = double.MinValue;
1677
                double y2 = double.MinValue;
1678
                range = new double[] { x1, y1, x2, y2 };
1679

    
1680
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1681
                foreach (var item in dependency.DrawingObjects)
1682
                {
1683
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1684
                    if (textBox != null)
1685
                    {
1686
                        if (dependency != null)
1687
                        {
1688
                            double tempX1;
1689
                            double tempY1;
1690
                            double tempX2;
1691
                            double tempY2;
1692
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1693
                            x1 = Math.Min(x1, tempX1);
1694
                            y1 = Math.Min(y1, tempY1);
1695
                            x2 = Math.Max(x2, tempX2);
1696
                            y2 = Math.Max(y2, tempY2);
1697

    
1698
                            range = new double[] { x1, y1, x2, y2 };
1699
                        }
1700
                    }
1701
                }
1702
                
1703
            }
1704
        }
1705

    
1706
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1707
        {
1708
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1709
            foreach (var symbol in symbols)
1710
            {
1711
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1712
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1713
                double x1 = 0;
1714
                double y1 = 0;
1715
                double x2 = 0;
1716
                double y2 = 0;
1717
                symbol2d.Range(out x1, out y1, out x2, out y2);
1718

    
1719
                tempRange[0] = Math.Min(tempRange[0], x1);
1720
                tempRange[1] = Math.Min(tempRange[1], y1);
1721
                tempRange[2] = Math.Max(tempRange[2], x2);
1722
                tempRange[3] = Math.Max(tempRange[3], y2);
1723

    
1724
                foreach (var childSymbol in symbol.ChildSymbols)
1725
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1726

    
1727
                ReleaseCOMObjects(_TargetItem);
1728
            }
1729

    
1730
            range = tempRange;
1731
        }
1732

    
1733
        /// <summary>
1734
        /// Child Modeling 된 Symbol의 Range를 구한다.
1735
        /// </summary>
1736
        /// <param name="childSymbol"></param>
1737
        /// <param name="range"></param>
1738
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1739
        {
1740
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1741
            if (_ChildSymbol != null)
1742
            {
1743
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1744
                double x1 = 0;
1745
                double y1 = 0;
1746
                double x2 = 0;
1747
                double y2 = 0;
1748
                symbol2d.Range(out x1, out y1, out x2, out y2);
1749
                range[0] = Math.Min(range[0], x1);
1750
                range[1] = Math.Min(range[1], y1);
1751
                range[2] = Math.Max(range[2], x2);
1752
                range[3] = Math.Max(range[3], y2);
1753

    
1754
                for (int i = 1; i < int.MaxValue; i++)
1755
                {
1756
                    double connX = 0;
1757
                    double connY = 0;
1758
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1759
                        points.Add(new double[] { connX, connY });
1760
                    else
1761
                        break;
1762
                }
1763

    
1764
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1765
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1766

    
1767
                ReleaseCOMObjects(_ChildSymbol);
1768
            }
1769
        }
1770

    
1771
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1772
        {
1773
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1774
            if (_ChildSymbol != null)
1775
            {
1776
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1777
                double x1 = 0;
1778
                double y1 = 0;
1779
                double x2 = 0;
1780
                double y2 = 0;
1781
                symbol2d.Range(out x1, out y1, out x2, out y2);
1782
                range[0] = Math.Min(range[0], x1);
1783
                range[1] = Math.Min(range[1], y1);
1784
                range[2] = Math.Max(range[2], x2);
1785
                range[3] = Math.Max(range[3], y2);
1786

    
1787
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1788
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1789
                ReleaseCOMObjects(_ChildSymbol);
1790
            }
1791
        }
1792

    
1793
        /// <summary>
1794
        /// Label Symbol Modeling
1795
        /// </summary>
1796
        /// <param name="symbol"></param>
1797
        private void LabelSymbolModeling(Symbol symbol)
1798
        {
1799
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1800
            {
1801
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1802
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1803
                    return;
1804
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1805

    
1806
                string symbolUID = itemAttribute.VALUE;
1807
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1808
                if (targetItem != null &&
1809
                    (targetItem.GetType() == typeof(Symbol) ||
1810
                    targetItem.GetType() == typeof(Equipment)))
1811
                {
1812
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1813
                    string sRep = null;
1814
                    if (targetItem.GetType() == typeof(Symbol))
1815
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1816
                    else if (targetItem.GetType() == typeof(Equipment))
1817
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1818
                    if (!string.IsNullOrEmpty(sRep))
1819
                    {
1820
                        // LEADER Line 검사
1821
                        bool leaderLine = false;
1822
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1823
                        if (symbolMapping != null)
1824
                            leaderLine = symbolMapping.LEADERLINE;
1825

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

    
1830
                        //Leader 선 센터로
1831
                        if (_LMLabelPresist != null)
1832
                        {
1833
                            // Target Item에 Label의 Attribute Input
1834
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1835

    
1836
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1837
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1838
                            if (dependency != null)
1839
                            {
1840
                                bool result = false;
1841
                                foreach (var attributes in dependency.AttributeSets)
1842
                                {
1843
                                    foreach (var attribute in attributes)
1844
                                    {
1845
                                        string name = attribute.Name;
1846
                                        string value = attribute.GetValue().ToString();
1847
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1848
                                        {
1849
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1850
                                            {
1851
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1852
                                                {
1853
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1854
                                                    double prevX = _TargetItem.get_XCoordinate();
1855
                                                    double prevY = _TargetItem.get_YCoordinate();
1856
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1857
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1858
                                                    result = true;
1859
                                                    break;
1860
                                                }
1861
                                            }
1862
                                        }
1863

    
1864
                                        if (result)
1865
                                            break;
1866
                                    }
1867

    
1868
                                    if (result)
1869
                                        break;
1870
                                }
1871
                            }
1872

    
1873
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1874
                            _LMLabelPresist.Commit();
1875
                            ReleaseCOMObjects(_LMLabelPresist);
1876
                        }
1877

    
1878
                        ReleaseCOMObjects(_TargetItem);
1879
                    }
1880
                }
1881
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1882
                {
1883
                    Line targetLine = targetItem as Line;
1884
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1885
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1886
                    if (connectedLMConnector != null)
1887
                    {
1888
                        // LEADER Line 검사
1889
                        bool leaderLine = false;
1890
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1891
                        if (symbolMapping != null)
1892
                            leaderLine = symbolMapping.LEADERLINE;
1893

    
1894
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1895
                        if (_LMLabelPresist != null)
1896
                        {
1897
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1898
                            _LMLabelPresist.Commit();
1899
                            ReleaseCOMObjects(_LMLabelPresist);
1900
                        }
1901
                        ReleaseCOMObjects(connectedLMConnector);
1902
                    }
1903

    
1904
                    foreach (var item in connectorVertices)
1905
                        if (item.Key != null)
1906
                            ReleaseCOMObjects(item.Key);
1907
                }
1908
            }
1909
        }
1910

    
1911
        /// <summary>
1912
        /// Equipment를 실제로 Modeling 메서드
1913
        /// </summary>
1914
        /// <param name="equipment"></param>
1915
        private void EquipmentModeling(Equipment equipment)
1916
        {
1917
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1918
                return;
1919

    
1920
            LMSymbol _LMSymbol = null;
1921
            LMSymbol targetItem = null;
1922
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1923
            double x = equipment.SPPID.ORIGINAL_X;
1924
            double y = equipment.SPPID.ORIGINAL_Y;
1925
            int mirror = 0;
1926
            double angle = equipment.ANGLE;
1927

    
1928
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1929

    
1930
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1931
            if (connector != null)
1932
            {
1933
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1934
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1935
                if (connEquipment != null)
1936
                {
1937
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1938
                        EquipmentModeling(connEquipment);
1939

    
1940
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1941
                    {
1942
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1943
                        if (targetItem != null)
1944
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1945
                        else
1946
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1947
                    }
1948
                    else
1949
                    {
1950
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1951
                    }
1952
                }
1953
                else if (connVendorPackage != null)
1954
                {
1955
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1956
                    {
1957
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1958
                        if (targetItem != null)
1959
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1960
                        else
1961
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1962
                    }
1963
                }
1964
                else
1965
                {
1966
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1967
                }
1968
            }
1969
            else
1970
            {
1971
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1972
            }
1973

    
1974
            if (_LMSymbol != null)
1975
            {
1976
                _LMSymbol.Commit();
1977
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1978
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1979
                ReleaseCOMObjects(_LMSymbol);
1980
            }
1981

    
1982
            if (targetItem != null)
1983
            {
1984
                ReleaseCOMObjects(targetItem);
1985
            }
1986

    
1987
            ReleaseCOMObjects(_LMSymbol);
1988
        }
1989

    
1990
        private void VendorPackageModeling(VendorPackage vendorPackage)
1991
        {
1992
            ETCSetting setting = ETCSetting.GetInstance();
1993
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1994
            {
1995
                string symbolPath = setting.VendorPackageSymbolPath;
1996
                double x = vendorPackage.SPPID.ORIGINAL_X;
1997
                double y = vendorPackage.SPPID.ORIGINAL_Y;
1998

    
1999
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2000
                if (symbol != null)
2001
                {
2002
                    symbol.Commit();
2003
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2004
                }
2005

    
2006
                ReleaseCOMObjects(symbol);
2007
                symbol = null;
2008
            }
2009
        }
2010

    
2011
        /// <summary>
2012
        /// 첫 진입점
2013
        /// </summary>
2014
        /// <param name="symbol"></param>
2015
        private void SymbolModelingBySymbol(Symbol symbol)
2016
        {
2017
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2018
            List<object> endObjects = new List<object>();
2019
            endObjects.Add(symbol);
2020

    
2021
            /// 심볼에 연결되어 있는 항목들을 모델링한다
2022
            foreach (var connector in symbol.CONNECTORS)
2023
            {
2024
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2025
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2026
                {
2027
                    endObjects.Add(connItem);
2028
                    if (connItem.GetType() == typeof(Symbol))
2029
                    {
2030
                        Symbol connSymbol = connItem as Symbol;
2031
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2032
                        {
2033
                            SymbolModeling(connSymbol, symbol);
2034
                        }
2035
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2036
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2037
                    }
2038
                    else if (connItem.GetType() == typeof(Line))
2039
                    {
2040
                        Line connLine = connItem as Line;
2041
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2042
                    }
2043
                }
2044
            }
2045
        }
2046

    
2047
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2048
        {
2049
            foreach (var connector in symbol.CONNECTORS)
2050
            {
2051
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2052
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2053
                {
2054
                    if (!endObjects.Contains(connItem))
2055
                    {
2056
                        endObjects.Add(connItem);
2057
                        if (connItem.GetType() == typeof(Symbol))
2058
                        {
2059
                            Symbol connSymbol = connItem as Symbol;
2060
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2061
                            {
2062
                                SymbolModeling(connSymbol, symbol);
2063
                            }
2064
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2065
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2066
                        }
2067
                        else if (connItem.GetType() == typeof(Line))
2068
                        {
2069
                            Line connLine = connItem as Line;
2070
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2071
                        }
2072
                    }
2073
                }
2074
            }
2075
        }
2076

    
2077
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2078
        {
2079
            foreach (var connector in line.CONNECTORS)
2080
            {
2081
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2082
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2083
                {
2084
                    if (!endObjects.Contains(connItem))
2085
                    {
2086
                        endObjects.Add(connItem);
2087
                        if (connItem.GetType() == typeof(Symbol))
2088
                        {
2089
                            Symbol connSymbol = connItem as Symbol;
2090
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2091
                            {
2092
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2093
                                int branchCount = 0;
2094
                                if (connLine != null)
2095
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2096

    
2097
                                List<Symbol> group = new List<Symbol>();
2098
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2099
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2100
                                List<Symbol> endModelingGroup = new List<Symbol>();
2101
                                if (priority != null)
2102
                                {
2103
                                    SymbolGroupModeling(priority, group);
2104

    
2105
                                    // Range 겹치는지 확인해야함
2106
                                    double[] prevRange = null;
2107
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2108
                                    double[] groupRange = null;
2109
                                    GetSPPIDSymbolRange(group, ref groupRange);
2110

    
2111
                                    double distanceX = 0;
2112
                                    double distanceY = 0;
2113
                                    bool overlapX = false;
2114
                                    bool overlapY = false;
2115
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2116
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2117
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2118
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2119
                                    {
2120
                                        RemoveSymbol(group);
2121
                                        foreach (var _temp in group)
2122
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2123

    
2124
                                        SymbolGroupModeling(priority, group);
2125
                                    }
2126
                                    else if (branchCount > 0)
2127
                                    {
2128
                                        LMConnector _connector = JustLineModeling(connLine);
2129
                                        if (_connector != null)
2130
                                        {
2131
                                            double distance = GetConnectorDistance(_connector);
2132
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2133
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2134
                                            _connector.Commit();
2135
                                            ReleaseCOMObjects(_connector);
2136
                                            _connector = null;
2137
                                            if (cellCount < branchCount + 1)
2138
                                            {
2139
                                                int moveCount = branchCount - cellCount;
2140
                                                RemoveSymbol(group);
2141
                                                foreach (var _temp in group)
2142
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2143

    
2144
                                                SymbolGroupModeling(priority, group);
2145
                                            }
2146
                                        }
2147
                                    }
2148
                                }
2149
                                else
2150
                                {
2151
                                    SymbolModeling(connSymbol, null);
2152
                                    // Range 겹치는지 확인해야함
2153
                                    double[] prevRange = null;
2154
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2155
                                    double[] connRange = null;
2156
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2157

    
2158
                                    double distanceX = 0;
2159
                                    double distanceY = 0;
2160
                                    bool overlapX = false;
2161
                                    bool overlapY = false;
2162
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2163
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2164
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2165
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2166
                                    {
2167
                                        RemoveSymbol(connSymbol);
2168
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2169

    
2170
                                        SymbolModeling(connSymbol, null);
2171
                                    }
2172
                                    else if (branchCount > 0)
2173
                                    {
2174
                                        LMConnector _connector = JustLineModeling(connLine);
2175
                                        if (_connector != null)
2176
                                        {
2177
                                            double distance = GetConnectorDistance(_connector);
2178
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2179
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2180
                                            _connector.Commit();
2181
                                            ReleaseCOMObjects(_connector);
2182
                                            _connector = null;
2183
                                            if (cellCount < branchCount + 1)
2184
                                            {
2185
                                                int moveCount = branchCount - cellCount;
2186
                                                RemoveSymbol(group);
2187
                                                foreach (var _temp in group)
2188
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2189

    
2190
                                                SymbolGroupModeling(priority, group);
2191
                                            }
2192
                                        }
2193
                                    }
2194
                                }
2195
                            }
2196
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2197
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2198
                        }
2199
                        else if (connItem.GetType() == typeof(Line))
2200
                        {
2201
                            Line connLine = connItem as Line;
2202
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2203
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2204
                        }
2205
                    }
2206
                }
2207
            }
2208
        }
2209

    
2210
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2211
        {
2212
            List<Symbol> endModelingGroup = new List<Symbol>();
2213
            SymbolModeling(firstSymbol, null);
2214
            endModelingGroup.Add(firstSymbol);
2215
            while (endModelingGroup.Count != group.Count)
2216
            {
2217
                foreach (var _symbol in group)
2218
                {
2219
                    if (!endModelingGroup.Contains(_symbol))
2220
                    {
2221
                        foreach (var _connector in _symbol.CONNECTORS)
2222
                        {
2223
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2224
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2225
                            {
2226
                                SymbolModeling(_symbol, _connSymbol);
2227
                                endModelingGroup.Add(_symbol);
2228
                                break;
2229
                            }
2230
                        }
2231
                    }
2232
                }
2233
            }
2234
        }
2235

    
2236
        /// <summary>
2237
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2238
        /// </summary>
2239
        /// <param name="childSymbol"></param>
2240
        /// <param name="parentSymbol"></param>
2241
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2242
        {
2243
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2244
            double x1 = 0;
2245
            double x2 = 0;
2246
            double y1 = 0;
2247
            double y2 = 0;
2248
            symbol2d.Range(out x1, out y1, out x2, out y2);
2249

    
2250
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2251
            if (_LMSymbol != null)
2252
            {
2253
                _LMSymbol.Commit();
2254
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2255
                foreach (var item in childSymbol.ChildSymbols)
2256
                    CreateChildSymbol(item, _LMSymbol, parent);
2257
            }
2258

    
2259

    
2260
            ReleaseCOMObjects(_LMSymbol);
2261
        }
2262
        double index = 0;
2263
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2264
        {
2265
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2266
                return;
2267

    
2268
            List<Line> group = new List<Line>();
2269
            GetConnectedLineGroup(line, group);
2270
            LineCoordinateCorrection(group);
2271

    
2272
            foreach (var groupLine in group)
2273
            {
2274
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2275
                {
2276
                    BranchLines.Add(groupLine);
2277
                    continue;
2278
                }
2279

    
2280
                bool diagonal = false;
2281
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2282
                    diagonal = true;
2283
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2284
                LMSymbol _LMSymbolStart = null;
2285
                LMSymbol _LMSymbolEnd = null;
2286
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2287
                foreach (var connector in groupLine.CONNECTORS)
2288
                {
2289
                    double x = 0;
2290
                    double y = 0;
2291
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2292
                    if (connector.ConnectedObject == null)
2293
                    {
2294
                        placeRunInputs.AddPoint(x, y);
2295
                    }
2296
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2297
                    {
2298
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2299
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2300
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2301
                        {
2302
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2303
                            if (_LMSymbolStart != null)
2304
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2305
                            else
2306
                                placeRunInputs.AddPoint(x, y);
2307
                        }
2308
                        else
2309
                        {
2310
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2311
                            if (_LMSymbolEnd != null)
2312
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2313
                            else
2314
                                placeRunInputs.AddPoint(x, y);
2315
                        }
2316
                    }
2317
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2318
                    {
2319
                        Line targetLine = connector.ConnectedObject as Line;
2320
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2321
                        {
2322
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2323
                            if (targetConnector != null)
2324
                            {
2325
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2326
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2327
                            }
2328
                            else
2329
                            {
2330
                                placeRunInputs.AddPoint( x, y);
2331
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2332
                            }
2333
                        }
2334
                        else
2335
                        {
2336
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2337
                            {
2338
                                index += 0.01;
2339
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2340
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2341
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2342
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2343
                                else
2344
                                {
2345
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2346
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2347
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2348
                                    else
2349
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2350
                                }
2351
                            }
2352

    
2353
                            placeRunInputs.AddPoint(x, y);
2354

    
2355
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2356
                            {
2357
                                index += 0.01;
2358
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2359
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2360
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2361
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2362
                                else
2363
                                {
2364
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2365
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2366
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2367
                                    else
2368
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2369
                                }
2370
                            }
2371
                        }
2372
                    }
2373
                }
2374

    
2375
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2376
                if (_lMConnector != null)
2377
                {
2378
                    _lMConnector.Commit();
2379
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2380

    
2381
                    bool bRemodelingStart = false;
2382
                    if (_LMSymbolStart != null)
2383
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2384
                    bool bRemodelingEnd = false;
2385
                    if (_LMSymbolEnd != null)
2386
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2387

    
2388
                    if (bRemodelingStart || bRemodelingEnd)
2389
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2390

    
2391
                    FlowMarkModeling(groupLine);
2392

    
2393
                    ReleaseCOMObjects(_lMConnector);
2394

    
2395
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2396
                    if (modelItem != null)
2397
                    {
2398
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2399
                        if (attribute != null)
2400
                            attribute.set_Value("End 1 is upstream (Inlet)");
2401
                        modelItem.Commit();
2402
                    }
2403
                    ReleaseCOMObjects(modelItem);
2404
                    modelItem = null;
2405
                }
2406
                else if (!isBranchModeling)
2407
                {
2408
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2409
                }
2410

    
2411
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2412
                x.ConnectedObject != null &&
2413
                x.ConnectedObject.GetType() == typeof(Line) &&
2414
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2415
                .Select(x => x.ConnectedObject)
2416
                .ToList();
2417

    
2418
                foreach (var item in removeLines)
2419
                    RemoveLineForModeling(item as Line);
2420

    
2421
                ReleaseCOMObjects(_LMAItem);
2422
                _LMAItem = null;
2423
                ReleaseCOMObjects(placeRunInputs);
2424
                placeRunInputs = null;
2425
                ReleaseCOMObjects(_LMSymbolStart);
2426
                _LMSymbolStart = null;
2427
                ReleaseCOMObjects(_LMSymbolEnd);
2428
                _LMSymbolEnd = null;
2429

    
2430
                if (isBranchModeling && BranchLines.Contains(groupLine))
2431
                    BranchLines.Remove(groupLine);
2432
            }
2433
        }
2434

    
2435
        private LMConnector JustLineModeling(Line line)
2436
        {
2437
            bool diagonal = false;
2438
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2439
                diagonal = true;
2440
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2441
            LMSymbol _LMSymbolStart = null;
2442
            LMSymbol _LMSymbolEnd = null;
2443
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2444
            foreach (var connector in line.CONNECTORS)
2445
            {
2446
                double x = 0;
2447
                double y = 0;
2448
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2449
                if (connector.ConnectedObject == null)
2450
                {
2451
                    placeRunInputs.AddPoint(x, y);
2452
                }
2453
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2454
                {
2455
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2456
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2457
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2458
                    {
2459
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2460
                        if (_LMSymbolStart != null)
2461
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2462
                        else
2463
                            placeRunInputs.AddPoint(x, y);
2464
                    }
2465
                    else
2466
                    {
2467
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2468
                        if (_LMSymbolEnd != null)
2469
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2470
                        else
2471
                            placeRunInputs.AddPoint(x, y);
2472
                    }
2473
                }
2474
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2475
                {
2476
                    Line targetLine = connector.ConnectedObject as Line;
2477
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2478
                    {
2479
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2480
                        if (targetConnector != null)
2481
                        {
2482
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2483
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2484
                        }
2485
                        else
2486
                        {
2487
                            placeRunInputs.AddPoint(x, y);
2488
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2489
                        }
2490
                    }
2491
                    else
2492
                        placeRunInputs.AddPoint(x, y);
2493
                }
2494
            }
2495

    
2496
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2497
            if (_lMConnector != null)
2498
                _lMConnector.Commit();
2499

    
2500
            ReleaseCOMObjects(_LMAItem);
2501
            _LMAItem = null;
2502
            ReleaseCOMObjects(placeRunInputs);
2503
            placeRunInputs = null;
2504
            ReleaseCOMObjects(_LMSymbolStart);
2505
            _LMSymbolStart = null;
2506
            ReleaseCOMObjects(_LMSymbolEnd);
2507
            _LMSymbolEnd = null;
2508

    
2509
            return _lMConnector;
2510
        }
2511

    
2512
        private void RemoveLineForModeling(Line line)
2513
        {
2514
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2515
            if (modelItem != null)
2516
            {
2517
                foreach (LMRepresentation rep in modelItem.Representations)
2518
                {
2519
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2520
                    {
2521
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2522
                        dynamic OID = rep.get_GraphicOID().ToString();
2523
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2524
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2525
                        int verticesCount = lineStringGeometry.VertexCount;
2526
                        double[] vertices = null;
2527
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2528
                        for (int i = 0; i < verticesCount; i++)
2529
                        {
2530
                            double x = 0;
2531
                            double y = 0;
2532
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2533
                            if (verticesCount == 2 && (x < 0 || y < 0))
2534
                                _placement.PIDRemovePlacement(rep);
2535
                        }
2536
                        ReleaseCOMObjects(_LMConnector);
2537
                    }
2538
                }
2539

    
2540
                ReleaseCOMObjects(modelItem);
2541
            }
2542
        }
2543

    
2544
        private void RemoveLine(Line line)
2545
        {
2546
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2547
            if (modelItem != null)
2548
            {
2549
                foreach (LMRepresentation rep in modelItem.Representations)
2550
                {
2551
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2552
                        _placement.PIDRemovePlacement(rep);
2553
                }
2554
                ReleaseCOMObjects(modelItem);
2555
            }
2556
            line.SPPID.ModelItemId = null;
2557
        }
2558

    
2559
        private void GetConnectedLineGroup(Line line, List<Line> group)
2560
        {
2561
            if (!group.Contains(line))
2562
                group.Add(line);
2563
            foreach (var connector in line.CONNECTORS)
2564
            {
2565
                if (connector.ConnectedObject != null &&
2566
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2567
                    !group.Contains(connector.ConnectedObject) &&
2568
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2569
                {
2570
                    Line connLine = connector.ConnectedObject as Line;
2571
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2572
                    {
2573
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2574
                            group.Insert(0, connLine);
2575
                        else
2576
                            group.Add(connLine);
2577
                        GetConnectedLineGroup(connLine, group);
2578
                    }
2579
                }
2580
            }
2581
        }
2582

    
2583
        private void LineCoordinateCorrection(List<Line> group)
2584
        {
2585
            // 순서대로 전 Item 기준 정렬
2586
            LineCoordinateCorrectionByStart(group);
2587

    
2588
            // 역으로 심볼이 있을 경우 좌표 보정
2589
            LineCoordinateCorrectionForLastLine(group);
2590
        }
2591

    
2592
        private void LineCoordinateCorrectionByStart(List<Line> group)
2593
        {
2594
            for (int i = 0; i < group.Count; i++)
2595
            {
2596
                Line line = group[i];
2597
                if (i == 0)
2598
                {
2599
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2600
                    if (symbolConnector != null)
2601
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2602
                }
2603
                else if (i != 0)
2604
                {
2605
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2606
                }
2607
            }
2608
        }
2609

    
2610
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2611
        {
2612
            Line checkLine = group[group.Count - 1];
2613
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2614
            if (lastSymbolConnector != null)
2615
            {
2616
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2617
                for (int i = group.Count - 2; i >= 0; i--)
2618
                {
2619
                    Line line = group[i + 1];
2620
                    Line prevLine = group[i];
2621

    
2622
                    // 같으면 보정
2623
                    if (line.SlopeType == prevLine.SlopeType)
2624
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2625
                    else
2626
                    {
2627
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2628
                        {
2629
                            double prevX = 0;
2630
                            double prevY = 0;
2631
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2632
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2633

    
2634
                            double x = 0;
2635
                            double y = 0;
2636
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2637
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2638
                        }
2639
                        else if (line.SlopeType == SlopeType.VERTICAL)
2640
                        {
2641
                            double prevX = 0;
2642
                            double prevY = 0;
2643
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2644
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2645

    
2646
                            double x = 0;
2647
                            double y = 0;
2648
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2649
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2650
                        }
2651
                        break;
2652
                    }
2653
                }
2654
            }
2655
        }
2656

    
2657
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2658
        {
2659
            double x = 0;
2660
            double y = 0;
2661
            if (connItem.GetType() == typeof(Symbol))
2662
            {
2663
                Symbol targetSymbol = connItem as Symbol;
2664
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2665
                if (targetConnector != null)
2666
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2667
                else
2668
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2669
            }
2670
            else if (connItem.GetType() == typeof(Line))
2671
            {
2672
                Line targetLine = connItem as Line;
2673
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2674
            }
2675

    
2676
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2677
        }
2678

    
2679
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2680
        {
2681
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2682
            int index = line.CONNECTORS.IndexOf(connector);
2683
            if (index == 0)
2684
            {
2685
                line.SPPID.START_X = x;
2686
                line.SPPID.START_Y = y;
2687
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2688
                    line.SPPID.END_Y = y;
2689
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2690
                    line.SPPID.END_X = x;
2691
            }
2692
            else
2693
            {
2694
                line.SPPID.END_X = x;
2695
                line.SPPID.END_Y = y;
2696
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2697
                    line.SPPID.START_Y = y;
2698
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2699
                    line.SPPID.START_X = x;
2700
            }
2701
        }
2702

    
2703
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2704
        {
2705
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2706
            int index = line.CONNECTORS.IndexOf(connector);
2707
            if (index == 0)
2708
            {
2709
                line.SPPID.START_X = x;
2710
                if (line.SlopeType == SlopeType.VERTICAL)
2711
                    line.SPPID.END_X = x;
2712
            }
2713
            else
2714
            {
2715
                line.SPPID.END_X = x;
2716
                if (line.SlopeType == SlopeType.VERTICAL)
2717
                    line.SPPID.START_X = x;
2718
            }
2719
        }
2720

    
2721
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2722
        {
2723
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2724
            int index = line.CONNECTORS.IndexOf(connector);
2725
            if (index == 0)
2726
            {
2727
                line.SPPID.START_Y = y;
2728
                if (line.SlopeType == SlopeType.HORIZONTAL)
2729
                    line.SPPID.END_Y = y;
2730
            }
2731
            else
2732
            {
2733
                line.SPPID.END_Y = y;
2734
                if (line.SlopeType == SlopeType.HORIZONTAL)
2735
                    line.SPPID.START_Y = y;
2736
            }
2737
        }
2738

    
2739
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2740
        {
2741
            if (symbol != null)
2742
            {
2743
                string repID = symbol.AsLMRepresentation().Id;
2744
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2745
                string lineUID = line.UID;
2746

    
2747
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2748
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2749
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2750

    
2751
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2752
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2753
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2754

    
2755
                if (startSpecBreak != null || startEndBreak != null)
2756
                    result = true;
2757
            }
2758
        }
2759

    
2760
        /// <summary>
2761
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2762
        /// </summary>
2763
        /// <param name="lines"></param>
2764
        /// <param name="prevLMConnector"></param>
2765
        /// <param name="startSymbol"></param>
2766
        /// <param name="endSymbol"></param>
2767
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2768
        {
2769
            string symbolPath = string.Empty;
2770
            #region get symbol path
2771
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2772
            symbolPath = GetSPPIDFileName(modelItem);
2773
            ReleaseCOMObjects(modelItem);
2774
            #endregion
2775
            bool diagonal = false;
2776
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2777
                diagonal = true;
2778
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2779
            LMConnector newConnector = null;
2780
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2781
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2782
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2783
            int verticesCount = lineStringGeometry.VertexCount;
2784
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2785

    
2786
            List<double[]> vertices = new List<double[]>();
2787
            for (int i = 1; i <= verticesCount; i++)
2788
            {
2789
                double x = 0;
2790
                double y = 0;
2791
                lineStringGeometry.GetVertex(i, ref x, ref y);
2792
                vertices.Add(new double[] { x, y });
2793
            }
2794

    
2795
            for (int i = 0; i < vertices.Count; i++)
2796
            {
2797
                double[] points = vertices[i];
2798
                // 시작 심볼이 있고 첫번째 좌표일 때
2799
                if (startSymbol != null && i == 0)
2800
                {
2801
                    if (bStart)
2802
                    {
2803
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2804
                        if (slopeType == SlopeType.HORIZONTAL)
2805
                            placeRunInputs.AddPoint(points[0], -0.1);
2806
                        else if (slopeType == SlopeType.VERTICAL)
2807
                            placeRunInputs.AddPoint(-0.1, points[1]);
2808
                        else
2809
                            placeRunInputs.AddPoint(points[0], -0.1);
2810

    
2811
                        placeRunInputs.AddPoint(points[0], points[1]);
2812
                    }
2813
                    else
2814
                    {
2815
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2816
                    }
2817
                }
2818
                // 마지막 심볼이 있고 마지막 좌표일 때
2819
                else if (endSymbol != null && i == vertices.Count - 1)
2820
                {
2821
                    if (bEnd)
2822
                    {
2823
                        placeRunInputs.AddPoint(points[0], points[1]);
2824

    
2825
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2826
                        if (slopeType == SlopeType.HORIZONTAL)
2827
                            placeRunInputs.AddPoint(points[0], -0.1);
2828
                        else if (slopeType == SlopeType.VERTICAL)
2829
                            placeRunInputs.AddPoint(-0.1, points[1]);
2830
                        else
2831
                            placeRunInputs.AddPoint(points[0], -0.1);
2832
                    }
2833
                    else
2834
                    {
2835
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2836
                    }
2837
                }
2838
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2839
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2840
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2841
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2842
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2843
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2844
                else
2845
                    placeRunInputs.AddPoint(points[0], points[1]);
2846
            }
2847

    
2848
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2849
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2850

    
2851
            ReleaseCOMObjects(placeRunInputs);
2852
            ReleaseCOMObjects(_LMAItem);
2853
            ReleaseCOMObjects(modelItem);
2854

    
2855
            if (newConnector != null)
2856
            {
2857
                newConnector.Commit();
2858
                if (startSymbol != null && bStart)
2859
                {
2860
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2861
                    placeRunInputs = new PlaceRunInputs();
2862
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2863
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2864
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2865
                    if (_LMConnector != null)
2866
                    {
2867
                        _LMConnector.Commit();
2868
                        RemoveConnectorForReModelingLine(newConnector);
2869
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2870
                        ReleaseCOMObjects(_LMConnector);
2871
                    }
2872
                    ReleaseCOMObjects(placeRunInputs);
2873
                    ReleaseCOMObjects(_LMAItem);
2874
                }
2875

    
2876
                if (endSymbol != null && bEnd)
2877
                {
2878
                    if (startSymbol != null)
2879
                    {
2880
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2881
                        newConnector = dicVertices.First().Key;
2882
                    }
2883

    
2884
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2885
                    placeRunInputs = new PlaceRunInputs();
2886
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2887
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2888
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2889
                    if (_LMConnector != null)
2890
                    {
2891
                        _LMConnector.Commit();
2892
                        RemoveConnectorForReModelingLine(newConnector);
2893
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2894
                        ReleaseCOMObjects(_LMConnector);
2895
                    }
2896
                    ReleaseCOMObjects(placeRunInputs);
2897
                    ReleaseCOMObjects(_LMAItem);
2898
                }
2899

    
2900
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2901
                ReleaseCOMObjects(newConnector);
2902
            }
2903

    
2904
            ReleaseCOMObjects(modelItem);
2905
        }
2906

    
2907
        /// <summary>
2908
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2909
        /// </summary>
2910
        /// <param name="connector"></param>
2911
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2912
        {
2913
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2914
            foreach (var item in dicVertices)
2915
            {
2916
                if (item.Value.Count == 2)
2917
                {
2918
                    bool result = false;
2919
                    foreach (var point in item.Value)
2920
                    {
2921
                        if (point[0] < 0 || point[1] < 0)
2922
                        {
2923
                            result = true;
2924
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2925
                            break;
2926
                        }
2927
                    }
2928

    
2929
                    if (result)
2930
                        break;
2931
                }
2932
            }
2933
            foreach (var item in dicVertices)
2934
                ReleaseCOMObjects(item.Key);
2935
        }
2936

    
2937
        /// <summary>
2938
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2939
        /// </summary>
2940
        /// <param name="symbol"></param>
2941
        /// <param name="line"></param>
2942
        /// <returns></returns>
2943
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2944
        {
2945
            LMSymbol _LMSymbol = null;
2946
            foreach (var connector in symbol.CONNECTORS)
2947
            {
2948
                if (connector.CONNECTEDITEM == line.UID)
2949
                {
2950
                    if (connector.Index == 0)
2951
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2952
                    else
2953
                    {
2954
                        ChildSymbol child = null;
2955
                        foreach (var childSymbol in symbol.ChildSymbols)
2956
                        {
2957
                            if (childSymbol.Connectors.Contains(connector))
2958
                                child = childSymbol;
2959
                            else
2960
                                child = GetChildSymbolByConnector(childSymbol, connector);
2961

    
2962
                            if (child != null)
2963
                                break;
2964
                        }
2965

    
2966
                        if (child != null)
2967
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2968
                    }
2969

    
2970
                    break;
2971
                }
2972
            }
2973

    
2974
            return _LMSymbol;
2975
        }
2976

    
2977
        /// <summary>
2978
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2979
        /// </summary>
2980
        /// <param name="item"></param>
2981
        /// <param name="connector"></param>
2982
        /// <returns></returns>
2983
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2984
        {
2985
            foreach (var childSymbol in item.ChildSymbols)
2986
            {
2987
                if (childSymbol.Connectors.Contains(connector))
2988
                    return childSymbol;
2989
                else
2990
                    return GetChildSymbolByConnector(childSymbol, connector);
2991
            }
2992

    
2993
            return null;
2994
        }
2995

    
2996
        /// <summary>
2997
        /// EndBreak 모델링 메서드
2998
        /// </summary>
2999
        /// <param name="endBreak"></param>
3000
        private void EndBreakModeling(EndBreak endBreak)
3001
        {
3002
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3003
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3004

    
3005
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3006
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3007
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3008

    
3009
            if (targetLMConnector != null)
3010
            {
3011
                // LEADER Line 검사
3012
                bool leaderLine = false;
3013
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3014
                if (symbolMapping != null)
3015
                    leaderLine = symbolMapping.LEADERLINE;
3016

    
3017
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
3018
                Array array = null;
3019
                if (point != null)
3020
                    array = new double[] { 0, point[0], point[1] };
3021
                else
3022
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3023
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3024
                if (_LmLabelPersist != null)
3025
                {
3026
                    _LmLabelPersist.Commit();
3027
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3028
                    if (_LmLabelPersist.ModelItemObject != null)
3029
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3030
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3031
                    ReleaseCOMObjects(_LmLabelPersist);
3032
                }
3033
                ReleaseCOMObjects(targetLMConnector);
3034
            }
3035
            else
3036
            {
3037
                Log.Write("End Break UID : " + endBreak.UID);
3038
                Log.Write("Can't find targetLMConnector");
3039
            }
3040
        }
3041

    
3042
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3043
        {
3044
            string symbolPath = string.Empty;
3045
            #region get symbol path
3046
            if (string.IsNullOrEmpty(changeSymbolPath))
3047
            {
3048
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3049
                symbolPath = GetSPPIDFileName(modelItem);
3050
                ReleaseCOMObjects(modelItem);
3051
            }
3052
            else
3053
                symbolPath = changeSymbolPath;
3054
            
3055
            #endregion
3056

    
3057
            LMConnector newConnector = null;
3058
            dynamic OID = connector.get_GraphicOID().ToString();
3059
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3060
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3061
            int verticesCount = lineStringGeometry.VertexCount;
3062
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3063
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3064

    
3065
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3066
            {
3067
                double[] vertices = null;
3068
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3069
                double x = 0;
3070
                double y = 0;
3071
                lineStringGeometry.GetVertex(1, ref x, ref y);
3072

    
3073
                string flowDirection = string.Empty;
3074
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3075
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3076
                    flowDirection = flowAttribute.get_Value().ToString();
3077

    
3078
                if (flowDirection == "End 1 is downstream (Outlet)")
3079
                {
3080
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3081
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3082
                    flowDirection = "End 1 is upstream (Inlet)";
3083
                }
3084
                else
3085
                {
3086
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3087
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3088
                }
3089
                string oldModelItemId = connector.ModelItemID;
3090
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3091
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3092
                newConnector.Commit();
3093
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3094
                if (!string.IsNullOrEmpty(flowDirection))
3095
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3096
                ReleaseCOMObjects(connector);
3097

    
3098
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3099
                {
3100
                    foreach (var repId in line.SPPID.Representations)
3101
                    {
3102
                        LMConnector _connector = dataSource.GetConnector(repId);
3103
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3104
                        {
3105
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3106
                            {
3107
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3108
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3109
                            }
3110
                        }
3111
                        ReleaseCOMObjects(_connector);
3112
                        _connector = null;
3113
                    }
3114
                }
3115
            }
3116

    
3117
            return newConnector;
3118
        }
3119

    
3120
        /// <summary>
3121
        /// SpecBreak Modeling 메서드
3122
        /// </summary>
3123
        /// <param name="specBreak"></param>
3124
        private void SpecBreakModeling(SpecBreak specBreak)
3125
        {
3126
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3127
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3128

    
3129
            if (upStreamObj != null &&
3130
                downStreamObj != null)
3131
            {
3132
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3133
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3134
                    targetLMConnector != null && 
3135
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3136
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3137

    
3138
                if (targetLMConnector != null)
3139
                {
3140
                    foreach (var attribute in specBreak.ATTRIBUTES)
3141
                    {
3142
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3143
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3144
                        {
3145
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3146
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
3147
                            Array array = null;
3148
                            if (point != null)
3149
                                array = new double[] { 0, point[0], point[1] };
3150
                            else
3151
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3152
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3153

    
3154
                            if (_LmLabelPersist != null)
3155
                            {
3156
                                _LmLabelPersist.Commit();
3157
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3158
                                if (_LmLabelPersist.ModelItemObject != null)
3159
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3160
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3161
                                ReleaseCOMObjects(_LmLabelPersist);
3162
                            }
3163

    
3164
                            // temp
3165
                            ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3166
                        }
3167
                    }
3168
                    ReleaseCOMObjects(targetLMConnector);
3169
                }
3170
                else
3171
                {
3172
                    Log.Write("Spec Break UID : " + specBreak.UID);
3173
                    Log.Write("Can't find targetLMConnector");
3174
                }
3175
            }
3176
        }
3177

    
3178
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3179
        {
3180
            LMConnector targetConnector = null;
3181
            Symbol targetSymbol = targetObj as Symbol;
3182
            Symbol connectedSymbol = connectedObj as Symbol;
3183
            Line targetLine = targetObj as Line;
3184
            Line connectedLine = connectedObj as Line;
3185
            if (targetSymbol != null && connectedSymbol != null)
3186
            {
3187
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3188
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3189

    
3190
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3191
                {
3192
                    if (connector.get_ItemStatus() != "Active")
3193
                        continue;
3194

    
3195
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3196
                    {
3197
                        targetConnector = connector;
3198
                        break;
3199
                    }
3200
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3201
                    {
3202
                        targetConnector = connector;
3203
                        break;
3204
                    }
3205
                }
3206

    
3207
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3208
                {
3209
                    if (connector.get_ItemStatus() != "Active")
3210
                        continue;
3211

    
3212
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3213
                    {
3214
                        targetConnector = connector;
3215
                        break;
3216
                    }
3217
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3218
                    {
3219
                        targetConnector = connector;
3220
                        break;
3221
                    }
3222
                }
3223

    
3224
                ReleaseCOMObjects(targetLMSymbol);
3225
                ReleaseCOMObjects(connectedLMSymbol);
3226
            }
3227
            else if (targetLine != null && connectedLine != null)
3228
            {
3229
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3230
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3231

    
3232
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3233
                {
3234
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3235
                    {
3236
                        if (targetConnector != null)
3237
                            break;
3238

    
3239
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3240
                        {
3241
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3242

    
3243
                            if (IsConnected(_LMConnector, connectedModelItem))
3244
                                targetConnector = _LMConnector;
3245
                            else
3246
                                ReleaseCOMObjects(_LMConnector);
3247
                        }
3248
                    }
3249

    
3250
                    ReleaseCOMObjects(targetModelItem);
3251
                }
3252
            }
3253
            else
3254
            {
3255
                LMSymbol connectedLMSymbol = null;
3256
                if (connectedSymbol != null)
3257
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3258
                else if (targetSymbol != null)
3259
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3260
                else
3261
                {
3262

    
3263
                }
3264
                LMModelItem targetModelItem = null;
3265
                if (targetLine != null)
3266
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3267
                else if (connectedLine != null)
3268
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3269
                else
3270
                {
3271

    
3272
                }
3273
                if (connectedLMSymbol != null && targetModelItem != null)
3274
                {
3275
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3276
                    {
3277
                        if (connector.get_ItemStatus() != "Active")
3278
                            continue;
3279

    
3280
                        if (IsConnected(connector, targetModelItem))
3281
                        {
3282
                            targetConnector = connector;
3283
                            break;
3284
                        }
3285
                    }
3286

    
3287
                    if (targetConnector == null)
3288
                    {
3289
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3290
                        {
3291
                            if (connector.get_ItemStatus() != "Active")
3292
                                continue;
3293

    
3294
                            if (IsConnected(connector, targetModelItem))
3295
                            {
3296
                                targetConnector = connector;
3297
                                break;
3298
                            }
3299
                        }
3300
                    }
3301
                }
3302

    
3303
            }
3304

    
3305
            return targetConnector;
3306
        }
3307

    
3308
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3309
        {
3310
            double[] result = null;
3311
            Line targetLine = targetObj as Line;
3312
            Symbol targetSymbol = targetObj as Symbol;
3313
            Line connLine = connObj as Line;
3314
            Symbol connSymbol = connObj as Symbol;
3315

    
3316
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
3317
            double lineMove = GridSetting.GetInstance().Length * 3;
3318
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3319
            {
3320
                result = GetConnectorVertices(targetConnector)[0];
3321
                if (targetSymbol != null && connSymbol != null)
3322
                {
3323
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3324
                    if (slopeType == SlopeType.HORIZONTAL)
3325
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3326
                    else if (slopeType == SlopeType.VERTICAL)
3327
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3328
                }
3329
                else if (targetLine != null)
3330
                {
3331
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3332
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3333
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3334
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3335
                }
3336
                else if (connLine != null)
3337
                {
3338
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3339
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3340
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3341
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3342
                }
3343
            }
3344
            else
3345
            {
3346
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3347
                {
3348
                    Line line = connObj as Line;
3349
                    LMConnector connectedConnector = null;
3350
                    int connIndex = 0;
3351
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3352
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3353

    
3354
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3355

    
3356
                    ReleaseCOMObjects(modelItem);
3357
                    ReleaseCOMObjects(connectedConnector);
3358

    
3359
                    if (vertices.Count > 0)
3360
                    {
3361
                        if (connIndex == 1)
3362
                            result = vertices[0];
3363
                        else if (connIndex == 2)
3364
                            result = vertices[vertices.Count - 1];
3365

    
3366
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3367
                        {
3368
                            result = new double[] { result[0], result[1] - lineMove };
3369
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3370
                            {
3371
                                result = new double[] { result[0] - lineMove, result[1] };
3372
                            }
3373
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3374
                            {
3375
                                result = new double[] { result[0] + lineMove, result[1] };
3376
                            }
3377
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3378
                            {
3379
                                result = new double[] { result[0] + lineMove, result[1] };
3380
                            }
3381
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3382
                            {
3383
                                result = new double[] { result[0] - lineMove, result[1] };
3384
                            }
3385
                        }
3386
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3387
                        {
3388
                            result = new double[] { result[0] - lineMove, result[1] };
3389
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3390
                            {
3391
                                result = new double[] { result[0], result[1] - lineMove };
3392
                            }
3393
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3394
                            {
3395
                                result = new double[] { result[0], result[1] + lineMove };
3396
                            }
3397
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3398
                            {
3399
                                result = new double[] { result[0], result[1] + lineMove };
3400
                            }
3401
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3402
                            {
3403
                                result = new double[] { result[0], result[1] - lineMove };
3404
                            }
3405
                        }
3406
                            
3407
                    }
3408
                }
3409
                else
3410
                {
3411
                    Log.Write("error in GetSegemtPoint");
3412
                }
3413
            }
3414

    
3415
            return result;
3416
        }
3417

    
3418
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3419
        {
3420
            bool result = false;
3421

    
3422
            foreach (LMRepresentation rep in modelItem.Representations)
3423
            {
3424
                if (result)
3425
                    break;
3426

    
3427
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3428
                {
3429
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3430

    
3431
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3432
                        connector.ConnectItem1SymbolObject != null &&
3433
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3434
                    {
3435
                        result = true;
3436
                        ReleaseCOMObjects(_LMConnector);
3437
                        break;
3438
                    }
3439
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3440
                        connector.ConnectItem2SymbolObject != null &&
3441
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3442
                    {
3443
                        result = true;
3444
                        ReleaseCOMObjects(_LMConnector);
3445
                        break;
3446
                    }
3447
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3448
                        connector.ConnectItem1SymbolObject != null &&
3449
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3450
                    {
3451
                        result = true;
3452
                        ReleaseCOMObjects(_LMConnector);
3453
                        break;
3454
                    }
3455
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3456
                        connector.ConnectItem2SymbolObject != null &&
3457
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3458
                    {
3459
                        result = true;
3460
                        ReleaseCOMObjects(_LMConnector);
3461
                        break;
3462
                    }
3463

    
3464
                    ReleaseCOMObjects(_LMConnector);
3465
                }
3466
            }
3467

    
3468

    
3469
            return result;
3470
        }
3471

    
3472
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3473
        {
3474
            foreach (LMRepresentation rep in modelItem.Representations)
3475
            {
3476
                if (connectedConnector != null)
3477
                    break;
3478

    
3479
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3480
                {
3481
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3482

    
3483
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3484
                        connector.ConnectItem1SymbolObject != null &&
3485
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3486
                    {
3487
                        connectedConnector = _LMConnector;
3488
                        connectorIndex = 1;
3489
                        break;
3490
                    }
3491
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3492
                        connector.ConnectItem2SymbolObject != null &&
3493
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3494
                    {
3495
                        connectedConnector = _LMConnector;
3496
                        connectorIndex = 2;
3497
                        break;
3498
                    }
3499
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3500
                        connector.ConnectItem1SymbolObject != null &&
3501
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3502
                    {
3503
                        connectedConnector = _LMConnector;
3504
                        connectorIndex = 1;
3505
                        break;
3506
                    }
3507
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3508
                        connector.ConnectItem2SymbolObject != null &&
3509
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3510
                    {
3511
                        connectedConnector = _LMConnector;
3512
                        connectorIndex = 2;
3513
                        break;
3514
                    }
3515

    
3516
                    if (connectedConnector == null)
3517
                        ReleaseCOMObjects(_LMConnector);
3518
                }
3519
            }
3520
        }
3521

    
3522
        /// <summary>
3523
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3524
        /// </summary>
3525
        /// <param name="modelItemID1"></param>
3526
        /// <param name="modelItemID2"></param>
3527
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3528
        {
3529
            try
3530
            {
3531
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3532
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3533
                List<double[]> vertices1 = null;
3534
                string graphicOID1 = string.Empty;
3535
                if (connector1 != null)
3536
                {
3537
                    vertices1 = GetConnectorVertices(connector1);
3538
                    graphicOID1 = connector1.get_GraphicOID();
3539
                }
3540
                _LMAItem item1 = modelItem1.AsLMAItem();
3541
                ReleaseCOMObjects(connector1);
3542
                connector1 = null;
3543

    
3544
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3545
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3546
                List<double[]> vertices2 = null;
3547
                string graphicOID2 = string.Empty;
3548
                if (connector2 != null)
3549
                {
3550
                    vertices2 = GetConnectorVertices(connector2);
3551
                    graphicOID2 = connector2.get_GraphicOID();
3552
                }
3553
                _LMAItem item2 = modelItem2.AsLMAItem();
3554
                ReleaseCOMObjects(connector2);
3555
                connector2 = null;
3556

    
3557
                // item2가 item1으로 조인
3558
                _placement.PIDJoinRuns(ref item1, ref item2);
3559
                item1.Commit();
3560
                item2.Commit();
3561

    
3562
                string beforeID = string.Empty;
3563
                string afterID = string.Empty;
3564

    
3565
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3566
                {
3567
                    beforeID = modelItem2.Id;
3568
                    afterID = modelItem1.Id;
3569
                    survivorId = afterID;
3570
                }
3571
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3572
                {
3573
                    beforeID = modelItem1.Id;
3574
                    afterID = modelItem2.Id;
3575
                    survivorId = afterID;
3576
                }
3577
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3578
                {
3579
                    int model1Cnt = GetConnectorCount(modelId1);
3580
                    int model2Cnt = GetConnectorCount(modelId2);
3581
                    if (model1Cnt == 0)
3582
                    {
3583
                        beforeID = modelItem1.Id;
3584
                        afterID = modelItem2.Id;
3585
                        survivorId = afterID;
3586
                    }
3587
                    else if (model2Cnt == 0)
3588
                    {
3589
                        beforeID = modelItem2.Id;
3590
                        afterID = modelItem1.Id;
3591
                        survivorId = afterID;
3592
                    }
3593
                    else
3594
                        survivorId = null;
3595
                }
3596
                else
3597
                {
3598
                    Log.Write("잘못된 경우");
3599
                    survivorId = null;
3600
                }
3601

    
3602
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3603
                {
3604
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3605
                    foreach (var line in lines)
3606
                        line.SPPID.ModelItemId = afterID;
3607
                }
3608

    
3609
                ReleaseCOMObjects(modelItem1);
3610
                ReleaseCOMObjects(item1);
3611
                ReleaseCOMObjects(modelItem2);
3612
                ReleaseCOMObjects(item2);
3613
            }
3614
            catch (Exception ex)
3615
            {
3616
                Log.Write("Join Error");
3617
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3618
            }
3619
        }
3620

    
3621
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3622
        {
3623
            bool result = false;
3624
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3625
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3626
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3627

    
3628
            foreach (var item in endBreaks)
3629
            {
3630
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3631
                {
3632
                    result = true;
3633
                    break;
3634
                }
3635
            }
3636

    
3637
            return result;
3638
        }
3639
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3640
        {
3641
            List<string> temp = new List<string>();
3642
            List<LMConnector> connectors = new List<LMConnector>();
3643
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3644
            {
3645
                if (connector.get_ItemStatus() != "Active")
3646
                    continue;
3647

    
3648
                LMModelItem modelItem = connector.ModelItemObject;
3649
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3650
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3651
                    temp.Add(modelItem.Id);
3652

    
3653
                if (temp.Contains(modelItem.Id) &&
3654
                    connOtherSymbol != null &&
3655
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3656
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3657
                    temp.Remove(modelItem.Id);
3658

    
3659

    
3660
                if (temp.Contains(modelItem.Id))
3661
                    connectors.Add(connector);
3662
                ReleaseCOMObjects(connOtherSymbol);
3663
                connOtherSymbol = null;
3664
                ReleaseCOMObjects(modelItem);
3665
                modelItem = null;
3666
            }
3667

    
3668
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3669
            {
3670
                if (connector.get_ItemStatus() != "Active")
3671
                    continue;
3672

    
3673
                LMModelItem modelItem = connector.ModelItemObject;
3674
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3675
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3676
                    temp.Add(modelItem.Id);
3677

    
3678
                if (temp.Contains(modelItem.Id) &&
3679
                    connOtherSymbol != null &&
3680
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3681
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3682
                    temp.Remove(modelItem.Id);
3683

    
3684
                if (temp.Contains(modelItem.Id))
3685
                    connectors.Add(connector);
3686
                ReleaseCOMObjects(connOtherSymbol);
3687
                connOtherSymbol = null;
3688
                ReleaseCOMObjects(modelItem);
3689
                modelItem = null;
3690
            }
3691

    
3692

    
3693
            List<string> result = new List<string>();
3694
            string originalName = GetSPPIDFileName(modelId);
3695
            foreach (var connector in connectors)
3696
            {
3697
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3698
                if (originalName == fileName)
3699
                    result.Add(connector.ModelItemID);
3700
                else
3701
                {
3702
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3703
                        result.Add(connector.ModelItemID);
3704
                    else
3705
                    {
3706
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3707
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3708
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3709
                            result.Add(connector.ModelItemID);
3710
                    }
3711
                }
3712
            }
3713

    
3714
            foreach (var connector in connectors)
3715
                ReleaseCOMObjects(connector);
3716
            
3717
            return result;
3718

    
3719

    
3720
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3721
            {
3722
                LMSymbol findResult = null;
3723
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3724
                    findResult = connector.ConnectItem1SymbolObject;
3725
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3726
                    findResult = connector.ConnectItem2SymbolObject;
3727

    
3728
                return findResult;
3729
            }
3730
        }
3731

    
3732
        /// <summary>
3733
        /// PipeRun의 좌표를 가져오는 메서드
3734
        /// </summary>
3735
        /// <param name="modelId"></param>
3736
        /// <returns></returns>
3737
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3738
        {
3739
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3740
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3741

    
3742
            if (modelItem != null)
3743
            {
3744
                foreach (LMRepresentation rep in modelItem.Representations)
3745
                {
3746
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3747
                    {
3748
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3749
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3750
                        {
3751
                            ReleaseCOMObjects(_LMConnector);
3752
                            _LMConnector = null;
3753
                            continue;
3754
                        }
3755
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3756
                        dynamic OID = rep.get_GraphicOID().ToString();
3757
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3758
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3759
                        int verticesCount = lineStringGeometry.VertexCount;
3760
                        double[] vertices = null;
3761
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3762
                        for (int i = 0; i < verticesCount; i++)
3763
                        {
3764
                            double x = 0;
3765
                            double y = 0;
3766
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3767
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3768
                        }
3769
                    }
3770
                }
3771

    
3772
                ReleaseCOMObjects(modelItem);
3773
            }
3774

    
3775
            return connectorVertices;
3776
        }
3777

    
3778
        private List<double[]> GetConnectorVertices(LMConnector connector)
3779
        {
3780
            List<double[]> vertices = new List<double[]>();
3781
            if (connector != null)
3782
            {
3783
                dynamic OID = connector.get_GraphicOID().ToString();
3784
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3785
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3786
                int verticesCount = lineStringGeometry.VertexCount;
3787
                double[] value = null;
3788
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3789
                for (int i = 0; i < verticesCount; i++)
3790
                {
3791
                    double x = 0;
3792
                    double y = 0;
3793
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3794
                    vertices.Add(new double[] { x, y });
3795
                }
3796
            }
3797
            return vertices;
3798
        }
3799

    
3800
        private double GetConnectorDistance(LMConnector connector)
3801
        {
3802
            double result = 0;
3803
            List<double[]> vertices = new List<double[]>();
3804
            if (connector != null)
3805
            {
3806
                dynamic OID = connector.get_GraphicOID().ToString();
3807
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3808
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3809
                int verticesCount = lineStringGeometry.VertexCount;
3810
                double[] value = null;
3811
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3812
                for (int i = 0; i < verticesCount; i++)
3813
                {
3814
                    double x = 0;
3815
                    double y = 0;
3816
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3817
                    vertices.Add(new double[] { x, y });
3818
                    if (vertices.Count > 1)
3819
                    {
3820
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3821
                    }
3822
                }
3823
            }
3824
            return result;
3825
        }
3826
        private double[] GetConnectorRange(LMConnector connector)
3827
        {
3828
            double[] result = null;
3829
            List<double[]> vertices = new List<double[]>();
3830
            if (connector != null)
3831
            {
3832
                dynamic OID = connector.get_GraphicOID().ToString();
3833
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3834
                double minX = 0;
3835
                double minY = 0;
3836
                double maxX = 0;
3837
                double maxY = 0;
3838

    
3839
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
3840
                result = new double[] { minX, minY, maxX, maxY };
3841
            }
3842
            return result;
3843
        }
3844
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3845
        {
3846
            List<double[]> vertices = null;
3847
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3848
            if (drawingObject != null)
3849
            {
3850
                vertices = new List<double[]>();
3851
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3852
                int verticesCount = lineStringGeometry.VertexCount;
3853
                double[] value = null;
3854
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3855
                for (int i = 0; i < verticesCount; i++)
3856
                {
3857
                    double x = 0;
3858
                    double y = 0;
3859
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3860
                    vertices.Add(new double[] { x, y });
3861
                }
3862
            }
3863
            return vertices;
3864
        }
3865
        /// <summary>
3866
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3867
        /// </summary>
3868
        /// <param name="connectorVertices"></param>
3869
        /// <param name="connX"></param>
3870
        /// <param name="connY"></param>
3871
        /// <returns></returns>
3872
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3873
        {
3874
            double length = double.MaxValue;
3875
            LMConnector targetConnector = null;
3876
            foreach (var item in connectorVertices)
3877
            {
3878
                List<double[]> points = item.Value;
3879
                for (int i = 0; i < points.Count - 1; i++)
3880
                {
3881
                    double[] point1 = points[i];
3882
                    double[] point2 = points[i + 1];
3883
                    double x1 = Math.Min(point1[0], point2[0]);
3884
                    double y1 = Math.Min(point1[1], point2[1]);
3885
                    double x2 = Math.Max(point1[0], point2[0]);
3886
                    double y2 = Math.Max(point1[1], point2[1]);
3887

    
3888
                    if ((x1 <= connX && x2 >= connX) ||
3889
                        (y1 <= connY && y2 >= connY))
3890
                    {
3891
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3892
                        if (length >= distance)
3893
                        {
3894
                            targetConnector = item.Key;
3895
                            length = distance;
3896
                        }
3897

    
3898
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3899
                        if (length >= distance)
3900
                        {
3901
                            targetConnector = item.Key;
3902
                            length = distance;
3903
                        }
3904
                    }
3905
                }
3906
            }
3907

    
3908
            // 못찾았을때.
3909
            length = double.MaxValue;
3910
            if (targetConnector == null)
3911
            {
3912
                foreach (var item in connectorVertices)
3913
                {
3914
                    List<double[]> points = item.Value;
3915

    
3916
                    foreach (double[] point in points)
3917
                    {
3918
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3919
                        if (length >= distance)
3920
                        {
3921
                            targetConnector = item.Key;
3922
                            length = distance;
3923
                        }
3924
                    }
3925
                }
3926
            }
3927

    
3928
            return targetConnector;
3929
        }
3930

    
3931
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3932
        {
3933
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3934
            if (vertices.Count == 0)
3935
                return null;
3936

    
3937
            double length = double.MaxValue;
3938
            LMConnector targetConnector = null;
3939
            double[] resultPoint = null;
3940
            List<double[]> targetVertices = null;
3941

    
3942
            // Vertices 포인트에 제일 가까운곳
3943
            foreach (var item in vertices)
3944
            {
3945
                List<double[]> points = item.Value;
3946
                for (int i = 0; i < points.Count; i++)
3947
                {
3948
                    double[] point = points[i];
3949
                    double tempX = point[0];
3950
                    double tempY = point[1];
3951

    
3952
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3953
                    if (length >= distance)
3954
                    {
3955
                        targetConnector = item.Key;
3956
                        length = distance;
3957
                        resultPoint = point;
3958
                        targetVertices = item.Value;
3959
                    }
3960
                }
3961
            }
3962

    
3963
            // Vertices Cross에 제일 가까운곳
3964
            foreach (var item in vertices)
3965
            {
3966
                List<double[]> points = item.Value;
3967
                for (int i = 0; i < points.Count - 1; i++)
3968
                {
3969
                    double[] point1 = points[i];
3970
                    double[] point2 = points[i + 1];
3971

    
3972
                    double maxLineX = Math.Max(point1[0], point2[0]);
3973
                    double minLineX = Math.Min(point1[0], point2[0]);
3974
                    double maxLineY = Math.Max(point1[1], point2[1]);
3975
                    double minLineY = Math.Min(point1[1], point2[1]);
3976

    
3977
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3978

    
3979
                    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]);
3980
                    if (crossingPoint != null)
3981
                    {
3982
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3983
                        if (length >= distance)
3984
                        {
3985
                            if (slope == SlopeType.Slope &&
3986
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3987
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3988
                            {
3989
                                targetConnector = item.Key;
3990
                                length = distance;
3991
                                resultPoint = crossingPoint;
3992
                                targetVertices = item.Value;
3993
                            }
3994
                            else if (slope == SlopeType.HORIZONTAL &&
3995
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3996
                            {
3997
                                targetConnector = item.Key;
3998
                                length = distance;
3999
                                resultPoint = crossingPoint;
4000
                                targetVertices = item.Value;
4001
                            }
4002
                            else if (slope == SlopeType.VERTICAL &&
4003
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4004
                            {
4005
                                targetConnector = item.Key;
4006
                                length = distance;
4007
                                resultPoint = crossingPoint;
4008
                                targetVertices = item.Value;
4009
                            }
4010
                        }
4011
                    }
4012
                }
4013
            }
4014

    
4015
            foreach (var item in vertices)
4016
                if (item.Key != null && item.Key != targetConnector)
4017
                    ReleaseCOMObjects(item.Key);
4018

    
4019
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4020
            {
4021
                double tempResultX = resultPoint[0];
4022
                double tempResultY = resultPoint[1];
4023
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4024

    
4025
                GridSetting gridSetting = GridSetting.GetInstance();
4026

    
4027
                for (int i = 0; i < targetVertices.Count; i++)
4028
                {
4029
                    double[] point = targetVertices[i];
4030
                    double tempX = targetVertices[i][0];
4031
                    double tempY = targetVertices[i][1];
4032
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4033
                    if (tempX == tempResultX && tempY == tempResultY)
4034
                    {
4035
                        if (i == 0)
4036
                        {
4037
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4038
                            bool containZeroLength = false;
4039
                            if (connSymbol != null)
4040
                            {
4041
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4042
                                {
4043
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4044
                                        containZeroLength = true;
4045
                                }
4046
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4047
                                {
4048
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4049
                                        containZeroLength = true;
4050
                                }
4051
                            }
4052

    
4053
                            if (connSymbol == null ||
4054
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4055
                                containZeroLength)
4056
                            {
4057
                                bool bCalcX = false;
4058
                                bool bCalcY = false;
4059
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4060
                                    bCalcX = true;
4061
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4062
                                    bCalcY = true;
4063
                                else
4064
                                {
4065
                                    bCalcX = true;
4066
                                    bCalcY = true;
4067
                                }
4068

    
4069
                                if (bCalcX)
4070
                                {
4071
                                    double nextX = targetVertices[i + 1][0];
4072
                                    double newX = 0;
4073
                                    if (nextX > tempX)
4074
                                    {
4075
                                        newX = tempX + gridSetting.Length;
4076
                                        if (newX > nextX)
4077
                                            newX = (point[0] + nextX) / 2;
4078
                                    }
4079
                                    else
4080
                                    {
4081
                                        newX = tempX - gridSetting.Length;
4082
                                        if (newX < nextX)
4083
                                            newX = (point[0] + nextX) / 2;
4084
                                    }
4085
                                    resultPoint = new double[] { newX, resultPoint[1] };
4086
                                }
4087

    
4088
                                if (bCalcY)
4089
                                {
4090
                                    double nextY = targetVertices[i + 1][1];
4091
                                    double newY = 0;
4092
                                    if (nextY > tempY)
4093
                                    {
4094
                                        newY = tempY + gridSetting.Length;
4095
                                        if (newY > nextY)
4096
                                            newY = (point[1] + nextY) / 2;
4097
                                    }
4098
                                    else
4099
                                    {
4100
                                        newY = tempY - gridSetting.Length;
4101
                                        if (newY < nextY)
4102
                                            newY = (point[1] + nextY) / 2;
4103
                                    }
4104
                                    resultPoint = new double[] { resultPoint[0], newY };
4105
                                }
4106
                            }
4107
                        }
4108
                        else if (i == targetVertices.Count - 1)
4109
                        {
4110
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4111
                            bool containZeroLength = false;
4112
                            if (connSymbol != null)
4113
                            {
4114
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4115
                                {
4116
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4117
                                        containZeroLength = true;
4118
                                }
4119
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4120
                                {
4121
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4122
                                        containZeroLength = true;
4123
                                }
4124
                            }
4125

    
4126
                            if (connSymbol == null ||
4127
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4128
                                containZeroLength)
4129
                            {
4130
                                bool bCalcX = false;
4131
                                bool bCalcY = false;
4132
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4133
                                    bCalcX = true;
4134
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4135
                                    bCalcY = true;
4136
                                else
4137
                                {
4138
                                    bCalcX = true;
4139
                                    bCalcY = true;
4140
                                }
4141

    
4142
                                if (bCalcX)
4143
                                {
4144
                                    double nextX = targetVertices[i - 1][0];
4145
                                    double newX = 0;
4146
                                    if (nextX > tempX)
4147
                                    {
4148
                                        newX = tempX + gridSetting.Length;
4149
                                        if (newX > nextX)
4150
                                            newX = (point[0] + nextX) / 2;
4151
                                    }
4152
                                    else
4153
                                    {
4154
                                        newX = tempX - gridSetting.Length;
4155
                                        if (newX < nextX)
4156
                                            newX = (point[0] + nextX) / 2;
4157
                                    }
4158
                                    resultPoint = new double[] { newX, resultPoint[1] };
4159
                                }
4160

    
4161
                                if (bCalcY)
4162
                                {
4163
                                    double nextY = targetVertices[i - 1][1];
4164
                                    double newY = 0;
4165
                                    if (nextY > tempY)
4166
                                    {
4167
                                        newY = tempY + gridSetting.Length;
4168
                                        if (newY > nextY)
4169
                                            newY = (point[1] + nextY) / 2;
4170
                                    }
4171
                                    else
4172
                                    {
4173
                                        newY = tempY - gridSetting.Length;
4174
                                        if (newY < nextY)
4175
                                            newY = (point[1] + nextY) / 2;
4176
                                    }
4177
                                    resultPoint = new double[] { resultPoint[0], newY };
4178
                                }
4179
                            }
4180
                        }
4181
                        break;
4182
                    }
4183
                }
4184
            }
4185

    
4186
            x = resultPoint[0];
4187
            y = resultPoint[1];
4188

    
4189
            return targetConnector;
4190
        }
4191

    
4192
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4193
        {
4194
            LMConnector result = null;
4195
            List<LMConnector> connectors = new List<LMConnector>();
4196
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4197

    
4198
            if (modelItem != null)
4199
            {
4200
                foreach (LMRepresentation rep in modelItem.Representations)
4201
                {
4202
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4203
                        connectors.Add(dataSource.GetConnector(rep.Id));
4204
                }
4205

    
4206
                ReleaseCOMObjects(modelItem);
4207
            }
4208

    
4209
            if (connectors.Count == 1)
4210
                result = connectors[0];
4211
            else
4212
                foreach (var item in connectors)
4213
                    ReleaseCOMObjects(item);
4214

    
4215
            return result;
4216
        }
4217

    
4218
        private LMConnector GetLMConnectorFirst(string modelItemID)
4219
        {
4220
            LMConnector result = null;
4221
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4222

    
4223
            if (modelItem != null)
4224
            {
4225
                foreach (LMRepresentation rep in modelItem.Representations)
4226
                {
4227
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4228
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4229
                    {
4230
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4231
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4232
                        {
4233
                            result = connector;
4234
                            break;
4235
                        }
4236
                        else
4237
                        {
4238
                            ReleaseCOMObjects(connector);
4239
                            connector = null;
4240
                        }
4241
                    }
4242
                }
4243
                ReleaseCOMObjects(modelItem);
4244
                modelItem = null;
4245
            }
4246

    
4247
            return result;
4248
        }
4249

    
4250
        private int GetConnectorCount(string modelItemID)
4251
        {
4252
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4253
            int result = 0;
4254
            if (modelItem != null)
4255
            {
4256
                foreach (LMRepresentation rep in modelItem.Representations)
4257
                {
4258
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4259
                        result++;
4260
                    ReleaseCOMObjects(rep);
4261
                }
4262
                ReleaseCOMObjects(modelItem);
4263
            }
4264

    
4265
            return result;
4266
        }
4267

    
4268
        public List<string> GetRepresentations(string modelItemID)
4269
        {
4270
            List<string> result = new List<string>(); ;
4271
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4272
            if (modelItem != null)
4273
            {
4274
                foreach (LMRepresentation rep in modelItem.Representations)
4275
                {
4276
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4277
                        result.Add(rep.Id);
4278
                }
4279
                ReleaseCOMObjects(modelItem);
4280
            }
4281

    
4282
            return result;
4283
        }
4284

    
4285
        private void LineNumberModeling(LineNumber lineNumber)
4286
        {
4287
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4288
            if (line != null)
4289
            {
4290
                double x = 0;
4291
                double y = 0;
4292
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4293

    
4294
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4295
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4296
                if (connectedLMConnector != null)
4297
                {
4298
                    Array points = new double[] { 0, x, y };
4299
                    lineNumber.SPPID.SPPID_X = x;
4300
                    lineNumber.SPPID.SPPID_Y = y;
4301
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4302

    
4303
                    if (_LmLabelPresist != null)
4304
                    {
4305
                        _LmLabelPresist.Commit();
4306
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4307
                        ReleaseCOMObjects(_LmLabelPresist);
4308
                    }
4309
                }
4310

    
4311
                foreach (var item in connectorVertices)
4312
                    ReleaseCOMObjects(item.Key);
4313
            }
4314
        }
4315
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4316
        {
4317
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4318
            if (line == null || line.SPPID.Vertices == null)
4319
                return;
4320

    
4321
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4322
            {
4323
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4324
                if (removeLabel != null)
4325
                { 
4326
                    GridSetting gridSetting = GridSetting.GetInstance();
4327
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4328
                    //
4329
                    double[] labelRange = null;
4330
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4331
                    List<double[]> vertices = GetConnectorVertices(connector);
4332

    
4333
                    double[] resultStart = null;
4334
                    double[] resultEnd = null;
4335
                    double distance = double.MaxValue;
4336
                    for (int i = 0; i < vertices.Count - 1; i++)
4337
                    {
4338
                        double[] startPoint = vertices[i];
4339
                        double[] endPoint = vertices[i + 1];
4340
                        foreach (var item in line.SPPID.Vertices)
4341
                        {
4342
                            double[] lineStartPoint = item[0];
4343
                            double[] lineEndPoint = item[item.Count - 1];
4344

    
4345
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4346
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4347
                            if (tempDistance < distance)
4348
                            {
4349
                                distance = tempDistance;
4350
                                resultStart = startPoint;
4351
                                resultEnd = endPoint;
4352
                            }
4353
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4354
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4355
                            if (tempDistance < distance)
4356
                            {
4357
                                distance = tempDistance;
4358
                                resultStart = startPoint;
4359
                                resultEnd = endPoint;
4360
                            }
4361
                        }
4362
                    }
4363

    
4364
                    if (resultStart != null && resultEnd != null)
4365
                    {
4366
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4367
                        double lineStartX = 0;
4368
                        double lineStartY = 0;
4369
                        double lineEndX = 0;
4370
                        double lineEndY = 0;
4371
                        double lineNumberX = 0;
4372
                        double lineNumberY = 0;
4373
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4374
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4375

    
4376
                        double lineX = (lineStartX + lineEndX) / 2;
4377
                        double lineY = (lineStartY + lineEndY) / 2;
4378
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4379
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4380

    
4381
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4382
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4383
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4384
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4385

    
4386
                        double offsetX = 0;
4387
                        double offsetY = 0;
4388
                        if (slope == SlopeType.HORIZONTAL)
4389
                        {
4390
                            // Line Number 아래
4391
                            if (lineY < lineNumberY)
4392
                            {
4393
                                offsetX = labelCenterX - SPPIDCenterX;
4394
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4395
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4396
                            }
4397
                            // Line Number 위
4398
                            else
4399
                            {
4400
                                offsetX = labelCenterX - SPPIDCenterX;
4401
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4402
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4403
                            }
4404
                        }
4405
                        else if (slope == SlopeType.VERTICAL)
4406
                        {
4407
                            // Line Number 오르쪽
4408
                            if (lineX < lineNumberX)
4409
                            {
4410
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4411
                                offsetY = labelCenterY - SPPIDCenterY;
4412
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4413
                            }
4414
                            // Line Number 왼쪽
4415
                            else
4416
                            {
4417
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4418
                                offsetY = labelCenterY - SPPIDCenterY;
4419
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4420
                            }
4421
                        }
4422

    
4423
                        if (offsetY != 0 || offsetY != 0)
4424
                        {
4425
                            if (connector.ConnectItem1SymbolObject != null &&
4426
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4427
                            {
4428
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4429

    
4430
                                double x1, y1, x2, y2, originX, originY;
4431
                                symbol.Range(out x1, out y1, out x2, out y2);
4432
                                symbol.GetOrigin(out originX, out originY);
4433
                                if (originX < lineNumber.SPPID.SPPID_X)
4434
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4435
                                else
4436
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4437
                            }
4438
                            else if (connector.ConnectItem2SymbolObject != null &&
4439
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4440
                            {
4441
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4442

    
4443
                                double x1, y1, x2, y2, originX, originY;
4444
                                symbol.Range(out x1, out y1, out x2, out y2);
4445
                                symbol.GetOrigin(out originX, out originY);
4446
                                if (originX < lineNumber.SPPID.SPPID_X)
4447
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4448
                                else
4449
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4450
                            }
4451

    
4452
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4453
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
4454
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
4455

    
4456
                            if (_LmLabelPresist != null)
4457
                            {
4458
                                _LmLabelPresist.Commit();
4459
                                lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4460
                            }
4461
                            ReleaseCOMObjects(_LmLabelPresist);
4462
                            _LmLabelPresist = null; 
4463
                        }
4464

    
4465
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4466
                        {
4467
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4468
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4469
                        }
4470
                    }
4471

    
4472

    
4473
                    ReleaseCOMObjects(connector);
4474
                    connector = null;
4475
                }
4476

    
4477
                ReleaseCOMObjects(removeLabel);
4478
                removeLabel = null;
4479
            }
4480
        }
4481
        /// <summary>
4482
        /// Flow Mark Modeling
4483
        /// </summary>
4484
        /// <param name="line"></param>
4485
        private void FlowMarkModeling(Line line)
4486
        {
4487
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4488
            {
4489
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4490
                if (connector != null)
4491
                {
4492
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4493
                    List<double[]> vertices = GetConnectorVertices(connector);
4494
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4495
                    double[] point = vertices[vertices.Count - 1];
4496
                    Array array = new double[] { 0, point[0], point[1] };
4497
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4498
                    if (_LMLabelPersist != null)
4499
                    {
4500
                        _LMLabelPersist.Commit();
4501
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4502
                        ReleaseCOMObjects(_LMLabelPersist);
4503
                    }
4504
                }
4505
            }
4506
        }
4507

    
4508
        /// <summary>
4509
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4510
        /// </summary>
4511
        /// <param name="lineNumber"></param>
4512
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4513
        {
4514
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4515
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4516
            {
4517
                if (a.ATTRIBUTE == "Tag Seq No")
4518
                    return 1;
4519
                else if (b.ATTRIBUTE == "Tag Seq No")
4520
                    return -1;
4521

    
4522
                return 0;
4523
            }
4524

    
4525
            foreach (LineRun run in lineNumber.RUNS)
4526
            {
4527
                foreach (var item in run.RUNITEMS)
4528
                {
4529
                    if (item.GetType() == typeof(Symbol))
4530
                    {
4531
                        Symbol symbol = item as Symbol;
4532
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4533
                        if (_LMSymbol != null)
4534
                        {
4535
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4536

    
4537
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4538
                            {
4539
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4540
                                {
4541
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4542
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4543
                                    {
4544
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4545
                                        if (_LMAAttribute != null)
4546
                                        {
4547
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4548
                                                _LMAAttribute.set_Value(attribute.VALUE);
4549
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4550
                                                _LMAAttribute.set_Value(attribute.VALUE);
4551
                                        }
4552
                                    }
4553
                                }
4554
                                _LMModelItem.Commit();
4555
                            }
4556
                            if (_LMModelItem != null)
4557
                                ReleaseCOMObjects(_LMModelItem);
4558
                        }
4559
                        if (_LMSymbol != null)
4560
                            ReleaseCOMObjects(_LMSymbol);
4561
                    }
4562
                    else if (item.GetType() == typeof(Line))
4563
                    {
4564
                        Line line = item as Line;
4565
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4566
                        {
4567
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4568
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4569
                            {
4570
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4571
                                {
4572
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4573
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4574
                                    {
4575
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4576
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
4577
                                        {
4578
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
4579
                                            if (_FluidSystemAttribute != null)
4580
                                            {
4581
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
4582
                                                if (dt.Rows.Count == 1)
4583
                                                {
4584
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
4585
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
4586
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4587
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
4588
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4589

    
4590
                                                    if (_LMAAttribute != null)
4591
                                                    {
4592
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4593
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4594
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4595
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4596
                                                    }
4597
                                                }
4598
                                                if (dt != null)
4599
                                                    dt.Dispose();
4600
                                            }
4601
                                        }
4602
                                        else if (_LMAAttribute != null)
4603
                                        {
4604
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4605
                                                _LMAAttribute.set_Value(attribute.VALUE);
4606
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4607
                                                _LMAAttribute.set_Value(attribute.VALUE);
4608
                                        }
4609
                                    }
4610
                                }
4611
                                _LMModelItem.Commit();
4612
                            }
4613
                            if (_LMModelItem != null)
4614
                                ReleaseCOMObjects(_LMModelItem);
4615
                            endLine.Add(line.SPPID.ModelItemId);
4616
                        }
4617
                    }
4618
                }
4619
            }
4620
        }
4621

    
4622
        /// <summary>
4623
        /// Symbol Attribute 입력 메서드
4624
        /// </summary>
4625
        /// <param name="item"></param>
4626
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4627
        {
4628
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4629
            string sRep = null;
4630
            if (targetItem.GetType() == typeof(Symbol))
4631
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4632
            else if (targetItem.GetType() == typeof(Equipment))
4633
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4634

    
4635
            if (!string.IsNullOrEmpty(sRep))
4636
            {
4637
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4638
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4639
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4640
                
4641
                foreach (var item in targetAttributes)
4642
                {
4643
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4644
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4645
                    {
4646
                        if (!mapping.IsText)
4647
                        {
4648
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4649
                            if (_Attribute != null)
4650
                            {
4651
                                _Attribute.set_Value(item.VALUE);
4652
                                // OPC 일경우 Attribute 저장
4653
                                if (targetItem.GetType() == typeof(Symbol))
4654
                                {
4655
                                    Symbol symbol = targetItem as Symbol;
4656
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4657
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4658
                                }
4659
                            }
4660
                        }
4661
                        else
4662
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
4663
                    }
4664
                }
4665
                _LMModelItem.Commit();
4666

    
4667
                ReleaseCOMObjects(_Attributes);
4668
                ReleaseCOMObjects(_LMModelItem);
4669
                ReleaseCOMObjects(_LMSymbol);
4670
            }
4671
        }
4672

    
4673
        /// <summary>
4674
        /// Input SpecBreak Attribute
4675
        /// </summary>
4676
        /// <param name="specBreak"></param>
4677
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4678
        {
4679
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4680
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4681

    
4682
            if (upStreamObj != null &&
4683
                downStreamObj != null)
4684
            {
4685
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4686

    
4687
                if (targetLMConnector != null)
4688
                {
4689
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4690
                    {
4691
                        string symbolPath = _LMLabelPersist.get_FileName();
4692
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4693
                        if (mapping != null)
4694
                        {
4695
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4696
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4697
                            {
4698
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4699
                                if (values.Length == 2)
4700
                                {
4701
                                    string upStreamValue = values[0];
4702
                                    string downStreamValue = values[1];
4703

    
4704
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4705
                                }
4706
                            }
4707
                        }
4708
                    }
4709

    
4710
                    ReleaseCOMObjects(targetLMConnector);
4711
                }
4712
            }
4713

    
4714

    
4715
            #region 내부에서만 쓰는 메서드
4716
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4717
            {
4718
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4719
                Line upStreamLine = _upStreamObj as Line;
4720
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4721
                Line downStreamLine = _downStreamObj as Line;
4722
                // 둘다 Line일 경우
4723
                if (upStreamLine != null && downStreamLine != null)
4724
                {
4725
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4726
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4727
                }
4728
                // 둘다 Symbol일 경우
4729
                else if (upStreamSymbol != null && downStreamSymbol != null)
4730
                {
4731
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4732
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4733
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4734

    
4735
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4736
                    {
4737
                        if (connector.get_ItemStatus() != "Active")
4738
                            continue;
4739

    
4740
                        if (connector.Id != zeroLenthConnector.Id)
4741
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4742
                    }
4743

    
4744
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4745
                    {
4746
                        if (connector.get_ItemStatus() != "Active")
4747
                            continue;
4748

    
4749
                        if (connector.Id != zeroLenthConnector.Id)
4750
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4751
                    }
4752

    
4753
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4754
                    {
4755
                        if (connector.get_ItemStatus() != "Active")
4756
                            continue;
4757

    
4758
                        if (connector.Id != zeroLenthConnector.Id)
4759
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4760
                    }
4761

    
4762
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4763
                    {
4764
                        if (connector.get_ItemStatus() != "Active")
4765
                            continue;
4766

    
4767
                        if (connector.Id != zeroLenthConnector.Id)
4768
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4769
                    }
4770

    
4771
                    ReleaseCOMObjects(zeroLenthConnector);
4772
                    ReleaseCOMObjects(upStreamLMSymbol);
4773
                    ReleaseCOMObjects(downStreamLMSymbol);
4774
                }
4775
                else if (upStreamSymbol != null && downStreamLine != null)
4776
                {
4777
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4778
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4779
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4780

    
4781
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4782
                    {
4783
                        if (connector.get_ItemStatus() != "Active")
4784
                            continue;
4785

    
4786
                        if (connector.Id == zeroLenthConnector.Id)
4787
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4788
                    }
4789

    
4790
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4791
                    {
4792
                        if (connector.get_ItemStatus() != "Active")
4793
                            continue;
4794

    
4795
                        if (connector.Id == zeroLenthConnector.Id)
4796
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4797
                    }
4798

    
4799
                    ReleaseCOMObjects(zeroLenthConnector);
4800
                    ReleaseCOMObjects(upStreamLMSymbol);
4801
                }
4802
                else if (upStreamLine != null && downStreamSymbol != null)
4803
                {
4804
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4805
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4806
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4807

    
4808
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4809
                    {
4810
                        if (connector.get_ItemStatus() != "Active")
4811
                            continue;
4812

    
4813
                        if (connector.Id == zeroLenthConnector.Id)
4814
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4815
                    }
4816

    
4817
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4818
                    {
4819
                        if (connector.get_ItemStatus() != "Active")
4820
                            continue;
4821

    
4822
                        if (connector.Id == zeroLenthConnector.Id)
4823
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4824
                    }
4825

    
4826
                    ReleaseCOMObjects(zeroLenthConnector);
4827
                    ReleaseCOMObjects(downStreamLMSymbol);
4828
                }
4829
            }
4830

    
4831
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4832
            {
4833
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4834
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4835
                {
4836
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4837
                    if (_LMAAttribute != null)
4838
                    {
4839
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4840
                            _LMAAttribute.set_Value(value);
4841
                        else if (_LMAAttribute.get_Value() != value)
4842
                            _LMAAttribute.set_Value(value);
4843
                    }
4844

    
4845
                    _LMModelItem.Commit();
4846
                }
4847
                if (_LMModelItem != null)
4848
                    ReleaseCOMObjects(_LMModelItem);
4849
            }
4850

    
4851
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4852
            {
4853
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4854
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4855
                {
4856
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4857
                    if (_LMAAttribute != null)
4858
                    {
4859
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4860
                            _LMAAttribute.set_Value(value);
4861
                        else if (_LMAAttribute.get_Value() != value)
4862
                            _LMAAttribute.set_Value(value);
4863
                    }
4864

    
4865
                    _LMModelItem.Commit();
4866
                }
4867
                if (_LMModelItem != null)
4868
                    ReleaseCOMObjects(_LMModelItem);
4869
            }
4870
            #endregion
4871
        }
4872

    
4873
        private void InputEndBreakAttribute(EndBreak endBreak)
4874
        {
4875
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4876
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4877

    
4878
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4879
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4880
            {
4881
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4882
                if (labelPersist != null)
4883
                {
4884
                    LMRepresentation representation = labelPersist.RepresentationObject;
4885
                    if (representation != null)
4886
                    {
4887
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4888
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4889
                        string modelItemID = connector.ModelItemID;
4890
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4891
                        {
4892
                            List<string> modelItemIDs = new List<string>();
4893
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4894
                            {
4895
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4896
                                foreach (LMConnector item in symbol.Connect1Connectors)
4897
                                {
4898
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4899
                                        modelItemIDs.Add(item.ModelItemID);
4900
                                    ReleaseCOMObjects(item);
4901
                                }
4902
                                foreach (LMConnector item in symbol.Connect2Connectors)
4903
                                {
4904
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4905
                                        modelItemIDs.Add(item.ModelItemID);
4906
                                    ReleaseCOMObjects(item);
4907
                                }
4908
                                ReleaseCOMObjects(symbol);
4909
                                symbol = null;
4910
                            }
4911
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4912
                            {
4913
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4914
                                foreach (LMConnector item in symbol.Connect1Connectors)
4915
                                {
4916
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4917
                                        modelItemIDs.Add(item.ModelItemID);
4918
                                    ReleaseCOMObjects(item);
4919
                                }
4920
                                foreach (LMConnector item in symbol.Connect2Connectors)
4921
                                {
4922
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4923
                                        modelItemIDs.Add(item.ModelItemID);
4924
                                    ReleaseCOMObjects(item);
4925
                                }
4926
                                ReleaseCOMObjects(symbol);
4927
                                symbol = null;
4928
                            }
4929

    
4930
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4931
                            if (modelItemIDs.Count == 1)
4932
                            {
4933
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4934
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4935
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4936
                                {
4937
                                    bool result = false;
4938
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4939
                                    {
4940
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4941
                                            result = true;
4942
                                        ReleaseCOMObjects(loop);
4943
                                    }
4944

    
4945
                                    if (result)
4946
                                    {
4947
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4948
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4949
                                        ZeroLengthModelItem.Commit();
4950
                                    }
4951
                                    else
4952
                                    {
4953
                                        List<string> loopModelItems = new List<string>();
4954
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4955
                                        {
4956
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4957
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4958
                                            {
4959
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4960
                                                    loopModelItems.Add(loop.ModelItemID);
4961
                                                ReleaseCOMObjects(loop);
4962
                                            }
4963
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4964
                                            {
4965
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4966
                                                    loopModelItems.Add(loop.ModelItemID);
4967
                                                ReleaseCOMObjects(loop);
4968
                                            }
4969
                                            ReleaseCOMObjects(_symbol);
4970
                                            _symbol = null;
4971
                                        }
4972
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4973
                                        {
4974
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4975
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4976
                                            {
4977
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4978
                                                    loopModelItems.Add(loop.ModelItemID);
4979
                                                ReleaseCOMObjects(loop);
4980
                                            }
4981
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4982
                                            {
4983
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4984
                                                    loopModelItems.Add(loop.ModelItemID);
4985
                                                ReleaseCOMObjects(loop);
4986
                                            }
4987
                                            ReleaseCOMObjects(_symbol);
4988
                                            _symbol = null;
4989
                                        }
4990

    
4991
                                        loopModelItems = loopModelItems.Distinct().ToList();
4992
                                        if (loopModelItems.Count == 1)
4993
                                        {
4994
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4995
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
4996
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
4997
                                            modelItem.Commit();
4998
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4999
                                            ZeroLengthModelItem.Commit();
5000

    
5001
                                            ReleaseCOMObjects(loopModelItem);
5002
                                            loopModelItem = null;
5003
                                        }
5004
                                    }
5005
                                }
5006
                                else
5007
                                {
5008
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5009
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5010
                                    ZeroLengthModelItem.Commit();
5011
                                }
5012
                                ReleaseCOMObjects(modelItem);
5013
                                modelItem = null;
5014
                                ReleaseCOMObjects(onlyOne);
5015
                                onlyOne = null;
5016
                            }
5017
                        }
5018
                        ReleaseCOMObjects(connector);
5019
                        connector = null;
5020
                        ReleaseCOMObjects(ZeroLengthModelItem);
5021
                        ZeroLengthModelItem = null;
5022
                    }
5023
                    ReleaseCOMObjects(representation);
5024
                    representation = null;
5025
                }
5026
                ReleaseCOMObjects(labelPersist);
5027
                labelPersist = null;
5028
            }
5029
        }
5030

    
5031
        /// <summary>
5032
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5033
        /// </summary>
5034
        /// <param name="text"></param>
5035
        private void NormalTextModeling(Text text)
5036
        {
5037
            LMSymbol _LMSymbol = null;
5038

    
5039
            LMItemNote _LMItemNote = null;
5040
            LMAAttribute _LMAAttribute = null;
5041

    
5042
            double x = 0;
5043
            double y = 0;
5044
            double angle = text.ANGLE;
5045
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5046

    
5047
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5048
            text.SPPID.SPPID_X = x;
5049
            text.SPPID.SPPID_Y = y;
5050

    
5051
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5052
            if (_LMSymbol != null)
5053
            {
5054
                _LMSymbol.Commit();
5055
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5056
                if (_LMItemNote != null)
5057
                {
5058
                    _LMItemNote.Commit();
5059
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5060
                    if (_LMAAttribute != null)
5061
                    {
5062
                        _LMAAttribute.set_Value(text.VALUE);
5063
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5064
                        _LMItemNote.Commit();
5065

    
5066

    
5067
                        double[] range = null;
5068
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5069
                        {
5070
                            double[] temp = null;
5071
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5072
                            if (temp != null)
5073
                            {
5074
                                if (range == null)
5075
                                    range = temp;
5076
                                else
5077
                                {
5078
                                    range = new double[] {
5079
                                            Math.Min(range[0], temp[0]),
5080
                                            Math.Min(range[1], temp[1]),
5081
                                            Math.Max(range[2], temp[2]),
5082
                                            Math.Max(range[3], temp[3])
5083
                                        };
5084
                                }
5085
                            }
5086
                        }
5087
                        text.SPPID.Range = range;
5088

    
5089
                        if (_LMAAttribute != null)
5090
                            ReleaseCOMObjects(_LMAAttribute);
5091
                        if (_LMItemNote != null)
5092
                            ReleaseCOMObjects(_LMItemNote);
5093
                    }
5094

    
5095
                    TextCorrectModeling(text);
5096
                }
5097
            }
5098
            if (_LMSymbol != null)
5099
                ReleaseCOMObjects(_LMSymbol);
5100
        }
5101

    
5102
        private void DefaultTextModeling(string value, double x, double y)
5103
        {
5104
            LMSymbol _LMSymbol = null;
5105

    
5106
            LMItemNote _LMItemNote = null;
5107
            LMAAttribute _LMAAttribute = null;
5108

    
5109
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5110
            if (_LMSymbol != null)
5111
            {
5112
                _LMSymbol.Commit();
5113
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5114
                if (_LMItemNote != null)
5115
                {
5116
                    _LMItemNote.Commit();
5117
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5118
                    if (_LMAAttribute != null)
5119
                    {
5120
                        _LMAAttribute.set_Value(value);
5121
                        _LMItemNote.Commit();
5122

    
5123
                        if (_LMAAttribute != null)
5124
                            ReleaseCOMObjects(_LMAAttribute);
5125
                        if (_LMItemNote != null)
5126
                            ReleaseCOMObjects(_LMItemNote);
5127
                    }
5128
                }
5129
            }
5130
            if (_LMSymbol != null)
5131
                ReleaseCOMObjects(_LMSymbol);
5132
        }
5133

    
5134
        private void AssociationTextModeling(Text text)
5135
        {
5136
            LMSymbol _LMSymbol = null;
5137
            LMConnector connectedLMConnector = null;
5138
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5139
            if (owner != null && owner.GetType() == typeof(Symbol))
5140
            {
5141
                Symbol symbol = owner as Symbol;
5142
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5143
                if (_LMSymbol != null)
5144
                {
5145
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5146
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5147
                    {
5148
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5149

    
5150
                        if (mapping != null)
5151
                        {
5152
                            double x = 0;
5153
                            double y = 0;
5154

    
5155
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5156
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5157
                            Array array = new double[] { 0, x, y };
5158
                            text.SPPID.SPPID_X = x;
5159
                            text.SPPID.SPPID_Y = y;
5160
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5161
                            if (_LMLabelPersist != null)
5162
                            {
5163
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5164
                                _LMLabelPersist.Commit();
5165
                                ReleaseCOMObjects(_LMLabelPersist);
5166
                            }
5167
                        }
5168
                    }
5169
                }
5170
            }
5171
            else if (owner != null && owner.GetType() == typeof(Line))
5172
            {
5173
                Line line = owner as Line;
5174
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5175
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5176

    
5177
                if (connectedLMConnector != null)
5178
                {
5179
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5180
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5181
                    {
5182
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5183

    
5184
                        if (mapping != null)
5185
                        {
5186
                            double x = 0;
5187
                            double y = 0;
5188
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5189
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5190
                            Array array = new double[] { 0, x, y };
5191

    
5192
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5193
                            if (_LMLabelPersist != null)
5194
                            {
5195
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5196
                                _LMLabelPersist.Commit();
5197
                                ReleaseCOMObjects(_LMLabelPersist);
5198
                            }
5199
                        }
5200
                    }
5201
                }
5202
            }
5203
            if (_LMSymbol != null)
5204
                ReleaseCOMObjects(_LMSymbol);
5205
        }
5206

    
5207
        private void TextCorrectModeling(Text text)
5208
        {
5209
            if (text.SPPID.Range == null)
5210
                return;
5211

    
5212
            bool needRemodeling = false;
5213
            bool loop = true;
5214
            GridSetting gridSetting = GridSetting.GetInstance();
5215
            while (loop)
5216
            {
5217
                loop = false;
5218
                foreach (var overlapText in document.TEXTINFOS)
5219
                {
5220
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5221
                        continue;
5222

    
5223
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5224
                    {
5225
                        double percentX = 0;
5226
                        double percentY = 0;
5227
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5228
                        {
5229
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5230
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5231
                        }
5232
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5233
                        {
5234
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5235
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5236
                        }
5237

    
5238
                        double tempX = 0;
5239
                        double tempY = 0;
5240
                        bool overlapX = false;
5241
                        bool overlapY = false;
5242
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5243
                        if (percentX >= percentY)
5244
                        {
5245
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5246
                            double move = gridSetting.Length * count;
5247
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5248
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5249
                            needRemodeling = true;
5250
                            loop = true;
5251
                        }
5252
                        else
5253
                        {
5254
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5255
                            double move = gridSetting.Length * count;
5256
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5257
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5258
                            needRemodeling = true;
5259
                            loop = true;
5260
                        }
5261
                    }
5262
                }
5263
            }
5264
            
5265

    
5266
            if (needRemodeling)
5267
            {
5268
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5269
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5270
                text.SPPID.RepresentationId = null;
5271

    
5272
                LMItemNote _LMItemNote = null;
5273
                LMAAttribute _LMAAttribute = null;
5274
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5275
                if (_LMSymbol != null)
5276
                {
5277
                    _LMSymbol.Commit();
5278
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5279
                    if (_LMItemNote != null)
5280
                    {
5281
                        _LMItemNote.Commit();
5282
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5283
                        if (_LMAAttribute != null)
5284
                        {
5285
                            _LMAAttribute.set_Value(text.VALUE);
5286
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5287
                            _LMItemNote.Commit();
5288

    
5289
                            ReleaseCOMObjects(_LMAAttribute);
5290
                            ReleaseCOMObjects(_LMItemNote);
5291
                        }
5292
                    }
5293
                }
5294

    
5295
                ReleaseCOMObjects(symbol);
5296
                symbol = null;
5297
                ReleaseCOMObjects(_LMItemNote);
5298
                _LMItemNote = null;
5299
                ReleaseCOMObjects(_LMAAttribute);
5300
                _LMAAttribute = null;
5301
                ReleaseCOMObjects(_LMSymbol);
5302
                _LMSymbol = null;
5303
            }
5304
        }
5305

    
5306
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5307
        {
5308
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5309
            {
5310
                List<Text> allTexts = new List<Text>();
5311
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5312
                LMRepresentation representation = targetLabel.RepresentationObject;
5313
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5314
                if (targetLabel.RepresentationObject != null && symbol != null)
5315
                {
5316
                    double[] symbolRange = null;
5317
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5318
                    if (symbolRange != null)
5319
                    {
5320
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5321
                        {
5322
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5323
                            if (findText != null)
5324
                            {
5325
                                double[] range = null;
5326
                                GetSPPIDSymbolRange(labelPersist, ref range);
5327
                                findText.SPPID.Range = range;
5328
                                allTexts.Add(findText);
5329
                            }
5330

    
5331
                            ReleaseCOMObjects(labelPersist);
5332
                        }
5333

    
5334
                        if (allTexts.Count > 0)
5335
                        {
5336
                            #region Sort Text By Y
5337
                            allTexts.Sort(SortTextByY);
5338
                            int SortTextByY(Text a, Text b)
5339
                            {
5340
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5341
                            }
5342
                            #endregion
5343

    
5344
                            #region 정렬하기전 방향
5345
                            List<Text> left = new List<Text>();
5346
                            List<Text> down = new List<Text>();
5347
                            List<Text> right = new List<Text>();
5348
                            List<Text> up = new List<Text>();
5349
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5350
                            foreach (var loopText in allTexts)
5351
                            {
5352
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5353
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5354
                                double originX = 0;
5355
                                double originY = 0;
5356
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5357
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5358

    
5359
                                if (angle < 45)
5360
                                {
5361
                                    // Text 오른쪽
5362
                                    if (textCenterX > originX)
5363
                                        right.Add(loopText);
5364
                                    // Text 왼쪽
5365
                                    else
5366
                                        left.Add(loopText); 
5367
                                }
5368
                                else
5369
                                {
5370
                                    // Text 아래쪽
5371
                                    if (textCenterY > originY)
5372
                                        down.Add(loopText);
5373
                                    // Text 위쪽
5374
                                    else
5375
                                        up.Add(loopText);
5376
                                }
5377
                            }
5378
                            
5379
                            #endregion
5380

    
5381
                            foreach (var texts in sortTexts)
5382
                            {
5383
                                if (texts.Count == 0 )
5384
                                    continue;
5385
                                
5386
                                #region 첫번째 Text로 기준 맞춤
5387
                                for (int i = 0; i < texts.Count; i++)
5388
                                {
5389
                                    if (i != 0)
5390
                                    {
5391
                                        Text currentText = texts[i];
5392
                                        Text prevText = texts[i - 1];
5393
                                        double minY = prevText.SPPID.Range[1];
5394
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5395
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5396
                                        double _gapX = centerX - centerPrevX;
5397
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5398
                                        MoveText(currentText, _gapX, _gapY);
5399
                                    }
5400
                                }
5401
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5402
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5403
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5404
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5405
                                rangeMinX.Sort();
5406
                                rangeMinY.Sort();
5407
                                rangeMaxX.Sort();
5408
                                rangeMaxY.Sort();
5409
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5410
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5411
                                #endregion
5412
                                #region 정렬
5413
                                Text correctBySymbol = texts[0];
5414
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5415
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5416
                                double originX = 0;
5417
                                double originY = 0;
5418
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5419
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5420
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5421
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5422

    
5423
                                double gapX = 0;
5424
                                double gapY = 0;
5425
                                if (angle < 45)
5426
                                {
5427
                                    // Text 오른쪽
5428
                                    if (textCenterX > originX)
5429
                                    {
5430
                                        gapX = rangeMinX[0] - symbolRange[2];
5431
                                        gapY = allTextCenterY - symbolCenterY;
5432
                                    }
5433
                                    // Text 왼쪽
5434
                                    else
5435
                                    {
5436
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5437
                                        gapY = allTextCenterY - symbolCenterY;
5438
                                    }
5439
                                }
5440
                                else
5441
                                {
5442
                                    // Text 아래쪽
5443
                                    if (textCenterY > originY)
5444
                                    {
5445
                                        gapX = allTextCenterX - symbolCenterX;
5446
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5447
                                    }
5448
                                    // Text 위쪽
5449
                                    else
5450
                                    {
5451
                                        gapX = allTextCenterX - symbolCenterX;
5452
                                        gapY = rangeMinY[0] - symbolRange[3];
5453
                                    }
5454
                                }
5455

    
5456
                                foreach (var item in texts)
5457
                                {
5458
                                    MoveText(item, gapX, gapY);
5459
                                    RemodelingAssociationText(item);
5460
                                }
5461
                                #endregion
5462
                            }
5463
                        }
5464
                    }
5465
                }
5466

    
5467
                void MoveText(Text moveText, double x, double y)
5468
                {
5469
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5470
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5471
                    moveText.SPPID.Range = new double[] {
5472
                        moveText.SPPID.Range[0] - x,
5473
                        moveText.SPPID.Range[1]- y,
5474
                        moveText.SPPID.Range[2]- x,
5475
                        moveText.SPPID.Range[3]- y
5476
                    };
5477
                }
5478

    
5479
                endTexts.AddRange(allTexts);
5480

    
5481
                ReleaseCOMObjects(targetLabel);
5482
                targetLabel = null;
5483
                ReleaseCOMObjects(representation);
5484
                representation = null;
5485
            }
5486
        }
5487

    
5488
        private void RemodelingAssociationText(Text text)
5489
        {
5490
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5491
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5492
            removeLabel.Commit();
5493
            ReleaseCOMObjects(removeLabel);
5494
            removeLabel = null;
5495

    
5496
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5497
            if (owner != null && owner.GetType() == typeof(Symbol))
5498
            {
5499
                Symbol symbol = owner as Symbol;
5500
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5501
                if (_LMSymbol != null)
5502
                {
5503
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5504
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5505
                    {
5506
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5507

    
5508
                        if (mapping != null)
5509
                        {
5510
                            double x = 0;
5511
                            double y = 0;
5512

    
5513
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5514
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5515
                            if (_LMLabelPersist != null)
5516
                            {
5517
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5518
                                _LMLabelPersist.Commit();
5519
                            }
5520
                            ReleaseCOMObjects(_LMLabelPersist);
5521
                            _LMLabelPersist = null;
5522
                        }
5523
                    }
5524
                }
5525
                ReleaseCOMObjects(_LMSymbol);
5526
                _LMSymbol = null;
5527
            }
5528
        }
5529

    
5530
        /// <summary>
5531
        /// Note Modeling
5532
        /// </summary>
5533
        /// <param name="note"></param>
5534
        private void NoteModeling(Note note, List<Note> correctList)
5535
        {
5536
            LMSymbol _LMSymbol = null;
5537
            LMItemNote _LMItemNote = null;
5538
            LMAAttribute _LMAAttribute = null;
5539

    
5540
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5541
            {
5542
                double x = 0;
5543
                double y = 0;
5544

    
5545
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5546
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5547
                note.SPPID.SPPID_X = x;
5548
                note.SPPID.SPPID_Y = y;
5549

    
5550
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5551
                if (_LMSymbol != null)
5552
                {
5553
                    _LMSymbol.Commit();
5554
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5555
                    if (_LMItemNote != null)
5556
                    {
5557
                        _LMItemNote.Commit();
5558
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5559
                        if (_LMAAttribute != null)
5560
                        {
5561
                            _LMAAttribute.set_Value(note.VALUE);
5562
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5563

    
5564
                            double[] range = null;
5565
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5566
                            {
5567
                                double[] temp = null;
5568
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5569
                                if (temp != null)
5570
                                {
5571
                                    if (range == null)
5572
                                        range = temp;
5573
                                    else
5574
                                    {
5575
                                        range = new double[] {
5576
                                            Math.Min(range[0], temp[0]),
5577
                                            Math.Min(range[1], temp[1]),
5578
                                            Math.Max(range[2], temp[2]),
5579
                                            Math.Max(range[3], temp[3])
5580
                                        };
5581
                                    }
5582
                                }
5583
                            }
5584
                            if (range != null)
5585
                                correctList.Add(note);
5586
                            note.SPPID.Range = range;
5587

    
5588

    
5589
                            _LMItemNote.Commit();
5590
                        }
5591
                    }
5592
                }
5593
            }
5594

    
5595
            if (_LMAAttribute != null)
5596
                ReleaseCOMObjects(_LMAAttribute);
5597
            if (_LMItemNote != null)
5598
                ReleaseCOMObjects(_LMItemNote);
5599
            if (_LMSymbol != null)
5600
                ReleaseCOMObjects(_LMSymbol);
5601
        }
5602

    
5603
        private void NoteCorrectModeling(Note note, List<Note> endList)
5604
        {
5605
            bool needRemodeling = false;
5606
            bool loop = true;
5607
            GridSetting gridSetting = GridSetting.GetInstance();
5608
            while (loop)
5609
            {
5610
                loop = false;
5611
                foreach (var overlap in endList)
5612
                {
5613
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5614
                    {
5615
                        double tempX = 0;
5616
                        double tempY = 0;
5617
                        bool overlapX = false;
5618
                        bool overlapY = false;
5619
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5620
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5621
                        if (overlapY && angle >= 45)
5622
                        {
5623
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5624
                            double move = gridSetting.Length * count;
5625
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5626
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5627
                            needRemodeling = true;
5628
                            loop = true;
5629
                        }
5630
                        if (overlapX && angle <= 45)
5631
                        {
5632
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5633
                            double move = gridSetting.Length * count;
5634
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5635
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5636
                            needRemodeling = true;
5637
                            loop = true;
5638
                        }
5639
                    }
5640
                }
5641
            }
5642

    
5643

    
5644
            if (needRemodeling)
5645
            {
5646
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5647
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5648
                note.SPPID.RepresentationId = null;
5649

    
5650
                LMItemNote _LMItemNote = null;
5651
                LMAAttribute _LMAAttribute = null;
5652
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5653
                if (_LMSymbol != null)
5654
                {
5655
                    _LMSymbol.Commit();
5656
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5657
                    if (_LMItemNote != null)
5658
                    {
5659
                        _LMItemNote.Commit();
5660
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5661
                        if (_LMAAttribute != null)
5662
                        {
5663
                            _LMAAttribute.set_Value(note.VALUE);
5664
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5665
                            _LMItemNote.Commit();
5666

    
5667
                            ReleaseCOMObjects(_LMAAttribute);
5668
                            ReleaseCOMObjects(_LMItemNote);
5669
                        }
5670
                    }
5671
                }
5672

    
5673
                ReleaseCOMObjects(symbol);
5674
                symbol = null;
5675
                ReleaseCOMObjects(_LMItemNote);
5676
                _LMItemNote = null;
5677
                ReleaseCOMObjects(_LMAAttribute);
5678
                _LMAAttribute = null;
5679
                ReleaseCOMObjects(_LMSymbol);
5680
                _LMSymbol = null;
5681
            }
5682

    
5683
            endList.Add(note);
5684
        }
5685

    
5686
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5687
        {
5688
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5689
            if (modelItem != null)
5690
            {
5691
                foreach (LMRepresentation rep in modelItem.Representations)
5692
                {
5693
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5694
                    {
5695
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5696
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5697
                        {
5698
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5699
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5700
                            if (modelItemIds.Count == 1)
5701
                            {
5702
                                string joinModelItemId = modelItemIds[0];
5703
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5704
                                if (survivorId != null)
5705
                                    break;
5706
                            }
5707
                        }
5708
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5709
                        {
5710
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5711
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5712
                            if (modelItemIds.Count == 1)
5713
                            {
5714
                                string joinModelItemId = modelItemIds[0];
5715
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5716
                                if (survivorId != null)
5717
                                    break;
5718
                            }
5719
                        }
5720
                    }
5721
                }
5722
            }
5723
        }
5724

    
5725
        /// <summary>
5726
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5727
        /// </summary>
5728
        /// <param name="x"></param>
5729
        /// <param name="y"></param>
5730
        /// <param name="originX"></param>
5731
        /// <param name="originY"></param>
5732
        /// <param name="SPPIDLabelLocation"></param>
5733
        /// <param name="location"></param>
5734
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5735
        {
5736
            if (location == Location.None)
5737
            {
5738
                x = originX;
5739
                y = originY;
5740
            }
5741
            else
5742
            {
5743
                if (location.HasFlag(Location.Center))
5744
                {
5745
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5746
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5747
                }
5748

    
5749
                if (location.HasFlag(Location.Left))
5750
                    x = SPPIDLabelLocation.X1;
5751
                else if (location.HasFlag(Location.Right))
5752
                    x = SPPIDLabelLocation.X2;
5753

    
5754
                if (location.HasFlag(Location.Down))
5755
                    y = SPPIDLabelLocation.Y1;
5756
                else if (location.HasFlag(Location.Up))
5757
                    y = SPPIDLabelLocation.Y2;
5758
            }
5759
        }
5760

    
5761
        /// <summary>
5762
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5763
        /// 1. Angle Valve
5764
        /// 2. 3개로 이루어진 Symbol Group
5765
        /// </summary>
5766
        /// <returns></returns>
5767
        private List<Symbol> GetPrioritySymbol()
5768
        {
5769
            DataTable symbolTable = document.SymbolTable;
5770
            // List에 순서대로 쌓는다.
5771
            List<Symbol> symbols = new List<Symbol>();
5772

    
5773
            // Angle Valve 부터
5774
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5775
            {
5776
                if (!symbols.Contains(symbol))
5777
                {
5778
                    double originX = 0;
5779
                    double originY = 0;
5780

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

    
5785
                    SlopeType slopeType1 = SlopeType.None;
5786
                    SlopeType slopeType2 = SlopeType.None;
5787
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5788
                    {
5789
                        double connectorX = 0;
5790
                        double connectorY = 0;
5791
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5792
                        if (slopeType1 == SlopeType.None)
5793
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5794
                        else
5795
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5796
                    }
5797

    
5798
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5799
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5800
                        symbols.Add(symbol);
5801
                }
5802
            }
5803

    
5804
            List<Symbol> tempSymbols = new List<Symbol>();
5805
            // Conn 갯수 기준
5806
            foreach (var item in document.SYMBOLS)
5807
            {
5808
                if (!symbols.Contains(item))
5809
                    tempSymbols.Add(item);
5810
            }
5811
            tempSymbols.Sort(SortSymbolPriority);
5812
            symbols.AddRange(tempSymbols);
5813

    
5814
            return symbols;
5815
        }
5816

    
5817
        private void SetPriorityLine(List<Line> lines)
5818
        {
5819
            lines.Sort(SortLinePriority);
5820

    
5821
            int SortLinePriority(Line a, Line b)
5822
            {
5823
                // Branch 없는것부터
5824
                int branchRetval = CompareBranchLine(a, b);
5825
                if (branchRetval != 0)
5826
                {
5827
                    return branchRetval;
5828
                }
5829
                else
5830
                {
5831
                    // Symbol 연결 갯수
5832
                    int connSymbolRetval = CompareConnSymbol(a, b);
5833
                    if (connSymbolRetval != 0)
5834
                    {
5835
                        return connSymbolRetval;
5836
                    }
5837
                    else
5838
                    {
5839
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5840
                        int connItemRetval = CompareConnItem(a, b);
5841
                        if (connItemRetval != 0)
5842
                        {
5843
                            return connItemRetval;
5844
                        }
5845
                        else
5846
                        {
5847
                            // ConnectedItem이 없는것
5848
                            int noneConnRetval = CompareNoneConn(a, b);
5849
                            if (noneConnRetval != 0)
5850
                            {
5851
                                return noneConnRetval;
5852
                            }
5853
                            else
5854
                            {
5855

    
5856
                            }
5857
                        }
5858
                    }
5859
                }
5860

    
5861
                return 0;
5862
            }
5863

    
5864
            int CompareNotSegmentLine(Line a, Line b)
5865
            {
5866
                List<Connector> connectorsA = a.CONNECTORS
5867
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5868
                    .ToList();
5869

    
5870
                List<Connector> connectorsB = b.CONNECTORS
5871
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5872
                    .ToList();
5873

    
5874
                // 오름차순
5875
                return connectorsB.Count.CompareTo(connectorsA.Count);
5876
            }
5877

    
5878
            int CompareConnSymbol(Line a, Line b)
5879
            {
5880
                List<Connector> connectorsA = a.CONNECTORS
5881
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5882
                    .ToList();
5883

    
5884
                List<Connector> connectorsB = b.CONNECTORS
5885
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5886
                    .ToList();
5887

    
5888
                // 오름차순
5889
                return connectorsB.Count.CompareTo(connectorsA.Count);
5890
            }
5891

    
5892
            int CompareConnItem(Line a, Line b)
5893
            {
5894
                List<Connector> connectorsA = a.CONNECTORS
5895
                    .Where(conn => conn.ConnectedObject != null && 
5896
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5897
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5898
                    .ToList();
5899

    
5900
                List<Connector> connectorsB = b.CONNECTORS
5901
                    .Where(conn => conn.ConnectedObject != null &&
5902
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5903
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5904
                    .ToList();
5905

    
5906
                // 오름차순
5907
                return connectorsB.Count.CompareTo(connectorsA.Count);
5908
            }
5909

    
5910
            int CompareBranchLine(Line a, Line b)
5911
            {
5912
                List<Connector> connectorsA = a.CONNECTORS
5913
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5914
                    .ToList();
5915
                List<Connector> connectorsB = b.CONNECTORS
5916
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5917
                    .ToList();
5918

    
5919
                // 내림차순
5920
                return connectorsA.Count.CompareTo(connectorsB.Count);
5921
            }
5922

    
5923
            int CompareNoneConn(Line a, Line b)
5924
            {
5925
                List<Connector> connectorsA = a.CONNECTORS
5926
                    .Where(conn => conn.ConnectedObject == null)
5927
                    .ToList();
5928

    
5929
                List<Connector> connectorsB = b.CONNECTORS
5930
                    .Where(conn => conn.ConnectedObject == null)
5931
                    .ToList();
5932

    
5933
                // 오름차순
5934
                return connectorsB.Count.CompareTo(connectorsA.Count);
5935
            }
5936
        }
5937

    
5938
        private void SortText(List<Text> texts)
5939
        {
5940
            texts.Sort(Sort);
5941

    
5942
            int Sort(Text a, Text b)
5943
            {
5944
                int yRetval = CompareY(a, b);
5945
                if (yRetval != 0)
5946
                {
5947
                    return yRetval;
5948
                }
5949
                else
5950
                {
5951
                    return CompareX(a, b);
5952
                }
5953
            }
5954

    
5955
            int CompareY(Text a, Text b)
5956
            {
5957
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5958
            }
5959

    
5960
            int CompareX(Text a, Text b)
5961
            {
5962
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5963
            }
5964
        }
5965
        private void SortNote(List<Note> notes)
5966
        {
5967
            notes.Sort(Sort);
5968

    
5969
            int Sort(Note a, Note b)
5970
            {
5971
                int yRetval = CompareY(a, b);
5972
                if (yRetval != 0)
5973
                {
5974
                    return yRetval;
5975
                }
5976
                else
5977
                {
5978
                    return CompareX(a, b);
5979
                }
5980
            }
5981

    
5982
            int CompareY(Note a, Note b)
5983
            {
5984
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5985
            }
5986

    
5987
            int CompareX(Note a, Note b)
5988
            {
5989
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5990
            }
5991
        }
5992

    
5993
        private void SortBranchLines()
5994
        {
5995
            BranchLines.Sort(SortBranchLine);
5996
            int SortBranchLine(Line a, Line b)
5997
            {
5998
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5999
                 x.ConnectedObject.GetType() == typeof(Line) &&
6000
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6001
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6002

    
6003
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6004
                 x.ConnectedObject.GetType() == typeof(Line) &&
6005
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6006
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6007

    
6008
                // 내림차순
6009
                return countA.CompareTo(countB);
6010
            }
6011
        }
6012

    
6013
        private static int SortSymbolPriority(Symbol a, Symbol b)
6014
        {
6015
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6016
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6017
            int retval = countB.CompareTo(countA);
6018
            if (retval != 0)
6019
                return retval;
6020
            else
6021
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6022
        }
6023

    
6024
        private string GetSPPIDFileName(LMModelItem modelItem)
6025
        {
6026
            string symbolPath = null;
6027
            foreach (LMRepresentation rep in modelItem.Representations)
6028
            {
6029
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6030
                {
6031
                    symbolPath = rep.get_FileName();
6032
                    break;
6033
                }
6034
            }
6035
            return symbolPath;
6036
        }
6037

    
6038
        private string GetSPPIDFileName(string modelItemId)
6039
        {
6040
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6041
            string symbolPath = null;
6042
            foreach (LMRepresentation rep in modelItem.Representations)
6043
            {
6044
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6045
                {
6046
                    symbolPath = rep.get_FileName();
6047
                    break;
6048
                }
6049
            }
6050
            ReleaseCOMObjects(modelItem);
6051
            return symbolPath;
6052
        }
6053

    
6054
        /// <summary>
6055
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6056
        /// </summary>
6057
        /// <param name="graphicOID"></param>
6058
        /// <param name="milliseconds"></param>
6059
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6060
        {
6061
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6062
            {
6063
                double minX = 0;
6064
                double minY = 0;
6065
                double maxX = 0;
6066
                double maxY = 0;
6067
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6068
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6069

    
6070
                Thread.Sleep(milliseconds);
6071
            }
6072
        }
6073

    
6074
        /// <summary>
6075
        /// ComObject를 Release
6076
        /// </summary>
6077
        /// <param name="objVars"></param>
6078
        public void ReleaseCOMObjects(params object[] objVars)
6079
        {
6080
            if (objVars != null)
6081
            {
6082
                int intNewRefCount = 0;
6083
                foreach (object obj in objVars)
6084
                {
6085
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6086
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6087
                }
6088
            }
6089
        }
6090

    
6091
        /// IDisposable 구현
6092
        ~AutoModeling()
6093
        {
6094
            this.Dispose(false);
6095
        }
6096

    
6097
        private bool disposed;
6098
        public void Dispose()
6099
        {
6100
            this.Dispose(true);
6101
            GC.SuppressFinalize(this);
6102
        }
6103

    
6104
        protected virtual void Dispose(bool disposing)
6105
        {
6106
            if (this.disposed) return;
6107
            if (disposing)
6108
            {
6109
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6110
            }
6111
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6112
            this.disposed = true;
6113
        }
6114
    }
6115
}
클립보드 이미지 추가 (최대 크기: 500 MB)