Debian Codegraph @

src/Base/Builder3D.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2011 Jürgen Riegel <[email protected]> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25
26 #include <algorithm>
27 #include <string>
28 #include <string_view>
29 #include <boost/algorithm/string.hpp>
30 #include <boost/algorithm/string/predicate.hpp>
31 #include <boost/lexical_cast.hpp>
32 #include <boost/tokenizer.hpp>
33
34 #include "Builder3D.h"
35 #include "Console.h"
36 #include "Exception.h"
37 #include "FileInfo.h"
38 #include "Stream.h"
39
40
41 using namespace Base;
42
43
44 constexpr float valueMinLegal {-1.0F};
45 constexpr float valueMaxLegal {1.0F};
46
47 ColorRGB::ColorRGB()
48 : Rgb {1.0F, 1.0F, 1.0F}
49 {}
50
51 ColorRGB::ColorRGB(float red, float green, float blue)
52 : Rgb {valueInRange(red), valueInRange(green), valueInRange(blue)}
53 {}
54
55 float ColorRGB::valueInRange(float value)
56 {
57 return std::clamp(value, valueMinLegal, valueMaxLegal);
58 }
59
60 const char* DrawStyle::styleAsString() const
61 {
62 switch (style) {
63 case Style::Filled:
64 return "FILLED";
65 case Style::Lines:
66 return "LINES";
67 case Style::Points:
68 return "POINTS";
69 case Style::Invisible:
70 return "INVISIBLE";
71 }
72 return "FILLED";
73 }
74
75 std::string DrawStyle::patternAsString() const
76 {
77 std::stringstream str;
78 str << "0x" << std::hex << linePattern;
79 return str.str();
80 }
81
82 const char* VertexOrdering::toString() const
83 {
84 switch (ordering) {
85 case Ordering::UnknownOrdering:
86 return "UNKNOWN_ORDERING";
87 case Ordering::Clockwise:
88 return "CLOCKWISE";
89 case Ordering::CounterClockwise:
90 return "COUNTERCLOCKWISE";
91 }
92 return "UNKNOWN_ORDERING";
93 }
94
95 const char* ShapeType::toString() const
96 {
97 switch (type) {
98 case Type::UnknownShapeType:
99 return "UNKNOWN_SHAPE_TYPE";
100 case Type::Convex:
101 return "SOLID";
102 }
103 return "UNKNOWN_SHAPE_TYPE";
104 }
105
106 const char* BindingElement::bindingAsString() const
107 {
108 switch (value) {
109 case Binding::PerPart:
110 return "PER_PART";
111 case Binding::PerPartIndexed:
112 return "PER_PART_INDEXED";
113 case Binding::PerFace:
114 return "PER_FACE";
115 case Binding::PerFaceIndexed:
116 return "PER_FACE_INDEXED";
117 case Binding::PerVertex:
118 return "PER_VERTEX";
119 case Binding::PerVertexIndexed:
120 return "PER_VERTEX_INDEXED";
121 default:
122 return "OVERALL";
123 }
124 }
125
126 const char* PolygonOffset::styleAsString() const
127 {
128 switch (style) {
129 case Style::Filled:
130 return "FILLED";
131 case Style::Lines:
132 return "LINES";
133 case Style::Points:
134 return "POINTS";
135 }
136 return "FILLED";
137 }
138
139 // -----------------------------------------------------------------------------
140
141 InventorOutput::InventorOutput(std::ostream& result, Indentation& indent)
142 : result(result)
143 , indent(indent)
144 {}
145
146 std::ostream& InventorOutput::stream()
147 {
148 return result;
149 }
150
151 std::ostream& InventorOutput::write()
152 {
153 result << indent;
154 return result;
155 }
156
157 std::ostream& InventorOutput::write(const char* str)
158 {
159 result << indent << str;
160 return result;
161 }
162
163 std::ostream& InventorOutput::write(const std::string& str)
164 {
165 result << indent << str;
166 return result;
167 }
168
169 std::ostream& InventorOutput::writeLine()
170 {
171 result << indent << '\n';
172 return result;
173 }
174
175 std::ostream& InventorOutput::writeLine(const char* str)
176 {
177 result << indent << str << '\n';
178 return result;
179 }
180
181 std::ostream& InventorOutput::writeLine(const std::string& str)
182 {
183 result << indent << str << '\n';
184 return result;
185 }
186
187 void InventorOutput::increaseIndent()
188 {
189 indent.increaseIndent();
190 }
191
192 void InventorOutput::decreaseIndent()
193 {
194 indent.decreaseIndent();
195 }
196
197 // -----------------------------------------------------------------------------
198
199 namespace Base
200 {
201 template<class type>
202 struct field_traits
203 {
204 };
205
206 template<>
207 struct field_traits<float>
208 {
209 using field_type = float;
210 static std::ostream& write(std::ostream& out, const field_type& item)
211 {
212 out << item;
213 return out;
214 }
215 };
216
217 template<>
218 struct field_traits<Vector3f>
219 {
220 using field_type = Vector3f;
221 static std::ostream& write(std::ostream& out, const field_type& item)
222 {
223 out << item.x << " " << item.y << " " << item.z;
224 return out;
225 }
226 };
227
228 template<>
229 struct field_traits<ColorRGB>
230 {
231 using field_type = ColorRGB;
232 static std::ostream& write(std::ostream& out, const field_type& item)
233 {
234 out << item.red() << " " << item.green() << " " << item.blue();
235 return out;
236 }
237 };
238
239 /**
240 * Writes a field type to a stream.
241 * @author Werner Mayer
242 */
243 class InventorFieldWriter
244 {
245 public:
246 template<typename T>
247 void write(const char* fieldName, const std::vector<T>& fieldData, InventorOutput& out) const;
248 };
249
250 template<typename T>
251 void InventorFieldWriter::write(
252 const char* fieldName,
253 const std::vector<T>& fieldData,
254 InventorOutput& out
255 ) const
256 {
257 if (fieldData.empty()) {
258 return;
259 }
260
261 if (fieldData.size() == 1) {
262 out.write() << fieldName << " ";
263 field_traits<T>::write(out.stream(), fieldData[0]) << '\n';
264 }
265 else {
266 out.write() << fieldName << " [\n";
267 out.increaseIndent();
268 for (auto it : fieldData) {
269 out.write();
270 field_traits<T>::write(out.stream(), it) << '\n';
271 }
272 out.decreaseIndent();
273 out.write() << "]\n";
274 }
275 }
276
277 template<>
278 void InventorFieldWriter::write<int>(
279 const char* fieldName,
280 const std::vector<int>& fieldData,
281 InventorOutput& out
282 ) const
283 {
284 if (fieldData.empty()) {
285 return;
286 }
287
288 out.write() << fieldName << " [\n";
289 out.increaseIndent();
290 std::size_t last_index {fieldData.size()};
291 std::size_t index {};
292 for (auto it : fieldData) {
293 if (index % 8 == 0) {
294 out.write();
295 }
296 if (index < last_index) {
297 out.stream() << it << ", ";
298 }
299 else {
300 out.stream() << it << " ] \n";
301 }
302 if (++index % 8 == 0) {
303 out.stream() << '\n';
304 }
305 }
306 out.decreaseIndent();
307 out.write() << "]\n";
308 }
309 } // namespace Base
310
311 // -----------------------------------------------------------------------------
312
313 LabelItem::LabelItem(std::string text)
314 : text(std::move(text))
315 {}
316
317 void LabelItem::write(InventorOutput& out) const
318 {
319 out.write("Label {\n");
320 out.write() << " label \"" << text << "\"\n";
321 out.write("}\n");
322 }
323
324 // -----------------------------------------------------------------------------
325
326 InfoItem::InfoItem(std::string text)
327 : text(std::move(text))
328 {}
329
330 void InfoItem::write(InventorOutput& out) const
331 {
332 out.write("Info {\n");
333 out.write() << " string \"" << text << "\"\n";
334 out.write("}\n");
335 }
336
337 // -----------------------------------------------------------------------------
338
339 BaseColorItem::BaseColorItem(const ColorRGB& rgb)
340 : rgb(rgb)
341 {}
342
343 void BaseColorItem::write(InventorOutput& out) const
344 {
345 out.write("BaseColor {\n");
346 out.write() << " rgb " << rgb.red() << " " << rgb.green() << " " << rgb.blue() << '\n';
347 out.write("}\n");
348 }
349
350 // -----------------------------------------------------------------------------
351
352 PointItem::PointItem(const Base::Vector3f& point, DrawStyle drawStyle, const ColorRGB& rgb)
353 : point(point)
354 , drawStyle(drawStyle)
355 , rgb(rgb)
356 {}
357
358 void PointItem::write(InventorOutput& out) const
359 {
360 out.write() << "Separator { \n";
361 out.write() << " Material { \n";
362 out.write() << " diffuseColor " << rgb.red() << " " << rgb.green() << " " << rgb.blue()
363 << '\n';
364 out.write() << " }\n";
365 out.write() << " MaterialBinding { value PER_PART }\n";
366 out.write() << " DrawStyle { pointSize " << drawStyle.pointSize << "}\n";
367 out.write() << " Coordinate3 {\n";
368 out.write() << " point [ " << point.x << " " << point.y << " " << point.z << "]\n";
369 out.write() << " }\n";
370 out.write() << " PointSet { }\n";
371 out.write() << "}\n";
372 }
373
374 // -----------------------------------------------------------------------------
375
376 LineItem::LineItem(const Base::Line3f& line, DrawStyle drawStyle, const ColorRGB& rgb)
377 : line(line)
378 , drawStyle(drawStyle)
379 , rgb(rgb)
380 {}
381
382 void LineItem::write(InventorOutput& out) const
383 {
384 std::string pattern = drawStyle.patternAsString();
385
386 out.write(" Separator { \n");
387 out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " "
388 << rgb.blue() << "} \n";
389 out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " linePattern " << pattern
390 << " } \n";
391 out.write() << " Coordinate3 { \n";
392 out.write() << " point [ ";
393 out.write() << line.p1.x << " " << line.p1.y << " " << line.p1.z << ",";
394 out.write() << line.p2.x << " " << line.p2.y << " " << line.p2.z;
395 out.write() << " ] \n";
396 out.write() << " } \n";
397 out.write() << " LineSet { } \n";
398 out.write() << " } \n";
399 }
400
401 // -----------------------------------------------------------------------------
402
403 MultiLineItem::MultiLineItem(std::vector<Vector3f> points, DrawStyle drawStyle, const ColorRGB& rgb)
404 : points {std::move(points)}
405 , drawStyle {drawStyle}
406 , rgb {rgb}
407 {}
408
409 void MultiLineItem::write(InventorOutput& out) const
410 {
411 std::string pattern = drawStyle.patternAsString();
412
413 out.write() << "Separator {\n";
414 out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " "
415 << rgb.blue() << "}\n";
416 out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " linePattern " << pattern
417 << " }\n";
418 out.write() << " Coordinate3 {\n";
419
420 InventorFieldWriter writer;
421 writer.write<Vector3f>("point", points, out);
422
423 out.write() << " }\n";
424 out.write() << " LineSet {\n";
425 out.write() << " numVertices [ -1 ]\n";
426 out.write() << " }\n";
427 out.write() << "}\n";
428 }
429
430 // -----------------------------------------------------------------------------
431
432 ArrowItem::ArrowItem(const Base::Line3f& line, DrawStyle drawStyle, const ColorRGB& rgb)
433 : line(line)
434 , drawStyle(drawStyle)
435 , rgb(rgb)
436 {}
437
438 void ArrowItem::write(InventorOutput& out) const
439 {
440 float length = line.Length();
441 float coneLength = length / 10.0F;
442 float coneRadius = coneLength / 2.0F;
443 float sf1 = length - coneLength;
444 float sf2 = length - coneLength / 2.0F;
445
446 Vector3f dir = line.GetDirection();
447 dir.Normalize();
448 dir.Scale(sf1, sf1, sf1);
449 Vector3f pt2s = line.p1 + dir;
450 dir.Normalize();
451 dir.Scale(sf2, sf2, sf2);
452 Vector3f cpt = line.p1 + dir;
453
454 Vector3f rot = Vector3f(0.0F, 1.0F, 0.0F) % dir;
455 rot.Normalize();
456 float angle = Vector3f(0.0F, 1.0F, 0.0F).GetAngle(dir);
457
458 out.write() << "Separator {\n";
459 out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " "
460 << rgb.blue() << "}\n";
461 out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " }\n";
462 out.write() << " Coordinate3 {\n";
463 out.write() << " point [ ";
464 out.write() << line.p1.x << " " << line.p1.y << " " << line.p1.z << ", ";
465 out.write() << pt2s.x << " " << pt2s.y << " " << pt2s.z;
466 out.write() << " ]\n";
467 out.write() << " }\n";
468 out.write() << " LineSet { }\n";
469 out.write() << " Transform { \n";
470 out.write() << " translation " << cpt.x << " " << cpt.y << " " << cpt.z << '\n';
471 out.write() << " rotation " << rot.x << " " << rot.y << " " << rot.z << " " << angle << '\n';
472 out.write() << " }\n";
473 out.write() << " Cone { bottomRadius " << coneRadius << " height " << coneLength << "} \n";
474 out.write() << "}\n";
475 }
476
477 // -----------------------------------------------------------------------------
478
479 BoundingBoxItem::BoundingBoxItem(
480 const Vector3f& pt1,
481 const Vector3f& pt2,
482 DrawStyle drawStyle,
483 const ColorRGB& rgb
484 )
485 : pt1 {pt1}
486 , pt2 {pt2}
487 , drawStyle {drawStyle}
488 , rgb {rgb}
489 {}
490
491 void BoundingBoxItem::write(InventorOutput& out) const
492 {
493 std::vector<Base::Vector3f> points(8);
494 points[0].Set(pt1.x, pt1.y, pt1.z);
495 points[1].Set(pt1.x, pt1.y, pt2.z);
496 points[2].Set(pt1.x, pt2.y, pt1.z);
497 points[3].Set(pt1.x, pt2.y, pt2.z);
498 points[4].Set(pt2.x, pt1.y, pt1.z);
499 points[5].Set(pt2.x, pt1.y, pt2.z);
500 points[6].Set(pt2.x, pt2.y, pt1.z);
501 points[7].Set(pt2.x, pt2.y, pt2.z);
502
503 std::vector<int> lineset = {0, 2, 6, 4, 0, -1, 1, 5, 7, 3, 1, -1, 7, 6, 2,
504 3, 7, -1, 3, 2, 0, 1, 3, -1, 5, 1, 0, 4, 5, -1};
505
506 out.write() << "Separator {\n";
507 out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " "
508 << rgb.blue() << "}\n";
509 out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << "}\n";
510
511 Coordinate3Item coords {points};
512 out.increaseIndent();
513 coords.write(out);
514 out.decreaseIndent();
515
516 IndexedLineSetItem indexed {lineset};
517 out.increaseIndent();
518 indexed.write(out);
519 out.decreaseIndent();
520
521 out.write() << "}\n";
522 }
523
524 // -----------------------------------------------------------------------------
525
526 void MaterialItem::setAmbientColor(const std::vector<ColorRGB>& rgb)
527 {
528 ambientColor = rgb;
529 }
530
531 void MaterialItem::setDiffuseColor(const std::vector<ColorRGB>& rgb)
532 {
533 diffuseColor = rgb;
534 }
535
536 void MaterialItem::setSpecularColor(const std::vector<ColorRGB>& rgb)
537 {
538 specularColor = rgb;
539 }
540
541 void MaterialItem::setEmissiveColor(const std::vector<ColorRGB>& rgb)
542 {
543 emissiveColor = rgb;
544 }
545
546 void MaterialItem::setShininess(const std::vector<float>& value)
547 {
548 shininess = value;
549 }
550
551 void MaterialItem::setTransparency(const std::vector<float>& value)
552 {
553 transparency = value;
554 }
555
556 void MaterialItem::write(InventorOutput& out) const
557 {
558 beginMaterial(out);
559 writeAmbientColor(out);
560 writeDiffuseColor(out);
561 writeSpecularColor(out);
562 writeEmissiveColor(out);
563 writeShininess(out);
564 writeTransparency(out);
565 endMaterial(out);
566 }
567
568 void MaterialItem::beginMaterial(InventorOutput& out) const
569 {
570 out.writeLine("Material {");
571 out.increaseIndent();
572 }
573
574 void MaterialItem::endMaterial(InventorOutput& out) const
575 {
576 out.decreaseIndent();
577 out.writeLine("}");
578 }
579
580 void MaterialItem::writeAmbientColor(InventorOutput& out) const
581 {
582 InventorFieldWriter writer;
583 writer.write<ColorRGB>("ambientColor", ambientColor, out);
584 }
585
586 void MaterialItem::writeDiffuseColor(InventorOutput& out) const
587 {
588 InventorFieldWriter writer;
589 writer.write<ColorRGB>("diffuseColor", diffuseColor, out);
590 }
591
592 void MaterialItem::writeSpecularColor(InventorOutput& out) const
593 {
594 InventorFieldWriter writer;
595 writer.write<ColorRGB>("specularColor", specularColor, out);
596 }
597
598 void MaterialItem::writeEmissiveColor(InventorOutput& out) const
599 {
600 InventorFieldWriter writer;
601 writer.write<ColorRGB>("emissiveColor", emissiveColor, out);
602 }
603
604 void MaterialItem::writeShininess(InventorOutput& out) const
605 {
606 InventorFieldWriter writer;
607 writer.write<float>("shininess", shininess, out);
608 }
609
610 void MaterialItem::writeTransparency(InventorOutput& out) const
611 {
612 InventorFieldWriter writer;
613 writer.write<float>("transparency", transparency, out);
614 }
615
616 // -----------------------------------------------------------------------------
617
618 MaterialBindingItem::MaterialBindingItem(BindingElement::Binding bind)
619 {
620 value.value = bind;
621 }
622
623 void MaterialBindingItem::setValue(BindingElement::Binding bind)
624 {
625 value.value = bind;
626 }
627
628 void MaterialBindingItem::write(InventorOutput& out) const
629 {
630 out.write() << "MaterialBinding { value " << value.bindingAsString() << " } \n";
631 }
632
633 // -----------------------------------------------------------------------------
634
635 DrawStyleItem::DrawStyleItem(DrawStyle value)
636 : style {value}
637 {}
638
639 void DrawStyleItem::setValue(DrawStyle value)
640 {
641 style = value;
642 }
643
644 void DrawStyleItem::write(InventorOutput& out) const
645 {
646 out.write() << "DrawStyle {\n";
647 out.write() << " style " << style.styleAsString() << '\n';
648 out.write() << " pointSize " << style.pointSize << '\n';
649 out.write() << " lineWidth " << style.lineWidth << '\n';
650 out.write() << " linePattern " << style.patternAsString() << '\n';
651 out.write() << "}\n";
652 }
653
654 // -----------------------------------------------------------------------------
655
656 ShapeHintsItem::ShapeHintsItem(float creaseAngle)
657 : creaseAngle(creaseAngle)
658 {}
659
660 void ShapeHintsItem::setVertexOrdering(VertexOrdering::Ordering value)
661 {
662 vertexOrdering.ordering = value;
663 }
664
665 void ShapeHintsItem::setShapeType(ShapeType::Type value)
666 {
667 shapeType.type = value;
668 }
669
670 void ShapeHintsItem::write(InventorOutput& out) const
671 {
672 out.write() << "ShapeHints {\n";
673 out.write() << " creaseAngle " << creaseAngle << '\n';
674 out.write() << " vertexOrdering " << vertexOrdering.toString() << '\n';
675 out.write() << " shapeType " << shapeType.toString() << '\n';
676 out.write() << "}\n";
677 }
678
679 // -----------------------------------------------------------------------------
680
681 void PolygonOffsetItem::setValue(PolygonOffset value)
682 {
683 offset = value;
684 }
685
686 void PolygonOffsetItem::write(InventorOutput& out) const
687 {
688 out.write() << "PolygonOffset {\n";
689 out.write() << " factor " << offset.factor << '\n';
690 out.write() << " units " << offset.units << '\n';
691 out.write() << " styles " << offset.styleAsString() << '\n';
692 out.write() << " on " << (offset.on ? "TRUE" : "FALSE") << '\n';
693 out.write() << "}\n";
694 }
695
696 // -----------------------------------------------------------------------------
697
698 Coordinate3Item::Coordinate3Item(std::vector<Vector3f> points)
699 : points(std::move(points))
700 {}
701
702 void Coordinate3Item::write(InventorOutput& out) const
703 {
704 beginPoint(out);
705 InventorFieldWriter writer;
706 writer.write<Vector3f>("point", points, out);
707 endPoint(out);
708 }
709
710 void Coordinate3Item::beginPoint(InventorOutput& out) const
711 {
712 out.writeLine("Coordinate3 {");
713 out.increaseIndent();
714 }
715
716 void Coordinate3Item::endPoint(InventorOutput& out) const
717 {
718 out.decreaseIndent();
719 out.writeLine("}");
720 }
721
722 // -----------------------------------------------------------------------------
723
724 void PointSetItem::write(InventorOutput& out) const
725 {
726 out.writeLine("PointSet { }");
727 }
728
729 // -----------------------------------------------------------------------------
730
731 void LineSetItem::write(InventorOutput& out) const
732 {
733 out.writeLine("LineSet { }");
734 }
735
736 // -----------------------------------------------------------------------------
737
738 FaceSetItem::FaceSetItem(std::vector<int> indices)
739 : indices(std::move(indices))
740 {}
741
742 void FaceSetItem::write(InventorOutput& out) const
743 {
744 out.write() << "FaceSet {\n";
745 out.increaseIndent();
746 InventorFieldWriter writer;
747 writer.write<int>("numVertices", indices, out);
748 out.decreaseIndent();
749 out.write() << "}\n";
750 }
751
752 // -----------------------------------------------------------------------------
753
754 IndexedLineSetItem::IndexedLineSetItem(std::vector<int> indices)
755 : indices(std::move(indices))
756 {}
757
758 void IndexedLineSetItem::write(InventorOutput& out) const
759 {
760 out.write() << "IndexedLineSet {\n";
761 out.increaseIndent();
762 InventorFieldWriter writer;
763 writer.write<int>("coordIndex", indices, out);
764 out.decreaseIndent();
765 out.write() << "}\n";
766 }
767
768 // -----------------------------------------------------------------------------
769
770 IndexedFaceSetItem::IndexedFaceSetItem(std::vector<int> indices)
771 : indices(std::move(indices))
772 {}
773
774 void IndexedFaceSetItem::write(InventorOutput& out) const
775 {
776 out.write() << "IndexedFaceSet {\n";
777 out.increaseIndent();
778 InventorFieldWriter writer;
779 writer.write<int>("coordIndex", indices, out);
780 out.decreaseIndent();
781 out.write() << "}\n";
782 }
783
784 // -----------------------------------------------------------------------------
785
786 NormalItem::NormalItem(std::vector<Base::Vector3f> vec)
787 : vector(std::move(vec))
788 {}
789
790 void NormalItem::write(InventorOutput& out) const
791 {
792 beginNormal(out);
793 InventorFieldWriter writer;
794 writer.write<Vector3f>("vector", vector, out);
795 endNormal(out);
796 }
797
798 void NormalItem::beginNormal(InventorOutput& out) const
799 {
800 out.writeLine("Normal {");
801 out.increaseIndent();
802 }
803
804 void NormalItem::endNormal(InventorOutput& out) const
805 {
806 out.decreaseIndent();
807 out.writeLine("}");
808 }
809
810 // -----------------------------------------------------------------------------
811
812 void NormalBindingItem::setValue(BindingElement::Binding bind)
813 {
814 value.value = bind;
815 }
816
817 void NormalBindingItem::write(InventorOutput& out) const
818 {
819 out.write() << "NormalBinding { value " << value.bindingAsString() << " }\n";
820 }
821
822 // -----------------------------------------------------------------------------
823
824 void CylinderItem::setRadius(float value)
825 {
826 radius = value;
827 }
828
829 void CylinderItem::setHeight(float value)
830 {
831 height = value;
832 }
833
834 void CylinderItem::write(InventorOutput& out) const
835 {
836 out.write() << "Cylinder {\n";
837 out.write() << " radius " << radius << "\n";
838 out.write() << " height " << height << "\n";
839 out.write() << " parts (SIDES | TOP | BOTTOM)\n";
840 out.write() << "}\n";
841 }
842
843 // -----------------------------------------------------------------------------
844
845 void ConeItem::setBottomRadius(float value)
846 {
847 bottomRadius = value;
848 }
849
850 void ConeItem::setHeight(float value)
851 {
852 height = value;
853 }
854
855 void ConeItem::write(InventorOutput& out) const
856 {
857 out.write() << "Cone { bottomRadius " << bottomRadius << " height " << height << " }\n";
858 }
859
860 // -----------------------------------------------------------------------------
861
862 void SphereItem::setRadius(float value)
863 {
864 radius = value;
865 }
866
867 void SphereItem::write(InventorOutput& out) const
868 {
869 out.write() << "Sphere { radius " << radius << " }\n";
870 }
871
872 // -----------------------------------------------------------------------------
873
874 void NurbsSurfaceItem::setControlPoints(int numU, int numV)
875 {
876 numUControlPoints = numU;
877 numVControlPoints = numV;
878 }
879
880 void NurbsSurfaceItem::setKnotVector(const std::vector<float>& uKnots, const std::vector<float>& vKnots)
881 {
882 uKnotVector = uKnots;
883 vKnotVector = vKnots;
884 }
885
886 void NurbsSurfaceItem::write(InventorOutput& out) const
887 {
888 out.write() << "NurbsSurface {\n";
889 out.write() << " numUControlPoints " << numUControlPoints << '\n';
890 out.write() << " numVControlPoints " << numVControlPoints << '\n';
891 out.increaseIndent();
892 InventorFieldWriter writer;
893 writer.write<float>("uKnotVector", uKnotVector, out);
894 writer.write<float>("vKnotVector", vKnotVector, out);
895 out.decreaseIndent();
896 out.write() << "}\n";
897 }
898
899 // -----------------------------------------------------------------------------
900
901 Text2Item::Text2Item(std::string string)
902 : string(std::move(string))
903 {}
904
905 void Text2Item::write(InventorOutput& out) const
906 {
907 out.write() << "Text2 { string \"" << string << "\" "
908 << "}\n";
909 }
910
911 // -----------------------------------------------------------------------------
912
913 // NOLINTNEXTLINE
914 TransformItem::TransformItem(const Base::Placement& placement)
915 : placement(placement)
916 {}
917
918 TransformItem::TransformItem(const Matrix4D& transform)
919 {
920 placement.fromMatrix(transform);
921 }
922
923 void TransformItem::write(InventorOutput& out) const
924 {
925 Base::Vector3d translation = placement.getPosition();
926 Base::Vector3d rotationaxis;
927 double angle {};
928 placement.getRotation().getValue(rotationaxis, angle);
929
930 out.write() << "Transform {\n";
931 out.write() << " translation " << translation.x << " " << translation.y << " " << translation.z
932 << '\n';
933 out.write() << " rotation " << rotationaxis.x << " " << rotationaxis.y << " " << rotationaxis.z
934 << " " << angle << '\n';
935 out.write() << "}" << '\n';
936 }
937
938 // -----------------------------------------------------------------------------
939
940 InventorBuilder::InventorBuilder(std::ostream& str)
941 : result(str)
942 {
943 addHeader();
944 }
945
946 InventorBuilder::~InventorBuilder() = default;
947
948 void InventorBuilder::addHeader()
949 {
950 result << "#Inventor V2.1 ascii \n\n";
951 }
952
953 void InventorBuilder::increaseIndent()
954 {
955 indent.increaseIndent();
956 }
957
958 void InventorBuilder::decreaseIndent()
959 {
960 indent.decreaseIndent();
961 }
962
963 void InventorBuilder::addNode(const NodeItem& node)
964 {
965 InventorOutput out(result, indent);
966 node.write(out);
967 }
968
969 void InventorBuilder::beginSeparator()
970 {
971 result << indent << "Separator { \n";
972 increaseIndent();
973 }
974
975 void InventorBuilder::endSeparator()
976 {
977 decreaseIndent();
978 result << indent << "}\n";
979 }
980
981 // -----------------------------------------------------------------------------
982
983 /**
984 * A constructor.
985 * A more elaborate description of the constructor.
986 */
987 Builder3D::Builder3D()
988 : result {}
989 , builder {result}
990 {}
991
992 /**
993 * A destructor.
994 * A more elaborate description of the destructor.
995 */
996 Builder3D::~Builder3D() = default;
997
998 void Builder3D::clear()
999 {
1000 // under gcc stringstream::str() returns a copy not a reference
1001 #if defined(_MSC_VER)
1002 result.str().clear();
1003 #endif
1004 result.clear();
1005 }
1006
1007 /**
1008 * Save the resulting inventor 3D representation to the Console().log() facility.
1009 * In DEBUG mode the Gui (if running) will trigger on that and show the representation in
1010 * the active Viewer/Document. It shows only one representation on time. If you need to
1011 * show more then one representation use saveToFile() instead.
1012 * @see saveToFile()
1013 */
1014 void Builder3D::saveToLog()
1015 {
1016 ILogger* obs = Base::Console().get("StatusBar");
1017 if (obs) {
1018 obs->sendLog(
1019 "Builder3D",
1020 result.str(),
1021 Base::LogStyle::Log,
1022 Base::IntendedRecipient::Developer,
1023 Base::ContentType::Untranslatable
1024 );
1025 }
1026 }
1027
1028 /**
1029 * Save the resulting inventor 3D representation to a file. Ending should be *.iv.
1030 * That enables you to show the result in a Inventor Viewer or in FreeCAD by:
1031 * /code
1032 * Gui.document().addAnnotation("Debug","MyFile.iv")
1033 * /endcode
1034 * @see saveToFile()
1035 */
1036 void Builder3D::saveToFile(const char* FileName)
1037 {
1038 Base::FileInfo fi(FileName);
1039 Base::ofstream file(fi);
1040 if (!file) {
1041 throw FileException("Cannot open file");
1042 }
1043
1044 file << result.str();
1045 }
1046
1047 void Builder3D::addNode(const NodeItem& item)
1048 {
1049 builder.addNode(item);
1050 }
1051
1052 void Builder3D::beginSeparator()
1053 {
1054 builder.beginSeparator();
1055 }
1056
1057 void Builder3D::endSeparator()
1058 {
1059 builder.endSeparator();
1060 }
1061
1062 // -----------------------------------------------------------------------------
1063
1064 template<typename T>
1065 std::vector<T> InventorLoader::readData(const char* fieldName) const
1066 {
1067 std::vector<T> fieldValues;
1068 std::string str;
1069
1070 // search for 'fieldName' and '['
1071 bool found = false;
1072 while (std::getline(inp, str)) {
1073 std::string::size_type point = str.find(fieldName);
1074 std::string::size_type open = str.find('[');
1075 if (point != std::string::npos && open > point) {
1076 str = str.substr(open);
1077 found = true;
1078 break;
1079 }
1080 }
1081
1082 if (!found) {
1083 return {};
1084 }
1085
1086 do {
1087 boost::char_separator<char> sep(" ,");
1088 boost::tokenizer<boost::char_separator<char>> tokens(str, sep);
1089 std::vector<std::string> token_results;
1090 token_results.assign(tokens.begin(), tokens.end());
1091
1092 for (const auto& it : token_results) {
1093 try {
1094 T value = boost::lexical_cast<T>(it);
1095 fieldValues.emplace_back(value);
1096 }
1097 catch (const boost::bad_lexical_cast&) {
1098 }
1099 }
1100
1101 // search for ']' to finish the reading
1102 if (str.find(']') != std::string::npos) {
1103 break;
1104 }
1105 } while (std::getline(inp, str));
1106
1107 return fieldValues;
1108 }
1109
1110 std::vector<Vector3f> InventorLoader::convert(const std::vector<float>& data) const
1111 {
1112 if (data.size() % 3 != 0) {
1113 throw std::string("Reading failed");
1114 }
1115
1116 std::size_t len = data.size() / 3;
1117 std::vector<Vector3f> points;
1118 points.reserve(len);
1119
1120 for (std::size_t i = 0; i < len; i++) {
1121 float x = data[3 * i];
1122 float y = data[3 * i + 1];
1123 float z = data[3 * i + 2];
1124 points.emplace_back(x, y, z);
1125 }
1126
1127 return points;
1128 }
1129
1130 std::vector<InventorLoader::Face> InventorLoader::convert(const std::vector<int32_t>& data) const
1131 {
1132 std::vector<Face> faces;
1133 faces.reserve(data.size());
1134 int32_t coordIndex = 0;
1135 for (const auto it : data) {
1136 if (it == 3) {
1137 faces.emplace_back(coordIndex, coordIndex + 1, coordIndex + 2);
1138 }
1139 else if (it == 4) {
1140 faces.emplace_back(coordIndex, coordIndex + 1, coordIndex + 2);
1141 faces.emplace_back(coordIndex, coordIndex + 2, coordIndex + 3);
1142 }
1143 coordIndex += it;
1144 }
1145 return faces;
1146 }
1147
1148 std::vector<std::vector<int32_t>> InventorLoader::split(const std::vector<int32_t>& data)
1149 {
1150 std::vector<std::vector<int32_t>> splitdata;
1151 std::vector<int32_t>::const_iterator begin = data.cbegin();
1152 std::vector<int32_t>::const_iterator it = begin;
1153
1154 while ((it = std::find(begin, data.cend(), -1)) != data.cend()) {
1155 splitdata.emplace_back(begin, it);
1156 begin = it;
1157 std::advance(begin, 1);
1158 }
1159 return splitdata;
1160 }
1161
1162 std::vector<InventorLoader::Face> InventorLoader::convert(
1163 const std::vector<std::vector<int32_t>>& coordIndex
1164 ) const
1165 {
1166 std::vector<Face> faces;
1167 faces.reserve(coordIndex.size());
1168 for (const auto& it : coordIndex) {
1169 if (it.size() == 3) {
1170 faces.emplace_back(it[0], it[1], it[2]);
1171 }
1172 else if (it.size() == 4) {
1173 faces.emplace_back(it[0], it[1], it[2]);
1174 faces.emplace_back(it[0], it[2], it[3]);
1175 }
1176 }
1177 return faces;
1178 }
1179
1180 void InventorLoader::readNormals()
1181 {
1182 auto data = readData<float>("vector");
1183 vector = convert(data);
1184 }
1185
1186 void InventorLoader::readCoords()
1187 {
1188 auto data = readData<float>("point");
1189 points = convert(data);
1190 }
1191
1192 void InventorLoader::readIndexedFaceSet()
1193 {
1194 auto data = readData<int32_t>("coordIndex");
1195 faces = convert(split(data));
1196 }
1197
1198 void InventorLoader::readFaceSet()
1199 {
1200 auto data = readData<int32_t>("numVertices");
1201 faces = convert(data);
1202 isnonindexed = true;
1203 }
1204
1205 bool InventorLoader::read()
1206 {
1207 if (!inp || inp.bad()) {
1208 return false;
1209 }
1210
1211 std::string line;
1212
1213 // Verify it's an Inventor 2.1 file
1214 std::getline(inp, line);
1215 if (line.find("#Inventor V2.1 ascii") == std::string::npos) {
1216 return false;
1217 }
1218
1219 while (std::getline(inp, line)) {
1220 // read the normals if they are defined
1221 if (line.find("Normal {") != std::string::npos) {
1222 readNormals();
1223 }
1224 else if (line.find("Coordinate3 {") != std::string::npos) {
1225 readCoords();
1226 }
1227 else if (line.find("IndexedFaceSet {") != std::string::npos) {
1228 readIndexedFaceSet();
1229 break;
1230 }
1231 else if (line.find("FaceSet {") != std::string::npos) {
1232 readFaceSet();
1233 break;
1234 }
1235 }
1236 return true;
1237 }
1238
1239 bool InventorLoader::isValid() const
1240 {
1241 int32_t value {static_cast<int32_t>(points.size())};
1242 auto inRange = [value](const Face& face) {
1243 if (face.p1 < 0 || face.p1 >= value) {
1244 return false;
1245 }
1246 if (face.p2 < 0 || face.p2 >= value) {
1247 return false;
1248 }
1249 if (face.p3 < 0 || face.p3 >= value) {
1250 return false;
1251 }
1252 return true;
1253 };
1254
1255 return std::all_of(faces.cbegin(), faces.cend(), [&inRange](const Face& face) {
1256 return inRange(face);
1257 });
1258 }
1259
1260 namespace Base
1261 {
1262 BaseExport Vector3f stringToVector(std::string str)
1263 {
1264 std::string_view view = str;
1265 if (!boost::starts_with(view, "(") || !boost::ends_with(str, ")")) {
1266 throw std::runtime_error("string is not a tuple");
1267 }
1268
1269 view.remove_prefix(1);
1270 view.remove_suffix(1);
1271
1272 str = view;
1273
1274 boost::char_separator<char> sep(" ,");
1275 boost::tokenizer<boost::char_separator<char>> tokens(str, sep);
1276 std::vector<std::string> token_results;
1277 token_results.assign(tokens.begin(), tokens.end());
1278
1279 if (token_results.size() != 3) {
1280 throw std::runtime_error("not a tuple of three floats");
1281 }
1282
1283 Base::Vector3f vec;
1284 vec.x = boost::lexical_cast<float>(token_results.at(0));
1285 vec.y = boost::lexical_cast<float>(token_results.at(1));
1286 vec.z = boost::lexical_cast<float>(token_results.at(2));
1287
1288 return vec;
1289 }
1290
1291 BaseExport std::string vectorToString(Vector3f vec)
1292 {
1293 return fmt::format("({},{},{})", vec.x, vec.y, vec.z);
1294 }
1295
1296 } // namespace Base