fc8ea81b8f5adc53f26df68141e99909c50d094a
[occt.git] / src / SelectMgr / SelectMgr_ViewerSelector.hxx
1 // Created on: 1995-02-15
2 // Created by: Roberc Coublanc
3 // Copyright (c) 1995-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 #ifndef _SelectMgr_ViewerSelector_HeaderFile
18 #define _SelectMgr_ViewerSelector_HeaderFile
19
20 #include <Standard_Transient.hxx>
21 #include <NCollection_DataMap.hxx>
22 #include <OSD_Chronometer.hxx>
23 #include <TColStd_SequenceOfInteger.hxx>
24 #include <TColStd_HArray1OfInteger.hxx>
25 #include <Select3D_BVHBuilder3d.hxx>
26 #include <SelectMgr_IndexedDataMapOfOwnerCriterion.hxx>
27 #include <SelectMgr_SelectingVolumeManager.hxx>
28 #include <SelectMgr_Selection.hxx>
29 #include <SelectMgr_SelectableObject.hxx>
30 #include <SelectMgr_SelectableObjectSet.hxx>
31 #include <SelectMgr_StateOfSelection.hxx>
32 #include <SelectMgr_ToleranceMap.hxx>
33 #include <SelectMgr_TypeOfDepthTolerance.hxx>
34 #include <Standard_OStream.hxx>
35 #include <SelectMgr_BVHThreadPool.hxx>
36
37 class SelectMgr_SelectionManager;
38 class SelectMgr_SensitiveEntitySet;
39 class SelectMgr_EntityOwner;
40 class Select3D_SensitiveEntity;
41
42 // resolve name collisions with X11 headers
43 #ifdef Status
44   #undef Status
45 #endif
46 typedef NCollection_DataMap<Handle(SelectMgr_SelectableObject), Handle(SelectMgr_SensitiveEntitySet) > SelectMgr_MapOfObjectSensitives;
47 typedef NCollection_DataMap<Handle(SelectMgr_SelectableObject), Handle(SelectMgr_SensitiveEntitySet) >::Iterator SelectMgr_MapOfObjectSensitivesIterator;
48
49 typedef NCollection_DataMap<Standard_Integer, SelectMgr_SelectingVolumeManager> SelectMgr_FrustumCache;
50
51 //! A framework to define finding, sorting the sensitive
52 //! primitives in a view. Services are also provided to
53 //! define the return of the owners of those primitives
54 //! selected. The primitives are sorted by criteria such
55 //! as priority of the primitive or its depth in the view
56 //! relative to that of other primitives.
57 //! Note that in 3D, the inheriting framework
58 //! StdSelect_ViewerSelector3d   is only to be used
59 //! if you do not want to use the services provided by
60 //! AIS.
61 //! Two tools are available to find and select objects
62 //! found at a given position in the view. If you want to
63 //! select the owners of all the objects detected at
64 //! point x,y,z you use the Init - More - Next - Picked
65 //! loop. If, on the other hand, you want to select only
66 //! one object detected at that point, you use the Init -
67 //! More - OnePicked loop. In this iteration, More is
68 //! used to see if an object was picked and
69 //! OnePicked, to get the object closest to the pick position.
70 //! Viewer selectors are driven by
71 //! SelectMgr_SelectionManager, and manipulate
72 //! the SelectMgr_Selection objects given to them by
73 //! the selection manager.
74 //!
75 //! Tolerances are applied to the entities in the following way:
76 //! 1. tolerance value stored in mytolerance will be used to calculate initial
77 //!    selecting frustum, which will be applied for intersection testing during
78 //!    BVH traverse;
79 //! 2. if tolerance of sensitive entity is less than mytolerance, the frustum for
80 //!    intersection detection will be resized according to its sensitivity.
81 class SelectMgr_ViewerSelector : public Standard_Transient
82 {
83   DEFINE_STANDARD_RTTIEXT(SelectMgr_ViewerSelector, Standard_Transient)
84   friend class SelectMgr_SelectionManager;
85 public:
86
87   //! Empties all the tables, removes all selections...
88   Standard_EXPORT void Clear();
89
90   //! Returns custom pixel tolerance value.
91   Standard_Integer CustomPixelTolerance() const { return myTolerances.CustomTolerance(); }
92
93   //! Sets the pixel tolerance <theTolerance>.
94   Standard_EXPORT void SetPixelTolerance (const Standard_Integer theTolerance);
95
96   //! Returns the largest sensitivity of picking
97   Standard_Real Sensitivity() const { return myTolerances.Tolerance(); }
98
99   //! Returns the largest pixel tolerance.
100   Standard_Integer PixelTolerance() const { return myTolerances.Tolerance(); }
101
102   //! Sorts the detected entites by priority and distance.
103   Standard_EXPORT virtual void SortResult();
104
105   //! Returns the picked element with the highest priority,
106   //! and which is the closest to the last successful mouse position.
107   Handle(SelectMgr_EntityOwner) OnePicked() const
108   {
109     return mystored.IsEmpty()
110          ? Handle(SelectMgr_EntityOwner)()
111          : Picked (1);
112   }
113
114   //! Return the flag determining precedence of picked depth (distance from eye to entity) over entity priority in sorted results; TRUE by default.
115   //! When flag is TRUE, priority will be considered only if entities have the same depth  within the tolerance.
116   //! When flag is FALSE, entities with higher priority will be in front regardless of their depth (like x-ray).
117   bool ToPickClosest() const { return myToPreferClosest; }
118
119   //! Set flag determining precedence of picked depth over entity priority in sorted results.
120   void SetPickClosest (bool theToPreferClosest) { myToPreferClosest = theToPreferClosest; }
121
122   //! Return the type of tolerance for considering two entities having a similar depth (distance from eye to entity);
123   //! SelectMgr_TypeOfDepthTolerance_SensitivityFactor by default.
124   SelectMgr_TypeOfDepthTolerance DepthToleranceType() const { return myDepthTolType; }
125
126   //! Return the tolerance for considering two entities having a similar depth (distance from eye to entity).
127   Standard_Real DepthTolerance() const { return myDepthTolerance; }
128
129   //! Set the tolerance for considering two entities having a similar depth (distance from eye to entity).
130   //! @param theType [in] type of tolerance value
131   //! @param theTolerance [in] tolerance value in 3D scale (SelectMgr_TypeOfDepthTolerance_Uniform)
132   //!                          or in pixels (SelectMgr_TypeOfDepthTolerance_UniformPixels);
133   //!                          value is ignored in case of SelectMgr_TypeOfDepthTolerance_SensitivityFactor
134   void SetDepthTolerance (SelectMgr_TypeOfDepthTolerance theType,
135                           Standard_Real theTolerance)
136   {
137     myDepthTolType   = theType;
138     myDepthTolerance = theTolerance;
139   }
140
141   //! Returns the number of detected owners.
142   Standard_Integer NbPicked() const { return mystored.Extent(); }
143
144   //! Clears picking results.
145   Standard_EXPORT void ClearPicked();
146
147   //! Returns the entity Owner for the object picked at specified position.
148   //! @param theRank rank of detected object within range 1...NbPicked()
149   Standard_EXPORT Handle(SelectMgr_EntityOwner) Picked (const Standard_Integer theRank) const;
150
151   //! Returns the Entity for the object picked at specified position.
152   //! @param theRank rank of detected object within range 1...NbPicked()
153   Standard_EXPORT const SelectMgr_SortCriterion& PickedData (const Standard_Integer theRank) const;
154
155   //! Returns the Entity for the object picked at specified position.
156   //! @param theRank rank of detected object within range 1...NbPicked()
157   const Handle(Select3D_SensitiveEntity)& PickedEntity (const Standard_Integer theRank) const { return PickedData (theRank).Entity; }
158
159   //! Returns the 3D point (intersection of picking axis with the object nearest to eye)
160   //! for the object picked at specified position.
161   //! @param theRank rank of detected object within range 1...NbPicked()
162   gp_Pnt PickedPoint (const Standard_Integer theRank) const { return PickedData (theRank).Point; }
163
164   Standard_EXPORT Standard_Boolean Contains (const Handle(SelectMgr_SelectableObject)& theObject) const;
165
166   //! Returns the default builder used to construct BVH of entity set.
167   const Handle(Select3D_BVHBuilder3d) EntitySetBuilder() { return myEntitySetBuilder; }
168
169   //! Sets the default builder used to construct BVH of entity set.
170   //! The new builder will be also assigned for already defined objects, but computed BVH trees will not be invalidated.
171   Standard_EXPORT void SetEntitySetBuilder (const Handle(Select3D_BVHBuilder3d)& theBuilder);
172
173   //! Returns the list of selection modes ModeList found in
174   //! this selector for the selectable object aSelectableObject.
175   //! Returns true if aSelectableObject is referenced inside
176   //! this selector; returns false if the object is not present
177   //! in this selector.
178   Standard_EXPORT Standard_Boolean Modes (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
179                                           TColStd_ListOfInteger& theModeList,
180                                           const SelectMgr_StateOfSelection theWantedState = SelectMgr_SOS_Any) const;
181
182   //! Returns true if the selectable object
183   //! aSelectableObject having the selection mode aMode
184   //! is active in this selector.
185   Standard_EXPORT Standard_Boolean IsActive (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
186                                              const Standard_Integer theMode) const;
187
188   //! Returns true if the selectable object
189   //! aSelectableObject having the selection mode aMode
190   //! is in this selector.
191   Standard_EXPORT Standard_Boolean IsInside (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
192                                              const Standard_Integer theMode) const;
193
194   //! Returns the selection status Status of the selection aSelection.
195   Standard_EXPORT SelectMgr_StateOfSelection Status (const Handle(SelectMgr_Selection)& theSelection) const;
196
197   Standard_EXPORT TCollection_AsciiString Status (const Handle(SelectMgr_SelectableObject)& theSelectableObject) const;
198
199   //! Returns the list of active entity owners
200   Standard_EXPORT void ActiveOwners (NCollection_List<Handle(SelectMgr_EntityOwner)>& theOwners) const;
201
202   //! Adds new object to the map of selectable objects
203   Standard_EXPORT void AddSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject);
204
205   //! Adds new selection to the object and builds its BVH tree
206   Standard_EXPORT void AddSelectionToObject (const Handle(SelectMgr_SelectableObject)& theObject,
207                                              const Handle(SelectMgr_Selection)& theSelection);
208
209   //! Moves existing object from set of not transform persistence objects
210   //! to set of transform persistence objects (or vice versa).
211   Standard_EXPORT void MoveSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject);
212
213   //! Removes selectable object from map of selectable ones
214   Standard_EXPORT void RemoveSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject);
215
216   //! Removes selection of the object and marks its BVH tree for rebuild
217   Standard_EXPORT void RemoveSelectionOfObject (const Handle(SelectMgr_SelectableObject)& theObject,
218                                                 const Handle(SelectMgr_Selection)& theSelection);
219
220   //! Marks BVH of selectable objects for rebuild. Parameter theIsForce set as true
221   //! guarantees that 1st level BVH for the viewer selector will be rebuilt during this call
222   Standard_EXPORT void RebuildObjectsTree (const Standard_Boolean theIsForce = Standard_False);
223
224   //! Marks BVH of sensitive entities of particular selectable object for rebuild. Parameter
225   //! theIsForce set as true guarantees that 2nd level BVH for the object given will be
226   //! rebuilt during this call
227   Standard_EXPORT void RebuildSensitivesTree (const Handle(SelectMgr_SelectableObject)& theObject,
228                                               const Standard_Boolean theIsForce = Standard_False);
229
230   //! Returns instance of selecting volume manager of the viewer selector
231   SelectMgr_SelectingVolumeManager& GetManager() { return mySelectingVolumeMgr; }
232
233   //! Return map of selectable objects.
234   const SelectMgr_SelectableObjectSet& SelectableObjects() const { return mySelectableObjects; }
235
236   //! Marks all added sensitive entities of all objects as non-selectable
237   Standard_EXPORT void ResetSelectionActivationStatus();
238
239   //! Is used for rectangular selection only
240   //! If theIsToAllow is false, only fully included sensitives will be detected, otherwise the algorithm will
241   //! mark both included and overlapped entities as matched
242   Standard_EXPORT void AllowOverlapDetection (const Standard_Boolean theIsToAllow);
243
244   //! Dumps the content of me into the stream
245   Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
246
247 public:
248
249   //! Enables/disables building BVH for sensitives in separate threads
250   Standard_EXPORT void SetToPrebuildBVH(Standard_Boolean theToPrebuild, Standard_Integer theThreadsNum = -1);
251
252   //! Queues a sensitive entity to build its BVH
253   Standard_EXPORT void QueueBVHBuild(const Handle(Select3D_SensitiveEntity)& theEntity);
254
255   //! Waits BVH threads finished building
256   Standard_EXPORT void WaitForBVHBuild();
257
258   //! Returns TRUE if building BVH for sensitives in separate threads is enabled
259   Standard_Boolean ToPrebuildBVH() const
260   {
261     return myToPrebuildBVH;
262   }
263
264 protected:
265
266   Standard_EXPORT SelectMgr_ViewerSelector();
267
268   //! Traverses BVH containing all added selectable objects and
269   //! finds candidates for further search of overlap
270   Standard_EXPORT void TraverseSensitives();
271
272   //! Internal function that checks if there is possible overlap between some entity of selectable object theObject and
273   //! current selecting volume.
274   //! @param theObject [in] the selectable object for traversal.
275   //! @param theMgr [in] the (un)transformed copy of the selecting volume manager representing active selection frustum.
276   //! @param theCamera, theProjectionMat, theWorldViewMat [in] the source camera and matrices for theMgr given.
277   //! @param theViewportWidth, theViewportHeight [in] viewport (window) dimensions for evaluating 
278   //!        object's transformation persistence.
279   Standard_EXPORT void traverseObject (const Handle(SelectMgr_SelectableObject)& theObject,
280                                        const SelectMgr_SelectingVolumeManager& theMgr,
281                                        const Handle(Graphic3d_Camera)& theCamera,
282                                        const Graphic3d_Mat4d& theProjectionMat,
283                                        const Graphic3d_Mat4d& theWorldViewMat,
284                                        const Graphic3d_Vec2i& theWinSize);
285
286   //! Internal function that checks if a particular sensitive
287   //! entity theEntity overlaps current selecting volume precisely
288   Standard_EXPORT void checkOverlap (const Handle(Select3D_SensitiveEntity)& theEntity,
289                                      const gp_GTrsf& theInversedTrsf,
290                                      SelectMgr_SelectingVolumeManager& theMgr);
291
292 private:
293
294   //! Checks if the entity given requires to scale current selecting frustum
295   Standard_Boolean isToScaleFrustum (const Handle(Select3D_SensitiveEntity)& theEntity);
296
297   //! In case if custom tolerance is set, this method will return sum of entity sensitivity and
298   //! custom tolerance. Otherwise, pure entity sensitivity factor will be returned.
299   Standard_Integer sensitivity (const Handle(Select3D_SensitiveEntity)& theEntity) const;
300
301   void Activate (const Handle(SelectMgr_Selection)& theSelection);
302
303   void Deactivate (const Handle(SelectMgr_Selection)& theSelection);
304
305   //! removes a Selection from the Selector
306   void Remove (const Handle(SelectMgr_Selection)& aSelection);
307
308   //! Internal function that checks if a current selecting frustum needs to be scaled and transformed for the entity and performs necessary calculations.
309   void computeFrustum (const Handle(Select3D_SensitiveEntity)& theEnt,
310                        const SelectMgr_SelectingVolumeManager& theMgrGlobal,
311                        const SelectMgr_SelectingVolumeManager& theMgrObject,
312                        const gp_GTrsf& theInvTrsf,
313                        SelectMgr_FrustumCache& theCachedMgrs,
314                        SelectMgr_SelectingVolumeManager& theResMgr);
315
316
317 private:
318
319   //! Compute 3d position for detected entity.
320   void updatePoint3d (SelectMgr_SortCriterion& theCriterion,
321                       const SelectBasics_PickResult& thePickResult,
322                       const Handle(Select3D_SensitiveEntity)& theEntity,
323                       const gp_GTrsf& theInversedTrsf,
324                       const SelectMgr_SelectingVolumeManager& theMgr) const;
325
326 protected:
327
328   Standard_Real                                 myDepthTolerance;
329   SelectMgr_TypeOfDepthTolerance                myDepthTolType;
330   Standard_Boolean                              myToPreferClosest;
331   SelectMgr_IndexedDataMapOfOwnerCriterion      mystored;
332   SelectMgr_SelectingVolumeManager              mySelectingVolumeMgr;
333   mutable SelectMgr_SelectableObjectSet         mySelectableObjects;
334   SelectMgr_ToleranceMap                        myTolerances;
335   NCollection_DataMap<Graphic3d_ZLayerId, Standard_Integer> myZLayerOrderMap;
336   Handle(Select3D_BVHBuilder3d)                 myEntitySetBuilder;
337   gp_Pnt                                        myCameraEye;
338   gp_Dir                                        myCameraDir;
339   Standard_Real                                 myCameraScale;
340
341   Standard_Boolean                              myToPrebuildBVH;
342   Handle(SelectMgr_BVHThreadPool)               myBVHThreadPool;
343
344   Handle(TColStd_HArray1OfInteger)             myIndexes;
345   Standard_Boolean                             myIsLeftChildQueuedFirst;
346   SelectMgr_MapOfObjectSensitives              myMapOfObjectSensitives;
347
348 };
349
350 DEFINE_STANDARD_HANDLE(SelectMgr_ViewerSelector, Standard_Transient)
351
352 #endif