-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathcontent_cao.cpp
More file actions
1855 lines (1610 loc) · 52.1 KB
/
content_cao.cpp
File metadata and controls
1855 lines (1610 loc) · 52.1 KB
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
// Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
#include "content_cao.h"
#include <IBillboardSceneNode.h>
#include <ICameraSceneNode.h>
#include <IMeshManipulator.h>
#include <AnimatedMeshSceneNode.h>
#include <ISceneNode.h>
#include "client/client.h"
#include "client/renderingengine.h"
#include "client/sound.h"
#include "client/texturesource.h"
#include "client/mapblock_mesh.h"
#include "client/content_mapblock.h"
#include "client/meshgen/collector.h"
#include "util/basic_macros.h"
#include "util/numeric.h"
#include "util/serialize.h"
#include "camera.h" // CameraModes
#include "collision.h"
#include "content_cso.h"
#include "clientobject.h"
#include "environment.h"
#include "itemdef.h"
#include "localplayer.h"
#include "map.h"
#include "mesh.h"
#include "nodedef.h"
#include "settings.h"
#include "tool.h"
#include "wieldmesh.h"
#include <algorithm>
#include <cmath>
#include "client/shader.h"
#include "client/minimap.h"
#include <quaternion.h>
#include <SMesh.h>
#include <IMeshBuffer.h>
#include <CMeshBuffer.h>
struct ToolCapabilities;
std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
template<typename T>
void SmoothTranslator<T>::init(T current)
{
val_old = current;
val_current = current;
val_target = current;
anim_time = 0;
anim_time_counter = 0;
aim_is_end = true;
}
template<typename T>
void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
{
aim_is_end = is_end_position;
val_old = val_current;
val_target = new_target;
if (update_interval > 0) {
anim_time = update_interval;
} else {
if (anim_time < 0.001 || anim_time > 1.0)
anim_time = anim_time_counter;
else
anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
}
anim_time_counter = 0;
}
template<typename T>
void SmoothTranslator<T>::translate(f32 dtime)
{
anim_time_counter = anim_time_counter + dtime;
T val_diff = val_target - val_old;
f32 moveratio = 1.0;
if (anim_time > 0.001)
moveratio = anim_time_counter / anim_time;
f32 move_end = aim_is_end ? 1.0 : 1.5;
// Move a bit less than should, to avoid oscillation
moveratio = std::min(moveratio * 0.8f, move_end);
val_current = val_old + val_diff * moveratio;
}
void SmoothTranslatorWrapped::translate(f32 dtime)
{
anim_time_counter = anim_time_counter + dtime;
f32 val_diff = std::abs(val_target - val_old);
if (val_diff > 180.f)
val_diff = 360.f - val_diff;
f32 moveratio = 1.0;
if (anim_time > 0.001)
moveratio = anim_time_counter / anim_time;
f32 move_end = aim_is_end ? 1.0 : 1.5;
// Move a bit less than should, to avoid oscillation
moveratio = std::min(moveratio * 0.8f, move_end);
wrappedApproachShortest(val_current, val_target,
val_diff * moveratio, 360.f);
}
void SmoothTranslatorWrappedv3f::translate(f32 dtime)
{
anim_time_counter = anim_time_counter + dtime;
v3f val_diff_v3f;
val_diff_v3f.X = std::abs(val_target.X - val_old.X);
val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
if (val_diff_v3f.X > 180.f)
val_diff_v3f.X = 360.f - val_diff_v3f.X;
if (val_diff_v3f.Y > 180.f)
val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
if (val_diff_v3f.Z > 180.f)
val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
f32 moveratio = 1.0;
if (anim_time > 0.001)
moveratio = anim_time_counter / anim_time;
f32 move_end = aim_is_end ? 1.0 : 1.5;
// Move a bit less than should, to avoid oscillation
moveratio = std::min(moveratio * 0.8f, move_end);
wrappedApproachShortest(val_current.X, val_target.X,
val_diff_v3f.X * moveratio, 360.f);
wrappedApproachShortest(val_current.Y, val_target.Y,
val_diff_v3f.Y * moveratio, 360.f);
wrappedApproachShortest(val_current.Z, val_target.Z,
val_diff_v3f.Z * moveratio, 360.f);
}
/*
Other stuff
*/
static bool setMaterialTextureAndFilters(video::SMaterial &material,
const std::string &texturestring, ITextureSource *tsrc)
{
bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
video::ITexture *texture = tsrc->getTextureForMesh(texturestring);
if (!texture)
return false;
material.setTexture(0, texture);
// don't filter low-res textures, makes them look blurry
const core::dimension2d<u32> &size = texture->getOriginalSize();
if (std::min(size.Width, size.Height) < TEXTURE_FILTER_MIN_SIZE)
use_trilinear_filter = use_bilinear_filter = false;
material.forEachTexture([=] (auto &tex) {
setMaterialFilters(tex, use_bilinear_filter, use_trilinear_filter,
use_anisotropic_filter);
});
return true;
}
static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
float txs, float tys, int col, int row)
{
video::SMaterial& material = bill->getMaterial(0);
core::matrix4& matrix = material.getTextureMatrix(0);
matrix.setTextureTranslate(txs*col, tys*row);
matrix.setTextureScale(txs, tys);
}
static bool logOnce(const std::ostringstream &from, std::ostream &log_to)
{
thread_local std::vector<u64> logged;
std::string message = from.str();
u64 hash = murmur_hash_64_ua(message.data(), message.length(), 0xBADBABE);
if (std::find(logged.begin(), logged.end(), hash) != logged.end())
return false;
logged.push_back(hash);
log_to << message << std::endl;
return true;
}
static void setColorParam(scene::ISceneNode *node, video::SColor color)
{
for (u32 i = 0; i < node->getMaterialCount(); ++i)
node->getMaterial(i).ColorParam = color;
}
static scene::SMesh *generateNodeMesh(Client *client, MapNode n,
std::vector<MeshAnimationInfo> &animation)
{
auto *ndef = client->ndef();
auto *shdsrc = client->getShaderSource();
MeshCollector collector(v3f(0), v3f());
{
MeshMakeData mmd(ndef, 1, MeshGrid{1});
n.setParam1(0xff);
mmd.fillSingleNode(n);
MapblockMeshGenerator(&mmd, &collector).generate();
}
const AlphaMode alpha_mode = ndef->get(n).alpha;
auto mesh = make_irr<scene::SMesh>();
animation.clear();
for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
for (PreMeshBuffer &p : collector.prebuffers[layer]) {
// reset the pre-computed light data stored in the vertex color,
// since we do that ourselves via updateLight().
for (auto &v : p.vertices)
v.Color.set(0xFFFFFFFF);
// but still apply the tile color
p.applyTileColor();
if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) {
animation.emplace_back(MeshAnimationInfo{
mesh->getMeshBufferCount(), 0, p.layer});
}
auto buf = make_irr<scene::SMeshBuffer>();
buf->append(&p.vertices[0], p.vertices.size(),
&p.indices[0], p.indices.size());
// Set up material
auto &mat = buf->Material;
p.layer.applyMaterialOptions(mat, layer);
getAdHocNodeShader(mat, shdsrc, "object_shader", alpha_mode, layer == 1);
mesh->addMeshBuffer(buf.get());
}
}
mesh->recalculateBoundingBox();
return mesh.release();
}
/*
GenericCAO
*/
GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
ClientActiveObject(0, client, env)
{
if (!client) {
ClientActiveObject::registerType(getType(), create);
} else {
m_client = client;
}
}
bool GenericCAO::getCollisionBox(aabb3f *toset) const
{
if (m_prop.physical)
{
//update collision box
toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
toset->MinEdge += m_position;
toset->MaxEdge += m_position;
return true;
}
return false;
}
bool GenericCAO::collideWithObjects() const
{
return m_prop.collideWithObjects;
}
void GenericCAO::initialize(const std::string &data)
{
processInitData(data);
}
void GenericCAO::processInitData(const std::string &data)
{
std::istringstream is(data, std::ios::binary);
const u8 version = readU8(is);
if (version < 1) {
errorstream << "GenericCAO: Unsupported init data version"
<< std::endl;
return;
}
// PROTOCOL_VERSION >= 37
m_name = deSerializeString16(is);
m_is_player = readU8(is);
m_id = readU16(is);
m_position = readV3F32(is);
m_rotation = readV3F32(is);
m_hp = readU16(is);
if (m_is_player) {
// Check if it's the current player
LocalPlayer *player = m_env->getLocalPlayer();
if (player && player->getName() == m_name) {
m_is_local_player = true;
m_is_visible = false;
player->setCAO(this);
}
}
const u8 num_messages = readU8(is);
for (u8 i = 0; i < num_messages; i++) {
std::string message = deSerializeString32(is);
processMessage(message);
}
m_rotation = wrapDegrees_0_360_v3f(m_rotation);
pos_translator.init(m_position);
rot_translator.init(m_rotation);
updateNodePos();
}
GenericCAO::~GenericCAO()
{
removeFromScene(true);
}
bool GenericCAO::getSelectionBox(aabb3f *toset) const
{
if (!m_prop.is_visible || !m_is_visible || m_is_local_player) {
return false;
}
*toset = m_selection_box;
return true;
}
void GenericCAO::updateParentChain() const
{
if (!m_matrixnode)
return;
// Update the entire chain of nodes to ensure absolute position is correct
std::vector<scene::ISceneNode *> chain;
for (scene::ISceneNode *node = m_matrixnode; node; node = node->getParent())
chain.push_back(node);
for (auto it = chain.rbegin(); it != chain.rend(); ++it)
(*it)->updateAbsolutePosition();
}
const v3f GenericCAO::getPosition() const
{
if (!getParent())
return pos_translator.val_current;
// Calculate real position in world based on MatrixNode
if (m_matrixnode) {
// FIXME work around #16221 which is caused by the camera position and thus
// offset not being in sync with the player (parent) CAO position.
// A better solution might restrict this update to the local player only
// or keep player and camera position in sync.
GenericCAO::updateParentChain();
v3s16 camera_offset = m_env->getCameraOffset();
return m_matrixnode->getAbsolutePosition() +
intToFloat(camera_offset, BS);
}
return m_position;
}
bool GenericCAO::isImmortal() const
{
return itemgroup_get(getGroups(), "immortal");
}
scene::ISceneNode *GenericCAO::getSceneNode() const
{
if (m_meshnode) {
return m_meshnode;
}
if (m_animated_meshnode) {
return m_animated_meshnode;
}
if (m_wield_meshnode) {
return m_wield_meshnode;
}
if (m_spritenode) {
return m_spritenode;
}
return NULL;
}
scene::AnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
{
return m_animated_meshnode;
}
void GenericCAO::setChildrenVisible(bool toset)
{
for (object_t cao_id : m_attachment_child_ids) {
GenericCAO *obj = m_env->getGenericCAO(cao_id);
if (obj) {
// Check if the entity is forced to appear in first person.
obj->setVisible(obj->m_force_visible ? true : toset);
}
}
}
void GenericCAO::setAttachment(object_t parent_id, const std::string &bone,
v3f position, v3f rotation, bool force_visible)
{
// Do checks to avoid circular references
// See similar check in `UnitSAO::setAttachment` (but with different types).
{
auto *obj = m_env->getActiveObject(parent_id);
if (obj == this) {
assert(false);
return;
}
bool problem = false;
if (obj) {
// The chain of wanted parent must not refer or contain "this"
for (obj = obj->getParent(); obj; obj = obj->getParent()) {
if (obj == this) {
problem = true;
break;
}
}
}
if (problem) {
warningstream << "Network or mod bug: "
<< "Attempted to attach object " << m_id << " to parent "
<< parent_id << " but former is an (in)direct parent of latter." << std::endl;
return;
}
}
const auto old_parent = m_attachment_parent_id;
m_attachment_parent_id = parent_id;
m_attachment_bone = bone;
m_attachment_position = position;
m_attachment_rotation = rotation;
m_force_visible = force_visible;
ClientActiveObject *parent = m_env->getActiveObject(parent_id);
if (parent_id != old_parent) {
if (auto *o = m_env->getActiveObject(old_parent))
o->removeAttachmentChild(m_id);
if (parent)
parent->addAttachmentChild(m_id);
}
updateAttachments();
// Forcibly show attachments if required by set_attach
if (m_force_visible) {
m_is_visible = true;
} else if (!m_is_local_player) {
// Objects attached to the local player should be hidden in first person
m_is_visible = !m_attached_to_local ||
m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
m_force_visible = false;
} else {
// Local players need to have this set,
// otherwise first person attachments fail.
m_is_visible = true;
}
}
void GenericCAO::getAttachment(object_t *parent_id, std::string *bone, v3f *position,
v3f *rotation, bool *force_visible) const
{
*parent_id = m_attachment_parent_id;
*bone = m_attachment_bone;
*position = m_attachment_position;
*rotation = m_attachment_rotation;
*force_visible = m_force_visible;
}
void GenericCAO::clearChildAttachments()
{
// Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
while (!m_attachment_child_ids.empty()) {
const auto child_id = *m_attachment_child_ids.begin();
if (auto *child = m_env->getActiveObject(child_id))
child->clearParentAttachment();
else
removeAttachmentChild(child_id);
}
}
void GenericCAO::addAttachmentChild(object_t child_id)
{
m_attachment_child_ids.insert(child_id);
}
void GenericCAO::removeAttachmentChild(object_t child_id)
{
m_attachment_child_ids.erase(child_id);
}
ClientActiveObject* GenericCAO::getParent() const
{
return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
nullptr;
}
void GenericCAO::removeFromScene(bool permanent)
{
// Should be true when removing the object permanently
// and false when refreshing (eg: updating visuals)
if (m_env && permanent) {
// The client does not know whether this object does re-appear to
// a later time, thus do not clear child attachments.
clearParentAttachment();
}
if (auto shadow = RenderingEngine::get_shadow_renderer())
if (auto node = getSceneNode())
shadow->removeNodeFromShadowList(node);
if (m_meshnode) {
m_meshnode->remove();
m_meshnode->drop();
m_meshnode = nullptr;
} else if (m_animated_meshnode) {
m_animated_meshnode->remove();
m_animated_meshnode->drop();
m_animated_meshnode = nullptr;
} else if (m_wield_meshnode) {
m_wield_meshnode->remove();
m_wield_meshnode->drop();
m_wield_meshnode = nullptr;
} else if (m_spritenode) {
m_spritenode->remove();
m_spritenode->drop();
m_spritenode = nullptr;
}
m_meshnode_animation.clear();
if (m_matrixnode) {
m_matrixnode->remove();
m_matrixnode->drop();
m_matrixnode = nullptr;
}
if (m_nametag) {
m_client->getCamera()->removeNametag(m_nametag);
m_nametag = nullptr;
}
if (m_marker && m_client->getMinimap())
m_client->getMinimap()->removeMarker(&m_marker);
}
void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
{
m_smgr = smgr;
if (getSceneNode() != NULL) {
return;
}
m_visuals_expired = false;
if (!m_prop.is_visible)
return;
infostream << "GenericCAO::addToScene(): " <<
enum_to_string(es_ObjectVisual, m_prop.visual)<< std::endl;
auto updateMaterialType = [this](bool hw_skin) {
if (m_prop.visual != OBJECTVISUAL_NODE &&
m_prop.visual != OBJECTVISUAL_WIELDITEM &&
m_prop.visual != OBJECTVISUAL_ITEM)
{
IShaderSource *shader_source = m_client->getShaderSource();
MaterialType material_type;
if (m_prop.shaded && m_prop.glow == 0)
material_type = (m_prop.use_texture_alpha) ?
TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
else
material_type = (m_prop.use_texture_alpha) ?
TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL,
false, hw_skin);
m_material_type = shader_source->getShaderInfo(shader_id).material;
} else {
// Not used, so make sure it's not valid
m_material_type = video::EMT_INVALID;
}
};
m_matrixnode = m_smgr->addDummyTransformationSceneNode();
m_matrixnode->grab();
auto setMaterial = [this](video::SMaterial &mat) {
if (m_material_type != video::EMT_INVALID)
mat.MaterialType = m_material_type;
mat.FogEnable = true;
mat.forEachTexture([] (auto &tex) {
tex.MinFilter = video::ETMINF_NEAREST_MIPMAP_NEAREST;
tex.MagFilter = video::ETMAGF_NEAREST;
});
};
auto setSceneNodeMaterials = [&] (scene::ISceneNode *node, bool hw_skin = false) {
updateMaterialType(hw_skin);
node->forEachMaterial(setMaterial);
};
switch(m_prop.visual) {
case OBJECTVISUAL_UPRIGHT_SPRITE: {
updateMaterialType(false);
auto mesh = make_irr<scene::SMesh>();
f32 dx = BS * m_prop.visual_size.X / 2;
f32 dy = BS * m_prop.visual_size.Y / 2;
video::SColor c(0xFFFFFFFF);
video::S3DVertex vertices[4] = {
video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
};
if (m_is_player) {
// Move minimal Y position to 0 (feet position)
for (auto &vertex : vertices)
vertex.Pos.Y += dy;
}
const u16 indices[] = {0,1,2,2,3,0};
for (int face : {0, 1}) {
auto buf = make_irr<scene::SMeshBuffer>();
// Front (0) or Back (1)
if (face == 1) {
for (auto &v : vertices)
v.Normal *= -1;
for (int i : {0, 2})
std::swap(vertices[i].Pos, vertices[i+1].Pos);
}
buf->append(vertices, 4, indices, 6);
// Set material
setMaterial(buf->getMaterial());
buf->getMaterial().ColorParam = c;
// Add to mesh
mesh->addMeshBuffer(buf.get());
}
mesh->recalculateBoundingBox();
m_meshnode = m_smgr->addMeshSceneNode(mesh.get(), m_matrixnode);
m_meshnode->grab();
break;
} case OBJECTVISUAL_CUBE: {
scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
m_meshnode->grab();
mesh->drop();
m_meshnode->setScale(m_prop.visual_size);
setSceneNodeMaterials(m_meshnode);
m_meshnode->forEachMaterial([this] (auto &mat) {
mat.BackfaceCulling = m_prop.backface_culling;
});
break;
} case OBJECTVISUAL_MESH: {
scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
if (mesh) {
if (!checkMeshNormals(mesh)) {
infostream << "GenericCAO: recalculating normals for mesh "
<< m_prop.mesh << std::endl;
m_smgr->getMeshManipulator()->
recalculateNormals(mesh, true, false);
}
m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode);
m_animated_meshnode->grab();
mesh->drop(); // The scene node took hold of it
m_animated_meshnode->setScale(m_prop.visual_size);
// set vertex colors to ensure alpha is set
setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
setSceneNodeMaterials(m_animated_meshnode, mesh->needsHwSkinning());
m_animated_meshnode->forEachMaterial([this] (auto &mat) {
mat.BackfaceCulling = m_prop.backface_culling;
});
m_animated_meshnode->setOnAnimateCallback([&](f32 dtime) {
for (auto it = m_bone_override.begin(); it != m_bone_override.end();) {
BoneOverride &props = it->second;
props.dtime_passed += dtime;
if (props.isIdentity()) {
it = m_bone_override.erase(it);
continue;
}
if (auto *bone = m_animated_meshnode->getJointNode(it->first.c_str())) {
bone->setPosition(props.getPosition(bone->getPosition()));
bone->setRotation(props.getRotationEulerDeg(bone->getRotation()));
bone->setScale(props.getScale(bone->getScale()));
}
++it;
}
});
} else
errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
break;
}
case OBJECTVISUAL_WIELDITEM:
case OBJECTVISUAL_ITEM: {
ItemStack item;
if (m_prop.wield_item.empty()) {
// Old format, only textures are specified.
infostream << "textures: " << m_prop.textures.size() << std::endl;
if (!m_prop.textures.empty()) {
infostream << "textures[0]: " << m_prop.textures[0]
<< std::endl;
IItemDefManager *idef = m_client->idef();
item = ItemStack(m_prop.textures[0], 1, 0, idef);
}
} else {
infostream << "serialized form: " << m_prop.wield_item << std::endl;
item.deSerialize(m_prop.wield_item, m_client->idef());
}
m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1);
m_wield_meshnode->setItem(item, m_client,
(m_prop.visual == OBJECTVISUAL_WIELDITEM));
m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
break;
} case OBJECTVISUAL_NODE: {
auto *mesh = generateNodeMesh(m_client, m_prop.node, m_meshnode_animation);
assert(mesh);
m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
m_meshnode->setSharedMaterials(true);
m_meshnode->grab();
mesh->drop();
m_meshnode->setScale(m_prop.visual_size);
setSceneNodeMaterials(m_meshnode);
break;
} default:
m_spritenode = m_smgr->addBillboardSceneNode(m_matrixnode);
m_spritenode->grab();
setSceneNodeMaterials(m_spritenode);
m_spritenode->setSize(v2f(m_prop.visual_size.X,
m_prop.visual_size.Y) * BS);
setBillboardTextureMatrix(m_spritenode, 1, 1, 0, 0);
// This also serves as fallback for unknown visual types
if (m_prop.visual != OBJECTVISUAL_SPRITE) {
m_spritenode->getMaterial(0).setTexture(0,
tsrc->getTextureForMesh("unknown_object.png"));
}
break;
}
/* don't update while punch texture modifier is active */
if (m_reset_textures_timer < 0)
updateTextures(m_current_texture_modifier);
if (scene::ISceneNode *node = getSceneNode()) {
node->setParent(m_matrixnode);
if (auto shadow = RenderingEngine::get_shadow_renderer())
shadow->addNodeToShadowList(node);
}
updateNametag();
updateMarker();
updateNodePos();
updateAnimation();
updateAttachments();
setNodeLight(m_last_light);
updateMeshCulling();
if (m_animated_meshnode) {
u32 mat_count = m_animated_meshnode->getMaterialCount();
assert(mat_count == m_animated_meshnode->getMesh()->getMeshBufferCount());
u32 max_tex_idx = 0;
for (u32 i = 0; i < mat_count; ++i) {
max_tex_idx = std::max(max_tex_idx,
m_animated_meshnode->getMesh()->getTextureSlot(i));
}
if (mat_count == 0 || m_prop.textures.empty()) {
// nothing
} else if (max_tex_idx >= m_prop.textures.size()) {
std::ostringstream oss;
oss << "GenericCAO::addToScene(): Model "
<< m_prop.mesh << " is missing " << (max_tex_idx + 1 - m_prop.textures.size())
<< " more texture(s), this is deprecated.";
logOnce(oss, warningstream);
video::ITexture *last = m_animated_meshnode->getMaterial(0).TextureLayers[0].Texture;
for (u32 i = 1; i < mat_count; i++) {
auto &layer = m_animated_meshnode->getMaterial(i).TextureLayers[0];
if (!layer.Texture)
layer.Texture = last;
last = layer.Texture;
}
}
}
}
void GenericCAO::updateLight(u32 day_night_ratio)
{
if (m_prop.glow < 0)
return;
u16 light_at_pos = 0;
u8 light_at_pos_intensity = 0;
bool pos_ok = false;
v3s16 pos[3];
u16 npos = getLightPosition(pos);
for (u16 i = 0; i < npos; i++) {
bool this_ok;
MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
if (this_ok) {
// Get light level at the position plus the entity glow
u16 this_light = getInteriorLight(n, m_prop.glow, m_client->ndef());
u8 this_light_intensity = MYMAX(this_light & 0xFF, this_light >> 8);
if (this_light_intensity > light_at_pos_intensity) {
light_at_pos = this_light;
light_at_pos_intensity = this_light_intensity;
}
pos_ok = true;
}
}
if (!pos_ok)
light_at_pos = LIGHT_SUN;
video::SColor light;
// Encode light into color, adding a small boost
// based on the entity glow.
light = encode_light(light_at_pos, m_prop.glow);
if (light != m_last_light) {
m_last_light = light;
setNodeLight(light);
}
}
void GenericCAO::setNodeLight(const video::SColor &light_color)
{
if (m_prop.visual == OBJECTVISUAL_WIELDITEM || m_prop.visual == OBJECTVISUAL_ITEM) {
if (m_wield_meshnode)
m_wield_meshnode->setLightColorAndAnimation(light_color,
m_client->getAnimationTime());
return;
}
{
auto *node = getSceneNode();
if (!node)
return;
setColorParam(node, light_color);
}
}
u16 GenericCAO::getLightPosition(v3s16 *pos)
{
const auto &box = m_prop.collisionbox;
pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
// Skip center pos if it falls into the same node as Min or MaxEdge
if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
return 2;
pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
return 3;
}
void GenericCAO::updateMarker()
{
if (!m_client->getMinimap())
return;
if (!m_prop.show_on_minimap) {
if (m_marker)
m_client->getMinimap()->removeMarker(&m_marker);
return;
}
if (m_marker)
return;
scene::ISceneNode *node = getSceneNode();
if (!node)
return;
m_marker = m_client->getMinimap()->addMarker(node);
}
void GenericCAO::updateNametag()
{
if (m_is_local_player) // No nametag for local player
return;
if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
// Delete nametag
if (m_nametag) {
m_client->getCamera()->removeNametag(m_nametag);
m_nametag = nullptr;
}
return;
}
scene::ISceneNode *node = getSceneNode();
if (!node)
return;
v3f pos;
pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
// Add or update nametag
Nametag tmp{node, m_prop.nametag, m_prop.nametag_color,
m_prop.nametag_bgcolor, m_prop.nametag_fontsize, pos,
m_prop.nametag_scale_z};
if (!m_nametag) {
m_nametag = m_client->getCamera()->addNametag(tmp);
assert(m_nametag);
} else {
*m_nametag = tmp;
}
}
void GenericCAO::updateNodePos()
{
if (getParent() != NULL)
return;
scene::ISceneNode *node = getSceneNode();
if (node) {
assert(m_matrixnode);
v3s16 camera_offset = m_env->getCameraOffset();
v3f pos = pos_translator.val_current -
intToFloat(camera_offset, BS);
getPosRotMatrix().setTranslation(pos);
if (node != m_spritenode) { // rotate if not a sprite
v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
setPitchYawRoll(getPosRotMatrix(), rot);
}
}
}
void GenericCAO::step(float dtime, ClientEnvironment *env)
{
// Handle model animations and update positions instantly to prevent lags
if (m_is_local_player) {
LocalPlayer *player = m_env->getLocalPlayer();
m_position = player->getPosition();
pos_translator.val_current = m_position;
m_rotation.Y = wrapDegrees_0_360(player->getYaw());
rot_translator.val_current = m_rotation;
if (m_is_visible) {
LocalPlayerAnimation old_anim = player->last_animation;
float old_anim_speed = player->last_animation_speed;
m_velocity = v3f(0,0,0);
m_acceleration = v3f(0,0,0);
const PlayerControl &controls = player->getPlayerControl();
f32 new_speed = player->local_animation_speed;
bool walking = false;
if (controls.movement_speed > 0.001f) {
new_speed *= controls.movement_speed;
walking = true;
}
v2f new_anim(0,0);
bool allow_update = false;
// increase speed if using fast or flying fast