-
Notifications
You must be signed in to change notification settings - Fork 4
/
PhysicsRemoteFPSAgentController.cs
8843 lines (7630 loc) · 367 KB
/
PhysicsRemoteFPSAgentController.cs
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
// Copyright Allen Institute for Artificial Intelligence 2017
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Priority_Queue;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.ImageEffects;
using UnityStandardAssets.Utility;
namespace UnityStandardAssets.Characters.FirstPerson {
[RequireComponent(typeof(CharacterController))]
public class PhysicsRemoteFPSAgentController : BaseFPSAgentController {
[SerializeField] protected GameObject[] ToSetActive = null;
[SerializeField] protected float PhysicsAgentSkinWidth = -1f; //change agent's skin width so that it collides directly with ground - otherwise sweeptests will fail for flat objects on floor
[SerializeField] protected GameObject AgentHand = null;
[SerializeField] protected GameObject DefaultHandPosition = null;
[SerializeField] protected GameObject ItemInHand = null; //current object in inventory
[SerializeField] protected GameObject[] RotateRLPivots = null;
[SerializeField] protected GameObject[] RotateRLTriggerBoxes = null;
[SerializeField] protected GameObject[] LookUDPivots = null;
[SerializeField] protected GameObject[] LookUDTriggerBoxes = null;
[SerializeField] protected SimObjPhysics[] VisibleSimObjPhysics; //all SimObjPhysics that are within camera viewport and range dictated by MaxViewDistancePhysics
[SerializeField] protected bool IsHandDefault = true;
[SerializeField] public bool FlightMode = false;
protected Vector3 thrust;
[SerializeField] Camera[] FlightCameras;
// Extra stuff
private PhysicsSceneManager _physicsSceneManager = null;
private PhysicsSceneManager physicsSceneManager
{
get {
if (_physicsSceneManager == null) {
_physicsSceneManager = GameObject.Find("PhysicsSceneManager").GetComponent<PhysicsSceneManager>();
}
return _physicsSceneManager;
}
}
[SerializeField] public string[] objectIdsInBox = new string[0];
[SerializeField] protected bool inTopLevelView = false;
[SerializeField] protected Vector3 lastLocalCameraPosition;
[SerializeField] protected Quaternion lastLocalCameraRotation;
[SerializeField] protected float cameraOrthSize;
protected Dictionary<string, Dictionary<int, Material[]>> maskedObjects = new Dictionary<string, Dictionary<int, Material[]>>();
protected float[, , ] flatSurfacesOnGrid = new float[0, 0, 0];
protected float[, ] distances = new float[0, 0];
protected float[, , ] normals = new float[0, 0, 0];
protected bool[, ] isOpenableGrid = new bool[0, 0];
protected string[] segmentedObjectIds = new string[0];
protected int actionIntReturn;
protected float actionFloatReturn;
protected bool actionBoolReturn;
protected float[] actionFloatsReturn;
protected Vector3[] actionVector3sReturn;
protected string[] actionStringsReturn;
[SerializeField] protected Vector3 standingLocalCameraPosition;
[SerializeField] protected Vector3 crouchingLocalCameraPosition;
protected HashSet<int> initiallyDisabledRenderers = new HashSet<int>();
public Vector3[] reachablePositions = new Vector3[0];
public bool alwaysReturnVisibleRange = false;
//face swap stuff here
public Material[] ScreenFaces; //0 - neutral, 1 - Happy, 2 - Mad, 3 - Angriest
public MeshRenderer MyFaceMesh;
public Bounds sceneBounds = new Bounds(
new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity),
new Vector3(-float.PositiveInfinity, -float.PositiveInfinity, -float.PositiveInfinity)
);
//change visibility check to use this distance when looking down
//protected float DownwardViewDistance = 2.0f;
// Use this for initialization
protected override void Start() {
base.Start();
//below, enable all the GameObjects on the Agent that Physics Mode requires
if (PhysicsAgentSkinWidth < 0.0f) {
Debug.LogError("Agent skin width must be > 0.0f, please set it in the editor. Forcing it to equal 0.01f for now.");
PhysicsAgentSkinWidth = 0.01f;
}
m_CharacterController.skinWidth = PhysicsAgentSkinWidth;
//for normal, non-drone flight operation mode
if (!FlightMode) {
foreach (GameObject go in ToSetActive) {
go.SetActive(true);
}
//On start, activate gravity
Vector3 movement = Vector3.zero;
movement.y = Physics.gravity.y * m_GravityMultiplier;
m_CharacterController.Move(movement);
}
standingLocalCameraPosition = m_Camera.transform.localPosition;
crouchingLocalCameraPosition = m_Camera.transform.localPosition;
crouchingLocalCameraPosition.y = 0.0f;
// Recordining initially disabled renderers and scene bounds
foreach (Renderer r in GameObject.FindObjectsOfType<Renderer>()) {
if (!r.enabled) {
initiallyDisabledRenderers.Add(r.GetInstanceID());
} else {
sceneBounds.Encapsulate(r.bounds);
}
}
}
//forceVisible is true to activate, false to deactivate
public void ToggleHideAndSeekObjects(ServerAction action) {
if (physicsSceneManager.ToggleHideAndSeek(action.forceVisible)) {
physicsSceneManager.ResetUniqueIdToSimObjPhysics();
actionFinished(true);
} else {
errorMessage = "No HideAndSeek object found";
actionFinished(false);
}
}
public Vector3 AgentHandLocation() {
return AgentHand.transform.position;
}
public float WhatIsAgentsMaxVisibleDistance() {
return maxVisibleDistance;
}
public GameObject WhatAmIHolding() {
return ItemInHand;
}
//get all sim objets of action.type, then sets their temperature decay timers to value
public void SetRoomTempDecayTimeForType(ServerAction action) {
//get all objects of type passed by action
SimObjPhysics[] simObjects = GameObject.FindObjectsOfType<SimObjPhysics>();
List<SimObjPhysics> simObjectsOfType = new List<SimObjPhysics>();
foreach (SimObjPhysics sop in simObjects)
{
if(sop.Type.ToString() == action.objectType)
{
simObjectsOfType.Add(sop);
}
}
//use SetHowManySecondsUntilRoomTemp to set them all
foreach (SimObjPhysics sop in simObjectsOfType)
{
sop.SetHowManySecondsUntilRoomTemp(action.TimeUntilRoomTemp);
}
actionFinished(true);
}
//get all sim objects and globally set the room temp decay time for all of them
public void SetGlobalRoomTempDecayTime(ServerAction action) {
//get all objects
SimObjPhysics[] simObjects = GameObject.FindObjectsOfType<SimObjPhysics>();
//use SetHowManySecondsUntilRoomTemp to set them all
foreach (SimObjPhysics sop in simObjects)
{
sop.SetHowManySecondsUntilRoomTemp(action.TimeUntilRoomTemp);
}
actionFinished(true);
}
//sets whether this scene should allow objects to decay temperature to room temp over time or not
public void SetDecayTemperatureBool(ServerAction action)
{
physicsSceneManager.GetComponent<PhysicsSceneManager>().AllowDecayTemperature = action.allowDecayTemperature;
actionFinished(true);
}
// Update is called once per frame
void Update() {
if (FlightMode) {
if (thrust.magnitude > 0.1) {
m_CharacterController.Move(thrust * Time.deltaTime);
}
thrust = Vector3.Lerp(thrust, Vector3.zero, 5 * Time.deltaTime);
}
}
private void LateUpdate() {
//make sure this happens in late update so all physics related checks are done ahead of time
//this is also mostly for in editor, the array of visible sim objects is found via server actions
//using VisibleSimObjs(action), so be aware of that
#if UNITY_EDITOR || UNITY_WEBGL
if (this.actionComplete && !FlightMode) {
ServerAction action = new ServerAction();
VisibleSimObjPhysics = VisibleSimObjs(action); //GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance);
}
//right now flight mode doesn't reset actionComplete so let's do this every update cuase why not
if (FlightMode) {
ServerAction action = new ServerAction();
VisibleSimObjPhysics = VisibleSimObjs(action);
}
#endif
}
private T[] flatten2DimArray<T>(T[, ] array) {
int nrow = array.GetLength(0);
int ncol = array.GetLength(1);
T[] flat = new T[nrow * ncol];
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
flat[i * ncol + j] = array[i, j];
}
}
return flat;
}
private T[] flatten3DimArray<T>(T[, , ] array) {
int n0 = array.GetLength(0);
int n1 = array.GetLength(1);
int n2 = array.GetLength(2);
T[] flat = new T[n0 * n1 * n2];
for (int i = 0; i < n0; i++) {
for (int j = 0; j < n1; j++) {
for (int k = 0; k < n2; k++) {
flat[i * n1 * n2 + j * n2 + k] = array[i, j, k];
}
}
}
return flat;
}
//generates object metatada based on sim object's properties
private ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj, bool isVisible) {
ObjectMetadata objMeta = new ObjectMetadata();
GameObject o = simObj.gameObject;
objMeta.name = o.name;
objMeta.position = o.transform.position;
objMeta.rotation = o.transform.eulerAngles;
objMeta.objectType = Enum.GetName(typeof(SimObjType), simObj.Type);
objMeta.receptacle = simObj.IsReceptacle;
objMeta.openable = simObj.IsOpenable;
if (objMeta.openable) {
objMeta.isOpen = simObj.IsOpen;
// if(simObj.Type == SimObjType.Microwave)
// {
// print("generating object metadata which means actionFinished should have been called!");
// print("microwave is open? " + objMeta.isOpen);
// }
}
objMeta.toggleable = simObj.IsToggleable;
if (objMeta.toggleable) {
objMeta.isToggled = simObj.IsToggled;
}
objMeta.breakable = simObj.IsBreakable;
if(objMeta.breakable) {
objMeta.isBroken = simObj.IsBroken;
}
objMeta.canFillWithLiquid = simObj.IsFillable;
if (objMeta.canFillWithLiquid) {
objMeta.isFilledWithLiquid = simObj.IsFilled;
}
objMeta.dirtyable = simObj.IsDirtyable;
if (objMeta.dirtyable) {
objMeta.isDirty = simObj.IsDirty;
}
objMeta.cookable = simObj.IsCookable;
if (objMeta.cookable) {
objMeta.isCooked = simObj.IsCooked;
}
//if the sim object is moveable or pickupable
if(simObj.IsPickupable || simObj.IsMoveable)
{
//this object should report back mass and salient materials
string [] salientMaterialsToString = new string [simObj.salientMaterials.Length];
for(int i = 0; i < simObj.salientMaterials.Length; i++)
{
salientMaterialsToString[i] = simObj.salientMaterials[i].ToString();
}
objMeta.salientMaterials = salientMaterialsToString;
//this object should also report back mass since it is moveable/pickupable
objMeta.mass = simObj.Mass;
}
//can this object change others to hot?
objMeta.canChangeTempToHot = simObj.canChangeTempToHot;
//can this object change others to cold?
objMeta.canChangeTempToCold = simObj.canChangeTempToCold;
//placeholder for heatable objects -kettle, pot, pan
// objMeta.abletocook = simObj.abletocook;
// if(objMeta.abletocook) {
// objMeta.isReadyToCook = simObj.IsHeated;
// }
objMeta.sliceable = simObj.IsSliceable;
if (objMeta.sliceable) {
objMeta.isSliced = simObj.IsSliced;
}
objMeta.canBeUsedUp = simObj.CanBeUsedUp;
if (objMeta.canBeUsedUp) {
objMeta.isUsedUp = simObj.IsUsedUp;
}
//object temperature to string
objMeta.ObjectTemperature = simObj.CurrentObjTemp.ToString();
objMeta.pickupable = simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup;//can this object be picked up?
objMeta.isPickedUp = simObj.isPickedUp;//returns true for if this object is currently being held by the agent
objMeta.objectId = simObj.UniqueID;
// TODO: using the isVisible flag on the object causes weird problems
// in the multiagent setting, explicitly giving this information for now.
objMeta.visible = isVisible; //simObj.isVisible;
objMeta.isMoving = simObj.inMotion;//keep track of if this object is actively moving
if(simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup)// || simObj.PrimaryProperty == SimObjPrimaryProperty.Moveable)
objMeta.objectBounds = WorldCoordinatesOfBoundingBox(simObj);
return objMeta;
}
public WorldSpaceBounds WorldCoordinatesOfBoundingBox(SimObjPhysics sop)
{
WorldSpaceBounds b = new WorldSpaceBounds();
if(sop.BoundingBox== null)
{
Debug.LogError(sop.transform.name + " is missing BoundingBox reference!");
return b;
}
BoxCollider col = sop.BoundingBox.GetComponent<BoxCollider>();
List<Vector3> corners = new List<Vector3>();
Vector3 p0 = col.transform.TransformPoint(col.center + new Vector3(col.size.x, -col.size.y, col.size.z) * 0.5f);
Vector3 p1 = col.transform.TransformPoint(col.center + new Vector3(-col.size.x, -col.size.y, col.size.z) * 0.5f);
Vector3 p2 = col.transform.TransformPoint(col.center + new Vector3(-col.size.x, -col.size.y, -col.size.z) * 0.5f);
Vector3 p3 = col.transform.TransformPoint(col.center + new Vector3(col.size.x, -col.size.y, -col.size.z) * 0.5f);
Vector3 p4 = col.transform.TransformPoint(col.center + new Vector3(col.size.x, col.size.y, col.size.z) * 0.5f);
Vector3 p5 = col.transform.TransformPoint(col.center + new Vector3(-col.size.x, col.size.y, col.size.z) * 0.5f);
Vector3 p6 = col.transform.TransformPoint(col.center + new Vector3(-col.size.x, +col.size.y, -col.size.z) * 0.5f);
Vector3 p7 = col.transform.TransformPoint(col.center + new Vector3(col.size.x, col.size.y, -col.size.z) * 0.5f);
corners.Add(p0);
corners.Add(p1);
corners.Add(p2);
corners.Add(p3);
corners.Add(p4);
corners.Add(p5);
corners.Add(p6);
corners.Add(p7);
b.objectBoundsCorners = corners.ToArray();
return b;
}
public override ObjectMetadata[] generateObjectMetadata() {
SimObjPhysics[] visibleSimObjs = VisibleSimObjs(false); // Update visibility for all sim objects for this agent
HashSet<SimObjPhysics> visibleSimObjsHash = new HashSet<SimObjPhysics>();
foreach (SimObjPhysics sop in visibleSimObjs) {
visibleSimObjsHash.Add(sop);
}
// Encode these in a json string and send it to the server
SimObjPhysics[] simObjects = GameObject.FindObjectsOfType<SimObjPhysics>();
int numObj = simObjects.Length;
List<ObjectMetadata> metadata = new List<ObjectMetadata>();
Dictionary<string, List<string>> parentReceptacles = new Dictionary<string, List<string>>();
for (int k = 0; k < numObj; k++) {
SimObjPhysics simObj = simObjects[k];
if (this.excludeObject(simObj.UniqueID)) {
continue;
}
ObjectMetadata meta = ObjectMetadataFromSimObjPhysics(simObj, visibleSimObjsHash.Contains(simObj));
if (meta.receptacle) {
List<string> receptacleObjectIds = simObj.Contains();
foreach (string oid in receptacleObjectIds) {
if (!parentReceptacles.ContainsKey(oid)) {
parentReceptacles[oid] = new List<string>();
}
parentReceptacles[oid].Add(simObj.UniqueID);
}
meta.receptacleObjectIds = receptacleObjectIds.ToArray();
}
meta.distance = Vector3.Distance(transform.position, simObj.gameObject.transform.position);
metadata.Add(meta);
}
foreach (ObjectMetadata meta in metadata) {
if (parentReceptacles.ContainsKey(meta.objectId)) {
meta.parentReceptacles = parentReceptacles[meta.objectId].ToArray();
}
}
return metadata.ToArray();
}
public override MetadataWrapper generateMetadataWrapper() {
// AGENT METADATA
ObjectMetadata agentMeta = new ObjectMetadata();
agentMeta.name = "agent";
agentMeta.position = transform.position;
agentMeta.rotation = transform.eulerAngles;
agentMeta.cameraHorizon = m_Camera.transform.rotation.eulerAngles.x;
if (agentMeta.cameraHorizon > 180) {
agentMeta.cameraHorizon -= 360;
}
// OTHER METADATA
MetadataWrapper metaMessage = new MetadataWrapper();
metaMessage.agent = agentMeta;
metaMessage.sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
metaMessage.objects = this.generateObjectMetadata();
//check scene manager to see if the scene's objects are at rest
metaMessage.isSceneAtRest = physicsSceneManager.isSceneAtRest;
metaMessage.collided = collidedObjects.Length > 0;
metaMessage.collidedObjects = collidedObjects;
metaMessage.screenWidth = Screen.width;
metaMessage.screenHeight = Screen.height;
metaMessage.cameraPosition = m_Camera.transform.position;
metaMessage.cameraOrthSize = cameraOrthSize;
cameraOrthSize = -1f;
metaMessage.fov = m_Camera.fieldOfView;
metaMessage.isStanding = (m_Camera.transform.localPosition - standingLocalCameraPosition).magnitude < 0.1f;
metaMessage.lastAction = lastAction;
metaMessage.lastActionSuccess = lastActionSuccess;
metaMessage.errorMessage = errorMessage;
metaMessage.actionReturn = this.actionReturn;
if (errorCode != ServerActionErrorCode.Undefined) {
metaMessage.errorCode = Enum.GetName(typeof(ServerActionErrorCode), errorCode);
}
List<InventoryObject> ios = new List<InventoryObject>();
if (ItemInHand != null) {
SimObjPhysics so = ItemInHand.GetComponent<SimObjPhysics>();
InventoryObject io = new InventoryObject();
io.objectId = so.UniqueID;
io.objectType = Enum.GetName(typeof(SimObjType), so.Type);
ios.Add(io);
}
metaMessage.inventoryObjects = ios.ToArray();
// HAND
metaMessage.hand = new HandMetadata();
metaMessage.hand.position = AgentHand.transform.position;
metaMessage.hand.localPosition = AgentHand.transform.localPosition;
metaMessage.hand.rotation = AgentHand.transform.eulerAngles;
metaMessage.hand.localRotation = AgentHand.transform.localEulerAngles;
// EXTRAS
metaMessage.reachablePositions = reachablePositions;
metaMessage.flatSurfacesOnGrid = flatten3DimArray(flatSurfacesOnGrid);
metaMessage.distances = flatten2DimArray(distances);
metaMessage.normals = flatten3DimArray(normals);
metaMessage.isOpenableGrid = flatten2DimArray(isOpenableGrid);
metaMessage.segmentedObjectIds = segmentedObjectIds;
metaMessage.objectIdsInBox = objectIdsInBox;
metaMessage.actionIntReturn = actionIntReturn;
metaMessage.actionFloatReturn = actionFloatReturn;
metaMessage.actionFloatsReturn = actionFloatsReturn;
metaMessage.actionStringsReturn = actionStringsReturn;
metaMessage.actionVector3sReturn = actionVector3sReturn;
if (alwaysReturnVisibleRange) {
metaMessage.visibleRange = visibleRange();
}
//test time
metaMessage.currentTime = TimeSinceStart();
// Resetting things
reachablePositions = new Vector3[0];
flatSurfacesOnGrid = new float[0, 0, 0];
distances = new float[0, 0];
normals = new float[0, 0, 0];
isOpenableGrid = new bool[0, 0];
segmentedObjectIds = new string[0];
objectIdsInBox = new string[0];
actionIntReturn = 0;
actionFloatReturn = 0.0f;
actionFloatsReturn = new float[0];
actionStringsReturn = new string[0];
actionVector3sReturn = new Vector3[0];
return metaMessage;
}
public float TimeSinceStart() {
return Time.time;
}
//return ID of closest CanPickup object by distance
public string UniqueIDOfClosestVisibleObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.PrimaryProperty == SimObjPrimaryProperty.CanPickup) {
objectID = o.UniqueID;
// print(objectID);
break;
}
}
return objectID;
}
//return ID of closest CanOpen or CanOpen_Fridge object by distance
public string UniqueIDOfClosestVisibleOpenableObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.GetComponent<CanOpen_Object>()) {
objectID = o.UniqueID;
break;
}
}
return objectID;
}
//return ID of closes toggleable object by distance
public string UniqueIDOfClosestToggleObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.GetComponent<CanToggleOnOff>()) {
objectID = o.UniqueID;
break;
}
}
return objectID;
}
public string UniqueIDOfClosestReceptacleObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) {
objectID = o.UniqueID;
break;
}
}
return objectID;
}
//return a reference to a SimObj that is Visible (in the VisibleSimObjPhysics array) and
//matches the passe din objectID
public GameObject FindObjectInVisibleSimObjPhysics(string objectID) {
GameObject target = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.uniqueID == objectID) {
target = o.gameObject;
}
}
return target;
}
protected Collider[] collidersWithinCapsuleCastOfAgent(float maxDistance) {
CapsuleCollider agentCapsuleCollider = GetComponent<CapsuleCollider>();
Vector3 point0, point1;
float radius;
agentCapsuleCollider.ToWorldSpaceCapsule(out point0, out point1, out radius);
if (point0.y <= point1.y) {
point1.y += maxDistance;
} else {
point0.y += maxDistance;
}
return Physics.OverlapCapsule(point0, point1, maxDistance, 1 << 8, QueryTriggerInteraction.Collide);
}
//*** Maybe make this better */
// This function should be called before and after doing a visibility check (before with
// enableColliders == false and after with it equaling true). It, in particular, will
// turn off/on all the colliders on agents which should not block visibility for the current agent
// (invisible agents for example).
protected void updateAllAgentCollidersForVisibilityCheck(bool enableColliders) {
foreach (BaseFPSAgentController agent in this.agentManager.agents) {
PhysicsRemoteFPSAgentController phyAgent = (PhysicsRemoteFPSAgentController) agent;
bool overlapping = (transform.position - phyAgent.transform.position).magnitude < 0.001f;
if (overlapping || phyAgent == this || !phyAgent.IsVisible) {
foreach (Collider c in phyAgent.GetComponentsInChildren<Collider>()) {
if (ItemInHand == null || !hasAncestor(c.transform.gameObject, ItemInHand)) {
c.enabled = enableColliders;
}
}
}
}
}
protected SimObjPhysics[] GetAllVisibleSimObjPhysics(Camera agentCamera, float maxDistance) {
#if UNITY_EDITOR
foreach (KeyValuePair<string, SimObjPhysics> pair in physicsSceneManager.UniqueIdToSimObjPhysics) {
// Set all objects to not be visible
pair.Value.isVisible = false;
}
#endif
List<SimObjPhysics> currentlyVisibleItems = new List<SimObjPhysics>();
Vector3 agentCameraPos = agentCamera.transform.position;
//get all sim objects in range around us that have colliders in layer 8 (visible), ignoring objects in the SimObjInvisible layer
//this will make it so the receptacle trigger boxes don't occlude the objects within them.
CapsuleCollider agentCapsuleCollider = GetComponent<CapsuleCollider>();
Vector3 point0, point1;
float radius;
agentCapsuleCollider.ToWorldSpaceCapsule(out point0, out point1, out radius);
if (point0.y <= point1.y) {
point1.y += maxDistance;
} else {
point0.y += maxDistance;
}
// Turn off the colliders corresponding to this agent
// and any invisible agents.
updateAllAgentCollidersForVisibilityCheck(false);
Collider[] colliders_in_view = Physics.OverlapCapsule(point0, point1, maxDistance, 1 << 8, QueryTriggerInteraction.Collide);
if (colliders_in_view != null) {
HashSet<SimObjPhysics> testedSops = new HashSet<SimObjPhysics>();
foreach (Collider item in colliders_in_view) {
SimObjPhysics sop = ancestorSimObjPhysics(item.gameObject);
//now we have a reference to our sim object
if (sop != null && !testedSops.Contains(sop)) {
testedSops.Add(sop);
//check against all visibility points, accumulate count. If at least one point is visible, set object to visible
if (sop.VisibilityPoints == null || sop.VisibilityPoints.Length > 0) {
Transform[] visPoints = sop.VisibilityPoints;
int visPointCount = 0;
foreach (Transform point in visPoints) {
//if this particular point is in view...
if (CheckIfVisibilityPointInViewport(sop, point, agentCamera, false)) {
visPointCount++;
#if !UNITY_EDITOR
// If we're in the unity editor then don't break on finding a visible
// point as we want to draw lines to each visible point.
break;
#endif
}
}
//if we see at least one vis point, the object is "visible"
if (visPointCount > 0) {
#if UNITY_EDITOR
sop.isVisible = true;
#endif
if (!currentlyVisibleItems.Contains(sop)) {
currentlyVisibleItems.Add(sop);
}
}
} else {
Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics " + sop + ".");
}
}
}
}
//check against anything in the invisible layers that we actually want to have occlude things in this round.
//normally receptacle trigger boxes must be ignored from the visibility check otherwise objects inside them will be occluded, but
//this additional check will allow us to see inside of receptacle objects like cabinets/fridges by checking for that interior
//receptacle trigger box. Oh boy!
Collider[] invisible_colliders_in_view = Physics.OverlapCapsule(point0, point1, maxDistance, 1 << 9, QueryTriggerInteraction.Collide);
// Collider[] invisible_colliders_in_view = Physics.OverlapSphere(agentCameraPos, maxDistance * DownwardViewDistance,
// 1 << 9, QueryTriggerInteraction.Collide);
if (invisible_colliders_in_view != null) {
foreach (Collider item in invisible_colliders_in_view) {
if (item.tag == "Receptacle") {
SimObjPhysics sop;
sop = item.GetComponentInParent<SimObjPhysics>();
//now we have a reference to our sim object
if (sop) {
//check against all visibility points, accumulate count. If at least one point is visible, set object to visible
if (sop.VisibilityPoints.Length > 0) {
Transform[] visPoints = sop.VisibilityPoints;
int visPointCount = 0;
foreach (Transform point in visPoints) {
//if this particular point is in view...
if (CheckIfVisibilityPointInViewport(sop, point, agentCamera, true)) {
visPointCount++;
}
}
//if we see at least one vis point, the object is "visible"
if (visPointCount > 0) {
#if UNITY_EDITOR
sop.isVisible = true;
#endif
if (!currentlyVisibleItems.Contains(sop)) {
currentlyVisibleItems.Add(sop);
}
}
} else
Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics prefab!");
}
}
}
}
// Turn back on the colliders corresponding to this agent
// and any invisible agents.
updateAllAgentCollidersForVisibilityCheck(true);
//populate array of visible items in order by distance
currentlyVisibleItems.Sort((x, y) => Vector3.Distance(x.transform.position, agentCameraPos).CompareTo(Vector3.Distance(y.transform.position, agentCameraPos)));
return currentlyVisibleItems.ToArray();
}
//use this to check if any given Vector3 coordinate is within the agent's viewport and also not obstructed
public bool CheckIfPointIsInViewport(Vector3 point) {
Vector3 viewPoint = m_Camera.WorldToViewportPoint(point);
float ViewPointRangeHigh = 1.0f;
float ViewPointRangeLow = 0.0f;
if (viewPoint.z > 0 //&& viewPoint.z < maxDistance * DownwardViewDistance //is in front of camera and within range of visibility sphere
&&
viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow //within x bounds of viewport
&&
viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) //within y bounds of viewport
{
RaycastHit hit;
updateAllAgentCollidersForVisibilityCheck(false);
if (Physics.Raycast(m_Camera.transform.position, point - m_Camera.transform.position, out hit,
Vector3.Distance(m_Camera.transform.position, point) - 0.01f, (1 << 8) | (1 << 10))) //reduce distance by slight offset
{
updateAllAgentCollidersForVisibilityCheck(true);
return false;
} else {
updateAllAgentCollidersForVisibilityCheck(true);
return true;
}
}
return false;
}
//check if the visibility point on a sim object, sop, is within the viewport
//has a inclueInvisible bool to check against triggerboxes as well, to check for visibility with things like Cabinets/Drawers
protected bool CheckIfVisibilityPointInViewport(SimObjPhysics sop, Transform point, Camera agentCamera, bool includeInvisible) {
bool result = false;
Vector3 viewPoint = agentCamera.WorldToViewportPoint(point.position);
float ViewPointRangeHigh = 1.0f;
float ViewPointRangeLow = 0.0f;
if (viewPoint.z > 0 //&& viewPoint.z < maxDistance * DownwardViewDistance //is in front of camera and within range of visibility sphere
&&
viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow //within x bounds of viewport
&&
viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) //within y bounds of viewport
{
//now cast a ray out toward the point, if anything occludes this point, that point is not visible
RaycastHit hit;
float raycastDistance = Vector3.Distance(point.position, m_Camera.transform.position) + 1.0f;
//check raycast against both visible and invisible layers, to check against ReceptacleTriggerBoxes which are normally
//ignored by the other raycast
if (includeInvisible) {
if (Physics.Raycast(agentCamera.transform.position, point.position - agentCamera.transform.position, out hit,
100f, (1 << 8) | (1 << 9) | (1 << 10))) {
if (hit.transform != sop.transform) {
result = false;
}
//if this line is drawn, then this visibility point is in camera frame and not occluded
//might want to use this for a targeting check as well at some point....
else {
result = true;
sop.isInteractable = true;
#if UNITY_EDITOR
Debug.DrawLine(agentCamera.transform.position, point.position, Color.cyan);
#endif
}
}
}
//only check against the visible layer, ignore the invisible layer
//so if an object ONLY has colliders on it that are not on layer 8, this raycast will go through them
else {
if (Physics.Raycast(agentCamera.transform.position, point.position - agentCamera.transform.position, out hit,
raycastDistance, (1 << 8) | (1 << 10))) {
if (hit.transform != sop.transform) {
//we didn't directly hit the sop we are checking for with this cast,
//check if it's because we hit something see-through
SimObjPhysics hitSop = hit.transform.GetComponent<SimObjPhysics>();
if (hitSop != null && hitSop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanSeeThrough)) {
//we hit something see through, so now find all objects in the path between
//the sop and the camera
RaycastHit[] hits;
hits = Physics.RaycastAll(agentCamera.transform.position, point.position - agentCamera.transform.position,
raycastDistance, (1 << 8), QueryTriggerInteraction.Ignore);
float[] hitDistances = new float[hits.Length];
for (int i = 0; i < hitDistances.Length; i++) {
hitDistances[i] = hits[i].distance; //Vector3.Distance(hits[i].transform.position, m_Camera.transform.position);
}
Array.Sort(hitDistances, hits);
foreach (RaycastHit h in hits) {
if (h.transform == sop.transform) {
//found the object we are looking for, great!
result = true;
break;
} else {
// Didn't find it, continue on only if the hit object was translucent
SimObjPhysics sopHitOnPath = null;
sopHitOnPath = h.transform.GetComponentInParent<SimObjPhysics>();
if (sopHitOnPath == null ||
!sopHitOnPath.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanSeeThrough)) {
//print("this is blocking: " + sopHitOnPath.name);
break;
}
}
}
}
} else {
//if this line is drawn, then this visibility point is in camera frame and not occluded
//might want to use this for a targeting check as well at some point....
result = true;
sop.isInteractable = true;
}
}
}
}
#if UNITY_EDITOR
if (result == true) {
Debug.DrawLine(agentCamera.transform.position, point.position, Color.cyan);
}
#endif
return result;
}
public override void LookDown(ServerAction response) {
float targetHorizon = 0.0f;
if (currentHorizonAngleIndex() > 0) {
targetHorizon = horizonAngles[currentHorizonAngleIndex() - 1];
}
int down = -1;
if (CheckIfAgentCanLook(targetHorizon, down)) {
DefaultAgentHand(response);
base.LookDown(response);
} else {
actionFinished(false);
}
SetUpRotationBoxChecks();
}
public override void LookUp(ServerAction controlCommand) {
float targetHorizon = 0.0f;
if (currentHorizonAngleIndex() < horizonAngles.Length - 1) {
targetHorizon = horizonAngles[currentHorizonAngleIndex() + 1];
}
int up = 1;
if (CheckIfAgentCanLook(targetHorizon, up)) {
DefaultAgentHand(controlCommand);
base.LookUp(controlCommand);
} else {
actionFinished(false);
}
SetUpRotationBoxChecks();
}
public bool CheckIfAgentCanLook(float targetAngle, int updown) {
//print(targetAngle);
if (ItemInHand == null) {
//Debug.Log("Look check passed: nothing in Agent Hand to prevent Angle change");
return true;
}
//returns true if Rotation is allowed
bool result = true;
//check if we can look up without hitting something
if (updown > 0) {
for (int i = 0; i < 3; i++) {
if (LookUDTriggerBoxes[i].GetComponent<RotationTriggerCheck>().isColliding == true) {
Debug.Log("Object In way, Can't Look Up");
return false;
}
}
}
//check if we can look down without hitting something
if (updown < 0) {
for (int i = 3; i < 6; i++) {
if (LookUDTriggerBoxes[i].GetComponent<RotationTriggerCheck>().isColliding == true) {
Debug.Log("Object in way, Can't Look down");
return false;
}
}
}
return result;
}
public override void RotateRight(ServerAction controlCommand) {
if (CheckIfAgentCanTurn(90)||controlCommand.forceAction) {
DefaultAgentHand(controlCommand);
base.RotateRight(controlCommand);
} else {
actionFinished(false);
}
}
public override void RotateLeft(ServerAction controlCommand) {
if (CheckIfAgentCanTurn(-90)||controlCommand.forceAction) {
DefaultAgentHand(controlCommand);
base.RotateLeft(controlCommand);
} else {
actionFinished(false);
}
}
//checks if agent is clear to rotate left/right without object in hand hitting anything
public bool CheckIfAgentCanTurn(int direction) {
bool result = true;
if (ItemInHand == null) {
//Debug.Log("Rotation check passed: nothing in Agent Hand");
return true;
}
if (direction != 90 && direction != -90) {
Debug.Log("Please give -90(left) or 90(right) as direction parameter");
return false;
}
//if turning right, check first 3 in array (30R, 60R, 90R)
if (direction > 0) {