-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathvoxec.h
3431 lines (2959 loc) · 101 KB
/
voxec.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef VOXEC_H
#define VOXEC_H
#ifdef WITH_IFC
#ifdef IFCOPENSHELL_05
#include <ifcgeom/IfcGeomIterator.h>
#else
#ifdef IFCOPENSHELL_08
#include <ifcgeom/Iterator.h>
#include <ifcgeom/kernels/opencascade/OpenCascadeConversionResult.h>
#else
#include <ifcgeom_schema_agnostic/IfcGeomIterator.h>
#endif
#endif
#include <ifcparse/IfcFile.h>
#include <boost/filesystem.hpp>
#include <Eigen/Dense>
// #define OLD_GROUP_BY
struct instance_filter_t {
virtual bool operator()(const IfcUtil::IfcBaseEntity*) const = 0;
};
struct filtered_files_t {
std::vector<IfcParse::IfcFile*> files;
instance_filter_t* filter = nullptr;
};
#else
namespace IfcParse {
class IfcFile {};
}
struct filtered_files_t {};
#endif
#include "voxelfile.h"
#include "processor.h"
#include "storage.h"
#include "offset.h"
#include "fill_gaps.h"
#include "traversal.h"
#include "json_logger.h"
#include <Bnd_Box.hxx>
#include <BRepBndLib.hxx>
#include <BRep_Builder.hxx>
#include <BRepTools.hxx>
#include <ProjLib.hxx>
#include <TopExp_Explorer.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepAlgoAPI_Common.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRepPrimAPI_MakeHalfSpace.hxx>
#include <set>
#include <map>
#include <exception>
#include <functional>
#include <boost/variant/apply_visitor.hpp>
#include <boost/tokenizer.hpp>
#include <boost/range/iterator_range.hpp>
#ifdef WIN32
#define DIRSEP "\\"
#else
#define DIRSEP "/"
#endif
size_t get_padding();
void set_padding(size_t);
typedef boost::variant<boost::blank, filtered_files_t, geometry_collection_t*, abstract_voxel_storage*, function_arg_value_type> symbol_value;
class voxel_operation;
class assertion_error : public std::runtime_error {
using std::runtime_error::runtime_error;
};
namespace {
template <typename T>
typename std::enable_if<boost::mpl::contains<symbol_value::types, T>::type::value, const T&>::type
get_value_(const symbol_value& v) {
return boost::get<T>(v);
}
template <typename T>
typename std::enable_if<boost::mpl::contains<function_arg_value_type::types, T>::type::value, const T&>::type
get_value_(const symbol_value& v) {
return boost::get<T>(boost::get<function_arg_value_type>(v));
}
template <typename T>
typename std::enable_if<boost::mpl::contains<symbol_value::types, T>::type::value, const T*>::type
get_value_opt_(const symbol_value& v) {
return boost::get<T>(&v);
}
template <typename T>
typename std::enable_if<boost::mpl::contains<function_arg_value_type::types, T>::type::value, const T*>::type
get_value_opt_(const symbol_value& v) {
// @todo?
return boost::get<T>(boost::get<function_arg_value_type>(&v));
}
}
class scope_map : public std::map<std::string, symbol_value> {
public:
const std::map<std::string, function_def_type>* functions;
class not_in_scope : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class value_error : public std::runtime_error {
using std::runtime_error::runtime_error;
};
template <typename T>
const T& get_value_or(const std::string& symbol, const T& default_value) const {
auto it = find(symbol);
if (it == end()) {
return default_value;
}
return get_value_<T>(it->second);
}
template <typename T>
const T& get_value(const std::string& symbol) const {
auto it = find(symbol);
if (it == end()) {
throw not_in_scope("Undefined variable " + symbol);
}
try {
return get_value_<T>(it->second);
} catch (boost::bad_get&) {
throw value_error(std::string("Expected ") + typeid(T).name() + " got type index " + std::to_string(it->second.which()));
}
}
const int get_length(const std::string& symbol) const {
auto it = find(symbol);
if (it == end()) {
throw not_in_scope("Undefined variable " + symbol);
}
try {
return get_value_<int>(it->second);
} catch (boost::bad_get&) {
return std::ceil(get_value_<double>(it->second) / get_value<double>("VOXELSIZE"));
}
}
const double get_length_f(const std::string& symbol) const {
auto it = find(symbol);
if (it == end()) {
throw not_in_scope("Undefined variable " + symbol);
}
try {
return get_value_<double>(it->second);
} catch (boost::bad_get&) {
return std::ceil(get_value_<int>(it->second) * get_value<double>("VOXELSIZE"));
}
}
bool has(const std::string& symbol) const {
auto it = find(symbol);
return it != end();
}
};
struct voxel_operation_map {
public:
typedef std::map<std::string, std::function<voxel_operation*()> > map_t;
static map_t& map();
static voxel_operation* create(const std::string& s) {
auto it = map().find(s);
if (it == map().end()) {
throw std::runtime_error("No operation named " + s);
}
return it->second();
}
};
struct argument_spec {
bool required;
std::string name;
std::string type;
};
class voxel_operation {
public:
boost::optional<std::function<void(float)>> application_progress_callback;
bool silent = false;
virtual const std::vector<argument_spec>& arg_names() const = 0;
virtual symbol_value invoke(const scope_map& scope) const = 0;
virtual bool catch_all() const {
return false;
}
virtual bool only_local() const {
return false;
}
virtual ~voxel_operation() {}
};
void invoke_function_by_name(scope_map& context, const std::string& function_name);
namespace {
json_logger::meta_data dump_info(abstract_voxel_storage* voxels) {
if (dynamic_cast<abstract_chunked_voxel_storage*>(voxels)) {
auto csize = dynamic_cast<abstract_chunked_voxel_storage*>(voxels)->chunk_size();
auto left = dynamic_cast<abstract_chunked_voxel_storage*>(voxels)->grid_offset();
auto nc = dynamic_cast<abstract_chunked_voxel_storage*>(voxels)->num_chunks();
auto right = (left + nc.as<long>()) - (decltype(left)::element_type)1;
auto sz = dynamic_cast<abstract_chunked_voxel_storage*>(voxels)->voxel_size();
auto szl = (long)dynamic_cast<abstract_chunked_voxel_storage*>(voxels)->chunk_size();
auto left_world = ((voxels->bounds()[0].as<long>() + left * szl).as<double>() * sz);
auto right_world = ((voxels->bounds()[1].as<long>() + left * szl).as<double>() * sz);
json_logger::meta_data md = {
{"count", (long)voxels->count()},
{"grid", left.format() + " - " + right.format()},
{"bounds", voxels->bounds()[0].format() + " - " + voxels->bounds()[1].format()},
{"world", left_world.format() + " - " + right_world.format()},
{"bits", (long)voxels->value_bits()},
{"chunk_size", (long) csize}
};
if (voxels->value_bits() == 32) {
uint32_t v, mi = std::numeric_limits<uint32_t>::max(), ma = std::numeric_limits<uint32_t>::min();
for (auto& ijk : *(regular_voxel_storage*)voxels) {
voxels->Get(ijk, &v);
if (v < mi) {
mi = v;
}
if (v > ma) {
ma = v;
}
}
md.insert({ "min_value", (long)mi });
md.insert({ "max_value", (long)ma });
}
return md;
}
return {};
}
}
#ifdef WITH_IFC
class op_parse_ifc_file : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "input", "string"} };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
using namespace boost::filesystem;
const std::string& pattern = scope.get_value<std::string>("input");
boost::regex regex = IfcGeom::wildcard_filter::wildcard_string_to_regex(pattern);
std::vector<IfcParse::IfcFile*> files;
for (auto& entry : boost::make_iterator_range(recursive_directory_iterator("."), {})) {
// strip off ./
std::string filename = entry.path().string().substr(2);
if (boost::regex_match(filename, regex)) {
std::string filename = entry.path().string();
{
std::ifstream fs(filename.c_str());
if (!fs.good()) {
throw std::runtime_error("Unable to open file " + filename);
}
}
#ifdef IFCOPENSHELL_05
IfcParse::IfcFile* f = new IfcParse::IfcFile();
if (!f->Init()) {
#else
IfcParse::IfcFile* f = new IfcParse::IfcFile(filename);
if (!f->good()) {
#endif
throw std::runtime_error("Unable to open file " + filename);
}
auto projects = f->instances_by_type("IfcProject");
if (projects) {
// @nb: a copy has to be made, because instances_by_type() returns a reference
// from the live map of the file which is updated upon removeEntity()
std::vector<IfcUtil::IfcBaseClass*> projects_copy(projects->begin(), projects->end());
if (projects->size() > 1) {
for (auto it = projects_copy.begin() + 1; it != projects_copy.end(); ++it) {
#ifdef IFCOPENSHELL_08
auto inverses = f->getInverse((*it)->id(), nullptr, -1);
#else
auto inverses = f->getInverse((*it)->data().id(), nullptr, -1);
#endif
f->removeEntity(*it);
for (auto& inv : *inverses) {
if (inv->declaration().name() == "IFCRELAGGREGATES") {
#ifdef IFCOPENSHELL_08
inv->set_attribute_value(4, projects_copy[0]);
#else
auto attr = new IfcWrite::IfcWriteArgument;
attr->set(projects_copy[0]);
inv->data().setArgument(4, attr);
#endif
}
}
}
}
}
files.push_back(f);
}
}
if (files.empty()) {
throw std::runtime_error("Not a single file matched pattern");
}
filtered_files_t ff;
ff.files = files;
return ff;
}
};
#ifdef WITH_IFC
#if defined(IFCOPENSHELL_07) || defined(IFCOPENSHELL_08)
typedef IfcGeom::Iterator iterator_t;
typedef aggregate_of_instance instance_list_t;
#else
typedef IfcGeom::Iterator<double> iterator_t;
typedef IfcEntityList instance_list_t;
#endif
#endif
class op_create_geometry : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "input", "ifcfile" }, { false, "include", "sequence"}, { false, "exclude", "sequence"}, { false, "optional", "integer"}, { false, "only_transparent", "integer"}, { false, "only_opaque", "integer"} };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
IfcGeom::entity_filter ef;
boost::optional<size_t> threads;
if (scope.has("THREADS")) {
int t = scope.get_value<int>("THREADS");
if (t > 1) {
threads = (size_t)t;
}
}
bool only_transparent = scope.get_value_or<int>("only_transparent", 0) == 1;
bool only_opaque = scope.get_value_or<int>("only_opaque", 0) == 1;
#ifdef IFCOPENSHELL_05
auto ifc_roof = IfcSchema::Type::IfcRoof;
auto ifc_slab = IfcSchema::Type::IfcSlab;
auto ifc_space = IfcSchema::Type::IfcSpace;
auto ifc_opening = IfcSchema::Type::IfcOpeningElement;
auto ifc_furnishing = IfcSchema::Type::IfcFurnishingElement;
// @todo what's this?
auto& ef_elements = ef_elements;
#else
// From IfcOpenShell v0.6.0 onwards, there is support for multiple
// schemas at runtime so type identification is based on strings.
std::string ifc_roof = "IfcRoof";
std::string ifc_slab = "IfcSlab";
std::string ifc_space = "IfcSpace";
std::string ifc_opening = "IfcOpeningElement";
std::string ifc_furnishing = "IfcFurnishingElement";
auto& ef_elements = ef.entity_names;
#endif
const filtered_files_t& ifc_files = scope.get_value<filtered_files_t>("input");
#ifdef IFCOPENSHELL_08
ifcopenshell::geometry::Settings settings_surface;
settings_surface.get<ifcopenshell::geometry::settings::UseElementHierarchy>().value = true;
settings_surface.get<ifcopenshell::geometry::settings::IteratorOutput>().value = ifcopenshell::geometry::settings::NATIVE;
#else
IfcGeom::IteratorSettings settings_surface;
settings_surface.set(IfcGeom::IteratorSettings::DISABLE_TRIANGULATION, true);
// settings_surface.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, true);
// Only to determine whether building element parts decompositions of slabs should be processed as roofs
#ifdef IFCOPENSHELL_07
settings_surface.set(IfcGeom::IteratorSettings::ELEMENT_HIERARCHY, true);
#else
settings_surface.set(IfcGeom::IteratorSettings::SEARCH_FLOOR, true);
#endif
#endif
boost::optional<bool> include, roof_slabs;
std::vector<std::string> entities;
if (scope.has("include")) {
entities = scope.get_value<std::vector<std::string> >("include");
include = true;
}
if (scope.has("exclude")) {
if (!entities.empty()) {
throw std::runtime_error("include and exclude cannot be specified together");
}
entities = scope.get_value<std::vector<std::string> >("exclude");
include = false;
}
if (include) {
ef.include = *include;
std::vector<std::string> entities_without_quotes;
std::transform(entities.begin(), entities.end(), std::back_inserter(entities_without_quotes), [](const std::string& v) {
return v.substr(1, v.size() - 2);
});
#ifdef IFCOPENSHELL_05
std::transform(entities_without_quotes.begin(), entities_without_quotes.end(), std::inserter(ef_elements, ef_elements.begin()), [](const std::string& v) {
return IfcSchema::Type::FromString(boost::to_upper_copy(v));
});
ef.traverse = ef_elements != {IfcSchema::Type::IfcSpace};
#else
ef_elements.insert(entities_without_quotes.begin(), entities_without_quotes.end());
// Normally we want decompositions to be included, so that a wall with IfcBuildingElement parts is processed including it's parts. For spaces we do not want that.
static const std::set<std::string> ONLY_SPACES{ { "IfcSpace" } };
ef.traverse = ef_elements != ONLY_SPACES;
#endif
if (*include) {
if (ef_elements.find(ifc_roof) != ef_elements.end()) {
// Including { IfcRoof, ... } then we need to include Slabs (as they are potentially roof slabs)
ef_elements.insert(ifc_slab);
roof_slabs = true;
}
} else {
if (ef_elements.find(ifc_roof) == ef_elements.end()) {
// Excluding NOT IfcRoof then we need to exclude Slabs as well (as they are potentially roof slabs)
if (ef_elements.erase(ifc_slab) > 0) {
roof_slabs = false;
}
}
}
} else {
ef.include = false;
ef.traverse = false;
ef_elements = { ifc_space, ifc_opening, ifc_furnishing };
}
geometry_collection_t* geometries = new geometry_collection_t;
auto filters_surface = std::vector<IfcGeom::filter_t>({ ef });
bool at_least_one_succesful = false;
for (auto ifc_file : ifc_files.files) {
std::unique_ptr<iterator_t> iterator;
#ifdef IFCOPENSHELL_05
iterator.reset(iterator_t(settings_surface, ifc_file, filters_surface));
#else
#ifdef IFCOPENSHELL_08
iterator.reset(new iterator_t("opencascade", settings_surface, ifc_file, filters_surface, threads.get_value_or(1)));
#else
if (threads) {
iterator.reset(new iterator_t(settings_surface, ifc_file, filters_surface, *threads));
} else {
iterator.reset(new iterator_t(settings_surface, ifc_file, filters_surface));
}
#endif
#endif
// For debugging geometry creation from IfcOpenShell
// Logger::SetOutput(&std::cout, &std::cout);
if (!iterator->initialize()) {
continue;
}
at_least_one_succesful = true;
int old_progress = -1;
for (;;) {
elem_t* elem = (elem_t*)iterator->get();
bool process = true;
if (boost::to_lower_copy(elem->name()).find("nulpunt") != std::string::npos) {
process = false;
}
#ifdef IFCOPENSHELL_05
if (roof_slabs && elem->product()->as<IfcSchema::IfcSlab>()) {
IfcSchema::IfcSlabTypeEnum::IfcSlabTypeEnum pdt = IfcSchema::IfcSlabTypeEnum::NOTDEFINED;
if (elem->product()->as<IfcSchema::IfcSlab>()->hasPredefinedType()) {
pdt = elem->product()->as<IfcSchema::IfcSlab>()->PredefinedType();
}
process = process && (pdt == IfcSchema::IfcSlabTypeEnum::IfcSlabType_ROOF) == *roof_slabs;
}
#else
auto elem_product = elem->product();
if (elem->product()->declaration().is("IfcBuildingElementPart")) {
auto parents = elem->parents();
if (parents.size()) {
// Assume the first parent of a building element part is
// the element that got it included by the hierarchical
// processing of element filters.
elem_product = parents.back()->product();
}
}
if (roof_slabs && elem_product->declaration().is("IfcSlab")) {
auto attr_value = elem_product->get("PredefinedType");
#ifdef IFCOPENSHELL_08
std::string pdt = attr_value.type() == IfcUtil::Argument_STRING ? (std::string)attr_value : std::string("");
#else
std::string pdt = attr_value->isNull() ? std::string("") : (std::string)(*attr_value);
#endif
process = process && (pdt == "ROOF") == *roof_slabs;
}
#endif
if (ifc_files.filter) {
try {
process = process && (*ifc_files.filter)(elem_product);
} catch (...) {
#ifdef IFCOPENSHELL_05
throw std::runtime_error("Error evaluating filter on " + elem_product->toString());
#else
#ifdef IFCOPENSHELL_08
std::ostringstream oss;
elem_product->toString(oss);
throw std::runtime_error("Error evaluating filter on " + oss.str());
#else
throw std::runtime_error("Error evaluating filter on " + elem_product->data().toString());
#endif
#endif
}
}
if (process) {
#ifdef IFCOPENSHELL_08
auto comp = elem->geometry().as_compound();
TopoDS_Compound compound = TopoDS::Compound(((ifcopenshell::geometry::OpenCascadeShape*)comp)->shape());
delete comp;
#else
TopoDS_Compound compound = elem->geometry().as_compound();
#endif
bool filtered_non_empty = true;
if (only_transparent || only_opaque) {
filtered_non_empty = false;
TopoDS_Compound filtered;
BRep_Builder B;
B.MakeCompound(filtered);
auto it = elem->geometry().begin();
for (TopoDS_Iterator jt(compound); jt.More(); ++it, jt.Next()) {
bool is_transparent = it->hasStyle() && it->Style().has_transparency() && it->Style().transparency > 1.e-9;
if (only_transparent == is_transparent) {
B.Add(filtered, jt.Value());
filtered_non_empty = true;
}
}
std::swap(compound, filtered);
}
if (filtered_non_empty) {
#ifdef IFCOPENSHELL_08
const auto& m = elem->transformation().data()->ccomponents();
gp_Trsf tr;
tr.SetValues(
m(0, 0), m(0, 1), m(0, 2), m(0, 3),
m(1, 0), m(1, 1), m(1, 2), m(1, 3),
m(2, 0), m(2, 1), m(2, 2), m(2, 3)
);
compound.Move(tr);
#else
compound.Move(elem->transformation().data());
#endif
BRepMesh_IncrementalMesh(compound, 0.001);
geometries->push_back(std::make_pair(std::pair<void*, int>(ifc_file, elem->id()), compound));
}
}
if (old_progress != iterator->progress()) {
old_progress = iterator->progress();
if (application_progress_callback) {
(*application_progress_callback)(old_progress / 100.f);
}
}
if (!iterator->next()) {
break;
}
}
}
if (scope.get_value_or<int>("optional", 0) == 0 && !at_least_one_succesful) {
json_logger::message(json_logger::LOG_FATAL, "Failed to generate geometry");
abort();
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(geometries->begin(), geometries->end(), g);
return geometries;
}
};
#endif
namespace {
abstract_voxel_storage* voxelize_2(abstract_voxel_storage* voxels, geometry_collection_t* surfaces) {
progress_writer progress;
processor p(voxels, progress);
p.process(surfaces->begin(), surfaces->end(), SURFACE(), output(MERGED()));
return voxels;
}
template <typename V = bit_t>
abstract_voxel_storage* voxelize(geometry_collection_t* surfaces, double vsize, int chunksize, const boost::optional<int>& threads, bool use_volume, bool silent = false) {
double x1, y1, z1, x2, y2, z2;
int nx, ny, nz;
Bnd_Box global_bounds;
for (auto& p : *surfaces) {
BRepBndLib::Add(p.second, global_bounds);
}
if (global_bounds.IsVoid()) {
return (abstract_voxel_storage*) new chunked_voxel_storage<V>(make_vec<long>(0, 0, 0), vsize, chunksize, make_vec<size_t>(1U, 1U, 1U));
}
global_bounds.Get(x1, y1, z1, x2, y2, z2);
nx = (int)ceil((x2 - x1) / vsize);
ny = (int)ceil((y2 - y1) / vsize);
nz = (int)ceil((z2 - z1) / vsize);
x1 -= vsize * get_padding();
y1 -= vsize * get_padding();
z1 -= vsize * get_padding();
nx += get_padding() * 2;
ny += get_padding() * 2;
nz += get_padding() * 2;
std::unique_ptr<fill_volume_t> method;
if (use_volume) {
method = std::make_unique<VOLUME>();
} else {
method = std::make_unique<SURFACE>();
}
if (std::is_same<V, voxel_uint32_t>::value) {
// @todo, uint32 defaults to VOLUME_PRODUCT_ID, make this explicit
// @why
// pr.use_scanline() = false;
chunked_voxel_storage<voxel_uint32_t>* storage = new chunked_voxel_storage<voxel_uint32_t>(x1, y1, z1, vsize, nx, ny, nz, chunksize);
if (threads && *threads != 1) {
progress_writer progress("voxelize", silent);
threaded_processor p(storage, *threads, progress);
p.process(surfaces->begin(), surfaces->end(), VOLUME_PRODUCT_ID(), output(MERGED()));
// @todo what actually happens to storage?
delete storage;
return p.voxels();
} else {
progress_writer progress("voxelize");
processor pr(storage, progress);
pr.process(surfaces->begin(), surfaces->end(), VOLUME_PRODUCT_ID(), output(MERGED()));
return storage;
}
} else {
if (threads && *threads != 1) {
progress_writer progress("voxelize", silent);
threaded_processor p(x1, y1, z1, vsize, nx, ny, nz, chunksize, *threads, progress);
p.process(surfaces->begin(), surfaces->end(), *method, output(MERGED()));
return p.voxels();
} else {
progress_writer progress;
auto voxels = factory().chunk_size(chunksize).create(x1, y1, z1, vsize, nx, ny, nz);
// nb: the other constructor would tell the constructor to delete the created voxels
processor p(voxels, progress);
p.process(surfaces->begin(), surfaces->end(), *method, output(MERGED()));
return voxels;
}
}
}
}
class op_voxelize : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "input", "surfaceset" }, {false, "VOXELSIZE", "real"}, {false, "type", "string"}, {false, "method", "string"} };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
geometry_collection_t* surfaces = scope.get_value<geometry_collection_t*>("input");
double vsize = scope.get_value<double>("VOXELSIZE");
int cs = scope.get_value<int>("CHUNKSIZE");
int t = scope.get_value<int>("THREADS");
std::string ty = scope.get_value_or<std::string>("type", "bit");
std::string method = scope.get_value_or<std::string>("method", "surface");
if (method != "surface" && method != "volume") {
throw std::runtime_error("Unsupported method " + method);
}
bool use_volume = method == "volume";
if (surfaces->size() == 0) {
// Just some arbitrary empty region
if (ty == "bit") {
return (abstract_voxel_storage*) new chunked_voxel_storage<bit_t>(make_vec<long>(0, 0, 0), vsize, cs, make_vec<size_t>(1U, 1U, 1U));
} else {
return (abstract_voxel_storage*) new chunked_voxel_storage<voxel_uint32_t>(make_vec<long>(0, 0, 0), vsize, cs, make_vec<size_t>(1U, 1U, 1U));
}
} else {
if (ty == "bit") {
return voxelize<bit_t>(surfaces, vsize, cs, t, use_volume, silent);
} else {
return voxelize<voxel_uint32_t>(surfaces, vsize, cs, t, use_volume, silent);
}
}
}
};
class op_print_components : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "input", "voxels" } };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
abstract_voxel_storage* voxels = scope.get_value<abstract_voxel_storage*>("input");
connected_components((regular_voxel_storage*) voxels, [](regular_voxel_storage* c) {
std::cout << "Component " << c->count() << std::endl;
});
symbol_value v;
return v;
}
};
class op_count_components : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "input", "voxels" } };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
abstract_voxel_storage* voxels = scope.get_value<abstract_voxel_storage*>("input");
int cnt = 0;
connected_components((regular_voxel_storage*)voxels, [&cnt](regular_voxel_storage* c) {
++cnt;
});
symbol_value v = cnt;
return v;
}
};
class op_print_values : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "input", "voxels" } };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
auto voxels = (regular_voxel_storage*) scope.get_value<abstract_voxel_storage*>("input");
uint32_t v;
std::set<uint32_t> vs;
for (auto& ijk : *voxels) {
voxels->Get(ijk, &v);
vs.insert(v);
}
bool first = true;
for (auto& x : vs) {
if (!first) {
std::cout << " ";
}
first = false;
std::cout << x;
}
symbol_value vv;
return vv;
}
};
class op_describe_components : public voxel_operation {
public:
const std::vector<argument_spec>& arg_names() const {
static std::vector<argument_spec> nm_ = { { true, "output_path", "string" }, { true, "input", "voxels" } };
return nm_;
}
symbol_value invoke(const scope_map& scope) const {
const std::string output_path = scope.get_value<std::string>("output_path");
std::ofstream ofs(output_path.c_str());
ofs << "[";
bool first = true;
abstract_voxel_storage* voxels = scope.get_value<abstract_voxel_storage*>("input");
connected_components((regular_voxel_storage*)voxels, [&ofs, &first](regular_voxel_storage* c) {
if (!first) {
ofs << ",";
}
auto info = dump_info(c);
ofs << json_logger::to_json_string(info);
first = false;
});
ofs << "]";
symbol_value v;
return v;
}
};
#include <boost/asio/thread_pool.hpp>
#include <boost/asio/post.hpp>
#include <thread>
#include <mutex>
namespace {
template <typename T>
class mt_list : public std::list<T> {
std::mutex m;
public:
void push_back(const T& t) {
std::lock_guard<std::mutex> lock{ m };
std::list<T>::push_back(t);
}
};
#ifdef OLD_GROUP_BY
template <typename Fn>
void group_by(regular_voxel_storage* groups, abstract_voxel_storage* voxels, Fn fn, int threads=1) {
uint32_t v;
std::set<uint32_t> vs;
for (auto& ijk : *groups) {
groups->Get(ijk, &v);
vs.insert(v);
}
bit_t desc_bits;
mt_list<std::pair<uint32_t, abstract_voxel_storage*>> results;
boost::asio::thread_pool pool(threads); // 4 threads
auto process = [&fn, &groups, &desc_bits, &voxels, &results, &threads](uint32_t id) {
uint32_t vv;
// A {0,1} dataset of `groups`==`id`
auto where_id = groups->empty_copy_as(&desc_bits);
for (auto& ijk : *groups) {
groups->Get(ijk, &vv);
if (vv == id) {
where_id->Set(ijk);
}
}
auto c = voxels->boolean_intersection(where_id);
delete where_id;
if (threads <= 1) {
fn(id, c);
} else {
results.push_back({ id, c });
}
};
for (auto& id : vs) {
if (threads > 1) {
boost::asio::post(pool, std::bind(process, id));
} else {
process(id);
}
}
if (threads > 1) {
pool.join();
for (auto& r : results) {
fn(r.first, r.second);
}
}
}
#else
template <typename Fn>
void group_by(regular_voxel_storage* groups, abstract_voxel_storage* voxels, Fn fn, std::map<uint32_t, size_t>& counts, bool use_bits=true, bool conserve_memory=true, bool only_counts=false) {
uint32_t v;
// conserve_memory=false
std::map<uint32_t, abstract_voxel_storage*> map;
// conserve_memory=true
uint32_t target;
std::set<uint32_t> vs;
std::set<uint32_t>::const_iterator vs_it;
abstract_voxel_storage* single;
{
auto acvs_voxels = dynamic_cast<abstract_chunked_voxel_storage*>(voxels);
auto acvs_groups = dynamic_cast<abstract_chunked_voxel_storage*>(groups);
if (!acvs_voxels || !acvs_groups) {
throw std::runtime_error("Group operations are not supported on non-chunked storage");
}
if (!(acvs_voxels->grid_offset() == acvs_groups->grid_offset()).all()) {
throw std::runtime_error("Group operations on unaligned voxel grids are not supported");
}
}
if (conserve_memory) {
for (auto& ijk : *(regular_voxel_storage*)voxels) {
groups->Get(ijk, &v);
vs.insert(v);
}
vs_it = vs.begin();
}
repeat:
if (conserve_memory) {
if (vs_it == vs.end()) {
return;
}
target = *vs_it;
if (use_bits) {
static bit_t fmt;
single = voxels->empty_copy_as(&fmt);
} else {
single = voxels->empty_copy();
}
}
// @todo use regions for multi threading
for (auto& ijk : *(regular_voxel_storage*)voxels) {
groups->Get(ijk, &v);
if (conserve_memory) {
if (v != target) {
continue;
}
} else {
if (v == 0) {
continue;
}
}
if (only_counts) {
counts[v] ++;
continue;
}
abstract_voxel_storage* r;
if (conserve_memory) {
r = single;
} else {
auto it = map.find(v);
if (it == map.end()) {
if (use_bits) {
static bit_t fmt;
map.insert({ v, r = voxels->empty_copy_as(&fmt) });
} else {
map.insert({ v, r = voxels->empty_copy() });
}
} else {
r = it->second;
}
}
if (use_bits) {
r->Set(ijk);
} else {
voxels->Get(ijk, &v);
r->Set(ijk, &v);
}