-
-
Notifications
You must be signed in to change notification settings - Fork 236
/
voxel_instancer.cpp
2195 lines (1840 loc) · 74.7 KB
/
voxel_instancer.cpp
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
#include "../../edition/voxel_tool.h"
#include "../../engine/buffered_task_scheduler.h"
#include "../../streams/save_block_data_task.h"
#include "../../util/containers/container_funcs.h"
#include "../../util/dstack.h"
#include "../../util/godot/classes/camera_3d.h"
#include "../../util/godot/classes/collision_shape_3d.h"
#include "../../util/godot/classes/engine.h"
#include "../../util/godot/classes/mesh_instance_3d.h"
#include "../../util/godot/classes/multimesh.h"
#include "../../util/godot/classes/node.h"
#include "../../util/godot/classes/ref_counted.h"
#include "../../util/godot/classes/resource_saver.h"
#include "../../util/godot/classes/time.h"
#include "../../util/godot/classes/viewport.h"
#include "../../util/godot/core/array.h"
#include "../../util/math/conv.h"
#include "../../util/profiling.h"
#include "../../util/string/format.h"
#include "../fixed_lod/voxel_terrain.h"
#include "../variable_lod/voxel_lod_terrain.h"
#include "load_instance_block_task.h"
#include "voxel_instance_component.h"
#include "voxel_instance_generator.h"
#include "voxel_instance_library_multimesh_item.h"
#include "voxel_instance_library_scene_item.h"
#include "voxel_instancer_quick_reloading_cache.h"
#include "voxel_instancer_rigidbody.h"
#ifdef TOOLS_ENABLED
#include "../../editor/camera_cache.h"
#include "../../util/godot/core/packed_arrays.h"
#endif
// Only needed for debug purposes, otherwise RenderingServer is used directly
#include "../../util/godot/classes/multimesh_instance_3d.h"
#include <algorithm>
namespace zylann::voxel {
namespace {
StdVector<Transform3f> &get_tls_transform_cache() {
static thread_local StdVector<Transform3f> tls_transform_cache;
return tls_transform_cache;
}
} // namespace
VoxelInstancer::VoxelInstancer() {
set_notify_transform(true);
set_process_internal(true);
_loading_results = make_shared_instance<VoxelInstancerTaskOutputQueue>();
fill(_mesh_lod_distances, 0.f);
}
VoxelInstancer::~VoxelInstancer() {
// Destroy everything
// Note: we don't destroy instances using nodes, we assume they were detached already
if (_library.is_valid()) {
_library->remove_listener(this);
}
}
void VoxelInstancer::clear_blocks() {
ZN_PROFILE_SCOPE();
// Destroy blocks, keep configured layers
for (auto it = _blocks.begin(); it != _blocks.end(); ++it) {
Block &block = **it;
for (unsigned int i = 0; i < block.bodies.size(); ++i) {
VoxelInstancerRigidBody *body = block.bodies[i];
body->detach_and_destroy();
}
for (unsigned int i = 0; i < block.scene_instances.size(); ++i) {
SceneInstance instance = block.scene_instances[i];
ERR_CONTINUE(instance.component == nullptr);
instance.component->detach();
ERR_CONTINUE(instance.root == nullptr);
instance.root->queue_free();
}
}
_blocks.clear();
for (auto it = _layers.begin(); it != _layers.end(); ++it) {
Layer &layer = it->second;
layer.blocks.clear();
}
for (unsigned int lod_index = 0; lod_index < _lods.size(); ++lod_index) {
Lod &lod = _lods[lod_index];
lod.modified_blocks.clear();
}
}
void VoxelInstancer::clear_blocks_in_layer(int layer_id) {
// Not optimal, but should work for now
for (size_t i = 0; i < _blocks.size(); ++i) {
Block &block = *_blocks[i];
if (block.layer_id == layer_id) {
remove_block(i);
// remove_block does a remove-at-swap so we have to re-iterate on the same slot
--i;
}
}
}
void VoxelInstancer::clear_layers() {
clear_blocks();
for (unsigned int lod_index = 0; lod_index < _lods.size(); ++lod_index) {
Lod &lod = _lods[lod_index];
lod.layers.clear();
lod.modified_blocks.clear();
}
_layers.clear();
}
void VoxelInstancer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_WORLD:
set_world(*get_world_3d());
update_visibility();
#ifdef TOOLS_ENABLED
_debug_renderer.set_world(get_world_3d().ptr());
#endif
break;
case NOTIFICATION_EXIT_WORLD:
set_world(nullptr);
#ifdef TOOLS_ENABLED
_debug_renderer.set_world(nullptr);
#endif
break;
case NOTIFICATION_PARENTED: {
VoxelLodTerrain *vlt = Object::cast_to<VoxelLodTerrain>(get_parent());
if (vlt != nullptr) {
_parent = vlt;
_parent_data_block_size_po2 = vlt->get_data_block_size_pow2();
_parent_mesh_block_size_po2 = vlt->get_mesh_block_size_pow2();
update_mesh_lod_distances_from_parent();
vlt->set_instancer(this);
} else {
VoxelTerrain *vt = Object::cast_to<VoxelTerrain>(get_parent());
if (vt != nullptr) {
_parent = vt;
_parent_data_block_size_po2 = vt->get_data_block_size_pow2();
_parent_mesh_block_size_po2 = vt->get_mesh_block_size_pow2();
update_mesh_lod_distances_from_parent();
vt->set_instancer(this);
}
}
// TODO may want to reload all instances? Not sure if worth implementing that use case
} break;
case NOTIFICATION_UNPARENTED:
clear_blocks();
if (_parent != nullptr) {
VoxelLodTerrain *vlt = Object::cast_to<VoxelLodTerrain>(_parent);
if (vlt != nullptr) {
vlt->set_instancer(nullptr);
} else {
VoxelTerrain *vt = Object::cast_to<VoxelTerrain>(get_parent());
if (vt != nullptr) {
vt->set_instancer(nullptr);
}
}
_parent = nullptr;
}
break;
case NOTIFICATION_TRANSFORM_CHANGED: {
ZN_PROFILE_SCOPE_NAMED("VoxelInstancer::NOTIFICATION_TRANSFORM_CHANGED");
if (!is_inside_tree() || _parent == nullptr) {
// The transform and other properties can be set by the scene loader,
// before we enter the tree
return;
}
const Transform3D parent_transform = get_global_transform();
const int base_block_size_po2 = _parent_mesh_block_size_po2;
// print_line(String("IP: {0}").format(varray(parent_transform.origin)));
for (auto it = _blocks.begin(); it != _blocks.end(); ++it) {
Block &block = **it;
if (!block.multimesh_instance.is_valid()) {
// The block exists as an empty block (if it did not exist, it would get generated)
continue;
}
const int block_size_po2 = base_block_size_po2 + block.lod_index;
const Vector3 block_local_pos(block.grid_position << block_size_po2);
// The local block transform never has rotation or scale so we can take a shortcut
const Transform3D block_transform(parent_transform.basis, parent_transform.xform(block_local_pos));
block.multimesh_instance.set_transform(block_transform);
}
} break;
case NOTIFICATION_VISIBILITY_CHANGED:
update_visibility();
#ifdef TOOLS_ENABLED
if (_gizmos_enabled) {
_debug_renderer.set_world(is_visible_in_tree() ? *get_world_3d() : nullptr);
}
#endif
break;
case NOTIFICATION_INTERNAL_PROCESS:
process();
break;
}
}
void VoxelInstancer::process() {
process_task_results();
if (_parent != nullptr && _library.is_valid() && _mesh_lod_distances[0] > 0.f) {
process_mesh_lods();
}
#ifdef TOOLS_ENABLED
if (_gizmos_enabled && is_visible_in_tree()) {
process_gizmos();
}
#endif
}
void VoxelInstancer::process_task_results() {
ZN_PROFILE_SCOPE();
static thread_local StdVector<VoxelInstanceLoadingTaskOutput> tls_results;
StdVector<VoxelInstanceLoadingTaskOutput> &results = tls_results;
#ifdef DEBUG_ENABLED
if (results.size()) {
ZN_PRINT_ERROR("Results were not cleaned up?");
}
#endif
{
MutexLock mlock(_loading_results->mutex);
// Copy results to temporary buffer
StdVector<VoxelInstanceLoadingTaskOutput> &src = _loading_results->results;
results.resize(src.size());
for (unsigned int i = 0; i < src.size(); ++i) {
results[i] = std::move(src[i]);
}
src.clear();
}
if (results.size() == 0) {
return;
}
Ref<World3D> maybe_world = get_world_3d();
ZN_ASSERT_RETURN(maybe_world.is_valid());
World3D &world = **maybe_world;
const Transform3D parent_transform = get_global_transform();
const int data_block_size_base = (1 << _parent_mesh_block_size_po2);
const int mesh_block_size_base = (1 << _parent_mesh_block_size_po2);
const int render_to_data_factor = mesh_block_size_base / data_block_size_base;
for (VoxelInstanceLoadingTaskOutput &output : results) {
auto layer_it = _layers.find(output.layer_id);
if (layer_it == _layers.end()) {
// Layer was removed since?
ZN_PRINT_VERBOSE(
format("Processing async instance generator results, but the layer isn't present ({}).",
static_cast<int>(output.layer_id))
);
continue;
}
Layer &layer = layer_it->second;
const VoxelInstanceLibraryItem *item = _library->get_item(output.layer_id);
ZN_ASSERT_CONTINUE_MSG(item != nullptr, "Item removed from library while it was loading?");
auto block_it = layer.blocks.find(output.render_block_position);
if (block_it == layer.blocks.end()) {
// The block was removed while the generation process was running?
ZN_PRINT_VERBOSE("Processing async instance generator results, but the block was removed.");
continue;
}
if (output.edited_mask != 0) {
Lod &lod = _lods[layer.lod_index];
const Vector3i minp = output.render_block_position * render_to_data_factor;
const Vector3i maxp = minp + Vector3iUtil::create(render_to_data_factor);
Vector3i bpos;
unsigned int i = 0;
for (bpos.z = minp.z; bpos.z < maxp.z; ++bpos.z) {
for (bpos.y = minp.y; bpos.y < maxp.y; ++bpos.y) {
for (bpos.x = minp.x; bpos.x < maxp.x; ++bpos.x) {
if ((output.edited_mask & (1 << i)) != 0) {
lod.edited_data_blocks.insert(bpos);
}
++i;
}
}
}
}
const int mesh_block_size = mesh_block_size_base << layer.lod_index;
const Transform3D block_local_transform = Transform3D(Basis(), output.render_block_position * mesh_block_size);
const Transform3D block_global_transform = parent_transform * block_local_transform;
update_block_from_transforms( //
block_it->second, //
to_span_const(output.transforms), //
output.render_block_position, //
layer, //
*item, //
output.layer_id, //
world, //
block_global_transform, //
block_local_transform.origin //
);
}
results.clear();
}
#ifdef TOOLS_ENABLED
void VoxelInstancer::process_gizmos() {
using namespace zylann::godot;
struct L {
static inline void draw_box(
DebugRenderer &dr,
const Transform3D parent_transform,
Vector3i bpos,
unsigned int lod_index,
unsigned int base_block_size_po2,
Color8 color
) {
const int block_size_po2 = base_block_size_po2 + lod_index;
const int block_size = 1 << block_size_po2;
const Vector3 block_local_pos(bpos << block_size_po2);
const Transform3D box_transform(
parent_transform.basis * (Basis().scaled(Vector3(block_size, block_size, block_size))),
parent_transform.xform(block_local_pos)
);
dr.draw_box(box_transform, color);
}
};
ERR_FAIL_COND(_parent == nullptr);
const Transform3D parent_transform = get_global_transform();
const int base_mesh_block_size_po2 = _parent_mesh_block_size_po2;
const int base_data_block_size_po2 = _parent_data_block_size_po2;
_debug_renderer.begin();
if (debug_get_draw_flag(DEBUG_DRAW_ALL_BLOCKS)) {
for (auto it = _blocks.begin(); it != _blocks.end(); ++it) {
const Block &block = **it;
Color8 color(0, 255, 0, 255);
if (block.multimesh_instance.is_valid()) {
if (block.multimesh_instance.get_multimesh().is_null()) {
// Allocated but without multimesh (wut?)
color = Color8(128, 0, 0, 255);
} else if (get_visible_instance_count(**block.multimesh_instance.get_multimesh()) == 0) {
// Allocated but empty multimesh
color = Color8(255, 64, 0, 255);
}
} else if (block.scene_instances.size() == 0) {
// Only draw blocks that are setup
continue;
}
L::draw_box(
_debug_renderer,
parent_transform,
block.grid_position,
block.lod_index,
base_mesh_block_size_po2,
color
);
}
}
if (debug_get_draw_flag(DEBUG_DRAW_EDITED_BLOCKS)) {
for (unsigned int lod_index = 0; lod_index < _lods.size(); ++lod_index) {
const Lod &lod = _lods[lod_index];
const Color8 edited_color(0, 255, 0, 255);
const Color8 unsaved_color(255, 255, 0, 255);
for (auto it = lod.edited_data_blocks.begin(); it != lod.edited_data_blocks.end(); ++it) {
L::draw_box(_debug_renderer, parent_transform, *it, lod_index, base_data_block_size_po2, edited_color);
}
for (auto it = lod.modified_blocks.begin(); it != lod.modified_blocks.end(); ++it) {
L::draw_box(_debug_renderer, parent_transform, *it, lod_index, base_data_block_size_po2, unsaved_color);
}
}
}
_debug_renderer.end();
}
#endif
VoxelInstancer::Layer &VoxelInstancer::get_layer(int id) {
auto it = _layers.find(id);
ZN_ASSERT(it != _layers.end());
return it->second;
}
const VoxelInstancer::Layer &VoxelInstancer::get_layer_const(int id) const {
auto it = _layers.find(id);
ZN_ASSERT(it != _layers.end());
return it->second;
}
namespace {
Vector3 get_global_camera_position(const Node &node) {
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
return zylann::voxel::godot::get_3d_editor_camera_position();
}
#endif
const Viewport *viewport = node.get_viewport();
ZN_ASSERT_RETURN_V(viewport != nullptr, Vector3());
const Camera3D *camera = viewport->get_camera_3d();
if (camera == nullptr) {
return Vector3();
}
return camera->get_global_position();
}
} // namespace
void VoxelInstancer::update_mesh_from_mesh_lod(
Block &block,
const VoxelInstanceLibraryMultiMeshItem::Settings &settings,
bool hide_beyond_max_lod,
bool instancer_is_visible
) {
if (hide_beyond_max_lod && block.current_mesh_lod == settings.mesh_lod_count) {
// Godot doesn't like null meshes, so we have to implement a different code path
// Can be invalid if there is currently no instance in this block
if (block.multimesh_instance.is_valid()) {
block.multimesh_instance.set_visible(false);
}
} else {
Ref<MultiMesh> multimesh = block.multimesh_instance.get_multimesh();
if (multimesh.is_valid()) {
block.multimesh_instance.set_visible(instancer_is_visible);
ZN_PROFILE_SCOPE();
multimesh->set_mesh(settings.mesh_lods[block.current_mesh_lod]);
}
}
}
void VoxelInstancer::update_mesh_lod_distances_from_parent() {
ZN_ASSERT_RETURN(_parent != nullptr);
VoxelLodTerrain *vlt = Object::cast_to<VoxelLodTerrain>(_parent);
if (vlt != nullptr) {
vlt->get_lod_distances(to_span(_mesh_lod_distances));
return;
}
VoxelTerrain *vt = Object::cast_to<VoxelTerrain>(_parent);
if (vt != nullptr) {
_mesh_lod_distances[0] = vt->get_max_view_distance();
}
}
void VoxelInstancer::process_mesh_lods() {
ZN_PROFILE_SCOPE();
ERR_FAIL_COND(_library.is_null());
// Note, this form of LOD must be visual only. It supports only one camera.
// Get viewer position
const Transform3D gtrans = get_global_transform();
const Vector3 cam_pos_global = get_global_camera_position(*this);
const Vector3 cam_pos_local = gtrans.affine_inverse().xform(cam_pos_global);
ERR_FAIL_COND(_parent == nullptr);
const unsigned int block_size = 1 << _parent_mesh_block_size_po2;
const float hysteresis = 1.05;
const uint64_t mesh_lod_update_time_budget_microseconds = 500;
const uint64_t time_up_time = Time::get_singleton()->get_ticks_usec() + mesh_lod_update_time_budget_microseconds;
const bool instancer_is_visible = is_visible_in_tree();
// const unsigned int initial_mesh_lod_time_sliced_block_index = _mesh_lod_time_sliced_block_index;
while (_mesh_lod_time_sliced_block_index < _blocks.size()) {
// Iterate a portion of blocks, then check timing budget once after that
const unsigned int desired_portion_size = 64;
const unsigned int portion_end = math::min(
_mesh_lod_time_sliced_block_index + desired_portion_size, static_cast<unsigned int>(_blocks.size())
);
Span<UniquePtr<Block>> blocks_portion = to_span_from_position_and_size(
_blocks, _mesh_lod_time_sliced_block_index, portion_end - _mesh_lod_time_sliced_block_index
);
_mesh_lod_time_sliced_block_index = portion_end;
for (UniquePtr<Block> &block_ptr : blocks_portion) {
Block &block = *block_ptr;
// Early exit for empty blocks (we only do this for multimeshes so no need to check other things)
if (!block.multimesh_instance.is_valid()) {
continue;
}
const VoxelInstanceLibraryItem *item_base = _library->get_item_const(block.layer_id);
ERR_CONTINUE(item_base == nullptr);
// TODO Optimization: would be nice to not need this cast by iterating only the same item types
const VoxelInstanceLibraryMultiMeshItem *item =
Object::cast_to<VoxelInstanceLibraryMultiMeshItem>(item_base);
if (item == nullptr) {
// Not a multimesh item
continue;
}
const VoxelInstanceLibraryMultiMeshItem::Settings &settings = item->get_multimesh_settings();
const bool hide_beyond_max_lod = item->get_hide_beyond_max_lod();
const unsigned int extended_mesh_lod_count = settings.mesh_lod_count + (hide_beyond_max_lod ? 1 : 0);
// Note, "hide beyond max lod" counts as having an extra LOD where the mesh is hidden. So an item can have
// only one mesh setup, yet be considered having LOD
if (extended_mesh_lod_count <= 1) {
// This block has no LOD
// TODO Optimization: would be nice to not need this conditional by iterating only item types that
// define lods
continue;
}
const int lod_index = item->get_lod_index();
Span<const float> distance_ratios = item->get_mesh_lod_distance_ratios();
const float max_distance = _mesh_lod_distances[lod_index];
// #ifdef DEBUG_ENABLED
// ERR_FAIL_COND(mesh_lod_count < VoxelInstanceLibraryMultiMeshItem::MAX_MESH_LODS);
// #endif
// const Lod &lod = _lods[lod_index];
const int lod_block_size = block_size << lod_index;
const int hs = lod_block_size >> 1;
const Vector3 block_center_local(block.grid_position * lod_block_size + Vector3i(hs, hs, hs));
const float distance_squared = cam_pos_local.distance_squared_to(block_center_local);
// Compute current mesh LOD index (note, block.current_mesh_lod can totally be out of range due to eventual
// config changes, or even as a way to force an update. This will bring it back in range)
unsigned int current_mesh_lod = block.current_mesh_lod;
while (current_mesh_lod + 1 < extended_mesh_lod_count &&
distance_squared > math::squared(
distance_ratios[current_mesh_lod] *
max_distance
// Exit distance is slightly higher so it has less chance to oscillate
// often when near the threshold
* hysteresis
)) {
// Decrease detail
++current_mesh_lod;
}
while (current_mesh_lod > 0 &&
(distance_squared < math::squared(distance_ratios[current_mesh_lod - 1] * max_distance)
// Allow mesh LOD index to go down if count is set lower
|| current_mesh_lod >= extended_mesh_lod_count)) {
// Increase detail
--current_mesh_lod;
}
// Apply if it changed
if (block.current_mesh_lod != current_mesh_lod) {
block.current_mesh_lod = current_mesh_lod;
update_mesh_from_mesh_lod(block, settings, hide_beyond_max_lod, instancer_is_visible);
}
}
if (Time::get_singleton()->get_ticks_usec() > time_up_time) {
break;
}
}
// const int64_t updated_blocks_count = _mesh_lod_time_sliced_block_index -
// initial_mesh_lod_time_sliced_block_index; const float updated_blocks_ratio = _blocks.size() != 0 ?
// updated_blocks_count / float(_blocks.size()) : 0; ZN_PROFILE_PLOT("Updated Instancer Blocks Mesh LOD",
// updated_blocks_ratio);
// Keep restarting the update every frame for now
if (_mesh_lod_time_sliced_block_index >= _blocks.size()) {
_mesh_lod_time_sliced_block_index = 0;
}
}
// We need to do this ourselves because we don't use nodes for multimeshes
void VoxelInstancer::update_visibility() {
if (!is_inside_tree()) {
return;
}
const bool instancer_is_visible = is_visible_in_tree();
for (auto it = _blocks.begin(); it != _blocks.end(); ++it) {
Block &block = **it;
if (block.multimesh_instance.is_valid()) {
bool visible_with_lod = true;
{
const VoxelInstanceLibraryItem *item_base = _library->get_item_const(block.layer_id);
ERR_CONTINUE(item_base == nullptr);
// TODO Optimization: would be nice to not need this cast by iterating only the same item types
const VoxelInstanceLibraryMultiMeshItem *item =
Object::cast_to<VoxelInstanceLibraryMultiMeshItem>(item_base);
if (item != nullptr) {
const VoxelInstanceLibraryMultiMeshItem::Settings &settings = item->get_multimesh_settings();
const bool hide_beyond_max_lod = item->get_hide_beyond_max_lod();
if (hide_beyond_max_lod) {
visible_with_lod = block.current_mesh_lod < settings.mesh_lod_count;
}
}
}
block.multimesh_instance.set_visible(instancer_is_visible && visible_with_lod);
}
}
}
void VoxelInstancer::set_world(World3D *world) {
for (auto it = _blocks.begin(); it != _blocks.end(); ++it) {
Block &block = **it;
if (block.multimesh_instance.is_valid()) {
block.multimesh_instance.set_world(world);
}
}
}
void VoxelInstancer::set_up_mode(UpMode mode) {
ERR_FAIL_COND(mode < 0 || mode >= UP_MODE_COUNT);
if (_up_mode == mode) {
return;
}
_up_mode = mode;
for (auto it = _layers.begin(); it != _layers.end(); ++it) {
regenerate_layer(it->first, false);
}
}
VoxelInstancer::UpMode VoxelInstancer::get_up_mode() const {
return _up_mode;
}
void VoxelInstancer::set_library(Ref<VoxelInstanceLibrary> library) {
if (library == _library) {
return;
}
if (_library.is_valid()) {
_library->remove_listener(this);
}
_library = library;
clear_layers();
if (_library.is_valid()) {
_library->for_each_item([this](int id, const VoxelInstanceLibraryItem &item) {
add_layer(id, item.get_lod_index());
if (_parent != nullptr && is_inside_tree()) {
regenerate_layer(id, true);
}
});
_library->add_listener(this);
}
update_configuration_warnings();
}
Ref<VoxelInstanceLibrary> VoxelInstancer::get_library() const {
return _library;
}
void VoxelInstancer::regenerate_layer(uint16_t layer_id, bool regenerate_blocks) {
ZN_PROFILE_SCOPE();
ERR_FAIL_COND(_parent == nullptr);
Ref<World3D> world_ref = get_world_3d();
ERR_FAIL_COND(world_ref.is_null());
World3D &world = **world_ref;
Layer &layer = get_layer(layer_id);
Ref<VoxelInstanceLibraryItem> item = _library->get_item(layer_id);
ERR_FAIL_COND(item.is_null());
if (item->get_generator().is_null()) {
return;
}
const Transform3D parent_transform = get_global_transform();
const VoxelLodTerrain *parent_vlt = Object::cast_to<VoxelLodTerrain>(_parent);
const VoxelTerrain *parent_vt = Object::cast_to<VoxelTerrain>(_parent);
if (regenerate_blocks) {
// Create blocks
StdVector<Vector3i> positions;
if (parent_vlt != nullptr) {
parent_vlt->get_meshed_block_positions_at_lod(layer.lod_index, positions);
} else if (parent_vt != nullptr) {
// Only LOD 0 is supported
if (layer.lod_index == 0) {
parent_vt->get_meshed_block_positions(positions);
}
}
for (unsigned int i = 0; i < positions.size(); ++i) {
const Vector3i pos = positions[i];
auto it = layer.blocks.find(pos);
if (it != layer.blocks.end()) {
continue;
}
create_block(layer, layer_id, pos, false);
}
}
const int render_to_data_factor = 1 << (_parent_mesh_block_size_po2 - _parent_mesh_block_size_po2);
ERR_FAIL_COND(render_to_data_factor <= 0 || render_to_data_factor > 2);
struct L {
// Does not return a bool so it can be used in bit-shifting operations without a compiler warning.
// Can be treated like a bool too.
static inline uint8_t has_edited_block(const Lod &lod, Vector3i pos) {
return lod.edited_data_blocks.find(pos) != lod.edited_data_blocks.end();
}
static inline void extract_octant_transforms(
const Block &render_block,
StdVector<Transform3f> &dst,
uint8_t octant_mask,
int render_block_size
) {
if (!render_block.multimesh_instance.is_valid()) {
return;
}
Ref<MultiMesh> multimesh = render_block.multimesh_instance.get_multimesh();
ERR_FAIL_COND(multimesh.is_null());
const int instance_count = zylann::godot::get_visible_instance_count(**multimesh);
const float h = render_block_size / 2;
for (int i = 0; i < instance_count; ++i) {
// TODO This is terrible in MT mode! Think about keeping a local copy...
const Transform3D t = multimesh->get_instance_transform(i);
const uint8_t octant_index = VoxelInstanceGenerator::get_octant_index(to_vec3f(t.origin), h);
if ((octant_mask & (1 << octant_index)) != 0) {
dst.push_back(to_transform3f(t));
}
}
}
};
// Update existing blocks
for (size_t block_index = 0; block_index < _blocks.size(); ++block_index) {
Block &block = *_blocks[block_index];
if (block.layer_id != layer_id) {
continue;
}
const int lod_index = block.lod_index;
const Lod &lod = _lods[lod_index];
// Each bit means "should this octant be generated". If 0, it means it was edited and should not change
uint8_t octant_mask = 0xff;
if (render_to_data_factor == 1) {
if (L::has_edited_block(lod, block.grid_position)) {
// Was edited, no regen on this
continue;
}
} else if (render_to_data_factor == 2) {
// The rendering block corresponds to 8 smaller data blocks
uint8_t edited_mask = 0;
const Vector3i data_pos0 = block.grid_position * render_to_data_factor;
edited_mask |= L::has_edited_block(lod, Vector3i(data_pos0.x, data_pos0.y, data_pos0.z));
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x + 1, data_pos0.y, data_pos0.z)) << 1);
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x, data_pos0.y + 1, data_pos0.z)) << 2);
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x + 1, data_pos0.y + 1, data_pos0.z)) << 3);
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x, data_pos0.y, data_pos0.z + 1)) << 4);
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x + 1, data_pos0.y, data_pos0.z + 1)) << 5);
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x, data_pos0.y + 1, data_pos0.z + 1)) << 6);
edited_mask |= (L::has_edited_block(lod, Vector3i(data_pos0.x + 1, data_pos0.y + 1, data_pos0.z + 1)) << 7);
octant_mask = ~edited_mask;
if (octant_mask == 0) {
// All data blocks were edited, no regen on the whole render block
continue;
}
}
StdVector<Transform3f> &transform_cache = get_tls_transform_cache();
transform_cache.clear();
Array surface_arrays;
if (parent_vlt != nullptr) {
surface_arrays = parent_vlt->get_mesh_block_surface(block.grid_position, lod_index);
} else if (parent_vt != nullptr) {
surface_arrays = parent_vt->get_mesh_block_surface(block.grid_position);
}
const int mesh_block_size = 1 << _parent_mesh_block_size_po2;
const int lod_block_size = mesh_block_size << lod_index;
item->get_generator()->generate_transforms(
transform_cache,
block.grid_position,
block.lod_index,
layer_id,
surface_arrays,
_up_mode,
octant_mask,
lod_block_size
);
if (render_to_data_factor == 2 && octant_mask != 0xff) {
// Complete transforms with edited ones
L::extract_octant_transforms(block, transform_cache, ~octant_mask, mesh_block_size);
// TODO What if these blocks had loaded data which wasn't yet uploaded for render?
// We may setup a local transform list as well since it's expensive to get it from VisualServer
}
const Transform3D block_local_transform(Basis(), Vector3(block.grid_position * lod_block_size));
const Transform3D block_transform = parent_transform * block_local_transform;
update_block_from_transforms(
block_index,
to_span_const(transform_cache),
block.grid_position,
layer,
**item,
layer_id,
world,
block_transform,
block_local_transform.origin
);
}
}
void VoxelInstancer::update_layer_meshes(int layer_id) {
Ref<VoxelInstanceLibraryItem> item_base = _library->get_item(layer_id);
ERR_FAIL_COND(item_base.is_null());
// This method is expected to run on a multimesh layer
VoxelInstanceLibraryMultiMeshItem *item = Object::cast_to<VoxelInstanceLibraryMultiMeshItem>(*item_base);
ERR_FAIL_COND(item == nullptr);
const bool hide_beyond_max_lod = item->get_hide_beyond_max_lod();
const bool instancer_is_visible = is_inside_tree() && is_visible_in_tree();
const VoxelInstanceLibraryMultiMeshItem::Settings &settings = item->get_multimesh_settings();
const unsigned int extended_mesh_lod_count = settings.mesh_lod_count + (hide_beyond_max_lod ? 1 : 0);
for (auto it = _blocks.begin(); it != _blocks.end(); ++it) {
Block &block = **it;
if (block.layer_id != layer_id || !block.multimesh_instance.is_valid()) {
continue;
}
block.multimesh_instance.set_render_layer(settings.render_layer);
block.multimesh_instance.set_material_override(settings.material_override);
block.multimesh_instance.set_cast_shadows_setting(settings.shadow_casting_setting);
block.multimesh_instance.set_gi_mode(settings.gi_mode);
block.current_mesh_lod = math::min(static_cast<unsigned int>(block.current_mesh_lod), extended_mesh_lod_count);
update_mesh_from_mesh_lod(block, settings, hide_beyond_max_lod, instancer_is_visible);
}
}
void VoxelInstancer::update_layer_scenes(int layer_id) {
Ref<VoxelInstanceLibraryItem> item_base = _library->get_item(layer_id);
ERR_FAIL_COND(item_base.is_null());
// This method is expected to run on a scene layer
VoxelInstanceLibrarySceneItem *item = Object::cast_to<VoxelInstanceLibrarySceneItem>(*item_base);
ERR_FAIL_COND(item == nullptr);
const int data_block_size_po2 = _parent_data_block_size_po2;
for (unsigned int block_index = 0; block_index < _blocks.size(); ++block_index) {
Block &block = *_blocks[block_index];
for (unsigned int instance_index = 0; instance_index < block.scene_instances.size(); ++instance_index) {
SceneInstance prev_instance = block.scene_instances[instance_index];
ERR_CONTINUE(prev_instance.root == nullptr);
SceneInstance instance = create_scene_instance(
*item, instance_index, block_index, prev_instance.root->get_transform(), data_block_size_po2
);
ERR_CONTINUE(instance.root == nullptr);
block.scene_instances[instance_index] = instance;
// We just drop the instance without saving, because this function is supposed to occur only in editor,
// or in the very rare cases where library is modified in game (which would invalidate saves anyways).
prev_instance.root->queue_free();
}
}
}
void VoxelInstancer::on_library_item_changed(int item_id, IInstanceLibraryItemListener::ChangeType change) {
ERR_FAIL_COND(_library.is_null());
// TODO It's unclear yet if some code paths do the right thing in case instances got edited
// This callback will fire after the library was loaded, so most of the time in the editor when the user changes
// things. If it happens in-game, it might cause performance issues. If so, it's better to configure the library
// before assigning it to the instancer.
switch (change) {
case IInstanceLibraryItemListener::CHANGE_ADDED: {
Ref<VoxelInstanceLibraryItem> item = _library->get_item(item_id);
ERR_FAIL_COND(item.is_null());
add_layer(item_id, item->get_lod_index());
regenerate_layer(item_id, true);
update_configuration_warnings();
} break;
case IInstanceLibraryItemListener::CHANGE_REMOVED:
remove_layer(item_id);
update_configuration_warnings();
break;
case IInstanceLibraryItemListener::CHANGE_GENERATOR:
regenerate_layer(item_id, false);
break;
case IInstanceLibraryItemListener::CHANGE_VISUAL:
update_layer_meshes(item_id);
break;
case IInstanceLibraryItemListener::CHANGE_SCENE:
update_layer_scenes(item_id);
break;
case IInstanceLibraryItemListener::CHANGE_LOD_INDEX: {
Ref<VoxelInstanceLibraryItem> item = _library->get_item(item_id);
ERR_FAIL_COND(item.is_null());
clear_blocks_in_layer(item_id);
Layer &layer = get_layer(item_id);
Lod &prev_lod = _lods[layer.lod_index];
unordered_remove_value(prev_lod.layers, item_id);
layer.lod_index = item->get_lod_index();
Lod &new_lod = _lods[layer.lod_index];
new_lod.layers.push_back(item_id);
regenerate_layer(item_id, true);
} break;
default:
ERR_PRINT("Unknown change");
break;
}
update_configuration_warnings();
}
void VoxelInstancer::add_layer(int layer_id, int lod_index) {
#ifdef DEBUG_ENABLED
ERR_FAIL_COND(lod_index < 0 || lod_index >= MAX_LOD);
ERR_FAIL_COND_MSG(_layers.find(layer_id) != _layers.end(), "Trying to add a layer that already exists");
#endif
Lod &lod = _lods[lod_index];
#ifdef DEBUG_ENABLED
ERR_FAIL_COND_MSG(
std::find(lod.layers.begin(), lod.layers.end(), layer_id) != lod.layers.end(),
"Layer already referenced by this LOD"
);
#endif
Layer layer;
layer.lod_index = lod_index;
_layers.insert({ layer_id, layer });
lod.layers.push_back(layer_id);
}
void VoxelInstancer::remove_layer(int layer_id) {
Layer &layer = get_layer(layer_id);
// Unregister that layer from the corresponding LOD structure
Lod &lod = _lods[layer.lod_index];
for (size_t i = 0; i < lod.layers.size(); ++i) {
if (lod.layers[i] == layer_id) {
lod.layers[i] = lod.layers.back();
lod.layers.pop_back();
break;
}
}
clear_blocks_in_layer(layer_id);
_layers.erase(layer_id);
}
void VoxelInstancer::remove_block(unsigned int block_index) {