Salome HOME
Naming functions were from FeaturesPlugin_Tools to ModelAPI_Tools
[modules/shaper.git] / src / ModelAPI / ModelAPI_Tools.cpp
1 // Copyright (C) 2014-2021  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <ModelAPI_AttributeBoolean.h>
21 #include <ModelAPI_AttributeDocRef.h>
22 #include <ModelAPI_AttributeDouble.h>
23 #include <ModelAPI_AttributeIntArray.h>
24 #include <ModelAPI_AttributeSelectionList.h>
25 #include <ModelAPI_CompositeFeature.h>
26 #include <ModelAPI_Document.h>
27 #include <ModelAPI_Events.h>
28 #include <ModelAPI_Object.h>
29 #include <ModelAPI_ResultBody.h>
30 #include <ModelAPI_ResultConstruction.h>
31 #include <ModelAPI_ResultGroup.h>
32 #include <ModelAPI_ResultParameter.h>
33 #include <ModelAPI_ResultPart.h>
34 #include <ModelAPI_Session.h>
35 #include "ModelAPI_Tools.h"
36 #include <ModelAPI_Validator.h>
37
38 #include <Config_Translator.h>
39 #include <Events_Loop.h>
40 #include <Locale_Convert.h>
41
42 #include <GeomAlgoAPI_MakeShape.h>
43 #include <GeomAPI_ShapeHierarchy.h>
44 #include <GeomAPI_ShapeIterator.h>
45
46 #include <algorithm>
47 #include <iostream>
48 #include <list>
49 #include <map>
50 #include <sstream>
51 #include <vector>
52 #include <array>
53
54 #define RECURSE_TOP_LEVEL 50
55
56 //#define DEBUG_REMOVE_FEATURES
57 //#define DEBUG_REMOVE_FEATURES_RECURSE
58 //#define DEBUG_CYCLING_1550
59
60 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
61 #include <sstream>
62 std::string getFeatureInfo(FeaturePtr theFeature)
63 {
64   if (!theFeature.get())
65     return "";
66   //std::ostringstream aPtrStr;
67   //aPtrStr << "[" << theFeature.get() << "] ";
68   std::string aFeatureInfo = /*aPtrStr.str() + */theFeature->name();
69   CompositeFeaturePtr aComposite = ModelAPI_Tools::compositeOwner(theFeature);
70   if (aComposite.get()) {
71       aFeatureInfo = aFeatureInfo + "[in " + aComposite->name() + "]";
72   }
73   return aFeatureInfo;
74 }
75 #endif
76
77 #ifdef DEBUG_REMOVE_FEATURES
78 void printMapInfo(const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
79                   const std::string& thePrefix)
80 {
81   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = theMainList.begin(),
82                                                               aMainLast = theMainList.end();
83   std::string anInfo;
84   for (; aMainIt != aMainLast; aMainIt++) {
85     FeaturePtr aMainListFeature = aMainIt->first;
86     std::set<FeaturePtr> aMainRefList = aMainIt->second;
87     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(), aLast = aMainRefList.end();
88     std::string aRefsInfo;
89     for (; anIt != aLast; anIt++) {
90       aRefsInfo += (*anIt)->name().c_str();
91       if (anIt != aLast)
92         aRefsInfo += ", ";
93     }
94     if (!aRefsInfo.empty()) {
95       anInfo = anInfo + aMainListFeature->name().c_str() + ": " + aRefsInfo + "\n";
96     }
97   }
98   std::cout << thePrefix.c_str() << " [feature: references to]: \n" << anInfo.c_str() << std::endl;
99 }
100
101 void printListInfo(const std::set<FeaturePtr>& theMainList,
102                   const std::string& thePrefix)
103 {
104   std::set<FeaturePtr>::const_iterator aMainIt = theMainList.begin(),
105                                        aMainLast = theMainList.end();
106   std::string anInfo;
107   for (; aMainIt != aMainLast; aMainIt++) {
108     FeaturePtr aRefFeature = *aMainIt;
109     anInfo += aRefFeature->name().c_str();
110     if (aMainIt != aMainLast)
111       anInfo += ", ";
112   }
113   std::cout << thePrefix.c_str() << ": " << anInfo.c_str() << std::endl;
114 }
115 #endif
116
117 namespace ModelAPI_Tools {
118
119 std::shared_ptr<GeomAPI_Shape> shape(const ResultPtr& theResult)
120 {
121   return theResult->shape();
122 }
123
124 // LCOV_EXCL_START
125 const char* toString(ModelAPI_ExecState theExecState)
126 {
127   switch (theExecState) {
128   case ModelAPI_StateDone: return "Done";
129   case ModelAPI_StateMustBeUpdated: return "Must be updated";
130   case ModelAPI_StateExecFailed: return "Execution failed";
131   case ModelAPI_StateInvalidArgument: return "Invalid argument";
132   case ModelAPI_StateNothing: return "Empty state";
133   default: return "Unknown ExecState.";
134   }
135 }
136
137 std::string getFeatureError(const FeaturePtr& theFeature)
138 {
139   std::string anError;
140   if (!theFeature.get() || !theFeature->data()->isValid() || theFeature->isAction())
141     return anError;
142
143   // to be removed later, this error should be got from the feature
144   if (theFeature->data()->execState() == ModelAPI_StateDone ||
145       theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
146     return anError;
147
148   // set error indication
149   anError = theFeature->error();
150   if (anError.empty()) {
151     bool isDone = ( theFeature->data()->execState() == ModelAPI_StateDone
152                  || theFeature->data()->execState() == ModelAPI_StateMustBeUpdated );
153     if (!isDone) {
154       anError = toString(theFeature->data()->execState());
155       // If the feature is Composite and error is StateInvalidArgument,
156       // error text should include error of first invalid sub-feature. Otherwise
157       // it is not clear what is the reason of the invalid argument.
158       if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
159         CompositeFeaturePtr aComposite =
160                     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
161         if (aComposite) {
162           bool aHasSubError = false;
163           for (int i = 0, aSize = aComposite->numberOfSubs(); i < aSize; i++) {
164             FeaturePtr aSubFeature = aComposite->subFeature(i);
165             std::string aSubFeatureError = getFeatureError(aSubFeature);
166             if (!aSubFeatureError.empty()) {
167               anError = anError + " in " + aSubFeature->getKind() + ".\n" + aSubFeatureError;
168               aHasSubError = true;
169               break;
170             }
171           }
172           if (!aHasSubError) { // #24260: error not in the sub-features, but in the argument
173             if (aComposite->getKind() == "Sketch" &&
174                 aComposite->selection("External")->isInvalid()) {
175               std::string aMsg = "The sketch base plane is invalid, ";
176               aMsg += "please push 'Change sketch plane' button to reselect it.";
177               anError = Config_Translator::translate(aComposite->getKind(), aMsg);
178             }
179           }
180         }
181       }
182     }
183   }
184
185   return anError;
186 }
187 // LCOV_EXCL_STOP
188
189 ObjectPtr objectByName(const DocumentPtr& theDocument, const std::string& theGroup,
190                        const std::wstring& theName)
191 {
192   for (int anIndex = 0; anIndex < theDocument->size(theGroup); ++anIndex) {
193     ObjectPtr anObject = theDocument->object(theGroup, anIndex);
194     if (anObject->data()->name() == theName)
195       return anObject;
196   }
197   // not found
198   return ObjectPtr();
199 }
200
201 //==================================================================================================
202 void loadModifiedShapes(ResultBodyPtr theResultBody,
203                         const ListOfShape& theBaseShapes,
204                         const ListOfShape& theTools,
205                         const GeomMakeShapePtr& theMakeShape,
206                         const GeomShapePtr theResultShape,
207                         const std::string& theNamePrefix)
208 {
209   theResultBody->storeModified(theBaseShapes, theResultShape, theMakeShape);
210
211   ListOfShape aShapes = theBaseShapes;
212   ListOfShape::const_iterator aToolIter = theTools.cbegin();
213   for (; aToolIter != theTools.cend(); aToolIter++)
214     aShapes.push_back(*aToolIter);
215
216   for (ListOfShape::const_iterator anIter = aShapes.begin(); anIter != aShapes.end(); ++anIter)
217   {
218     theResultBody->loadModifiedShapes(theMakeShape, *anIter, GeomAPI_Shape::VERTEX, theNamePrefix);
219     theResultBody->loadModifiedShapes(theMakeShape, *anIter, GeomAPI_Shape::EDGE, theNamePrefix);
220     theResultBody->loadModifiedShapes(theMakeShape, *anIter, GeomAPI_Shape::FACE, theNamePrefix);
221   }
222 }
223
224 //==================================================================================================
225 void loadModifiedShapes(ResultBodyPtr theResultBody,
226                         const GeomShapePtr& theBaseShape,
227                         const GeomMakeShapePtr& theMakeShape,
228                         const std::string theName)
229 {
230   switch (theBaseShape->shapeType()) {
231   case GeomAPI_Shape::COMPOUND: {
232     for (GeomAPI_ShapeIterator anIt(theBaseShape); anIt.more(); anIt.next())
233     {
234       loadModifiedShapes(theResultBody,
235         anIt.current(),
236         theMakeShape,
237         theName);
238     }
239     break;
240   }
241   case GeomAPI_Shape::COMPSOLID:
242   case GeomAPI_Shape::SOLID:
243   case GeomAPI_Shape::SHELL: {
244     theResultBody->loadModifiedShapes(theMakeShape,
245       theBaseShape,
246       GeomAPI_Shape::FACE,
247       theName);
248   }
249   case GeomAPI_Shape::FACE:
250   case GeomAPI_Shape::WIRE: {
251     theResultBody->loadModifiedShapes(theMakeShape,
252       theBaseShape,
253       GeomAPI_Shape::EDGE,
254       theName);
255   }
256   case GeomAPI_Shape::EDGE: {
257     theResultBody->loadModifiedShapes(theMakeShape,
258       theBaseShape,
259       GeomAPI_Shape::VERTEX,
260       theName);
261   }
262   default: // [to avoid compilation warning]
263     break;
264   }
265 }
266
267 //==================================================================================================
268 void loadDeletedShapes(ResultBodyPtr theResultBody,
269                       const GeomShapePtr theBaseShape,
270                       const ListOfShape& theTools,
271                       const GeomMakeShapePtr& theMakeShape,
272                       const GeomShapePtr theResultShapesCompound)
273 {
274   ListOfShape aShapes = theTools;
275   if (theBaseShape.get())
276     aShapes.push_front(theBaseShape);
277
278   for (ListOfShape::const_iterator anIter = aShapes.begin(); anIter != aShapes.end(); anIter++)
279   {
280     theResultBody->loadDeletedShapes(theMakeShape,
281       *anIter,
282       GeomAPI_Shape::VERTEX,
283       theResultShapesCompound);
284     theResultBody->loadDeletedShapes(theMakeShape,
285       *anIter,
286       GeomAPI_Shape::EDGE,
287       theResultShapesCompound);
288     theResultBody->loadDeletedShapes(theMakeShape,
289       *anIter,
290       GeomAPI_Shape::FACE,
291       theResultShapesCompound);
292     // store information about deleted solids because of unittest TestBooleanCommon_SolidsHistory
293     // on OCCT 7.4.0 : common produces modified compsolid, so, move to the end for removed solids
294     // starts to produce whole compsolid
295     theResultBody->loadDeletedShapes(theMakeShape,
296       *anIter,
297       GeomAPI_Shape::SOLID,
298       theResultShapesCompound);
299   }
300 }
301
302 //==================================================================================================
303 void loadDeletedShapes(std::vector<ResultBaseAlgo>& theResultBaseAlgoList,
304                         const ListOfShape& theTools,
305                         const GeomShapePtr theResultShapesCompound)
306 {
307   for (std::vector<ResultBaseAlgo>::iterator anIt = theResultBaseAlgoList.begin();
308     anIt != theResultBaseAlgoList.end();
309     ++anIt)
310   {
311     ResultBaseAlgo& aRCA = *anIt;
312     loadDeletedShapes(aRCA.resultBody,
313       aRCA.baseShape,
314       theTools,
315       aRCA.makeShape,
316       theResultShapesCompound);
317   }
318 }
319
320 bool findVariable(const DocumentPtr& theDocument, FeaturePtr theSearcher,
321                   const std::wstring& theName, double& outValue, ResultParameterPtr& theParam)
322 {
323   ObjectPtr aParamObj = objectByName(theDocument, ModelAPI_ResultParameter::group(), theName);
324   theParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aParamObj);
325   if (!theParam.get())
326     return false;
327   // avoid usage of parameters created later than the initial parameter
328
329   if (theSearcher.get()) {
330     FeaturePtr aParamFeat = theDocument->feature(theParam);
331     if (aParamFeat == theSearcher || theDocument->isLater(aParamFeat, theSearcher))
332       return false;
333   }
334   AttributeDoublePtr aValueAttribute = theParam->data()->real(ModelAPI_ResultParameter::VALUE());
335   outValue = aValueAttribute->value();
336   return true;
337 }
338
339 bool findVariable(FeaturePtr theSearcher, const std::wstring& theName, double& outValue,
340                   ResultParameterPtr& theParam, const DocumentPtr& theDocument)
341 {
342   SessionPtr aSession = ModelAPI_Session::get();
343   std::list<DocumentPtr> aDocList;
344   DocumentPtr aDocument = theDocument.get() ? theDocument : aSession->activeDocument();
345   if (findVariable(aDocument, theSearcher, theName, outValue, theParam))
346     return true;
347   DocumentPtr aRootDocument = aSession->moduleDocument();
348   if (aDocument != aRootDocument) {
349     // any parameters in PartSet is okindependently on the Part position (issu #1504)
350     if (findVariable(aRootDocument, FeaturePtr(), theName, outValue, theParam))
351       return true;
352   }
353   return false;
354 }
355
356 ResultPtr findPartResult(const DocumentPtr& theMain, const DocumentPtr& theSub)
357 {
358   // to optimize and avoid of crash on partset document close
359   // (don't touch the sub-document structure)
360   if (theMain != theSub) {
361     for (int a = theMain->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
362       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
363           theMain->object(ModelAPI_ResultPart::group(), a));
364       if (aPart && aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->value() == theSub) {
365         return aPart;
366       }
367     }
368   }
369   return ResultPtr();
370 }
371
372 FeaturePtr findPartFeature(const DocumentPtr& theMain, const DocumentPtr& theSub)
373 {
374   // to optimize and avoid of crash on partset document close
375   // (don't touch the sub-document structure)
376   if (theMain != theSub) {
377     // iteration from top to bottom to avoid finding the movement documents before the original
378     int aSize = theMain->size(ModelAPI_Feature::group());
379     for (int a = 0; a < aSize; a++) {
380       FeaturePtr aPartFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(
381           theMain->object(ModelAPI_Feature::group(), a));
382       if (aPartFeat.get()) {
383         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aPartFeat->results();
384         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
385         for(; aRes != aResList.end(); aRes++) {
386           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
387           if (aPart.get()) {
388             if (aPart->isActivated() && aPart->partDoc() == theSub)
389               return aPartFeat;
390           } else break; // if the first is not Part, others are also not
391         }
392       }
393     }
394   }
395   return FeaturePtr();
396 }
397
398 CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
399 {
400   if (theFeature.get() && theFeature->data() && theFeature->data()->isValid()) {
401     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
402     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.begin();
403     for(; aRefIter != aRefs.end(); aRefIter++) {
404       CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>
405         ((*aRefIter)->owner());
406       if (aComp.get() && aComp->data()->isValid() && aComp->isSub(theFeature))
407         return aComp;
408     }
409   }
410   return CompositeFeaturePtr(); // not found
411 }
412
413 ResultBodyPtr bodyOwner(const ResultPtr& theSub, const bool theRoot)
414 {
415   if (theSub.get()) {
416     ObjectPtr aParent = theSub->document()->parent(theSub);
417     if (aParent.get()) {
418       if (theRoot) { // try to find parent of parent
419         ResultPtr aResultParent = std::dynamic_pointer_cast<ModelAPI_Result>(aParent);
420         ResultBodyPtr aGrandParent = bodyOwner(aResultParent, true);
421         if (aGrandParent.get())
422           aParent = aGrandParent;
423       }
424       return std::dynamic_pointer_cast<ModelAPI_ResultBody>(aParent);
425     }
426   }
427   return ResultBodyPtr(); // not found
428 }
429
430 int bodyIndex(const ResultPtr& theSub)
431 {
432   int anIndex = -1;
433   ResultBodyPtr aParent = bodyOwner(theSub);
434   if (aParent.get()) {
435     ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
436     if (aBody.get() && aParent->isSub(aBody, anIndex))
437       return anIndex;
438   }
439   return anIndex; // not found
440 }
441
442 bool hasSubResults(const ResultPtr& theResult)
443 {
444   ResultBodyPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
445   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
446 }
447
448 void allSubs(const ResultBodyPtr& theResult, std::list<ResultPtr>& theResults,
449              const bool theLowerOnly) {
450   // iterate sub-bodies of compsolid
451   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
452   if (aComp.get()) {
453     int aNumSub = aComp->numberOfSubs();
454     for (int a = 0; a < aNumSub; a++) {
455       ResultBodyPtr aSub = aComp->subResult(a);
456       if (!theLowerOnly || aSub->numberOfSubs() == 0)
457         theResults.push_back(aSub);
458       allSubs(aSub, theResults);
459     }
460   }
461 }
462
463 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
464 {
465   if (!theFeature.get()) // safety: for empty feature no results
466     return;
467   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
468   std::list<ResultPtr>::const_iterator aRIter = aResults.begin();
469   for (; aRIter != aResults.cend(); aRIter++) {
470     theResults.push_back(*aRIter);
471     ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRIter);
472     allSubs(aResult, theResults);
473   }
474 }
475
476 //******************************************************************
477 bool allDocumentsActivated(std::wstring& theNotActivatedNames)
478 {
479   theNotActivatedNames = L"";
480   bool anAllPartActivated = true;
481
482   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
483   int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
484   for (int i = 0; i < aSize; i++) {
485     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
486     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
487     if (!aPart->isActivated()) {
488       anAllPartActivated = false;
489       if (!theNotActivatedNames.empty())
490         theNotActivatedNames += L", ";
491       theNotActivatedNames += aObject->data()->name().c_str();
492     }
493   }
494   return anAllPartActivated;
495 }
496
497 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
498                                  const bool /*theFlushRedisplay*/,
499                                  const bool theUseComposite,
500                                  const bool theUseRecursion)
501 {
502 #ifdef DEBUG_REMOVE_FEATURES
503   printListInfo(theFeatures, "selection: ");
504 #endif
505
506   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
507   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
508 #ifdef DEBUG_REMOVE_FEATURES
509   printMapInfo(aReferences, "allDependencies: ");
510 #endif
511
512   std::set<FeaturePtr> aFeaturesRefsTo;
513   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
514 #ifdef DEBUG_REMOVE_FEATURES
515   printListInfo(aFeaturesRefsTo, "references: ");
516 #endif
517
518   std::set<FeaturePtr> aFeatures = theFeatures;
519   if (!aFeaturesRefsTo.empty())
520     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
521 #ifdef DEBUG_REMOVE_FEATURES
522   printListInfo(aFeatures, "removeFeatures: ");
523 #endif
524
525   return ModelAPI_Tools::removeFeatures(aFeatures, false);
526 }
527
528 //***********************************************************************
529 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
530                     const bool theFlushRedisplay)
531 {
532   bool isDone = false;
533   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
534                                        aLast = theFeatures.end();
535   for (; anIt != aLast; anIt++) {
536     FeaturePtr aFeature = *anIt;
537     if (aFeature.get()) {
538       DocumentPtr aDoc = aFeature->document();
539       // flush REDISPLAY signal after remove feature
540       aDoc->removeFeature(aFeature);
541       isDone = true;
542     }
543   }
544   if (isDone && theFlushRedisplay) {
545     // the redisplay signal should be flushed in order to erase
546     // the feature presentation in the viewer
547     // if should be done after removeFeature() of document
548     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
549   }
550   return true;
551 }
552
553 //***********************************************************************
554 // Fills the references list by all references of the feature from the references map.
555 // This is a recusive method to find references by next found feature in the map of references.
556 // \param theFeature a feature to find references
557 // \param theReferencesMap a map of references
558 // \param theReferences an out container of references
559 void addRefsToFeature(const FeaturePtr& theFeature,
560                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
561                       int theRecLevel,
562                       std::set<FeaturePtr>& theReferences)
563 {
564   if (theRecLevel > RECURSE_TOP_LEVEL)
565     return;
566   theRecLevel++;
567
568   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
569     return; // this feature is not in the selection list, so exists without references to it
570   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
571
572   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
573                                        aLast = aMainReferences.end();
574   for (; anIt != aLast; anIt++) {
575     FeaturePtr aRefFeature = *anIt;
576     if (theReferences.find(aRefFeature) == theReferences.end()) {
577       addRefsToFeature(aRefFeature, theReferencesMap, theRecLevel, theReferences);
578       theReferences.insert(aRefFeature);
579     }
580   }
581 }
582
583 // For each feature from the feature list it searches references to the feature and append them
584 // to the references map. This is a recusive method.
585 // \param theFeature a feature to find references
586 // \param theReferencesMap a map of references
587 // \param theReferences an out container of references
588 void findReferences(const std::set<FeaturePtr>& theFeatures,
589                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
590                     const bool theUseComposite, const bool theUseRecursion, int theRecLevel)
591 {
592   if (theRecLevel > RECURSE_TOP_LEVEL)
593     return;
594   theRecLevel++;
595   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
596                                         aLast = theFeatures.end();
597   for (; anIt != aLast; anIt++) {
598     FeaturePtr aFeature = *anIt;
599     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
600       DocumentPtr aSelFeatureDoc = aFeature->document();
601       std::set<FeaturePtr> aSelRefFeatures;
602       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
603       if (theUseComposite) { // do not filter selection
604         theReferences[aFeature] = aSelRefFeatures;
605       }
606       else { // filter references to skip composition features of the current feature
607         std::set<FeaturePtr> aFilteredFeatures;
608         std::set<FeaturePtr>::const_iterator aRefIt = aSelRefFeatures.begin(),
609                                              aRefLast = aSelRefFeatures.end();
610         for (; aRefIt != aRefLast; aRefIt++) {
611           FeaturePtr aCFeature = *aRefIt;
612           CompositeFeaturePtr aComposite =
613             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
614           if (aComposite.get() && aComposite->isSub(aFeature))
615             continue; /// composite of the current feature should be skipped
616           aFilteredFeatures.insert(aCFeature);
617         }
618         theReferences[aFeature] = aFilteredFeatures;
619       }
620       if (theUseRecursion) {
621 #ifdef DEBUG_CYCLING_1550
622         findReferences(aSelRefFeatures, theReferences, theUseComposite,
623                        theUseRecursion, theRecLevel);
624 #else
625         findReferences(theReferences[aFeature], theReferences, theUseComposite, theUseRecursion,
626                        theRecLevel);
627 #endif
628       }
629     }
630   }
631 }
632
633 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
634                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
635                        const bool theUseComposite,
636                        const bool theUseRecursion)
637 {
638   // For dependencies, find main_list:
639   // sk_1(ext_1, vertex_1)
640   // ext_1(bool_1, sk_3)
641   // vertex_1()
642   // sk_2(ext_2)
643   // ext_2(bool_2)
644   // sk_3()
645   // Information: bool_1 is not selected, ext_2(bool_2) exists
646   // find all referenced features
647   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
648   int aRecLevel = 0;
649   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion, aRecLevel);
650
651 #ifdef DEBUG_REMOVE_FEATURES
652   printMapInfo(aMainList, "firstDependencies");
653 #endif
654   // find all dependencies for each object:
655   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
656   // ext_1(bool_1, sk_3)
657   // vertex_1()
658   // sk_2(ext_2) + (bool_1)
659   // ext_2(bool_1)
660   // sk_3()
661   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
662                                                               aMainLast = aMainList.end();
663   for (; aMainIt != aMainLast; aMainIt++) {
664     FeaturePtr aMainListFeature = aMainIt->first;
665
666     //std::string aName = aMainListFeature->name();
667     std::set<FeaturePtr> aMainRefList = aMainIt->second;
668
669 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
670     char aBuf[50];
671     int n = sprintf(aBuf, "%d", aMainRefList.size());
672     std::string aSize(aBuf);
673     std::cout << "_findAllReferences for the Feature: " << getFeatureInfo(aMainListFeature)
674               << ", references size = " << aSize << std::endl;
675 #endif
676     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
677                                          aLast = aMainRefList.end();
678     std::set<FeaturePtr> aResultRefList;
679     aResultRefList.insert(aMainRefList.begin(), aMainRefList.end());
680     for (; anIt != aLast; anIt++) {
681       FeaturePtr aFeature = *anIt;
682       aRecLevel = 0;
683 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
684       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
685 #endif
686       aRecLevel++;
687       addRefsToFeature(aFeature, aMainList,
688                        aRecLevel, aResultRefList/*aMainRefList*/);
689     }
690     theReferences[aMainListFeature] = aResultRefList;
691   }
692 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
693     std::cout << std::endl;
694 #endif
695
696 #ifdef DEBUG_REMOVE_FEATURES
697   printMapInfo(theReferences, "allDependencies");
698 #endif
699 }
700
701 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
702                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
703                         std::set<FeaturePtr>& theFeaturesRefsTo)
704 {
705   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
706                                        aLast = theFeatures.end();
707   for (; anIt != aLast; anIt++) {
708     FeaturePtr aFeature = *anIt;
709     if (theReferences.find(aFeature) == theReferences.end())
710       continue;
711     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
712     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
713     for (; aRefIt != aRefLast; aRefIt++) {
714       FeaturePtr aRefFeature = *aRefIt;
715       CompositeFeaturePtr aComposite =
716         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
717       if (aComposite.get() && aComposite->isSub(aFeature))
718         continue; /// composite of the current feature should not be removed
719
720       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
721           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
722         theFeaturesRefsTo.insert(aRefFeature);
723     }
724   }
725 }
726
727 void getConcealedResults(const FeaturePtr& theFeature,
728                          std::list<std::shared_ptr<ModelAPI_Result> >& theResults)
729 {
730   SessionPtr aSession = ModelAPI_Session::get();
731
732   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
733   theFeature->data()->referencesToObjects(aRefs);
734   std::list<std::pair<std::string, std::list<ObjectPtr> > >::const_iterator
735                                                   anIt = aRefs.begin(), aLast = aRefs.end();
736   std::set<ResultPtr> alreadyThere; // to avoid duplications
737   for (; anIt != aLast; anIt++) {
738     if (!aSession->validators()->isConcealed(theFeature->getKind(), anIt->first))
739       continue; // use only concealed attributes
740     std::list<ObjectPtr> anObjects = (*anIt).second;
741     std::list<ObjectPtr>::const_iterator anOIt = anObjects.begin(), anOLast = anObjects.end();
742     for (; anOIt != anOLast; anOIt++) {
743       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anOIt);
744       if (aResult && aResult->isConcealed()) {
745         if (alreadyThere.find(aResult) == alreadyThere.end()) // issue 1712, avoid duplicates
746           alreadyThere.insert(aResult);
747         else continue;
748         theResults.push_back(aResult);
749       }
750     }
751   }
752 }
753
754 std::pair<std::wstring, bool> getDefaultName(const std::shared_ptr<ModelAPI_Result>& theResult,
755                                              const bool theInherited,
756                                              const bool theRecursive)
757 {
758   typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
759
760   SessionPtr aSession = ModelAPI_Session::get();
761
762   ResultBodyPtr anOwnerRes = bodyOwner(theResult);
763   if (anOwnerRes) {
764     // names of sub-solids in CompSolid should be default (for example,
765     // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
766     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
767     std::wostringstream aDefaultName;
768     aDefaultName << getDefaultName(anOwnerRes).first;
769     aDefaultName << "_" << (bodyIndex(theResult) + 1);
770     return std::pair<std::wstring, bool>(aDefaultName.str(), false);
771   }
772
773   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
774   DataPtr aData = anOwner->data();
775
776   ListOfReferences aReferences;
777   // find first result with user-defined name
778   ListOfReferences::const_iterator aFoundRef = aReferences.end();
779   if (theInherited) {
780     aData->referencesToObjects(aReferences);
781
782     for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
783          aRefIt != aReferences.end(); ++aRefIt) {
784       bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
785       bool isMainArg = isConcealed &&
786                        aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
787       if (isConcealed) {
788         // check the referred object is a Body
789         // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
790         bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
791                       aRefIt->second.front().get() &&
792                       aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
793         if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
794             aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
795           aFoundRef = aRefIt;
796
797         if (isMainArg)
798           break;
799       }
800     }
801   }
802   // get the result number in the feature
803   int anIndexInOwner = 0;
804   const std::list<ResultPtr>& anOwnerResults = anOwner->results();
805   std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
806   for(; aResIt != anOwnerResults.cend(); aResIt++) {
807     if(*aResIt == theResult)
808       break;
809     anIndexInOwner++;
810   }
811
812   // find an object which is concealed by theResult
813   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
814     // store number of references for each object
815     std::map<ResultPtr, int> aNbRefToObject;
816     // search the object by result index
817     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
818     int aResultIndex = anIndexInOwner;
819     while (--aResultIndex >= 0) {
820       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
821       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
822       if (aParentBody)
823         aCurRes = aParentBody;
824       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
825         aNbRefToObject[aCurRes] = 1;
826       else
827         aNbRefToObject[aCurRes] += 1;
828
829       ++anObjIt;
830       if (anObjIt == aFoundRef->second.end()) {
831         anObjIt = aFoundRef->second.begin();
832         break;
833       }
834     }
835     // check the result is a Body
836     if (anObjIt->get() && (*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
837       // check the result is part of CompSolid
838       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
839       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
840       if (aParentBody)
841         anObjRes = aParentBody;
842
843       // return name of reference result only if it has been renamed by the user,
844       // in other case compose a default name
845       if (anObjRes->data()->hasUserDefinedName() ||
846           (theRecursive && anObjRes->data()->name() != getDefaultName(anObjRes).first)) {
847         std::wstringstream aName;
848         aName << anObjRes->data()->name();
849         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
850         if (aFound != aNbRefToObject.end()) {
851           // to generate unique name, add suffix if there are several results
852           // referring to the same shape
853           aName << "_" << aFound->second + 1;
854         }
855         return std::pair<std::wstring, bool>(aName.str(), true);
856       }
857     }
858   }
859
860   // compose default name by the name of the feature and the index of result
861   std::wstringstream aDefaultName;
862   aDefaultName << anOwner->name();
863   // if there are several results (issue #899: any number of result),
864   // add unique prefix starting from second
865   if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
866     aDefaultName << "_" << anIndexInOwner + 1;
867   return std::pair<std::wstring, bool>(aDefaultName.str(), false);
868 }
869
870 std::set<FeaturePtr> getParents(const FeaturePtr& theFeature)
871 {
872   std::set<FeaturePtr> aParents;
873   for (FeaturePtr aCurFeat = theFeature; aCurFeat; ) {
874     CompositeFeaturePtr aFoundComposite;
875     const std::set<AttributePtr>& aRefs = aCurFeat->data()->refsToMe();
876     for (std::set<AttributePtr>::const_iterator anIt = aRefs.begin();
877       anIt != aRefs.end(); ++anIt) {
878       FeaturePtr aF = ModelAPI_Feature::feature((*anIt)->owner());
879       aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aF);
880       if (aFoundComposite && aFoundComposite->isSub(aCurFeat))
881         break;
882       else
883         aFoundComposite = CompositeFeaturePtr();
884     }
885
886     if (aFoundComposite) {
887       aParents.insert(aFoundComposite);
888       aCurFeat = aFoundComposite;
889     }
890     else {
891       // add the part containing high-level feature
892       SessionPtr aSession = ModelAPI_Session::get();
893       DocumentPtr aPartSetDoc = aSession->moduleDocument();
894       std::list<FeaturePtr> aPartSetFeatures = aPartSetDoc->allFeatures();
895       for (std::list<FeaturePtr>::const_iterator anIt = aPartSetFeatures.begin();
896         anIt != aPartSetFeatures.end(); ++anIt) {
897         aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
898         if (aFoundComposite && aFoundComposite->isSub(aCurFeat)) {
899           aParents.insert(aFoundComposite);
900           break;
901         }
902       }
903
904       aCurFeat = FeaturePtr();
905     }
906   }
907   return aParents;
908 }
909
910 void fillShapeHierarchy(const GeomShapePtr& theShape,
911                         const ResultPtr& theContext,
912                         GeomAPI_ShapeHierarchy& theHierarchy)
913 {
914   ResultBodyPtr aResCompSolidPtr = ModelAPI_Tools::bodyOwner(theContext);
915   if (aResCompSolidPtr.get()) {
916     std::shared_ptr<GeomAPI_Shape> aContextShape = aResCompSolidPtr->shape();
917     if (aContextShape->shapeType() <= GeomAPI_Shape::COMPSOLID) {
918       theHierarchy.addParent(theShape, aContextShape);
919       fillShapeHierarchy(aContextShape, aResCompSolidPtr, theHierarchy);
920     }
921   }
922 }
923
924
925 void removeResults(const std::list<ResultPtr>& theResults)
926 {
927   // collect all documents where the results must be removed
928   std::map<DocumentPtr, std::list<ResultPtr> > aDocs;
929
930   std::list<ResultPtr>::const_iterator aResIter = theResults.cbegin();
931   for(; aResIter != theResults.cend(); aResIter++) {
932     DocumentPtr aDoc = (*aResIter)->document();
933     if (!aDocs.count(aDoc))
934       aDocs[aDoc] = std::list<ResultPtr>();
935     aDocs[aDoc].push_back(*aResIter);
936   }
937   // create a "remove" feature in each doc
938   std::map<DocumentPtr, std::list<ResultPtr> >::iterator aDoc = aDocs.begin();
939   for(; aDoc != aDocs.end(); aDoc++) {
940     FeaturePtr aRemove = aDoc->first->addFeature("RemoveResults");
941     if (aRemove) {
942       for(aResIter = aDoc->second.cbegin(); aResIter != aDoc->second.cend(); aResIter++)
943         aRemove->selectionList("results")->append(*aResIter, GeomShapePtr());
944     }
945   }
946 }
947
948 // used by GUI only
949 // LCOV_EXCL_START
950
951 //**************************************************************
952 void setDeflection(ResultPtr theResult, const double theDeflection)
953 {
954   if (!theResult.get())
955     return;
956
957   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
958   if (aDeflectionAttr.get() != NULL) {
959     aDeflectionAttr->setValue(theDeflection);
960   }
961 }
962
963 double getDeflection(const std::shared_ptr<ModelAPI_Result>& theResult)
964 {
965   double aDeflection = -1;
966   // get deflection from the attribute of the result
967   if (theResult.get() != NULL &&
968     theResult->data()->attribute(ModelAPI_Result::DEFLECTION_ID()).get() != NULL) {
969     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
970     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
971       double aValue = aDoubleAttr->value();
972       if (aValue > 0) /// zero value should not be used as a deflection(previous studies)
973         aDeflection = aDoubleAttr->value();
974     }
975   }
976   return aDeflection;
977 }
978
979 //******************************************************
980 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
981 {
982   if (!theResult.get())
983     return;
984
985   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
986   if (aColorAttr.get() != NULL) {
987     if (!aColorAttr->size()) {
988       aColorAttr->setSize(3);
989     }
990     aColorAttr->setValue(0, theColor[0]);
991     aColorAttr->setValue(1, theColor[1]);
992     aColorAttr->setValue(2, theColor[2]);
993   }
994 }
995
996 void getColor(const std::shared_ptr<ModelAPI_Result>& theResult, std::vector<int>& theColor)
997 {
998   theColor.clear();
999   // get color from the attribute of the result
1000   if (theResult.get() != NULL &&
1001     theResult->data()->attribute(ModelAPI_Result::COLOR_ID()).get() != NULL) {
1002     AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1003     if (aColorAttr.get() && aColorAttr->size()) {
1004       theColor.push_back(aColorAttr->value(0));
1005       theColor.push_back(aColorAttr->value(1));
1006       theColor.push_back(aColorAttr->value(2));
1007     }
1008   }
1009 }
1010
1011 //******************************************************
1012 void getIsoLines(const std::shared_ptr<ModelAPI_Result>& theResult,
1013   bool& isVisible, std::vector<int>& theNbLines)
1014 {
1015   theNbLines.clear();
1016   isVisible = false;
1017   if (!theResult.get())
1018     return;
1019   if (theResult->groupName() == ModelAPI_ResultConstruction::group()) {
1020     theNbLines.push_back(0);
1021     theNbLines.push_back(0);
1022   }
1023   else {
1024     // get color from the attribute of the result
1025     AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1026     if (aAttr.get()) {
1027       if (aAttr->size()) {
1028         theNbLines.push_back(aAttr->value(0));
1029         theNbLines.push_back(aAttr->value(1));
1030       }
1031     }
1032     AttributeBooleanPtr aBoolAttr =
1033       theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
1034     if (aBoolAttr.get()) {
1035       isVisible = aBoolAttr->value();
1036     }
1037   }
1038 }
1039
1040 //******************************************************
1041 void setIsoLines(ResultPtr theResult, const std::vector<int>& theIso)
1042 {
1043   if (!theResult.get())
1044     return;
1045
1046   AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1047   if (aAttr.get() != NULL) {
1048     if (!aAttr->size()) {
1049       aAttr->setSize(2);
1050     }
1051     aAttr->setValue(0, theIso[0]);
1052     aAttr->setValue(1, theIso[1]);
1053   }
1054 }
1055
1056 //******************************************************
1057 void showIsoLines(std::shared_ptr<ModelAPI_Result> theResult, bool theShow)
1058 {
1059   if (!theResult.get())
1060     return;
1061
1062   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
1063   if (aAttr.get() != NULL) {
1064     aAttr->setValue(theShow);
1065   }
1066 }
1067
1068 //******************************************************
1069 bool isShownIsoLines(std::shared_ptr<ModelAPI_Result> theResult)
1070 {
1071   if (!theResult.get())
1072     return false;
1073
1074   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
1075   if (aAttr.get() != NULL) {
1076     return aAttr->value();
1077   }
1078   return false;
1079 }
1080
1081 //**************************************************************
1082 void setTransparency(ResultPtr theResult, double theTransparency)
1083 {
1084   if (!theResult.get())
1085     return;
1086
1087   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1088   if (anAttribute.get() != NULL) {
1089     anAttribute->setValue(theTransparency);
1090   }
1091 }
1092
1093 double getTransparency(const std::shared_ptr<ModelAPI_Result>& theResult)
1094 {
1095   double aTransparency = -1;
1096   // get transparency from the attribute of the result
1097   if (theResult.get() != NULL &&
1098     theResult->data()->attribute(ModelAPI_Result::TRANSPARENCY_ID()).get() != NULL) {
1099     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1100     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
1101       aTransparency = aDoubleAttr->value();
1102     }
1103   }
1104   return aTransparency;
1105 }
1106
1107 void copyVisualizationAttrs(
1108   std::shared_ptr<ModelAPI_Result> theSource, std::shared_ptr<ModelAPI_Result> theDest)
1109 {
1110   // color
1111   AttributeIntArrayPtr aSourceColor = theSource->data()->intArray(ModelAPI_Result::COLOR_ID());
1112   if (aSourceColor.get() && aSourceColor->isInitialized() && aSourceColor->size()) {
1113     AttributeIntArrayPtr aDestColor = theDest->data()->intArray(ModelAPI_Result::COLOR_ID());
1114     if (aDestColor.get()) {
1115       aDestColor->setSize(aSourceColor->size());
1116       for(int a = 0; a < aSourceColor->size(); a++)
1117         aDestColor->setValue(a, aSourceColor->value(a));
1118     }
1119   }
1120   // Iso-lines
1121   AttributeIntArrayPtr aSource = theSource->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1122   if (aSource.get() && aSource->isInitialized() && aSource->size()) {
1123     AttributeIntArrayPtr aDest = theDest->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1124     if (aDest.get()) {
1125       aDest->setSize(aSource->size());
1126       for(int a = 0; a < aSource->size(); a++)
1127         aDest->setValue(a, aSource->value(a));
1128     }
1129   }
1130   // deflection
1131   AttributeDoublePtr aSourceDefl = theSource->data()->real(ModelAPI_Result::DEFLECTION_ID());
1132   if (aSourceDefl.get() && aSourceDefl->isInitialized()) {
1133     AttributeDoublePtr aDestDefl = theDest->data()->real(ModelAPI_Result::DEFLECTION_ID());
1134     if (aDestDefl.get()) {
1135       aDestDefl->setValue(aSourceDefl->value());
1136     }
1137   }
1138   // transparency
1139   AttributeDoublePtr aSourceTransp = theSource->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1140   if (aSourceTransp.get() && aSourceTransp->isInitialized()) {
1141     AttributeDoublePtr aDestTransp = theDest->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1142     if (aDestTransp.get()) {
1143       aDestTransp->setValue(aSourceTransp->value());
1144     }
1145   }
1146 }
1147
1148 std::list<FeaturePtr> referencedFeatures(
1149   std::shared_ptr<ModelAPI_Result> theTarget, const std::string& theFeatureKind,
1150   const bool theSortResults)
1151 {
1152   std::set<FeaturePtr> aResSet; // collect in the set initially to avoid duplicates
1153   std::list<ResultPtr> allSubRes;
1154   allSubRes.push_back(theTarget);
1155   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theTarget);
1156   if (aBody.get())
1157     allSubs(aBody, allSubRes);
1158   std::list<ResultPtr>::iterator aSub = allSubRes.begin();
1159   for(; aSub != allSubRes.end(); aSub++) {
1160     const std::set<AttributePtr>& aRefs = (*aSub)->data()->refsToMe();
1161     std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1162     for(; aRef != aRefs.cend(); aRef++) {
1163       FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1164       if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1165         aResSet.insert(aFeat);
1166     }
1167   }
1168   // add also feature of the target that may be referenced as a whole
1169   FeaturePtr aTargetFeature = theTarget->document()->feature(theTarget);
1170   const std::set<AttributePtr>& aRefs = aTargetFeature->data()->refsToMe();
1171   std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1172   for(; aRef != aRefs.cend(); aRef++) {
1173     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1174     if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1175       aResSet.insert(aFeat);
1176   }
1177   // check also Group-operations that may refer to groups - add them for theFeatureKind "Group"
1178   if (theFeatureKind == "Group") {
1179     std::set<FeaturePtr> aGroupOperations;
1180     for(bool aNeedIterate = true; aNeedIterate; ) {
1181       std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1182       for(; aResIter != aResSet.end(); aResIter++) {
1183         std::list<ResultPtr>::const_iterator aGroupRes = (*aResIter)->results().cbegin();
1184         for(; aGroupRes != (*aResIter)->results().cend(); aGroupRes++) {
1185           const std::set<AttributePtr>& aGroupRefs = (*aGroupRes)->data()->refsToMe();
1186           std::set<AttributePtr>::const_iterator aRefIt = aGroupRefs.cbegin();
1187           for(; aRefIt != aGroupRefs.cend(); aRefIt++) {
1188             FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
1189             if (aFeat.get() && !aGroupOperations.count(aFeat) && !aFeat->results().empty() &&
1190                 aFeat->firstResult()->groupName() == ModelAPI_ResultGroup::group()) {
1191               // iterate results of this group operation because it may be without theTarget shape
1192               GeomShapePtr aTargetShape = theTarget->shape();
1193               bool anIsIn = false;
1194               std::list<ResultPtr>::const_iterator anOpRes = aFeat->results().cbegin();
1195               for(; anOpRes != aFeat->results().cend() && !anIsIn; anOpRes++) {
1196                 GeomShapePtr anOpShape = (*anOpRes)->shape();
1197                 if (!anOpShape.get() || anOpShape->isNull())
1198                   continue;
1199                 for(GeomAPI_ShapeIterator aSubIt(anOpShape); aSubIt.more(); aSubIt.next()) {
1200                   if (aTargetShape->isSubShape(aSubIt.current(), false)) {
1201                     anIsIn = true;
1202                     break;
1203                   }
1204                 }
1205               }
1206               if (anIsIn)
1207                 aGroupOperations.insert(aFeat);
1208             }
1209           }
1210         }
1211       }
1212       // insert all new group operations into result and if they are, check for next dependencies
1213       aNeedIterate = false;
1214       std::set<FeaturePtr>::iterator aGroupOpIter = aGroupOperations.begin();
1215       for(; aGroupOpIter != aGroupOperations.end(); aGroupOpIter++) {
1216         if (aResSet.find(*aGroupOpIter) == aResSet.end()) {
1217           aResSet.insert(*aGroupOpIter);
1218           aNeedIterate = true;
1219         }
1220       }
1221     }
1222   }
1223
1224   std::list<FeaturePtr> aResList;
1225   std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1226   for(; aResIter != aResSet.end(); aResIter++) {
1227     if (theSortResults) { // sort results by creation-order
1228       std::list<FeaturePtr>::iterator aListIter = aResList.begin();
1229       for(; aListIter != aResList.end(); aListIter++) {
1230         if ((*aResIter)->document()->isLater(*aListIter, *aResIter))
1231           break;
1232       }
1233       if (aListIter == aResList.end()) // goes to the end
1234         aResList.push_back(*aResIter);
1235       else
1236         aResList.insert(aListIter, *aResIter);
1237     } else //just push to the end unsorted
1238       aResList.push_back(*aResIter);
1239   }
1240   return aResList;
1241 }
1242
1243 void setValues(std::vector<int>& theRGB, const int theRed, const int theGreen, const int theBlue)
1244 {
1245   theRGB.push_back(theRed);
1246   theRGB.push_back(theGreen);
1247   theRGB.push_back(theBlue);
1248 }
1249
1250 std::vector<int> HSVtoRGB(int theH, int theS, int theV)
1251 {
1252   std::vector<int> aRGB;
1253   if (theH < 0 || theH > 360 ||
1254       theS < 0 || theS > 100 ||
1255       theV < 0 || theV > 100)
1256     return aRGB;
1257
1258   int aHi = (int)theH/60;
1259   double aV = theV;
1260   double aVmin = (100 - theS)*theV/100;
1261   double anA = (theV - aVmin)* (theH % 60) / 60;
1262   double aVinc = aVmin + anA;
1263   double aVdec = theV - anA;
1264   double aPercentToValue = 255./100;
1265   int aV_int    = (int)(aV*aPercentToValue);
1266   int aVinc_int = (int)(aVinc*aPercentToValue);
1267   int aVmin_int = (int)(aVmin*aPercentToValue);
1268   int aVdec_int = (int)(aVdec*aPercentToValue);
1269
1270   switch(aHi) {
1271     case 0: setValues(aRGB, aV_int,    aVinc_int, aVmin_int); break;
1272     case 1: setValues(aRGB, aVdec_int, aV_int,    aVmin_int); break;
1273     case 2: setValues(aRGB, aVmin_int, aV_int,    aVinc_int); break;
1274     case 3: setValues(aRGB, aVmin_int, aVdec_int, aV_int); break;
1275     case 4: setValues(aRGB, aVinc_int, aVmin_int, aV_int); break;
1276     case 5: setValues(aRGB, aV_int,    aVmin_int, aVdec_int); break;
1277     default: break;
1278   }
1279   return aRGB;
1280 }
1281
1282 std::array<std::vector<int>, 10> myColorTab = {
1283   std::vector<int> {255, 0, 0},
1284   std::vector<int> {0, 255, 0},
1285   std::vector<int> {0, 0, 255},
1286   std::vector<int> {255, 255, 0},
1287   std::vector<int> {0, 255, 255},
1288   std::vector<int> {255, 0, 255},
1289   std::vector<int> {255, 94, 0},
1290   std::vector<int> {132, 255, 0},
1291   std::vector<int> {132, 0, 255},
1292   std::vector<int> {0, 0, 0},
1293 };
1294
1295 void findRandomColor(std::vector<int>& theValues, bool theReset)
1296 {
1297   static size_t i = 0;
1298   static std::vector<std::vector<int>> usedGeneratedColor;
1299
1300   // True when disabling auto-color
1301   if ( theReset ) {
1302     i = 0;
1303     return;
1304   }
1305
1306   theValues.clear();
1307   if (i < myColorTab.size()) {
1308     theValues = myColorTab[i++];
1309   } else {
1310       int timeout = 0;
1311       std::vector<int> aHSVColor;
1312       std::vector<int> aRGBColor;
1313       do {
1314         aHSVColor = {rand() % 360 , rand() % (100 - 50 + 1) + 50, rand() % (100 - 50 + 1) + 50};
1315         aRGBColor = HSVtoRGB(aHSVColor[0], aHSVColor[1], aHSVColor[2]);
1316         timeout++;
1317       } while (
1318         timeout < 20 &&
1319         std::find(usedGeneratedColor.begin(), usedGeneratedColor.end(), aHSVColor)
1320         != usedGeneratedColor.end() &&
1321         std::find(myColorTab.begin(), myColorTab.end(), aRGBColor) != myColorTab.end());
1322       usedGeneratedColor.push_back(aHSVColor);
1323       theValues = aRGBColor;
1324   }
1325 }
1326
1327 // LCOV_EXCL_STOP
1328
1329 } // namespace ModelAPI_Tools