Debian Codegraph @

src/App/ComplexGeoData.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /****************************************************************************
3 * *
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * Copyright (c) 2022 Zheng, Lei <[email protected]> *
6 * Copyright (c) 2023 FreeCAD Project Association *
7 * *
8 * This file is part of FreeCAD. *
9 * *
10 * FreeCAD is free software: you can redistribute it and/or modify it *
11 * under the terms of the GNU Lesser General Public License as *
12 * published by the Free Software Foundation, either version 2.1 of the *
13 * License, or (at your option) any later version. *
14 * *
15 * FreeCAD is distributed in the hope that it will be useful, but *
16 * WITHOUT ANY WARRANTY; without even the implied warranty of *
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
18 * Lesser General Public License for more details. *
19 * *
20 * You should have received a copy of the GNU Lesser General Public *
21 * License along with FreeCAD. If not, see *
22 * <https://www.gnu.org/licenses/>. *
23 * *
24 ***************************************************************************/
25
26
27 #ifndef APP_COMPLEX_GEO_DATA_H
28 #define APP_COMPLEX_GEO_DATA_H
29
30 #include <algorithm>
31 #include <optional>
32
33 #include <Base/Handle.h>
34 #include <Base/Matrix.h>
35 #include <Base/Persistence.h>
36 #include "MappedName.h"
37 #include "MappedElement.h"
38 #include "ElementMap.h"
39 #include "StringHasher.h"
40
41 #ifdef __GNUC__
42 #include <cstdint>
43 #endif
44
45
46 namespace Base
47 {
48 class Placement;
49 class Rotation;
50 template<class _Precision>
51 class BoundBox3; // NOLINT
52 using BoundBox3d = BoundBox3<double>;
53 } // namespace Base
54
55 namespace Data
56 {
57
58 // struct MappedChildElements;
59 /// Option for App::GeoFeature::searchElementCache()
60 enum class SearchOption
61 {
62 /// Whether to compare shape geometry
63 CheckGeometry = 1,
64 SingleResult = 2,
65 };
66 typedef Base::Flags<SearchOption> SearchOptions;
67
68 /** Segments
69 * Sub-element type of the ComplexGeoData type
70 * It is used to split an object in further sub-parts.
71 */
72 class AppExport Segment: public Base::BaseClass
73 {
74 TYPESYSTEM_HEADER_WITH_OVERRIDE(); // NOLINT
75
76 public:
77 ~Segment() override = default;
78 virtual std::string getName() const = 0;
79 };
80
81 enum ElementMapResetPolicy
82 {
83 AllowNoMap,
84 ForceEmptyMap
85 };
86
87 /** ComplexGeoData Object
88 */
89 class AppExport ComplexGeoData: public Base::Persistence, public Base::Handled
90 {
91 TYPESYSTEM_HEADER_WITH_OVERRIDE(); // NOLINT
92
93 public:
94 struct Line
95 {
96 uint32_t I1;
97 uint32_t I2;
98 };
99 struct Facet
100 {
101 uint32_t I1;
102 uint32_t I2;
103 uint32_t I3;
104 };
105 struct Domain
106 {
107 std::vector<Base::Vector3d> points;
108 std::vector<Facet> facets;
109 };
110
111 /// Constructor
112 ComplexGeoData();
113 /// Destructor
114 ~ComplexGeoData() override = default;
115
116 /** @name Sub-element management */
117 //@{
118 /** Sub type list
119 * List of different sub-element types
120 * its NOT a list of the sub-elements itself
121 */
122 virtual std::vector<const char*> getElementTypes() const = 0;
123 virtual unsigned long countSubElements(const char* Type) const = 0;
124 /// Returns a generic element type and index. The determined element type isn't
125 /// necessarily supported by this geometry.
126 static std::pair<std::string, unsigned long> getTypeAndIndex(const char* Name);
127 /// get the sub-element by type and number
128 virtual Segment* getSubElement(const char* Type, unsigned long) const = 0;
129 /// get sub-element by combined name
130 virtual Segment* getSubElementByName(const char* Name) const;
131 /** Get lines from segment */
132 virtual void getLinesFromSubElement(const Segment*,
133 std::vector<Base::Vector3d>& Points,
134 std::vector<Line>& lines) const;
135 /** Get faces from segment */
136 virtual void getFacesFromSubElement(const Segment*,
137 std::vector<Base::Vector3d>& Points,
138 std::vector<Base::Vector3d>& PointNormals,
139 std::vector<Facet>& faces) const;
140 //@}
141
142 /** @name Placement control */
143 //@{
144 /** Applies an additional transformation to the current transformation. */
145 void applyTransform(const Base::Matrix4D& rclTrf);
146 /** Applies an additional translation to the current transformation. */
147 void applyTranslation(const Base::Vector3d&);
148 /** Applies an additional rotation to the current transformation. */
149 void applyRotation(const Base::Rotation&);
150 /** Override the current transformation with a placement
151 * using the setTransform() method.
152 */
153 void setPlacement(const Base::Placement& rclPlacement);
154 /** Return the current transformation as placement using
155 * getTransform().
156 */
157 Base::Placement getPlacement() const;
158 /** Override the current transformation with the new one.
159 * This method has to be handled by the child classes.
160 * the actual placement and matrix is not part of this class.
161 */
162 virtual void setTransform(const Base::Matrix4D& rclTrf) = 0;
163 /** Return the current matrix
164 * This method has to be handled by the child classes.
165 * the actual placement and matrix is not part of this class.
166 */
167 virtual Base::Matrix4D getTransform() const = 0;
168 //@}
169
170 /** @name Modification */
171 //@{
172 /// Applies a transformation on the real geometric data type
173 virtual void transformGeometry(const Base::Matrix4D& rclMat) = 0;
174 //@}
175
176 /** @name Getting basic geometric entities */
177 //@{
178 /// Get the standard accuracy to be used with getPoints, getLines or getFaces
179 virtual double getAccuracy() const;
180 /// Get the bound box
181 virtual Base::BoundBox3d getBoundBox() const = 0;
182 /** Get point from line object intersection */
183 virtual Base::Vector3d getPointFromLineIntersection(const Base::Vector3f& base,
184 const Base::Vector3f& dir) const;
185 /** Get points from object with given accuracy */
186 virtual void getPoints(std::vector<Base::Vector3d>& Points,
187 std::vector<Base::Vector3d>& Normals,
188 double Accuracy,
189 uint16_t flags = 0) const;
190 /** Get lines from object with given accuracy */
191 virtual void getLines(std::vector<Base::Vector3d>& Points,
192 std::vector<Line>& lines,
193 double Accuracy,
194 uint16_t flags = 0) const;
195 /** Get faces from object with given accuracy */
196 virtual void getFaces(std::vector<Base::Vector3d>& Points,
197 std::vector<Facet>& faces,
198 double Accuracy,
199 uint16_t flags = 0) const;
200 /** Get the center of gravity
201 * If this method is implemented then true is returned and the center of gravity.
202 * The default implementation only returns false.
203 */
204 virtual bool getCenterOfGravity(Base::Vector3d& center) const;
205 virtual std::optional<Base::Vector3d> centerOfGravity() const;
206 //@}
207
208 static const std::string& elementMapPrefix();
209
210 /** @name Element name mapping */
211 //@{
212
213 /** Get element indexed name
214 *
215 * @param name: the input name
216 * @param sid: optional output of and App::StringID involved forming this mapped name
217 *
218 * @return Returns an indexed name.
219 */
220 IndexedName getIndexedName(const MappedName& name, ElementIDRefs* sid = nullptr) const;
221
222 /** Get element mapped name
223 *
224 * @param name: the input name
225 * @param allowUnmapped: If the queried element is not mapped, then return
226 * an empty name if \c allowUnmapped is false, or
227 * else, return the indexed name.
228 * @param sid: optional output of and App::StringID involved forming this mapped name
229 * @return Returns the mapped name.
230 */
231 MappedName getMappedName(const IndexedName& element,
232 bool allowUnmapped = false,
233 ElementIDRefs* sid = nullptr) const;
234
235 /** Return a pair of indexed name and mapped name
236 *
237 * @param name: the input name.
238 * @param sid: optional output of any App::StringID involved in forming
239 * this mapped name
240 * @param copy: if true, copy the name string, or else use it as constant
241 * string, and caller must make sure the memory is not freed.
242 *
243 * @return Returns the MappedElement which contains both the indexed and
244 * mapped name.
245 *
246 * This function guesses whether the input name is an indexed name or
247 * mapped, and perform a lookup and return the names found. If the input
248 * name contains only alphabets and underscore followed by optional digits,
249 * it will be treated as indexed name. Or else, it will be treated as
250 * mapped name.
251 */
252 MappedElement
253 getElementName(const char* name, ElementIDRefs* sid = nullptr, bool copy = false) const;
254
255 /** Add a sub-element name mapping.
256 *
257 * @param element: the original \c Type + \c Index element name
258 * @param name: the mapped sub-element name. May or may not start with
259 * elementMapPrefix().
260 * @param sid: in case you use a hasher to hash the element name, pass in
261 * the string id reference using this parameter. You can have more than one
262 * string id associated with the same name.
263 * @param overwrite: if true, it will overwrite existing names
264 *
265 * @return Returns the stored mapped element name.
266 *
267 * An element can have multiple mapped names. However, a name can only be
268 * mapped to one element
269 *
270 * Note: the original proc was in the context of ComplexGeoData, which provided `Tag` access,
271 * now you must pass in `long masterTag` explicitly.
272 */
273 MappedName setElementName(const IndexedName& element,
274 const MappedName& name,
275 long masterTag,
276 const ElementIDRefs* sid = nullptr,
277 bool overwrite = false)
278 {
279 return _elementMap->setElementName(element, name, masterTag, sid, overwrite);
280 }
281
282 bool hasElementMap() const
283 {
284 return _elementMap != nullptr;
285 }
286
287 /** Get mapped element names
288 *
289 * @param element: original element name with \c Type + \c Index
290 * @param needUnmapped: if true, return the original element name if no
291 * mapping is found
292 *
293 * @return a list of mapped names of the give element along with their
294 * associated string ID references
295 */
296 std::vector<std::pair<MappedName, ElementIDRefs>>
297 getElementMappedNames(const IndexedName& element, bool needUnmapped = false) const;
298
299 /// Hash the child element map postfixes to shorten element name from hierarchical maps
300 void hashChildMaps();
301
302 /// Check if there is child element map
303 bool hasChildElementMap() const;
304
305 /// Append the Tag (if and only if it is non zero) into the element map
306 virtual void
307 reTagElementMap(long tag, App::StringHasherRef hasher, const char* postfix = nullptr)
308 {
309 (void)tag;
310 (void)hasher;
311 (void)postfix;
312 }
313
314 // NOTE: getElementHistory is now in ElementMap
315 long getElementHistory(const MappedName& name,
316 MappedName* original = nullptr,
317 std::vector<MappedName>* history = nullptr) const
318 {
319 if (_elementMap != nullptr) {
320 return _elementMap->getElementHistory(name, Tag, original, history);
321 }
322 return 0;
323 };
324
325 void setMappedChildElements(const std::vector<Data::ElementMap::MappedChildElements>& children);
326 std::vector<Data::ElementMap::MappedChildElements> getMappedChildElements() const;
327
328 char elementType(const Data::MappedName&) const;
329 char elementType(const Data::IndexedName&) const;
330 char elementType(const char* name) const;
331
332 /** Reset/swap the element map
333 *
334 * @param elementMap: optional new element map
335 *
336 * @return Returns the existing element map.
337 */
338 virtual ElementMapPtr resetElementMap(ElementMapPtr elementMap = ElementMapPtr());
339
340 /// Get the entire element map
341 std::vector<MappedElement> getElementMap() const;
342
343 /// Set the entire element map
344 void setElementMap(const std::vector<MappedElement>& elements);
345
346 /// Get the current element map size
347 size_t getElementMapSize(bool flush = true) const;
348
349 /// Return the higher level element names of the given element
350 virtual std::vector<IndexedName> getHigherElements(const char* name, bool silent = false) const;
351
352 /// Return the current element map version
353 virtual std::string getElementMapVersion() const;
354
355 /// Return true to signal element map version change
356 virtual bool checkElementMapVersion(const char* ver) const;
357
358 /// Check if the given sub-name only contains an element name
359 static bool isElementName(const char* subName)
360 {
361 return (subName != nullptr) && (*subName != 0) && findElementName(subName) == subName;
362 }
363
364 /** Iterate through the history of the give element name with a given callback
365 *
366 * @param name: the input element name
367 * @param cb: trace callback with call signature.
368 * @sa TraceCallback
369 */
370 void traceElement(const MappedName& name, TraceCallback cb) const
371 {
372 _elementMap->traceElement(name, Tag, std::move(cb));
373 }
374
375 /** Flush an internal buffering for element mapping */
376 virtual void flushElementMap() const;
377 //@}
378
379 /** @name Save/restore */
380 //@{
381 void Save(Base::Writer& writer) const override;
382 void Restore(Base::XMLReader& reader) override;
383 void SaveDocFile(Base::Writer& writer) const override;
384 void RestoreDocFile(Base::Reader& reader) override;
385 unsigned int getMemSize() const override;
386 void setPersistenceFileName(const char* name) const;
387 virtual void beforeSave() const;
388 bool isRestoreFailed() const
389 {
390 return _restoreFailed;
391 }
392 void resetRestoreFailure() const
393 {
394 _restoreFailed = true;
395 }
396 //@}
397
398 /**
399 * Debugging method to dump an entire element map in human readable form to a stream
400 * @param stream
401 */
402 void dumpElementMap(std::ostream& stream) const;
403 /**
404 * Debugging method to dump an entire element map in human readable form into a string
405 * @return The string
406 */
407 const std::string dumpElementMap() const;
408
409 protected:
410 /// from local to outside
411 inline Base::Vector3d transformPointToOutside(const Base::Vector3f& vec) const
412 {
413 // clang-format off
414 return getTransform() * Base::Vector3d(static_cast<double>(vec.x),
415 static_cast<double>(vec.y),
416 static_cast<double>(vec.z));
417 // clang-format on
418 }
419 /// from local to outside
420 template<typename Vec>
421 inline std::vector<Base::Vector3d> transformPointsToOutside(const std::vector<Vec>& input) const
422 {
423 // clang-format off
424 std::vector<Base::Vector3d> output;
425 output.reserve(input.size());
426 Base::Matrix4D mat(getTransform());
427 std::transform(input.cbegin(), input.cend(), std::back_inserter(output),
428 [&mat](const Vec& vec) {
429 return mat * Base::Vector3d(static_cast<double>(vec.x),
430 static_cast<double>(vec.y),
431 static_cast<double>(vec.z));
432 });
433
434 return output;
435 // clang-format on
436 }
437 inline Base::Vector3d transformVectorToOutside(const Base::Vector3f& vec) const
438 {
439 // clang-format off
440 Base::Matrix4D mat(getTransform());
441 mat.setCol(3, Base::Vector3d());
442 return mat * Base::Vector3d(static_cast<double>(vec.x),
443 static_cast<double>(vec.y),
444 static_cast<double>(vec.z));
445 // clang-format on
446 }
447 template<typename Vec>
448 std::vector<Base::Vector3d> transformVectorsToOutside(const std::vector<Vec>& input) const
449 {
450 // clang-format off
451 std::vector<Base::Vector3d> output;
452 output.reserve(input.size());
453 Base::Matrix4D mat(getTransform());
454 mat.setCol(3, Base::Vector3d());
455 std::transform(input.cbegin(), input.cend(), std::back_inserter(output),
456 [&mat](const Vec& vec) {
457 return mat * Base::Vector3d(static_cast<double>(vec.x),
458 static_cast<double>(vec.y),
459 static_cast<double>(vec.z));
460 });
461
462 return output;
463 // clang-format on
464 }
465 /// from local to inside
466 inline Base::Vector3f transformPointToInside(const Base::Vector3d& vec) const
467 {
468 Base::Matrix4D tmpM(getTransform());
469 tmpM.inverse();
470 Base::Vector3d tmp = tmpM * vec;
471 return Base::Vector3f(static_cast<float>(tmp.x),
472 static_cast<float>(tmp.y),
473 static_cast<float>(tmp.z));
474 }
475
476 public:
477 mutable long Tag {0};
478
479 /// String hasher for element name shortening
480 mutable App::StringHasherRef Hasher;
481
482 protected:
483 void restoreStream(std::istream& stream, std::size_t count);
484 void readElements(Base::XMLReader& reader, size_t count);
485
486 /// from local to outside
487 inline Base::Vector3d transformToOutside(const Base::Vector3f& vec) const
488 {
489 // clang-format off
490 return getTransform() * Base::Vector3d(static_cast<double>(vec.x),
491 static_cast<double>(vec.y),
492 static_cast<double>(vec.z));
493 // clang-format on
494 }
495 /// from local to inside
496 inline Base::Vector3f transformToInside(const Base::Vector3d& vec) const
497 {
498 Base::Matrix4D tmpM(getTransform());
499 tmpM.inverse();
500 Base::Vector3d tmp = tmpM * vec;
501 return Base::Vector3f(static_cast<float>(tmp.x),
502 static_cast<float>(tmp.y),
503 static_cast<float>(tmp.z));
504 }
505
506 protected:
507 ElementMapPtr elementMap(bool flush = true) const;
508 ElementMapPtr ensureElementMap(bool flush = true);
509
510 private:
511 ElementMapPtr _elementMap;
512
513 protected:
514 mutable std::string _persistenceName;
515 mutable bool _restoreFailed = false;
516 };
517
518 } // namespace Data
519
520 ENABLE_BITMASK_OPERATORS(Data::SearchOption)
521 #endif