-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathEntityScriptingInterface.cpp
More file actions
2440 lines (2106 loc) · 105 KB
/
Copy pathEntityScriptingInterface.cpp
File metadata and controls
2440 lines (2106 loc) · 105 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
//
// EntityScriptingInterface.cpp
// libraries/entities/src
//
// Created by Brad Hefta-Gaub on 12/6/13.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "EntityScriptingInterface.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <QFutureWatcher>
#include <QtConcurrent/QtConcurrentRun>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <shared/QtHelpers.h>
#include <VariantMapToScriptValue.h>
#include <SharedUtil.h>
#include <SpatialParentFinder.h>
#include <AvatarHashMap.h>
#include "EntityItemID.h"
#include "EntitiesLogging.h"
#include "EntityDynamicFactoryInterface.h"
#include "EntityDynamicInterface.h"
#include "EntitySimulation.h"
#include "EntityTree.h"
#include "LightEntityItem.h"
#include "ModelEntityItem.h"
#include "QVariantGLM.h"
#include "SimulationOwner.h"
#include "ZoneEntityItem.h"
#include "WebEntityItem.h"
#include <EntityScriptClient.h>
#include <Profile.h>
#include "GrabPropertyGroup.h"
const QString GRABBABLE_USER_DATA = "{\"grabbableKey\":{\"grabbable\":true}}";
const QString NOT_GRABBABLE_USER_DATA = "{\"grabbableKey\":{\"grabbable\":false}}";
EntityScriptingInterface::EntityScriptingInterface(bool bidOnSimulationOwnership) :
_entityTree(nullptr),
_bidOnSimulationOwnership(bidOnSimulationOwnership)
{
auto nodeList = DependencyManager::get<NodeList>();
connect(nodeList.data(), &NodeList::isAllowedEditorChanged, this, &EntityScriptingInterface::canAdjustLocksChanged);
connect(nodeList.data(), &NodeList::canRezChanged, this, &EntityScriptingInterface::canRezChanged);
connect(nodeList.data(), &NodeList::canRezTmpChanged, this, &EntityScriptingInterface::canRezTmpChanged);
connect(nodeList.data(), &NodeList::canRezCertifiedChanged, this, &EntityScriptingInterface::canRezCertifiedChanged);
connect(nodeList.data(), &NodeList::canRezTmpCertifiedChanged, this, &EntityScriptingInterface::canRezTmpCertifiedChanged);
connect(nodeList.data(), &NodeList::canWriteAssetsChanged, this, &EntityScriptingInterface::canWriteAssetsChanged);
connect(nodeList.data(), &NodeList::canGetAndSetPrivateUserDataChanged, this, &EntityScriptingInterface::canGetAndSetPrivateUserDataChanged);
auto& packetReceiver = nodeList->getPacketReceiver();
packetReceiver.registerListener(PacketType::EntityScriptCallMethod,
PacketReceiver::makeSourcedListenerReference<EntityScriptingInterface>(this, &EntityScriptingInterface::handleEntityScriptCallMethodPacket));
}
void EntityScriptingInterface::queueEntityMessage(PacketType packetType,
EntityItemID entityID, const EntityItemProperties& properties) {
getEntityPacketSender()->queueEditEntityMessage(packetType, _entityTree, entityID, properties);
}
void EntityScriptingInterface::resetActivityTracking() {
_activityTracking.addedEntityCount = 0;
_activityTracking.deletedEntityCount = 0;
_activityTracking.editedEntityCount = 0;
}
bool EntityScriptingInterface::canAdjustLocks() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->isAllowedEditor();
}
bool EntityScriptingInterface::canRez() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanRez();
}
bool EntityScriptingInterface::canRezTmp() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanRezTmp();
}
bool EntityScriptingInterface::canRezCertified() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanRezCertified();
}
bool EntityScriptingInterface::canRezTmpCertified() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanRezTmpCertified();
}
bool EntityScriptingInterface::canWriteAssets() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanWriteAssets();
}
bool EntityScriptingInterface::canReplaceContent() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanReplaceContent();
}
bool EntityScriptingInterface::canGetAndSetPrivateUserData() {
auto nodeList = DependencyManager::get<NodeList>();
return nodeList->getThisNodeCanGetAndSetPrivateUserData();
}
void EntityScriptingInterface::setEntityTree(EntityTreePointer elementTree) {
if (_entityTree) {
disconnect(_entityTree.get(), &EntityTree::addingEntityPointer, this, &EntityScriptingInterface::onAddingEntity);
disconnect(_entityTree.get(), &EntityTree::deletingEntityPointer, this, &EntityScriptingInterface::onDeletingEntity);
disconnect(_entityTree.get(), &EntityTree::addingEntity, this, &EntityScriptingInterface::addingEntity);
disconnect(_entityTree.get(), &EntityTree::deletingEntity, this, &EntityScriptingInterface::deletingEntity);
disconnect(_entityTree.get(), &EntityTree::clearingEntities, this, &EntityScriptingInterface::clearingEntities);
}
_entityTree = elementTree;
if (_entityTree) {
connect(_entityTree.get(), &EntityTree::addingEntityPointer, this, &EntityScriptingInterface::onAddingEntity, Qt::DirectConnection);
connect(_entityTree.get(), &EntityTree::deletingEntityPointer, this, &EntityScriptingInterface::onDeletingEntity, Qt::DirectConnection);
connect(_entityTree.get(), &EntityTree::addingEntity, this, &EntityScriptingInterface::addingEntity);
connect(_entityTree.get(), &EntityTree::deletingEntity, this, &EntityScriptingInterface::deletingEntity);
connect(_entityTree.get(), &EntityTree::clearingEntities, this, &EntityScriptingInterface::clearingEntities);
}
}
EntityItemProperties convertPropertiesToScriptSemantics(const EntityItemProperties& entitySideProperties,
bool scalesWithParent) {
// In EntityTree code, properties.position and properties.rotation are relative to the parent. In javascript,
// they are in world-space. The local versions are put into localPosition and localRotation and position and
// rotation are converted from local to world space.
EntityItemProperties scriptSideProperties = entitySideProperties;
scriptSideProperties.setLocalPosition(entitySideProperties.getPosition());
scriptSideProperties.setLocalRotation(entitySideProperties.getRotation());
scriptSideProperties.setLocalVelocity(entitySideProperties.getVelocity());
scriptSideProperties.setLocalAngularVelocity(entitySideProperties.getAngularVelocity());
scriptSideProperties.setLocalDimensions(entitySideProperties.getDimensions());
bool success;
glm::vec3 worldPosition = SpatiallyNestable::localToWorld(entitySideProperties.getPosition(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent,
success);
glm::quat worldRotation = SpatiallyNestable::localToWorld(entitySideProperties.getRotation(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent,
success);
glm::vec3 worldVelocity = SpatiallyNestable::localToWorldVelocity(entitySideProperties.getVelocity(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent,
success);
glm::vec3 worldAngularVelocity = SpatiallyNestable::localToWorldAngularVelocity(entitySideProperties.getAngularVelocity(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent,
success);
glm::vec3 worldDimensions = SpatiallyNestable::localToWorldDimensions(entitySideProperties.getDimensions(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent,
success);
scriptSideProperties.setPosition(worldPosition);
scriptSideProperties.setRotation(worldRotation);
scriptSideProperties.setVelocity(worldVelocity);
scriptSideProperties.setAngularVelocity(worldAngularVelocity);
scriptSideProperties.setDimensions(worldDimensions);
return scriptSideProperties;
}
// TODO: this method looks expensive and should take properties by reference, update it, and return void
EntityItemProperties convertPropertiesFromScriptSemantics(const EntityItemProperties& scriptSideProperties,
bool scalesWithParent) {
// convert position and rotation properties from world-space to local, unless localPosition and localRotation
// are set. If they are set, they overwrite position and rotation.
EntityItemProperties entitySideProperties = scriptSideProperties;
bool success;
if (scriptSideProperties.localPositionChanged()) {
entitySideProperties.setPosition(scriptSideProperties.getLocalPosition());
} else if (scriptSideProperties.positionChanged()) {
glm::vec3 localPosition = SpatiallyNestable::worldToLocal(entitySideProperties.getPosition(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent, success);
entitySideProperties.setPosition(localPosition);
}
if (scriptSideProperties.localRotationChanged()) {
entitySideProperties.setRotation(scriptSideProperties.getLocalRotation());
} else if (scriptSideProperties.rotationChanged()) {
glm::quat localRotation = SpatiallyNestable::worldToLocal(entitySideProperties.getRotation(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent, success);
entitySideProperties.setRotation(localRotation);
}
if (scriptSideProperties.localVelocityChanged()) {
entitySideProperties.setVelocity(scriptSideProperties.getLocalVelocity());
} else if (scriptSideProperties.velocityChanged()) {
glm::vec3 localVelocity = SpatiallyNestable::worldToLocalVelocity(entitySideProperties.getVelocity(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent, success);
entitySideProperties.setVelocity(localVelocity);
}
if (scriptSideProperties.localAngularVelocityChanged()) {
entitySideProperties.setAngularVelocity(scriptSideProperties.getLocalAngularVelocity());
} else if (scriptSideProperties.angularVelocityChanged()) {
glm::vec3 localAngularVelocity =
SpatiallyNestable::worldToLocalAngularVelocity(entitySideProperties.getAngularVelocity(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent, success);
entitySideProperties.setAngularVelocity(localAngularVelocity);
}
if (scriptSideProperties.localDimensionsChanged()) {
entitySideProperties.setDimensions(scriptSideProperties.getLocalDimensions());
} else if (scriptSideProperties.dimensionsChanged()) {
glm::vec3 localDimensions = SpatiallyNestable::worldToLocalDimensions(entitySideProperties.getDimensions(),
entitySideProperties.getParentID(),
entitySideProperties.getParentJointIndex(),
scalesWithParent, success);
entitySideProperties.setDimensions(localDimensions);
}
return entitySideProperties;
}
void synchronizeSpatialKey(const GrabPropertyGroup& grabProperties, QJsonObject& grabbableKey, bool& userDataChanged) {
if (grabProperties.equippableLeftPositionChanged() ||
grabProperties.equippableRightPositionChanged() ||
grabProperties.equippableRightRotationChanged() ||
grabProperties.equippableIndicatorURLChanged() ||
grabProperties.equippableIndicatorScaleChanged() ||
grabProperties.equippableIndicatorOffsetChanged()) {
QJsonObject spatialKey = grabbableKey["spatialKey"].toObject();
if (grabProperties.equippableLeftPositionChanged()) {
if (grabProperties.getEquippableLeftPosition() == INITIAL_LEFT_EQUIPPABLE_POSITION) {
spatialKey.remove("leftRelativePosition");
} else {
spatialKey["leftRelativePosition"] =
QJsonValue::fromVariant(vec3ToQMap(grabProperties.getEquippableLeftPosition()));
}
}
if (grabProperties.equippableRightPositionChanged()) {
if (grabProperties.getEquippableRightPosition() == INITIAL_RIGHT_EQUIPPABLE_POSITION) {
spatialKey.remove("rightRelativePosition");
} else {
spatialKey["rightRelativePosition"] =
QJsonValue::fromVariant(vec3ToQMap(grabProperties.getEquippableRightPosition()));
}
}
if (grabProperties.equippableLeftRotationChanged()) {
spatialKey["relativeRotation"] =
QJsonValue::fromVariant(quatToQMap(grabProperties.getEquippableLeftRotation()));
} else if (grabProperties.equippableRightRotationChanged()) {
spatialKey["relativeRotation"] =
QJsonValue::fromVariant(quatToQMap(grabProperties.getEquippableRightRotation()));
}
grabbableKey["spatialKey"] = spatialKey;
userDataChanged = true;
}
}
void synchronizeGrabbableKey(const GrabPropertyGroup& grabProperties, QJsonObject& userData, bool& userDataChanged) {
if (grabProperties.triggerableChanged() ||
grabProperties.grabbableChanged() ||
grabProperties.grabFollowsControllerChanged() ||
grabProperties.grabKinematicChanged() ||
grabProperties.equippableChanged() ||
grabProperties.equippableLeftPositionChanged() ||
grabProperties.equippableRightPositionChanged() ||
grabProperties.equippableRightRotationChanged()) {
QJsonObject grabbableKey = userData["grabbableKey"].toObject();
if (grabProperties.triggerableChanged()) {
if (grabProperties.getTriggerable()) {
grabbableKey["triggerable"] = true;
} else {
grabbableKey.remove("triggerable");
}
}
if (grabProperties.grabbableChanged()) {
if (grabProperties.getGrabbable()) {
grabbableKey.remove("grabbable");
} else {
grabbableKey["grabbable"] = false;
}
}
if (grabProperties.grabFollowsControllerChanged()) {
if (grabProperties.getGrabFollowsController()) {
grabbableKey.remove("ignoreIK");
} else {
grabbableKey["ignoreIK"] = false;
}
}
if (grabProperties.grabKinematicChanged()) {
if (grabProperties.getGrabKinematic()) {
grabbableKey.remove("kinematic");
} else {
grabbableKey["kinematic"] = false;
}
}
if (grabProperties.equippableChanged()) {
if (grabProperties.getEquippable()) {
grabbableKey["equippable"] = true;
} else {
grabbableKey.remove("equippable");
}
}
if (grabbableKey.contains("spatialKey")) {
synchronizeSpatialKey(grabProperties, grabbableKey, userDataChanged);
}
userData["grabbableKey"] = grabbableKey;
userDataChanged = true;
}
}
void synchronizeGrabJoints(const GrabPropertyGroup& grabProperties, QJsonObject& joints) {
QJsonArray rightHand = joints["RightHand"].toArray();
QJsonObject rightHandPosition = rightHand.size() > 0 ? rightHand[0].toObject() : QJsonObject();
QJsonObject rightHandRotation = rightHand.size() > 1 ? rightHand[1].toObject() : QJsonObject();
QJsonArray leftHand = joints["LeftHand"].toArray();
QJsonObject leftHandPosition = leftHand.size() > 0 ? leftHand[0].toObject() : QJsonObject();
QJsonObject leftHandRotation = leftHand.size() > 1 ? leftHand[1].toObject() : QJsonObject();
if (grabProperties.equippableLeftPositionChanged()) {
leftHandPosition =
QJsonValue::fromVariant(vec3ToQMap(grabProperties.getEquippableLeftPosition())).toObject();
}
if (grabProperties.equippableRightPositionChanged()) {
rightHandPosition =
QJsonValue::fromVariant(vec3ToQMap(grabProperties.getEquippableRightPosition())).toObject();
}
if (grabProperties.equippableLeftRotationChanged()) {
leftHandRotation =
QJsonValue::fromVariant(quatToQMap(grabProperties.getEquippableLeftRotation())).toObject();
}
if (grabProperties.equippableRightRotationChanged()) {
rightHandRotation =
QJsonValue::fromVariant(quatToQMap(grabProperties.getEquippableRightRotation())).toObject();
}
rightHand = QJsonArray();
rightHand.append(rightHandPosition);
rightHand.append(rightHandRotation);
joints["RightHand"] = rightHand;
leftHand = QJsonArray();
leftHand.append(leftHandPosition);
leftHand.append(leftHandRotation);
joints["LeftHand"] = leftHand;
}
void synchronizeEquipHotspot(const GrabPropertyGroup& grabProperties, QJsonObject& userData, bool& userDataChanged) {
if (grabProperties.equippableLeftPositionChanged() ||
grabProperties.equippableRightPositionChanged() ||
grabProperties.equippableRightRotationChanged() ||
grabProperties.equippableIndicatorURLChanged() ||
grabProperties.equippableIndicatorScaleChanged() ||
grabProperties.equippableIndicatorOffsetChanged()) {
QJsonArray equipHotspots = userData["equipHotspots"].toArray();
QJsonObject equipHotspot = equipHotspots[0].toObject();
QJsonObject joints = equipHotspot["joints"].toObject();
synchronizeGrabJoints(grabProperties, joints);
if (grabProperties.equippableIndicatorURLChanged()) {
equipHotspot["modelURL"] = grabProperties.getEquippableIndicatorURL();
}
if (grabProperties.equippableIndicatorScaleChanged()) {
QJsonObject scale =
QJsonValue::fromVariant(vec3ToQMap(grabProperties.getEquippableIndicatorScale())).toObject();
equipHotspot["radius"] = scale;
equipHotspot["modelScale"] = scale;
}
if (grabProperties.equippableIndicatorOffsetChanged()) {
equipHotspot["position"] =
QJsonValue::fromVariant(vec3ToQMap(grabProperties.getEquippableIndicatorOffset())).toObject();
}
equipHotspot["joints"] = joints;
equipHotspots = QJsonArray();
equipHotspots.append(equipHotspot);
userData["equipHotspots"] = equipHotspots;
userDataChanged = true;
}
}
void synchronizeWearable(const GrabPropertyGroup& grabProperties, QJsonObject& userData, bool& userDataChanged) {
if (grabProperties.equippableLeftPositionChanged() ||
grabProperties.equippableRightPositionChanged() ||
grabProperties.equippableRightRotationChanged() ||
grabProperties.equippableIndicatorURLChanged() ||
grabProperties.equippableIndicatorScaleChanged() ||
grabProperties.equippableIndicatorOffsetChanged()) {
QJsonObject wearable = userData["wearable"].toObject();
QJsonObject joints = wearable["joints"].toObject();
synchronizeGrabJoints(grabProperties, joints);
wearable["joints"] = joints;
userData["wearable"] = wearable;
userDataChanged = true;
}
}
void synchronizeEditedGrabProperties(EntityItemProperties& properties, const QString& previousUserdata) {
// After sufficient warning to content creators, we should be able to remove this.
if (properties.grabbingRelatedPropertyChanged()) {
// This edit touches a new-style grab property, so make userData agree...
GrabPropertyGroup& grabProperties = properties.getGrab();
bool userDataChanged { false };
// if the edit changed userData, use the updated version coming along with the edit. If not, use
// what was already in the entity.
QByteArray userDataString;
if (properties.userDataChanged()) {
userDataString = properties.getUserData().toUtf8();
} else {
userDataString = previousUserdata.toUtf8();;
}
QJsonObject userData = QJsonDocument::fromJson(userDataString).object();
if (userData.contains("grabbableKey")) {
synchronizeGrabbableKey(grabProperties, userData, userDataChanged);
}
if (userData.contains("equipHotspots")) {
synchronizeEquipHotspot(grabProperties, userData, userDataChanged);
}
if (userData.contains("wearable")) {
synchronizeWearable(grabProperties, userData, userDataChanged);
}
if (userDataChanged) {
properties.setUserData(QJsonDocument(userData).toJson());
}
} else if (properties.userDataChanged()) {
// This edit touches userData (and doesn't touch a new-style grab property). Check for grabbableKey in the
// userdata and make the new-style grab properties agree
convertGrabUserDataToProperties(properties);
}
}
QUuid EntityScriptingInterface::addEntityInternal(const EntityItemProperties& properties, entity::HostType entityHostType) {
PROFILE_RANGE(script_entities, __FUNCTION__);
_activityTracking.addedEntityCount++;
EntityItemProperties propertiesWithSimID = properties;
propertiesWithSimID.setEntityHostType(entityHostType);
if (entityHostType == entity::HostType::AVATAR) {
// only allow adding our own avatar entities from script
propertiesWithSimID.setOwningAvatarID(AVATAR_SELF_ID);
} else if (entityHostType == entity::HostType::LOCAL) {
// For now, local entities are always collisionless
// TODO: create a separate, local physics simulation that just handles local entities (and MyAvatar?)
propertiesWithSimID.setCollisionless(true);
}
// the created time will be set in EntityTree::addEntity by recordCreationTime()
auto nodeList = DependencyManager::get<NodeList>();
auto sessionID = nodeList->getSessionUUID();
propertiesWithSimID.setLastEditedBy(sessionID);
bool scalesWithParent = propertiesWithSimID.getScalesWithParent();
propertiesWithSimID = convertPropertiesFromScriptSemantics(propertiesWithSimID, scalesWithParent);
propertiesWithSimID.setDimensionsInitialized(properties.dimensionsChanged());
synchronizeEditedGrabProperties(propertiesWithSimID, QString());
EntityItemID id;
// If we have a local entity tree set, then also update it.
bool success = addLocalEntityCopy(propertiesWithSimID, id);
// queue the packet
if (success) {
queueEntityMessage(PacketType::EntityAdd, id, propertiesWithSimID);
return id;
} else {
return QUuid();
}
}
bool EntityScriptingInterface::addLocalEntityCopy(EntityItemProperties& properties, EntityItemID& id, bool isClone) {
bool success = true;
id = EntityItemID(QUuid::createUuid());
if (_entityTree) {
_entityTree->withWriteLock([&] {
EntityItemPointer entity = _entityTree->addEntity(id, properties, isClone);
if (entity) {
if (properties.queryAACubeRelatedPropertyChanged()) {
// due to parenting, the server may not know where something is in world-space, so include the bounding cube.
bool success;
AACube queryAACube = entity->getQueryAACube(success);
if (success) {
properties.setQueryAACube(queryAACube);
}
}
entity->setLastBroadcast(usecTimestampNow());
// since we're creating this object we will immediately volunteer to own its simulation
entity->upgradeScriptSimulationPriority(VOLUNTEER_SIMULATION_PRIORITY);
properties.setLastEdited(entity->getLastEdited());
} else {
qCDebug(entities) << "script failed to add new Entity to local Octree";
success = false;
}
});
}
return success;
}
QUuid EntityScriptingInterface::addModelEntity(const QString& name, const QString& modelUrl, const QString& textures,
const QString& shapeType, bool dynamic, bool collisionless, bool grabbable,
const glm::vec3& position, const glm::vec3& gravity) {
_activityTracking.addedEntityCount++;
EntityItemProperties properties;
properties.setType(EntityTypes::Model);
properties.setName(name);
properties.setModelURL(modelUrl);
properties.setShapeTypeFromString(shapeType);
properties.setDynamic(dynamic);
properties.setCollisionless(collisionless);
properties.setUserData(grabbable ? GRABBABLE_USER_DATA : NOT_GRABBABLE_USER_DATA);
properties.setPosition(position);
properties.setGravity(gravity);
if (!textures.isEmpty()) {
properties.setTextures(textures);
}
auto nodeList = DependencyManager::get<NodeList>();
auto sessionID = nodeList->getSessionUUID();
properties.setLastEditedBy(sessionID);
return addEntity(properties);
}
QUuid EntityScriptingInterface::cloneEntity(const QUuid& entityIDToClone) {
EntityItemID newEntityID;
EntityItemProperties properties = getEntityProperties(entityIDToClone);
bool cloneAvatarEntity = properties.getCloneAvatarEntity();
properties.convertToCloneProperties(entityIDToClone);
if (properties.getEntityHostType() == entity::HostType::LOCAL) {
// Local entities are only cloned locally
return addEntityInternal(properties, entity::HostType::LOCAL);
} else if (cloneAvatarEntity) {
return addEntityInternal(properties, entity::HostType::AVATAR);
} else {
// setLastEdited timestamp to 0 to ensure this entity gets updated with the properties
// from the server-created entity, don't change this unless you know what you are doing
properties.setLastEdited(0);
bool success = addLocalEntityCopy(properties, newEntityID, true);
if (success) {
getEntityPacketSender()->queueCloneEntityMessage(entityIDToClone, newEntityID);
return newEntityID;
} else {
return QUuid();
}
}
}
EntityItemProperties EntityScriptingInterface::getEntityProperties(const QUuid& entityID) {
const EntityPropertyFlags noSpecificProperties;
return getEntityProperties(entityID, noSpecificProperties);
}
EntityItemProperties EntityScriptingInterface::getEntityProperties(const QUuid& entityID, EntityPropertyFlags desiredProperties) {
PROFILE_RANGE(script_entities, __FUNCTION__);
bool scalesWithParent { false };
EntityItemProperties results;
if (_entityTree) {
_entityTree->withReadLock([&] {
EntityItemPointer entity = _entityTree->findEntityByEntityItemID(EntityItemID(entityID));
if (entity) {
scalesWithParent = entity->getScalesWithParent();
if (desiredProperties.getHasProperty(PROP_POSITION) ||
desiredProperties.getHasProperty(PROP_ROTATION) ||
desiredProperties.getHasProperty(PROP_LOCAL_POSITION) ||
desiredProperties.getHasProperty(PROP_LOCAL_ROTATION) ||
desiredProperties.getHasProperty(PROP_LOCAL_VELOCITY) ||
desiredProperties.getHasProperty(PROP_LOCAL_ANGULAR_VELOCITY) ||
desiredProperties.getHasProperty(PROP_LOCAL_DIMENSIONS)) {
// if we are explicitly getting position or rotation, we need parent information to make sense of them.
desiredProperties.setHasProperty(PROP_PARENT_ID);
desiredProperties.setHasProperty(PROP_PARENT_JOINT_INDEX);
}
if (desiredProperties.isEmpty()) {
// these are left out of EntityItem::getEntityProperties so that localPosition and localRotation
// don't end up in json saves, etc. We still want them here, though.
EncodeBitstreamParams params; // unknown
desiredProperties = entity->getEntityProperties(params);
desiredProperties.setHasProperty(PROP_LOCAL_POSITION);
desiredProperties.setHasProperty(PROP_LOCAL_ROTATION);
desiredProperties.setHasProperty(PROP_LOCAL_VELOCITY);
desiredProperties.setHasProperty(PROP_LOCAL_ANGULAR_VELOCITY);
desiredProperties.setHasProperty(PROP_LOCAL_DIMENSIONS);
}
results = entity->getProperties(desiredProperties);
}
});
}
return convertPropertiesToScriptSemantics(results, scalesWithParent);
}
struct EntityPropertiesResult {
EntityPropertiesResult(const EntityItemProperties& properties, bool scalesWithParent) :
properties(properties),
scalesWithParent(scalesWithParent) {
}
EntityPropertiesResult() = default;
EntityItemProperties properties;
bool scalesWithParent{ false };
};
// Static method to make sure that we have the right script engine.
// Using sender() or QtScriptable::engine() does not work for classes used by multiple threads (script-engines)
QScriptValue EntityScriptingInterface::getMultipleEntityProperties(QScriptContext* context, QScriptEngine* engine) {
const int ARGUMENT_ENTITY_IDS = 0;
const int ARGUMENT_EXTENDED_DESIRED_PROPERTIES = 1;
auto entityScriptingInterface = DependencyManager::get<EntityScriptingInterface>();
const auto entityIDs = qscriptvalue_cast<QVector<QUuid>>(context->argument(ARGUMENT_ENTITY_IDS));
return entityScriptingInterface->getMultipleEntityPropertiesInternal(engine, entityIDs, context->argument(ARGUMENT_EXTENDED_DESIRED_PROPERTIES));
}
QScriptValue EntityScriptingInterface::getMultipleEntityPropertiesInternal(QScriptEngine* engine, QVector<QUuid> entityIDs, const QScriptValue& extendedDesiredProperties) {
PROFILE_RANGE(script_entities, __FUNCTION__);
EntityPsuedoPropertyFlags psuedoPropertyFlags;
const auto readExtendedPropertyStringValue = [&](QScriptValue extendedProperty) {
const auto extendedPropertyString = extendedProperty.toString();
if (extendedPropertyString == "id") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::ID);
} else if (extendedPropertyString == "type") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::Type);
} else if (extendedPropertyString == "age") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::Age);
} else if (extendedPropertyString == "ageAsText") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::AgeAsText);
} else if (extendedPropertyString == "lastEdited") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::LastEdited);
} else if (extendedPropertyString == "boundingBox") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::BoundingBox);
} else if (extendedPropertyString == "originalTextures") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::OriginalTextures);
} else if (extendedPropertyString == "renderInfo") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::RenderInfo);
} else if (extendedPropertyString == "clientOnly") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::ClientOnly);
} else if (extendedPropertyString == "avatarEntity") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::AvatarEntity);
} else if (extendedPropertyString == "localEntity") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::LocalEntity);
} else if (extendedPropertyString == "faceCamera") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::FaceCamera);
} else if (extendedPropertyString == "isFacingAvatar") {
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::IsFacingAvatar);
}
};
if (extendedDesiredProperties.isString()) {
readExtendedPropertyStringValue(extendedDesiredProperties);
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::FlagsActive);
} else if (extendedDesiredProperties.isArray()) {
const quint32 length = extendedDesiredProperties.property("length").toInt32();
for (quint32 i = 0; i < length; i++) {
readExtendedPropertyStringValue(extendedDesiredProperties.property(i));
}
psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::FlagsActive);
}
EntityPropertyFlags desiredProperties = qscriptvalue_cast<EntityPropertyFlags>(extendedDesiredProperties);
bool needsScriptSemantics = desiredProperties.getHasProperty(PROP_POSITION) ||
desiredProperties.getHasProperty(PROP_ROTATION) ||
desiredProperties.getHasProperty(PROP_LOCAL_POSITION) ||
desiredProperties.getHasProperty(PROP_LOCAL_ROTATION) ||
desiredProperties.getHasProperty(PROP_LOCAL_VELOCITY) ||
desiredProperties.getHasProperty(PROP_LOCAL_ANGULAR_VELOCITY) ||
desiredProperties.getHasProperty(PROP_LOCAL_DIMENSIONS);
if (needsScriptSemantics) {
// if we are explicitly getting position or rotation, we need parent information to make sense of them.
desiredProperties.setHasProperty(PROP_PARENT_ID);
desiredProperties.setHasProperty(PROP_PARENT_JOINT_INDEX);
}
QVector<EntityPropertiesResult> resultProperties;
if (_entityTree) {
PROFILE_RANGE(script_entities, "EntityScriptingInterface::getMultipleEntityProperties>Obtaining Properties");
int i = 0;
const int lockAmount = 500;
int size = entityIDs.size();
while (i < size) {
_entityTree->withReadLock([&] {
for (int j = 0; j < lockAmount && i < size; ++i, ++j) {
const auto& entityID = entityIDs.at(i);
const EntityItemPointer entity = _entityTree->findEntityByEntityItemID(EntityItemID(entityID));
if (entity) {
if (psuedoPropertyFlags.none() && desiredProperties.isEmpty()) {
// these are left out of EntityItem::getEntityProperties so that localPosition and localRotation
// don't end up in json saves, etc. We still want them here, though.
EncodeBitstreamParams params; // unknown
desiredProperties = entity->getEntityProperties(params);
desiredProperties.setHasProperty(PROP_LOCAL_POSITION);
desiredProperties.setHasProperty(PROP_LOCAL_ROTATION);
desiredProperties.setHasProperty(PROP_LOCAL_VELOCITY);
desiredProperties.setHasProperty(PROP_LOCAL_ANGULAR_VELOCITY);
desiredProperties.setHasProperty(PROP_LOCAL_DIMENSIONS);
psuedoPropertyFlags.set();
needsScriptSemantics = true;
}
auto properties = entity->getProperties(desiredProperties, true);
EntityPropertiesResult result(properties, entity->getScalesWithParent());
resultProperties.append(result);
}
}
});
}
}
QScriptValue finalResult = engine->newArray(resultProperties.size());
quint32 i = 0;
if (needsScriptSemantics) {
PROFILE_RANGE(script_entities, "EntityScriptingInterface::getMultipleEntityProperties>Script Semantics");
foreach(const auto& result, resultProperties) {
finalResult.setProperty(i++, convertPropertiesToScriptSemantics(result.properties, result.scalesWithParent)
.copyToScriptValue(engine, false, false, false, psuedoPropertyFlags));
}
} else {
PROFILE_RANGE(script_entities, "EntityScriptingInterface::getMultipleEntityProperties>Skip Script Semantics");
foreach(const auto& result, resultProperties) {
finalResult.setProperty(i++, result.properties.copyToScriptValue(engine, false, false, false, psuedoPropertyFlags));
}
}
return finalResult;
}
QUuid EntityScriptingInterface::editEntity(const QUuid& id, const EntityItemProperties& scriptSideProperties) {
PROFILE_RANGE(script_entities, __FUNCTION__);
_activityTracking.editedEntityCount++;
const auto sessionID = DependencyManager::get<NodeList>()->getSessionUUID();
EntityItemProperties properties = scriptSideProperties;
EntityItemID entityID(id);
if (!_entityTree) {
properties.setLastEditedBy(sessionID);
queueEntityMessage(PacketType::EntityEdit, entityID, properties);
return id;
}
EntityItemPointer entity(nullptr);
SimulationOwner simulationOwner;
_entityTree->withReadLock([&] {
// make a copy of entity for local logic outside of tree lock
entity = _entityTree->findEntityByEntityItemID(entityID);
if (!entity) {
return;
}
if (entity->isAvatarEntity() && !entity->isMyAvatarEntity()) {
// don't edit other avatar's avatarEntities
properties = EntityItemProperties();
return;
}
// make a copy of simulationOwner for local logic outside of tree lock
simulationOwner = entity->getSimulationOwner();
});
QString previousUserdata;
if (entity) {
if (properties.hasTransformOrVelocityChanges() && entity->hasGrabs()) {
// if an entity is grabbed, the grab will override any position changes
properties.clearTransformOrVelocityChanges();
}
if (properties.hasSimulationRestrictedChanges()) {
if (_bidOnSimulationOwnership) {
// flag for simulation ownership, or upgrade existing ownership priority
// (actual bids for simulation ownership are sent by the PhysicalEntitySimulation)
entity->upgradeScriptSimulationPriority(properties.computeSimulationBidPriority());
if (entity->isLocalEntity() || entity->isMyAvatarEntity() || simulationOwner.getID() == sessionID) {
// we own the simulation --> copy ALL restricted properties
properties.copySimulationRestrictedProperties(entity);
} else {
// we don't own the simulation but think we would like to
uint8_t desiredPriority = entity->getScriptSimulationPriority();
if (desiredPriority < simulationOwner.getPriority()) {
// the priority at which we'd like to own it is not high enough
// --> assume failure and clear all restricted property changes
properties.clearSimulationRestrictedProperties();
} else {
// the priority at which we'd like to own it is high enough to win.
// --> assume success and copy ALL restricted properties
properties.copySimulationRestrictedProperties(entity);
}
}
} else if (!simulationOwner.getID().isNull()) {
// someone owns this but not us
// clear restricted properties
properties.clearSimulationRestrictedProperties();
}
// clear the cached simulationPriority level
entity->upgradeScriptSimulationPriority(0);
}
// set these to make EntityItemProperties::getScalesWithParent() work correctly
entity::HostType entityHostType = entity->getEntityHostType();
properties.setEntityHostType(entityHostType);
if (entityHostType == entity::HostType::LOCAL) {
properties.setCollisionless(true);
}
properties.setOwningAvatarID(entity->getOwningAvatarID());
// make sure the properties has a type, so that the encode can know which properties to include
properties.setType(entity->getType());
previousUserdata = entity->getUserData();
} else if (_bidOnSimulationOwnership) {
// bail when simulation participants don't know about entity
return QUuid();
}
// TODO: it is possible there is no remaining useful changes in properties and we should bail early.
// How to check for this cheaply?
properties = convertPropertiesFromScriptSemantics(properties, properties.getScalesWithParent());
synchronizeEditedGrabProperties(properties, previousUserdata);
properties.setLastEditedBy(sessionID);
// done reading and modifying properties --> start write
bool updatedEntity = false;
_entityTree->withWriteLock([&] {
updatedEntity = _entityTree->updateEntity(entityID, properties);
});
// FIXME: We need to figure out a better way to handle this. Allowing these edits to go through potentially
// breaks entities that are parented.
//
// To handle cases where a script needs to edit an entity with a _known_ entity id but doesn't exist
// in the local entity tree, we need to allow those edits to go through to the server.
// if (!updatedEntity) {
// return QUuid();
// }
bool hasQueryAACubeRelatedChanges = properties.queryAACubeRelatedPropertyChanged();
// done writing, send update
_entityTree->withReadLock([&] {
// find the entity again: maybe it was removed since we last found it
entity = _entityTree->findEntityByEntityItemID(entityID);
if (entity) {
uint64_t now = usecTimestampNow();
entity->setLastBroadcast(now);
if (hasQueryAACubeRelatedChanges) {
properties.setQueryAACube(entity->getQueryAACube());
// if we've moved an entity with children, check/update the queryAACube of all descendents and tell the server
// if they've changed.
entity->forEachDescendant([&](SpatiallyNestablePointer descendant) {
if (descendant->getNestableType() == NestableType::Entity) {
if (descendant->updateQueryAACube()) {
EntityItemPointer entityDescendant = std::static_pointer_cast<EntityItem>(descendant);
EntityItemProperties newQueryCubeProperties;
newQueryCubeProperties.setQueryAACube(descendant->getQueryAACube());
newQueryCubeProperties.setLastEdited(properties.getLastEdited());
queueEntityMessage(PacketType::EntityEdit, descendant->getID(), newQueryCubeProperties);
entityDescendant->setLastBroadcast(now);
}
}
});
}
}
});
if (!entity) {
if (hasQueryAACubeRelatedChanges) {
// Sometimes ESS don't have the entity they are trying to edit in their local tree. In this case,
// convertPropertiesFromScriptSemantics doesn't get called and local* edits will get dropped.
// This is because, on the script side, "position" is in world frame, but in the network
// protocol and in the internal data-structures, "position" is "relative to parent".
// Compensate here. The local* versions will get ignored during the edit-packet encoding.
if (properties.localPositionChanged()) {
properties.setPosition(properties.getLocalPosition());
}
if (properties.localRotationChanged()) {
properties.setRotation(properties.getLocalRotation());
}
if (properties.localVelocityChanged()) {
properties.setVelocity(properties.getLocalVelocity());
}
if (properties.localAngularVelocityChanged()) {
properties.setAngularVelocity(properties.getLocalAngularVelocity());
}
if (properties.localDimensionsChanged()) {
properties.setDimensions(properties.getLocalDimensions());
}
}
// we've made an edit to an entity we don't know about, or to a non-entity. If it's a known non-entity,
// print a warning and don't send an edit packet to the entity-server.
QSharedPointer<SpatialParentFinder> parentFinder = DependencyManager::get<SpatialParentFinder>();
if (parentFinder) {
bool success;
auto nestableWP = parentFinder->find(id, success, static_cast<SpatialParentTree*>(_entityTree.get()));
if (success) {
auto nestable = nestableWP.lock();
if (nestable) {
NestableType nestableType = nestable->getNestableType();
if (nestableType == NestableType::Avatar) {
qCWarning(entities) << "attempted edit on non-entity: " << id << nestable->getName();
return QUuid(); // null script value to indicate failure
}
}
}
}
}
// we queue edit packets even if we don't know about the entity. This is to allow AC agents
// to edit entities they know only by ID.
queueEntityMessage(PacketType::EntityEdit, entityID, properties);
return id;
}
void EntityScriptingInterface::deleteEntity(const QUuid& id) {
PROFILE_RANGE(script_entities, __FUNCTION__);
_activityTracking.deletedEntityCount++;
if (!_entityTree) {
return;
}
EntityItemID entityID(id);
// If we have a local entity tree set, then also update it.
std::vector<EntityItemPointer> entitiesToDeleteImmediately;
_entityTree->withWriteLock([&] {
EntityItemPointer entity = _entityTree->findEntityByEntityItemID(entityID);
if (entity) {
if (entity->isAvatarEntity() && !entity->isMyAvatarEntity()) {
// don't delete other avatar's avatarEntities
return;
}
if (entity->getLocked()) {
return;
}
// Deleting an entity has consequences for linked children: some can be deleted but others can't.
// Local- and my-avatar-entities can be deleted immediately, but other-avatar-entities can't be deleted
// by this context, and a domain-entity must round trip through the entity-server for authorization.
if (entity->isDomainEntity() && !_entityTree->isServerlessMode()) {
getEntityPacketSender()->queueEraseEntityMessage(id);
} else {
entitiesToDeleteImmediately.push_back(entity);
const auto sessionID = DependencyManager::get<NodeList>()->getSessionUUID();
entity->collectChildrenForDelete(entitiesToDeleteImmediately, sessionID);
_entityTree->deleteEntitiesByPointer(entitiesToDeleteImmediately);
}
}