Salome HOME
simplify Python ImportShapesFromFile and importPolylines
[modules/hydro.git] / src / HYDROData / HYDROData_Image.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include "HYDROData_Image.h"
20
21 #include "HYDROData_Document.h"
22 #include "HYDROData_Lambert93.h"
23 #include "HYDROData_OperationsFactory.h"
24 #include "HYDROData_Tool.h"
25
26 #include <TDataStd_RealArray.hxx>
27 #include <TDataStd_ByteArray.hxx>
28 #include <TDataStd_Integer.hxx>
29 #include <TDataStd_IntegerArray.hxx>
30 #include <TDataStd_ReferenceList.hxx>
31 #include <TDataStd_UAttribute.hxx>
32 #include <TDataStd_AsciiString.hxx>
33
34 #include <NCSDefs.h>
35 #include <NCSFile.h>
36
37 #ifdef WIN32
38   #pragma warning ( disable: 4251 )
39 #endif
40
41 #include <ImageComposer_Operator.h>
42 #include <ImageComposer_MetaTypes.h>
43
44 #include <QStringList>
45 #include <QFile>
46 #include <QFileInfo>
47
48 #ifdef WIN32
49   #pragma warning ( default: 4251 )
50 #endif
51
52 static const Standard_GUID GUID_SELF_SPLIT("997995aa-5c19-40bf-9a60-ab4b70ad04d8");
53 static const Standard_GUID GUID_HAS_LOCAL_POINTS("FD8841AA-FC44-42fa-B6A7-0F682CCC6F27");
54 static const Standard_GUID GUID_HAS_GLOBAL_POINTS("330D0E81-742D-4ea3-92D4-484877CFA7C1");
55
56 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Image, HYDROData_Entity)
57
58 HYDROData_Image::HYDROData_Image()
59 : HYDROData_Entity( Geom_2d )
60 {
61 }
62
63 HYDROData_Image::~HYDROData_Image()
64 {
65 }
66
67 QStringList HYDROData_Image::DumpToPython( const QString&       thePyScriptPath,
68                                            MapOfTreatedObjects& theTreatedObjects ) const
69 {
70   QStringList aResList = dumpObjectCreation( theTreatedObjects );
71   QString anImageName = GetObjPyName();
72
73   QString aFilePath = GetFilePath();
74   if ( !aFilePath.isEmpty() )
75   {
76     aResList << QString( "" );
77     aResList << QString( "if not(%1.LoadImage( \"%2\" )):" )
78                 .arg( anImageName ).arg( aFilePath );
79     aResList << QString( "  raise ValueError('problem while loading image')" );
80     aResList << QString( "" );
81
82     // Dump transformation points for image
83
84     bool anIsByTwoPoints = IsByTwoPoints();
85
86     QPoint aLocalPointA, aLocalPointB, aLocalPointC;
87     if ( GetLocalPoints( aLocalPointA, aLocalPointB, aLocalPointC ) )
88     {
89       QString aGap = QString().fill( ' ', anImageName.size() + 17 );
90
91       aResList << QString( "%1.SetLocalPoints( QPoint( %2, %3 )," )
92                   .arg( anImageName ).arg( aLocalPointA.x() ).arg( aLocalPointA.y() );
93       aResList << QString( aGap             + "QPoint( %1, %2 )" )
94                   .arg( aLocalPointB.x() ).arg( aLocalPointB.y() );
95       if ( !anIsByTwoPoints )
96       {
97         aResList.last().append( "," );
98         aResList << QString( aGap             +  "QPoint( %1, %2 ) )" )
99                     .arg( aLocalPointC.x() ).arg( aLocalPointC.y() );
100       }
101       else
102       {
103         aResList.last().append( " )" );
104       }
105       aResList << QString( "" );
106     }
107
108     HYDROData_Image::TransformationMode aTransformationMode;
109     QPointF aTrsfPointA, aTrsfPointB, aTrsfPointC;
110     if ( GetGlobalPoints( aTransformationMode, aTrsfPointA, aTrsfPointB, aTrsfPointC ) )
111     {
112       QString aGap = QString().fill( ' ', anImageName.size() + 18 );
113
114       aResList << QString( "%1.SetGlobalPoints( %2," )
115                   .arg( anImageName ).arg( aTransformationMode );
116       aResList << QString( aGap             +  "QPointF( %1, %2 )," )
117                   .arg( aTrsfPointA.x(), 0, 'f', 3  ).arg( aTrsfPointA.y(), 0, 'f', 3  );
118       aResList << QString( aGap             +  "QPointF( %1, %2 )" )
119                   .arg( aTrsfPointB.x(), 0, 'f', 3  ).arg( aTrsfPointB.y(), 0, 'f', 3  );
120       if ( !anIsByTwoPoints )
121       {
122         aResList.last().append( "," );
123         aResList << QString( aGap             +  "QPointF( %1, %2 ) )" )
124                     .arg( aTrsfPointC.x(), 0, 'f', 3  ).arg( aTrsfPointC.y(), 0, 'f', 3  );
125       }
126       else
127       {
128         aResList.last().append( " )" );
129       }
130
131       if ( aTransformationMode == ReferenceImage )
132       {
133         Handle(HYDROData_Image) aRefImg = GetTrsfReferenceImage();
134         setPythonReferenceObject( thePyScriptPath, theTreatedObjects, aResList, aRefImg, "SetTrsfReferenceImage" );
135       }
136     }
137   }
138   else
139   {
140     // Image is composed from other image(s)
141
142     QString anOperatorName = OperatorName();
143     if ( !anOperatorName.isEmpty() )
144     {
145       aResList << QString( "" );
146
147       aResList << QString( "%1.SetOperatorName( \"%2\" )" )
148                   .arg( anImageName ).arg( anOperatorName );
149
150       ImageComposer_Operator* anImageOp = 
151         HYDROData_OperationsFactory::Factory()->Operator( OperatorName() );
152       if ( anImageOp )
153       {
154         // Dump operation arguments
155         QString anOpArgsArrayName;
156         QStringList anOpArgs = anImageOp->dumpArgsToPython( anOpArgsArrayName );
157         if ( !anOpArgs.isEmpty() )
158         {
159           aResList << QString( "" );
160           aResList << anOpArgs;
161
162           aResList << QString( "" );
163           aResList << QString( "%1.SetArgs( %2 )" )
164                       .arg( anImageName ).arg( anOpArgsArrayName );
165         }
166       }
167     }
168     
169     int aNbReferences = NbReferences();
170     if ( aNbReferences > 0 )
171     {
172       aResList << QString( "" );
173
174       for ( int i = 0; i < aNbReferences; ++i )
175       {
176         Handle(HYDROData_Image) aRefImg = Handle(HYDROData_Image)::DownCast( Reference( i ) );
177         setPythonReferenceObject( thePyScriptPath, theTreatedObjects, aResList, aRefImg, "AppendReference" );
178       }
179     }
180   }
181
182   aResList << QString( "" );
183   aResList << QString( "%1.Update()" ).arg( anImageName );
184
185   return aResList;
186 }
187
188 void HYDROData_Image::Update()
189 {
190   bool anIsToUpdate = IsMustBeUpdated( Geom_2d );
191
192   HYDROData_Entity::Update();
193
194   if ( !anIsToUpdate )
195     return;
196
197   HYDROData_OperationsFactory* aFactory = HYDROData_OperationsFactory::Factory();
198
199   ImageComposer_Operator* anOp = aFactory->Operator( OperatorName() );
200   if ( anOp ) // Update image if there is an operation
201   {
202     // Fill by arguments and process the operation
203     anOp->setBinArgs( Args() );
204
205     QVariant anObj1, anObj2;
206     int aNbReferences = NbReferences();
207
208     if ( aNbReferences > 0 )
209     {
210       // First referenced object
211       Handle(HYDROData_Entity) aRefObj = Reference( 0 );
212       if ( !aRefObj.IsNull() )
213       {
214         anObj1 = aRefObj->GetDataVariant();
215         if ( !anObj1.isNull() && anObj1.canConvert<ImageComposer_Image>() )
216         {
217           ImageComposer_Image anImage = anObj1.value<ImageComposer_Image>();
218           QTransform aTransform = anImage.transform();
219           SetTrsf( aTransform );
220         }
221       }
222     }
223
224     if ( aNbReferences > 1 )
225     {
226       // Second referenced object
227       Handle(HYDROData_Entity) aRefObj = Reference( 1 );
228       if ( !aRefObj.IsNull() )
229         anObj2 = aRefObj->GetDataVariant();
230     }
231
232     ImageComposer_Image aResImg = anOp->process( anObj1, anObj2 );
233     SetImage( aResImg );
234     SetTrsf( aResImg.transform() );
235   }
236   else // Update image if it positioned relatively to other image
237   {
238     UpdateTrsf();
239   }
240
241   ClearChanged();
242 }
243
244 bool HYDROData_Image::IsHas2dPrs() const
245 {
246   return true;
247 }
248
249 QVariant HYDROData_Image::GetDataVariant()
250 {
251   QTransform aTransform = Trsf();
252
253   ImageComposer_Image anImage = Image();
254   anImage.setTransform( aTransform );
255
256   QVariant aVarData;
257   aVarData.setValue<ImageComposer_Image>( anImage );
258   
259   return aVarData;
260 }
261
262 HYDROData_SequenceOfObjects HYDROData_Image::GetAllReferenceObjects() const
263 {
264   HYDROData_SequenceOfObjects aResSeq = HYDROData_Entity::GetAllReferenceObjects();
265
266   Handle(HYDROData_Image) aRefImage = GetTrsfReferenceImage();
267   if ( !aRefImage.IsNull() )
268     aResSeq.Append( aRefImage );
269
270   HYDROData_SequenceOfObjects aSeqRefObjects = GetReferenceObjects( 0 );
271   aResSeq.Append( aSeqRefObjects );
272
273   return aResSeq;
274 }
275
276 void HYDROData_Image::SetImage(const QImage& theImage)
277 {
278   if ( theImage.isNull() )
279   {
280     // for empty image remove all previously stored attributes
281     myLab.ForgetAttribute(TDataStd_IntegerArray::GetID());
282     myLab.ForgetAttribute(TDataStd_ByteArray::GetID());
283   }
284   else
285   {
286     QImage anImage;
287
288     // convert 8-bits images
289     if ( theImage.format() == QImage::Format_Indexed8 ) {
290       anImage = theImage.convertToFormat( QImage::Format_RGB32 );
291     } else {
292       anImage = theImage;
293     }
294
295     // store width, height, bytes per line and format in integer array 
296     Handle(TDataStd_IntegerArray) aParams;
297     if (!myLab.FindAttribute(TDataStd_IntegerArray::GetID(), aParams)) {
298       aParams = TDataStd_IntegerArray::Set(myLab, 1, 4);
299       aParams->SetID(TDataStd_IntegerArray::GetID());
300     }
301     aParams->SetValue(1, anImage.width());
302     aParams->SetValue(2, anImage.height());
303     aParams->SetValue(3, anImage.bytesPerLine());
304     aParams->SetValue(4, (int)(anImage.format()));
305     // store data of image in byte array
306     const char* aData = (const char*)(anImage.bits());
307     SaveByteArray(0, aData, anImage.byteCount());
308   }
309
310   Changed( Geom_2d );
311 }
312
313 bool HYDROData_Image::LoadImage( const QString& theFilePath )
314 {
315   QFileInfo aFI(theFilePath);
316   QImage anImage;
317   HYDROData_Image::ECW_FileInfo* theECWInfo;
318   if (aFI.suffix().toLower() == "ecw")
319   {
320     theECWInfo = new HYDROData_Image::ECW_FileInfo;
321     HYDROData_Image::OpenECW(theFilePath.toLatin1().data(), anImage, theECWInfo);
322   }
323   else
324     anImage = QImage(theFilePath);
325   SetImage( anImage );
326   SetFilePath( theFilePath );
327   return !anImage.isNull();
328 }
329
330 bool HYDROData_Image::OpenECW(char* theFileName, QImage& theImage, ECW_FileInfo* theECWInfo)
331 {
332   NCSFileView *pNCSFileView;
333   NCSFileViewFileInfo *pNCSFileInfo;
334   NCSError eError = NCS_SUCCESS;
335   UINT32 band, nBands;
336   UINT32 XSize, YSize;
337   NCSecwInit();
338
339   eError = NCScbmOpenFileView(theFileName, &pNCSFileView, NULL);
340   if(eError != NCS_SUCCESS)
341     return false;
342
343   eError = NCScbmGetViewFileInfo(pNCSFileView, &pNCSFileInfo);
344   if(eError != NCS_SUCCESS)
345     return false;
346
347   XSize = pNCSFileInfo->nSizeX;
348   YSize = pNCSFileInfo->nSizeY;
349   nBands = pNCSFileInfo->nBands;
350   if (theECWInfo)
351   {
352     //ECW_CellUnits myCellSizeUnits;
353     CellSizeUnits aCellUnits = pNCSFileInfo->eCellSizeUnits;
354     if (aCellUnits == ECW_CELL_UNITS_METERS)
355       theECWInfo->myCellSizeUnits = ECW_CellUnits_Meters;
356     else if (aCellUnits == ECW_CELL_UNITS_DEGREES)
357       theECWInfo->myCellSizeUnits = ECW_CellUnits_Deg;
358     else if (aCellUnits == ECW_CELL_UNITS_FEET)
359       theECWInfo->myCellSizeUnits = ECW_CellUnits_Feet;
360     else
361       theECWInfo->myCellSizeUnits = ECW_CellUnits_Unknown;
362     theECWInfo->myCellIncrementX = pNCSFileInfo->fCellIncrementX;
363     theECWInfo->myCellIncrementY = pNCSFileInfo->fCellIncrementY;
364     theECWInfo->myOriginX = pNCSFileInfo->fOriginX;
365     theECWInfo->myOriginY = pNCSFileInfo->fOriginY;
366     theECWInfo->myXSize = pNCSFileInfo->nSizeX;
367     theECWInfo->myYSize = pNCSFileInfo->nSizeY;
368   }
369
370   std::vector<UINT32> band_list(nBands);
371   for( band = 0; band < nBands; band++ )
372     band_list[band] = band;
373
374   eError = NCScbmSetFileView(pNCSFileView, nBands, &band_list[0], 0, 0, XSize - 1, YSize - 1, XSize, YSize); //view an image into the original size
375
376   if(eError != NCS_SUCCESS)
377   {
378     NCScbmCloseFileView(pNCSFileView);
379     return false;
380   }
381
382   UINT8 *pRGBTriplets;
383   pRGBTriplets = (UINT8 *) malloc(XSize*3);
384
385   QImage anImage(XSize, YSize, QImage::Format_RGB32);
386
387   for(UINT32 line = 0; line < YSize; line++)
388   {
389     NCSEcwReadStatus eStatus;
390     eStatus = NCScbmReadViewLineRGB(pNCSFileView, pRGBTriplets);
391     if(eStatus == NCSECW_READ_OK)
392     {
393       QRgb* crp = (QRgb*)anImage.scanLine(line);  
394       for(UINT32 j = 0; j < XSize; j++)
395       {
396         QRgb val = qRgb((int)pRGBTriplets[j*3],(int)pRGBTriplets[j*3+1],(int)pRGBTriplets[j*3+2]);
397         memcpy((void*)(crp+j), &val, sizeof(QRgb)); 
398       }
399     }
400     else    
401     {
402       free(pRGBTriplets);
403       NCScbmCloseFileView(pNCSFileView);
404       return false;
405     }
406   }
407
408   free(pRGBTriplets);
409   NCScbmCloseFileView(pNCSFileView);
410   theImage = anImage;
411   return true;
412 }
413
414 bool HYDROData_Image::LoadImageECW( const QString& theFilePath )
415 {
416   QImage anImage;
417   if (HYDROData_Image::OpenECW(theFilePath.toLatin1().data(), anImage, NULL))
418   {
419     SetImage( anImage );
420     SetFilePath( theFilePath );
421   }
422   return !anImage.isNull();
423 }
424
425 QImage HYDROData_Image::Image()
426 {
427   Handle(TDataStd_IntegerArray) aParams;
428   if (!myLab.FindAttribute(TDataStd_IntegerArray::GetID(), aParams))
429     return QImage(); // return empty image if there is no array
430   int aLen = 0;
431   uchar* anArray = (uchar*)ByteArray(0, aLen);
432   if (!aLen)
433     return QImage(); // return empty image if there is no array
434   QImage aResult(anArray, aParams->Value(1), aParams->Value(2),
435                  aParams->Value(3), QImage::Format(aParams->Value(4)));
436   return aResult;
437 }
438
439 void HYDROData_Image::SetFilePath( const QString& theFilePath )
440 {
441   TCollection_AsciiString anAsciiStr( theFilePath.toStdString().c_str() );
442   Handle(TDataStd_AsciiString) anAttr = TDataStd_AsciiString::Set( myLab.FindChild( DataTag_FilePath ), anAsciiStr );
443   anAttr->SetID(TDataStd_AsciiString::GetID());
444   Changed( Geom_2d );
445 }
446
447 QString HYDROData_Image::GetFilePath() const
448 {
449   QString aRes;
450
451   TDF_Label aLabel = myLab.FindChild( DataTag_FilePath, false );
452   if ( !aLabel.IsNull() )
453   {
454     Handle(TDataStd_AsciiString) anAsciiStr;
455     if ( aLabel.FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
456       aRes = QString( anAsciiStr->Get().ToCString() );
457   }
458
459   return aRes;
460 }
461
462 void HYDROData_Image::SetTrsf(const QTransform& theTrsf)
463 {
464   // locate 9 coeffs of matrix into the real array
465   Handle(TDataStd_RealArray) anArray;
466   if (!myLab.FindAttribute(TDataStd_RealArray::GetID(), anArray)) {
467     if (theTrsf.isIdentity()) return; // no need to store identity transformation
468     anArray = TDataStd_RealArray::Set(myLab, 1, 9);
469     anArray->SetID(TDataStd_RealArray::GetID());
470   }
471   anArray->SetValue(1, theTrsf.m11());
472   anArray->SetValue(2, theTrsf.m12());
473   anArray->SetValue(3, theTrsf.m13());
474   anArray->SetValue(4, theTrsf.m21());
475   anArray->SetValue(5, theTrsf.m22());
476   anArray->SetValue(6, theTrsf.m23());
477   anArray->SetValue(7, theTrsf.m31());
478   anArray->SetValue(8, theTrsf.m32());
479   anArray->SetValue(9, theTrsf.m33());
480
481   Changed( Geom_2d );
482 }
483
484 QTransform HYDROData_Image::Trsf() const
485 {
486   // get 9 coeffs of matrix from the real array
487   Handle(TDataStd_RealArray) anArray;
488   if (!myLab.FindAttribute(TDataStd_RealArray::GetID(), anArray))
489     return QTransform(); // return identity if there is no array
490   QTransform aTrsf(
491     anArray->Value(1), anArray->Value(2), anArray->Value(3), 
492     anArray->Value(4), anArray->Value(5), anArray->Value(6), 
493     anArray->Value(7), anArray->Value(8), anArray->Value(9));
494   return aTrsf;
495 }
496
497 void HYDROData_Image::UpdateTrsf()
498 {
499   QPoint aPointA, aPointB, aPointC;
500   if ( !GetLocalPoints( aPointA, aPointB, aPointC ) )
501     return;
502
503   TransformationMode aTrsfMode;
504   QPointF aTrsfPointA, aTrsfPointB, aTrsfPointC;
505   if ( !GetGlobalPoints( aTrsfMode, aTrsfPointA, aTrsfPointB, aTrsfPointC ) )
506     return;
507
508   QTransform aRefTransform;
509   Handle(HYDROData_Image) aRefImage = GetTrsfReferenceImage();
510
511   bool anIsRefImage = aTrsfMode == ReferenceImage;
512   if ( anIsRefImage )
513   {
514     if ( aRefImage.IsNull() )
515       return;
516
517     aRefTransform = aRefImage->Trsf();
518   }
519
520   bool anIsByTwoPoints = IsByTwoPoints();
521
522   // Convert lambert coordinates to cartesian
523   if ( aTrsfMode == ManualGeodesic )
524   {
525     double aXCart = 0, aYCart = 0;
526
527     HYDROData_Lambert93::toXY( aTrsfPointA.y(), aTrsfPointA.x(), aXCart, aYCart );
528     aTrsfPointA = QPointF( aXCart, aYCart );
529
530     HYDROData_Lambert93::toXY( aTrsfPointB.y(), aTrsfPointB.x(), aXCart, aYCart );
531     aTrsfPointB = QPointF( aXCart, aYCart );
532
533     if ( !anIsByTwoPoints )
534     {
535       HYDROData_Lambert93::toXY( aTrsfPointC.y(), aTrsfPointC.x(), aXCart, aYCart );
536       aTrsfPointC = QPointF( aXCart, aYCart );
537     }
538   }
539
540   // generate third points if needed
541   if ( anIsByTwoPoints )
542   {
543     aPointC = generateThirdPoint( aPointA, aPointB, true ).toPoint();
544     aTrsfPointC = generateThirdPoint( aTrsfPointA, aTrsfPointB, anIsRefImage );
545   }
546
547   int xa = aPointA.x();
548   int ya = aPointA.y();
549   int xb = aPointB.x();
550   int yb = aPointB.y();
551   int xc = aPointC.x();
552   int yc = aPointC.y();
553
554   double xta = aTrsfPointA.x();
555   double yta = aTrsfPointA.y();
556   double xtb = aTrsfPointB.x();
557   double ytb = aTrsfPointB.y();
558   double xtc = aTrsfPointC.x();
559   double ytc = aTrsfPointC.y();
560
561   // first, check that three input points don't belong to a single line
562   if( ( yb - ya ) * ( xc - xa ) == ( yc - ya ) * ( xb - xa ) )
563     return;
564
565   // the same check for the reference points
566   if( anIsRefImage && ( ( ytb - yta ) * ( xtc - xta ) == ( ytc - yta ) * ( xtb - xta ) ) )
567     return;
568
569   QTransform aTransform1( xa, ya, 1, xb, yb, 1, xc, yc, 1 );
570   QTransform aTransform2( xta, yta, 1, xtb, ytb, 1, xtc, ytc, 1 );
571
572   bool anIsInvertible = false;
573   QTransform aTransform1Inverted = aTransform1.inverted( &anIsInvertible );
574   if( !anIsInvertible )
575     return;
576
577   QTransform aResTransform = aTransform1Inverted * aTransform2;
578   if( anIsRefImage )
579     aResTransform *= aRefTransform;
580
581   SetTrsf( aResTransform );
582 }
583
584 bool HYDROData_Image::IsByTwoPoints() const
585 {
586   if ( !HasLocalPoints() || !HasGlobalPoints() )
587     return false;
588
589   QPoint aPointA, aPointB, aPointC;
590   GetLocalPoints( aPointA, aPointB, aPointC );
591
592   return aPointC.x() < 0 && aPointC.y() < 0; 
593 }
594
595 bool HYDROData_Image::HasReferences() const
596 {
597   Handle(HYDROData_Image) aRefImage = GetTrsfReferenceImage();
598   int aNbReferences = NbReferences();
599
600   return !aRefImage.IsNull() || aNbReferences > 0;
601 }
602
603 void HYDROData_Image::RemoveAllReferences()
604 {
605   if ( !HasReferences() )
606     return;
607
608   Handle(HYDROData_Image) aRefImage = GetTrsfReferenceImage();
609   if ( !aRefImage.IsNull() )
610   {
611     RemoveTrsfReferenceImage();
612   }
613   else
614   {
615     ClearReferences();
616     SetOperatorName( "" );
617     SetArgs( "" );
618     SetIsSelfSplit( false );
619   }
620
621   bool anIsByTwoPoints = IsByTwoPoints();
622
623   QImage anImage = Image();
624   if ( anImage.isNull() )
625   {
626     ClearChanged();
627     return;
628   }
629
630   // Set local points to default position
631   QPoint aLocalPointA = QPoint( 0, 0 );
632   QPoint aLocalPointB = QPoint( anImage.width(), 0 );
633   QPoint aLocalPointC = anIsByTwoPoints ? QPoint( INT_MIN, INT_MIN ) : QPoint( 0, anImage.height() );
634
635   SetLocalPoints( aLocalPointA, aLocalPointB, aLocalPointC, false );
636
637   // Calculate global points
638   QTransform aTransform = Trsf();
639
640   QPointF aTrsfPointA = QPointF( aTransform.map( aLocalPointA ) );
641   QPointF aTrsfPointB = QPointF( aTransform.map( aLocalPointB ) );
642   QPointF aTrsfPointC = anIsByTwoPoints ? QPointF( INT_MIN, INT_MIN ) : 
643                                           QPointF( aTransform.map( aLocalPointC ) );
644
645   SetGlobalPoints( ManualCartesian, aTrsfPointA, aTrsfPointB, aTrsfPointC );
646
647   ClearChanged();
648 }
649
650 void HYDROData_Image::SetLocalPoints( const QPoint& thePointA,
651                                       const QPoint& thePointB,
652                                       const QPoint& thePointC,
653                                       const bool    theIsUpdate )
654 {
655   Handle(TDataStd_RealArray) anArray;
656   if ( !myLab.FindChild( DataTag_TrsfPoints ).FindAttribute( TDataStd_RealArray::GetID(), anArray ) )
657   {
658     anArray = TDataStd_RealArray::Set( myLab.FindChild( DataTag_TrsfPoints ), 1, 12 );
659     anArray->SetID(TDataStd_RealArray::GetID());
660   }
661
662   anArray->SetValue( 1, thePointA.x() );
663   anArray->SetValue( 2, thePointA.y() );
664   anArray->SetValue( 3, thePointB.x() );
665   anArray->SetValue( 4, thePointB.y() );
666   anArray->SetValue( 5, thePointC.x() );
667   anArray->SetValue( 6, thePointC.y() );
668
669   TDataStd_UAttribute::Set( myLab.FindChild( DataTag_TrsfPoints ), GUID_HAS_LOCAL_POINTS );
670
671   if ( theIsUpdate )
672     UpdateTrsf();
673
674   Changed( Geom_2d );
675 }
676
677 bool HYDROData_Image::GetLocalPoints( QPoint& thePointA,
678                                       QPoint& thePointB,
679                                       QPoint& thePointC ) const
680 {
681   if ( !HasLocalPoints() )
682     return false;
683
684   Handle(TDataStd_RealArray) anArray;
685   myLab.FindChild( DataTag_TrsfPoints ).FindAttribute( TDataStd_RealArray::GetID(), anArray );
686
687   thePointA = QPointF( anArray->Value( 1 ), anArray->Value( 2 ) ).toPoint();
688   thePointB = QPointF( anArray->Value( 3 ), anArray->Value( 4 ) ).toPoint();
689   thePointC = QPointF( anArray->Value( 5 ), anArray->Value( 6 ) ).toPoint();
690
691   return true;
692 }
693
694 bool HYDROData_Image::HasLocalPoints() const
695 {
696   TDF_Label aLabel = myLab.FindChild( DataTag_TrsfPoints, false );
697   if ( aLabel.IsNull() || !aLabel.IsAttribute( GUID_HAS_LOCAL_POINTS ) )
698     return false;
699
700   Handle(TDataStd_RealArray) anArray;
701   return aLabel.FindAttribute( TDataStd_RealArray::GetID(), anArray );
702 }
703
704
705 void HYDROData_Image::SetGlobalPoints( const TransformationMode& theMode,
706                                        const QPointF&            thePointA,
707                                        const QPointF&            thePointB,
708                                        const QPointF&            thePointC,
709                                        const bool                theIsUpdate )
710 {
711   Handle(TDataStd_RealArray) anArray;
712   if ( !myLab.FindChild( DataTag_TrsfPoints ).FindAttribute( TDataStd_RealArray::GetID(), anArray ) )
713   {
714     anArray = TDataStd_RealArray::Set( myLab.FindChild( DataTag_TrsfPoints ), 1, 12 );
715     anArray->SetID(TDataStd_RealArray::GetID());
716   }
717
718   anArray->SetValue( 7,  thePointA.x() );
719   anArray->SetValue( 8,  thePointA.y() );
720   anArray->SetValue( 9,  thePointB.x() );
721   anArray->SetValue( 10, thePointB.y() );
722   anArray->SetValue( 11, thePointC.x() );
723   anArray->SetValue( 12, thePointC.y() );
724   
725   SetTrsfMode( theMode );
726
727   TDataStd_UAttribute::Set( myLab.FindChild( DataTag_TrsfPoints ), GUID_HAS_GLOBAL_POINTS );
728
729   if ( theIsUpdate )
730     UpdateTrsf();
731
732   Changed( Geom_2d );
733 }
734
735 bool HYDROData_Image::GetGlobalPoints( TransformationMode& theMode,
736                                        QPointF&            thePointA,
737                                        QPointF&            thePointB,
738                                        QPointF&            thePointC ) const
739 {
740   if ( !HasGlobalPoints() )
741     return false;
742
743   theMode = GetTrsfMode();
744
745   Handle(TDataStd_RealArray) anArray;
746   myLab.FindChild( DataTag_TrsfPoints ).FindAttribute( TDataStd_RealArray::GetID(), anArray );
747
748   thePointA = QPointF( anArray->Value( 7  ), anArray->Value( 8  ) );
749   thePointB = QPointF( anArray->Value( 9  ), anArray->Value( 10 ) );
750   thePointC = QPointF( anArray->Value( 11 ), anArray->Value( 12 ) );
751
752   return true;
753 }
754
755 bool HYDROData_Image::SetGlobalPointsFromFile( const QString& theFileName )
756 {
757   bool aRes = false;
758
759   // Try to open the file
760   QFile aFile( theFileName );
761   if ( !aFile.exists() || !aFile.open( QIODevice::ReadOnly ) ) {
762     return aRes;
763   }
764
765   QPointF aPointA, aPointB;
766   double aXmin, anYmin, aXmax, anYmax;
767   aXmin = anYmin = aXmax = anYmax = -1;
768
769   while ( !aFile.atEnd() && 
770           ( aXmin < 0 || anYmin < 0 || aXmax < 0 || anYmax < 0 ) ) {
771     // Read line
772     QString aLine = aFile.readLine().simplified();
773     aLine.replace( " ", "" );
774     if ( aLine.isEmpty() ) {
775       continue;
776     }
777
778     // Try to read double value after ":"
779     bool isDoubleOk = false;
780     double aDoubleValue = -1;
781     QStringList aValues = aLine.split( ":", QString::SkipEmptyParts );
782     if ( aValues.count() == 2 ) {
783       aDoubleValue = aValues.last().toDouble( &isDoubleOk );
784     }
785
786     // Check the result
787     if ( !isDoubleOk ||
788          HYDROData_Tool::IsNan( aDoubleValue ) ||
789          HYDROData_Tool::IsInf( aDoubleValue ) ) {
790       continue;
791     }
792
793     // Set the value
794     if ( aLine.startsWith( "Xminimum" ) ) {
795       aXmin = aDoubleValue;    
796     } 
797     else if ( aLine.startsWith( "Yminimum" ) ) {
798       anYmin = aDoubleValue; 
799     }
800     else if ( aLine.startsWith( "Xmaximum" ) ) {
801       aXmax = aDoubleValue;
802     }
803     else if ( aLine.startsWith( "Ymaximum" ) ) {
804       anYmax = aDoubleValue;  
805     }
806   }
807
808   // Close the file
809   aFile.close();
810
811   if ( aXmin >= 0 && anYmin >= 0 ) {
812     aPointA.setX( aXmin );
813     aPointA.setY( anYmin );
814   }
815     
816   if ( aXmax >= 0 && anYmax >= 0 ) {
817     aPointB.setX( aXmax );
818     aPointB.setY( anYmax );
819   }
820
821   if ( !aPointA.isNull() && !aPointB.isNull() ) {
822     SetGlobalPoints( ManualCartesian, aPointA, aPointB );
823     aRes = true;
824   }
825
826   return aRes;
827 }
828
829 bool HYDROData_Image::HasGlobalPoints() const
830 {
831   TDF_Label aLabel = myLab.FindChild( DataTag_TrsfPoints, false );
832   if ( aLabel.IsNull() || !aLabel.IsAttribute( GUID_HAS_GLOBAL_POINTS ) )
833     return false;
834
835   Handle(TDataStd_RealArray) anArray;
836   return aLabel.FindAttribute( TDataStd_RealArray::GetID(), anArray );
837 }
838
839 void HYDROData_Image::SetReferencePoints( const Handle(HYDROData_Image)& theRefImage,
840                                           const QPointF&                 thePointA,
841                                           const QPointF&                 thePointB,
842                                           const QPointF&                 thePointC,
843                                           const bool                     theIsUpdate )
844 {
845   SetTrsfReferenceImage( theRefImage );
846   SetGlobalPoints( ReferenceImage, thePointA, thePointB, thePointC, theIsUpdate );
847 }
848
849 bool HYDROData_Image::GetReferencePoints( Handle(HYDROData_Image)& theRefImage,
850                                           QPointF&                 thePointA,
851                                           QPointF&                 thePointB,
852                                           QPointF&                 thePointC ) const
853 {
854   if ( !HasReferencePoints() )
855     return false;
856
857   theRefImage = GetTrsfReferenceImage();
858
859   TransformationMode aMode;
860   GetGlobalPoints( aMode, thePointA, thePointB, thePointC );
861
862   return true;
863 }
864
865 bool HYDROData_Image::HasReferencePoints() const
866 {
867   if ( !HasGlobalPoints() )
868     return false;
869
870   Handle(HYDROData_Image) aRefImage = GetTrsfReferenceImage();
871   if ( aRefImage.IsNull() )
872     return false;
873
874   TransformationMode aTrsfMode = GetTrsfMode();
875   if ( aTrsfMode != ReferenceImage )
876     return false;
877
878   return true;
879 }
880
881 void HYDROData_Image::SetTrsfMode( const TransformationMode& theMode )
882 {
883   Handle(TDataStd_Integer) anAttr = TDataStd_Integer::Set( myLab.FindChild( DataTag_TrsfMode ), (int)theMode );
884   anAttr->SetID(TDataStd_Integer::GetID());
885   Changed( Geom_2d );
886 }
887
888 HYDROData_Image::TransformationMode HYDROData_Image::GetTrsfMode() const
889 {
890   TransformationMode aResMode = ManualGeodesic;
891
892   TDF_Label aLabel = myLab.FindChild( DataTag_TrsfPoints, false );
893   if ( !aLabel.IsNull() )
894   {
895     Handle(TDataStd_Integer) aMode;
896     if ( myLab.FindChild( DataTag_TrsfMode ).FindAttribute( TDataStd_Integer::GetID(), aMode ) )
897       aResMode = (TransformationMode)aMode->Get();
898   }
899
900   return aResMode;
901 }
902
903 void HYDROData_Image::SetTrsfReferenceImage( const Handle(HYDROData_Image)& theRefImage )
904 {
905   SetReferenceObject( theRefImage, DataTag_TrsfImage );
906   Changed( Geom_2d );
907 }
908
909 Handle(HYDROData_Image) HYDROData_Image::GetTrsfReferenceImage() const
910 {
911   return Handle(HYDROData_Image)::DownCast( GetReferenceObject( DataTag_TrsfImage ) );
912 }
913
914 void HYDROData_Image::RemoveTrsfReferenceImage()
915 {
916   RemoveReferenceObject( DataTag_TrsfImage );
917   Changed( Geom_2d );
918 }
919
920 void HYDROData_Image::AppendReference( const Handle(HYDROData_Entity)& theReferenced )
921 {
922   AddReferenceObject( theReferenced, 0 );
923   Changed( Geom_2d );
924 }
925
926 int HYDROData_Image::NbReferences() const
927 {
928   return NbReferenceObjects( 0 );
929 }
930
931 Handle(HYDROData_Entity) HYDROData_Image::Reference( const int theIndex ) const
932 {
933   return GetReferenceObject( 0, theIndex );
934 }
935
936 void HYDROData_Image::ChangeReference(
937     const int theIndex, Handle(HYDROData_Entity) theReferenced)
938 {
939   SetReferenceObject( theReferenced, 0, theIndex );
940   Changed( Geom_2d );
941 }
942
943 void HYDROData_Image::RemoveReference(const int theIndex)
944 {
945   RemoveReferenceObject( 0, theIndex );
946   Changed( Geom_2d );
947 }
948
949 void HYDROData_Image::ClearReferences()
950 {
951   ClearReferenceObjects( 0 );
952   Changed( Geom_2d );
953 }
954
955 void HYDROData_Image::SetOperatorName( const QString theOpName )
956 {
957   TCollection_AsciiString anAsciiStr( theOpName.toStdString().c_str() );
958   Handle(TDataStd_AsciiString) anAttr = TDataStd_AsciiString::Set( myLab.FindChild( DataTag_Operator ), anAsciiStr );
959   anAttr->SetID(TDataStd_AsciiString::GetID());
960   Changed( Geom_2d );
961 }
962
963 QString HYDROData_Image::OperatorName() const
964 {
965   QString aRes;
966
967   TDF_Label aLabel = myLab.FindChild( DataTag_Operator, false );
968   if ( !aLabel.IsNull() )
969   {
970     Handle(TDataStd_AsciiString) anAsciiStr;
971     if ( aLabel.FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
972       aRes = QString( anAsciiStr->Get().ToCString() );
973   }
974
975   return aRes;
976 }
977
978 void HYDROData_Image::SetArgs(const QByteArray& theArgs)
979 {
980   SaveByteArray(DataTag_Operator, theArgs.constData(), theArgs.length());
981   Changed( Geom_2d );
982 }
983
984 QByteArray HYDROData_Image::Args() const
985 {
986   int aLen = 0;
987   const char* aData = ByteArray(DataTag_Operator, aLen);
988   if (!aLen)
989     return QByteArray();
990   return QByteArray(aData, aLen);
991 }
992
993 void HYDROData_Image::SetIsSelfSplit(bool theFlag)
994 {
995   if (theFlag) {
996     TDataStd_UAttribute::Set(myLab, GUID_SELF_SPLIT);
997   } else {
998     myLab.ForgetAttribute(GUID_SELF_SPLIT);
999   }
1000   Changed( Geom_2d );
1001 }
1002
1003 bool HYDROData_Image::IsSelfSplit() const
1004 {
1005   return myLab.IsAttribute(GUID_SELF_SPLIT);
1006 }
1007
1008 QPointF HYDROData_Image::generateThirdPoint( const QPointF& thePointA,
1009                                              const QPointF& thePointB,
1010                                              const bool&    theIsLocal ) const
1011 {
1012   // Rotate vector to 90 degrees : clockwise - for local
1013   //                               counterclockwise - for global
1014   const double aTheta = theIsLocal ? -M_PI_2 : M_PI_2;
1015
1016   QPointF aResPoint;
1017
1018   // Move to (0,0) for correct rotation
1019   double x = thePointB.x() - thePointA.x();
1020   double y = thePointB.y() - thePointA.y();
1021
1022   aResPoint.setX( x * cos( aTheta ) - y * sin( aTheta ) );
1023   aResPoint.setY( x * sin( aTheta ) + y * cos( aTheta ) );
1024
1025   // Move back to origin position
1026   aResPoint.setX( aResPoint.x() + thePointA.x() );
1027   aResPoint.setY( aResPoint.y() + thePointA.y() );
1028
1029   return aResPoint;
1030 }
1031