forked from allenai/ai2thor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPhysicsRemoteFPSAgentController.cs
2408 lines (2064 loc) · 107 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.Linq;
using UnityEngine;
namespace UnityStandardAssets.Characters.FirstPerson {
[RequireComponent(typeof(CharacterController))]
public class PhysicsRemoteFPSAgentController : BaseFPSAgentController {
// Used to expand agent capsule in collision checks for open/close actions
protected const float ExpandAgentCapsuleBy = 0.1f;
protected float serverActionMoveMagnitude;
// Use this for initialization
public override void Start() { base.Start(); }
// forceVisible is true to activate, false to deactivate
public float WhatIsAgentsMaxVisibleDistance() { return maxVisibleDistance; }
public SimObjPhysics WhatAmIHolding() { return ItemInHand; }
// get all sim objets of action.type, then sets their temperature decay
// timers to value
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.agentState == AgentState.ActionComplete) {
ServerAction action = new ServerAction();
VisibleSimObjPhysics = VisibleSimObjs(action); // GetAllVisibleSimObjPhysics(m_Camera,
// maxVisibleDistance);
}
#endif
}
public override ObjectMetadata[] generateObjectMetadata() { return base.generateObjectMetadata(); }
public override MetadataWrapper generateMetadataWrapper() { return base.generateMetadataWrapper(); }
public override ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj, bool isVisible) { return base.ObjectMetadataFromSimObjPhysics(simObj, isVisible); }
// change the radius of the agent's capsule on the char controller
// component, and the capsule collider component
// EDITOR DEBUG SCRIPTS:
//////////////////////////////////////////////////////////////////////
#if UNITY_EDITOR
// return ID of closest CanPickup object by distance
public string ObjectIdOfClosestVisibleObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.PrimaryProperty == SimObjPrimaryProperty.CanPickup) {
objectID = o.ObjectID;
break;
}
}
return objectID;
}
public string ObjectIdOfClosestPickupableOrMoveableObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.PrimaryProperty == SimObjPrimaryProperty.CanPickup || o.PrimaryProperty == SimObjPrimaryProperty.Moveable) {
objectID = o.ObjectID;
break;
}
}
return objectID;
}
// return ID of closest CanOpen or CanOpen_Fridge object by distance
public string ObjectIdOfClosestReceptacleObject() {
string objectID = null;
foreach (SimObjPhysics o in VisibleSimObjPhysics) {
if (o.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) {
objectID = o.ObjectID;
break;
}
}
return objectID;
}
#endif
/////////////////////////////////////////////////////////
// return a reference to a SimObj that is Visible (in the
// VisibleSimObjPhysics array) and matches the passed in objectID
public GameObject FindObjectInVisibleSimObjPhysics(string objectID, SimObjPhysics[] visibleSimObjects = null) {
GameObject target = null;
foreach (SimObjPhysics o in visibleSimObjects == null ? VisibleSimObjPhysics : visibleSimObjects) {
if (o.objectID == objectID) {
target = o.gameObject;
}
}
return target;
}
// 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);
// increasing these grants a very slight flexibiltiy in object placement
// if the agent is below or above a receptacle
float ViewPointRangeHigh = 1.0f;
float ViewPointRangeLow = -1.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, (1 << 8) | (1 << 10))) {
updateAllAgentCollidersForVisibilityCheck(true);
// this should be set to true for object placement flexibility
return true;
}
}
updateAllAgentCollidersForVisibilityCheck(true);
return false;
}
// checks if a float is a multiple of 0.1f
private bool CheckIfFloatIsMultipleOfOneTenth(float f) {
if (((decimal)f % 0.1M == 0) == false)
return false;
else
return true;
}
public override void LookDown(ServerAction action) {
if (action.degrees < 0) {
errorMessage = "LookDown action requires positive degree value. Invalid value used: " + action.degrees;
actionFinished(false);
return;
}
if (!CheckIfFloatIsMultipleOfOneTenth(action.degrees)) {
errorMessage = "LookDown action requires degree value to be a multiple of 0.1f";
actionFinished(false);
return;
}
// default degree increment to 30
if (action.degrees == 0) {
action.degrees = 30f;
}
// force the degree increment to the nearest tenths place
// this is to prevent too small of a degree increment change that could
// cause float imprecision
action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f;
if (!checkForUpDownAngleLimit("down", action.degrees)) {
errorMessage = "can't look down beyond " + maxDownwardLookAngle + " degrees below the forward horizon";
errorCode = ServerActionErrorCode.LookDownCantExceedMin;
actionFinished(false);
return;
}
if (CheckIfAgentCanRotate("down", action.degrees)) {
// only default hand if not manually Interacting with things
if (!action.manualInteract)
DefaultAgentHand();
base.LookDown(action);
return;
}
else {
errorMessage = "a held item: " + ItemInHand.objectID + " will collide with something if agent rotates down " + action.degrees + " degrees";
actionFinished(false);
}
}
public override void LookUp(ServerAction action) {
if (action.degrees < 0) {
errorMessage = "LookUp action requires positive degree value. Invalid value used: " + action.degrees;
actionFinished(false);
return;
}
if (!CheckIfFloatIsMultipleOfOneTenth(action.degrees)) {
errorMessage = "LookUp action requires degree value to be a multiple of 0.1f";
actionFinished(false);
return;
}
// default degree increment to 30
if (action.degrees == 0) {
action.degrees = 30f;
}
// force the degree increment to the nearest tenths place
// this is to prevent too small of a degree increment change that could
// cause float imprecision
action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f;
if (!checkForUpDownAngleLimit("up", action.degrees)) {
errorMessage = "can't look up beyond " + maxUpwardLookAngle + " degrees above the forward horizon";
errorCode = ServerActionErrorCode.LookDownCantExceedMin;
actionFinished(false);
return;
}
if (CheckIfAgentCanRotate("up", action.degrees)) {
// only default hand if not manually Interacting with things
if (!action.manualInteract)
DefaultAgentHand();
base.LookUp(action);
}
else {
errorMessage = "a held item: " + ItemInHand.objectID + " will collide with something if agent rotates up " + action.degrees + " degrees";
actionFinished(false);
}
}
public override void RotateRight(ServerAction action) {
// if controlCommand.degrees is default (0), rotate by the default
// rotation amount set on initialize
if (action.degrees == 0f)
action.degrees = rotateStepDegrees;
if (CheckIfAgentCanRotate("right", action.degrees) || action.forceAction) {
// only default hand if not manually Interacting with things
if (!action.manualInteract) {
DefaultAgentHand();
}
base.RotateRight(action);
}
else {
errorMessage = "a held item: " + ItemInHand.transform.name + " with something if agent rotates Right " + action.degrees + " degrees";
actionFinished(false);
}
}
public override void RotateLeft(ServerAction action) {
// if controlCommand.degrees is default (0), rotate by the default
// rotation amount set on initialize
if (action.degrees == 0f)
action.degrees = rotateStepDegrees;
if (CheckIfAgentCanRotate("left", action.degrees) || action.forceAction) {
// only default hand if not manually Interacting with things
if (!action.manualInteract)
DefaultAgentHand();
base.RotateLeft(action);
}
else {
errorMessage = "a held item: " + ItemInHand.transform.name + " with something if agent rotates Left " + action.degrees + " degrees";
actionFinished(false);
}
}
private bool checkArcForCollisions(Vector3[] corners, Vector3 origin, float degrees, string dir) {
bool result = true;
// generate arc points in the positive y axis rotation
foreach (Vector3 v in corners) {
Vector3[] pointsOnArc = GenerateArcPoints(v, origin, degrees, dir);
// raycast from first point in pointsOnArc, stepwise to the last
// point. If any collisions are hit, immediately return
for (int i = 0; i < pointsOnArc.Length; i++) {
// debug draw spheres to show path of arc
// GameObject Sphere =
// GameObject.CreatePrimitive(PrimitiveType.Sphere);
// Sphere.transform.position = pointsOnArc[i];
// Sphere.transform.localScale = new Vector3(0.02f, 0.02f,
// 0.02f); Sphere.GetComponent<SphereCollider>().enabled =
// false;
RaycastHit hit;
// do linecasts from the first point, sequentially, to the last
if (i < pointsOnArc.Length - 1) {
// Debug.DrawLine(pointsOnArc[i], pointsOnArc[i+1],
// Color.magenta, 50f);
if (Physics.Linecast(pointsOnArc[i], pointsOnArc[i + 1], out hit, 1 << 8 | 1 << 10, QueryTriggerInteraction.Ignore)) {
if (hit.transform.GetComponent<SimObjPhysics>()) {
// if we hit the item in our hand, skip
if (hit.transform.GetComponent<SimObjPhysics>().transform == ItemInHand.transform)
continue;
}
if (hit.transform == this.transform) {
// don't worry about clipping the object into this
// agent
continue;
}
result = false;
break;
}
}
}
}
return result;
}
// for use with each of the 8 corners of a picked up object's bounding box -
// returns an array of Vector3 points along the arc of the rotation for a
// given starting point given a starting Vector3, rotate about an origin
// point for a total given angle. maxIncrementAngle is the maximum value of
// the increment between points on the arc. if leftOrRight is true - rotate
// around Y (rotate left/right), false - rotate around X (look up/down)
private Vector3[] GenerateArcPoints(Vector3 startingPoint, Vector3 origin, float angle, string dir) {
float incrementAngle = angle / 10f; // divide the total amount we are rotating by 10 to get
// 10 points on the arc
Vector3[] arcPoints = new Vector3[11]; // we just always want 10 points in addition to our
// starting corner position (11 total) to check
// against per corner
float currentIncrementAngle;
if (dir == "left") // Yawing left (Rotating across XZ plane around Y-pivot)
{
for (int i = 0; i < arcPoints.Length; i++) {
currentIncrementAngle = i * -incrementAngle;
// move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
// rotate the rotPoint around the origin the current increment's
// angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.up, currentIncrementAngle);
// set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
// arcPoints[i] = RotatePointAroundPivot(startingPoint, origin,
// new Vector3(0, currentIncrementAngle, 0));
}
}
if (dir == "right") // Yawing right (Rotating across XZ plane around Y-pivot)
{
for (int i = 0; i < arcPoints.Length; i++) {
currentIncrementAngle = i * incrementAngle;
// move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
// rotate the rotPoint around the origin the current increment's
// angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.up, currentIncrementAngle);
// set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
// arcPoints[i] = RotatePointAroundPivot(startingPoint, origin,
// new Vector3(0, currentIncrementAngle, 0));
}
}
else if (dir == "up") // Pitching up(Rotating across YZ plane around X-pivot)
{
for (int i = 0; i < arcPoints.Length; i++) {
// reverse the increment angle because of the right handedness
// orientation of the local x-axis
currentIncrementAngle = i * -incrementAngle;
// move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
// rotate the rotPoint around the origin the current increment's
// angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.right, currentIncrementAngle);
// set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
// arcPoints[i] = RotatePointAroundPivot(startingPoint, origin,
// new Vector3(0, currentIncrementAngle, 0));
}
}
else if (dir == "down") // Pitching down (Rotating across YZ plane
// around X-pivot)
{
for (int i = 0; i < arcPoints.Length; i++) {
// reverse the increment angle because of the right handedness
// orientation of the local x-axis
currentIncrementAngle = i * incrementAngle;
// move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
// rotate the rotPoint around the origin the current increment's
// angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.right, currentIncrementAngle);
// set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
// arcPoints[i] = RotatePointAroundPivot(startingPoint, origin,
// new Vector3(0, currentIncrementAngle, 0));
}
}
return arcPoints;
}
// checks if agent is clear to rotate left/right/up/down some number of
// degrees while holding an object
public bool CheckIfAgentCanRotate(string direction, float degrees) {
// If the Item the agent is holding isn't active, it's geometry won't
// interfere with looking Note for code review: Is there a case where
// this game object's parent is inactive, but this object is active (but
// treated as inactive)?
if (ItemInHand == null || !ItemInHand.gameObject.activeInHierarchy) {
// Debug.Log("Look check passed: nothing in Agent Hand to prevent
// Angle change");
return true;
}
bool result = true;
BoxCollider bb = ItemInHand.boundingBoxCollider;
// get world coordinates of object in hand's bounding box corners
Vector3[] corners = UtilityFunctions.CornerCoordinatesOfBoxColliderToWorld(bb);
// ok now we have each corner, let's rotate them the specified direction
if (direction == "right" || direction == "left") {
result = checkArcForCollisions(corners, m_CharacterController.transform.position, degrees, direction);
}
else if (direction == "up" || direction == "down") {
result = checkArcForCollisions(corners, m_Camera.transform.position, degrees, direction);
}
// no checks flagged anything, good to go, return true i guess
return result;
}
private bool checkForUpDownAngleLimit(string direction, float degrees) {
bool result = true;
// check the angle between the agent's forward vector and the proposed
// rotation vector if it exceeds the min/max based on if we are rotating
// up or down, return false
// first move the rotPoint to the camera
rotPoint.transform.position = m_Camera.transform.position;
// zero out the rotation first
rotPoint.transform.rotation = m_Camera.transform.rotation;
if (direction == "down") {
rotPoint.Rotate(new Vector3(degrees, 0, 0));
// note: maxDownwardLookAngle is negative because SignedAngle()
// returns a... signed angle... so even though the input is
// LookDown(degrees) with degrees being positive, it still needs to
// check against this negatively signed direction.
if (Mathf.Round(Vector3.SignedAngle(rotPoint.transform.forward, m_CharacterController.transform.forward, m_CharacterController.transform.right) * 10.0f) / 10.0f <
-maxDownwardLookAngle) {
result = false;
}
}
if (direction == "up") {
rotPoint.Rotate(new Vector3(-degrees, 0, 0));
if (Mathf.Round(Vector3.SignedAngle(rotPoint.transform.forward, m_CharacterController.transform.forward, m_CharacterController.transform.right) * 10.0f) / 10.0f >
maxUpwardLookAngle) {
result = false;
}
}
return result;
}
protected bool moveObject(SimObjPhysics sop, Vector3 targetPosition, bool snapToGrid = false, HashSet<Transform> ignoreCollisionWithTransforms = null) {
Vector3 lastPosition = sop.transform.position;
if (snapToGrid) {
float mult = 1.0f / gridSize;
float gridX = Convert.ToSingle(Math.Round(targetPosition.x * mult) / mult);
float gridZ = Convert.ToSingle(Math.Round(targetPosition.z * mult) / mult);
targetPosition = new Vector3(gridX, targetPosition.y, gridZ);
}
Vector3 dir = targetPosition - sop.transform.position;
RaycastHit[] sweepResults =
UtilityFunctions.CastAllPrimitiveColliders(sop.gameObject, targetPosition - sop.transform.position, dir.magnitude, 1 << 8 | 1 << 10, QueryTriggerInteraction.Ignore);
if (sweepResults.Length > 0) {
foreach (RaycastHit hit in sweepResults) {
if (ignoreCollisionWithTransforms == null || !ignoreCollisionWithTransforms.Contains(hit.transform)) {
errorMessage = hit.transform.name + " is in the way of moving " + sop.ObjectID;
return false;
}
}
}
sop.transform.position = targetPosition;
return true;
}
public override void TeleportFull(ServerAction action) {
targetTeleport = new Vector3(action.x, action.y, action.z);
if (action.forceAction) {
DefaultAgentHand();
transform.position = targetTeleport;
transform.rotation = Quaternion.Euler(new Vector3(0.0f, action.rotation.y, 0.0f));
if (action.standing) {
m_Camera.transform.localPosition = standingLocalCameraPosition;
} else {
m_Camera.transform.localPosition = crouchingLocalCameraPosition;
}
m_Camera.transform.localEulerAngles = new Vector3(action.horizon, 0.0f, 0.0f);
} else {
if (!agentManager.SceneBounds.Contains(targetTeleport)) {
errorMessage = "Teleport target out of scene bounds.";
actionFinished(false);
return;
}
Vector3 oldPosition = transform.position;
Quaternion oldRotation = transform.rotation;
Vector3 oldLocalHandPosition = new Vector3();
Quaternion oldLocalHandRotation = new Quaternion();
if (ItemInHand != null) {
oldLocalHandPosition = ItemInHand.transform.localPosition;
oldLocalHandRotation = ItemInHand.transform.localRotation;
}
Vector3 oldCameraLocalEulerAngle = m_Camera.transform.localEulerAngles;
Vector3 oldCameraLocalPosition = m_Camera.transform.localPosition;
DefaultAgentHand();
transform.position = targetTeleport;
// apply gravity after teleport so we aren't floating in the air
Vector3 m = new Vector3();
m.y = Physics.gravity.y * this.m_GravityMultiplier;
m_CharacterController.Move(m);
transform.rotation = Quaternion.Euler(new Vector3(0.0f, action.rotation.y, 0.0f));
if (action.standing) {
m_Camera.transform.localPosition = standingLocalCameraPosition;
} else {
m_Camera.transform.localPosition = crouchingLocalCameraPosition;
}
m_Camera.transform.localEulerAngles = new Vector3(action.horizon, 0.0f, 0.0f);
bool agentCollides = isAgentCapsuleColliding(collidersToIgnoreDuringMovement);
bool handObjectCollides = isHandObjectColliding(true);
if (agentCollides) {
errorMessage = "Cannot teleport due to agent collision.";
Debug.Log(errorMessage);
} else if (handObjectCollides) {
errorMessage = "Cannot teleport due to hand object collision.";
Debug.Log(errorMessage);
}
if (agentCollides || handObjectCollides) {
if (ItemInHand != null) {
ItemInHand.transform.localPosition = oldLocalHandPosition;
ItemInHand.transform.localRotation = oldLocalHandRotation;
}
transform.position = oldPosition;
transform.rotation = oldRotation;
m_Camera.transform.localPosition = oldCameraLocalPosition;
m_Camera.transform.localEulerAngles = oldCameraLocalEulerAngle;
actionFinished(false);
return;
}
}
Vector3 v = new Vector3();
v.y = Physics.gravity.y * this.m_GravityMultiplier;
m_CharacterController.Move(v);
snapAgentToGrid();
actionFinished(true);
}
protected Vector3 FindClosestPoint(Vector3 position, SimObjPhysics target) {
bool isNull = true;
Vector3 bestClosestPoint = new Vector3();
float bestDistance = 0;
foreach (Collider collider in target.MyColliders) {
Vector3 closestPoint = collider.ClosestPoint(position);
float distance = Vector3.Distance(position, closestPoint);
if (isNull || distance < bestDistance) {
isNull = false;
bestClosestPoint = closestPoint;
bestDistance = distance;
}
}
return bestClosestPoint;
}
public void ApplyForceObject(ServerAction action) {
GameObject player = this.gameObject;
if (action.forceAction) {
action.forceVisible = true;
}
SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId];
VisibilityBools visibilityBools = objectIsCurrentlyVisible(target, maxVisibleDistance);
if (Vector3.Distance(transform.position, FindClosestPoint(transform.position, target)) < maxVisibleDistance && !ObjectIsVisibleSimObjOrRoomStructure(target)) {
if (!visibilityBools.inViewportAndVisible && !visibilityBools.notInViewportButNotObstructed) {
errorMessage = "Target " + action.objectId + " is within distance of interaction but obstructed.";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_VISIBLE);
actionFinished(false);
return;
}
if (!visibilityBools.inViewportAndVisible && visibilityBools.notInViewportButNotObstructed) {
errorMessage = "Target " + action.objectId + " is within distance of interaction but not visible.";
Debug.Log(errorMessage);
Debug.Log(string.Format("Agent - X rotation: {0} - Y rotation {1}.", m_Camera.transform.eulerAngles.x, transform.eulerAngles.y));
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_VISIBLE);
actionFinished(false);
return;
}
}
if (!ObjectIsVisibleSimObjOrRoomStructure(target)) {
errorMessage = action.objectId + " is out of reach.";
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.OUT_OF_REACH);
actionFinished(false);
return;
}
if (target.GetComponent<StructureObject>() && Vector3.Distance(transform.position, FindClosestPoint(transform.position, target)) < maxVisibleDistance) {
errorMessage = action.objectId + " is not moveable.";
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_MOVEABLE);
actionFinished(false);
return;
}
if (target == null || !target.GetComponent<SimObjPhysics>()) {
if (Vector3.Distance(transform.position, FindClosestPoint(transform.position, target)) < maxVisibleDistance) {
errorMessage = "Target must be SimObjPhysics!";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_INTERACTABLE);
actionFinished(false);
return;
}
}
bool canbepushed = false;
if (target.PrimaryProperty == SimObjPrimaryProperty.CanPickup || target.PrimaryProperty == SimObjPrimaryProperty.Moveable)
canbepushed = true;
if (!canbepushed) {
errorMessage = "Target Sim Object cannot be moved. It's primary property must be Pickupable or Moveable";
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_MOVEABLE);
actionFinished(false);
return;
}
target.myRigidbody.isKinematic = false;
ServerAction apply = new ServerAction();
apply.moveMagnitude = action.moveMagnitude;
Vector3 dir = Vector3.zero;
if (action.z == 1) {
dir = gameObject.transform.forward;
}
if (action.z == -1) {
dir = -gameObject.transform.forward;
}
apply.x = dir.x;
apply.y = dir.y;
apply.z = dir.z;
if (action.action == "TorqueObject") {
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.SUCCESSFUL);
actionFinished(true);
target.ApplyTorque(action);
} else if (action.action == "RotateObject") {
bool succesfulRotation = target.ApplyRotation(action);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), succesfulRotation ? ActionStatus.SUCCESSFUL : ActionStatus.OBSTRUCTED);
actionFinished(succesfulRotation);
} else if (action.action == "MoveObject") {
bool succesfullMovement = target.ApplyMovement(action);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), succesfullMovement ? ActionStatus.SUCCESSFUL : ActionStatus.OBSTRUCTED);
actionFinished(succesfullMovement);
} else {
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.SUCCESSFUL);
actionFinished(true);
sopApplyForce(apply, target);
}
}
// pause physics autosimulation! Automatic physics simulation can be resumed
// using the UnpausePhysicsAutoSim() action. additionally, auto simulation
// will automatically resume from the LateUpdate() check on AgentManager.cs
// - if the scene has come to rest, physics autosimulation will resume
protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float length) {
// apply force, return action finished immediately
if (physicsSceneManager.physicsSimulationPaused) {
sop.ApplyForce(action);
if (length >= 0.00001f) {
WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length };
actionFinished(true, feedback);
}
// why is this here?
else {
actionFinished(true);
}
}
// if physics is automatically being simulated, use coroutine rather
// than returning actionFinished immediately
else {
sop.ApplyForce(action);
StartCoroutine(checkIfObjectHasStoppedMoving(sop, length));
}
}
// wrapping the SimObjPhysics.ApplyForce function since lots of things use
// it....
protected void sopApplyForce(ServerAction action, SimObjPhysics sop) { sopApplyForce(action, sop, 0.0f); }
// used to check if an specified sim object has come to rest
// set useTimeout bool to use a faster time out
private IEnumerator checkIfObjectHasStoppedMoving(SimObjPhysics sop, float length, bool useTimeout = false) {
// yield for the physics update to make sure this yield is consistent
// regardless of framerate
yield return new WaitForFixedUpdate();
float startTime = Time.time;
float waitTime = TimeToWaitForObjectsToComeToRest;
if (useTimeout) {
waitTime = 1.0f;
}
if (sop != null) {
Rigidbody rb = sop.myRigidbody;
bool stoppedMoving = false;
while (Time.time - startTime < waitTime) {
if (sop == null)
break;
float currentVelocity = Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude);
float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime;
// ok the accel is basically zero, so it has stopped moving
if (Mathf.Abs(accel) <= 0.001f) {
// force the rb to stop moving just to be safe
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.Sleep();
stoppedMoving = true;
break;
}
else
yield return new WaitForFixedUpdate();
}
// so we never stopped moving and we are using the timeout
if (!stoppedMoving && useTimeout) {
errorMessage = "object couldn't come to rest";
actionFinished(false);
yield break;
}
// return to metadatawrapper.actionReturn if an object was touched
// during this interaction
if (length != 0.0f) {
WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length };
// force objec to stop moving
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.Sleep();
actionFinished(true, feedback);
}
// if passed in length is 0, don't return feedback cause not all
// actions need that
else {
DefaultAgentHand();
actionFinished(true, "object settled after: " + (Time.time - startTime));
}
}
else {
errorMessage = "null reference sim obj in checkIfObjectHasStoppedMoving call";
actionFinished(false);
}
}
// Sweeptest to see if the object Agent is holding will prohibit movement
// for use with TouchThenApplyForce feedback return
public struct WhatDidITouch {
public bool didHandTouchSomething; // did the hand touch something or
// did it hit nothing?
public string objectId; // id of object touched, if it is a sim object
public float armsLength; // the amount the hand moved from it's starting
// position to hit the object touched
}
// checks if the target position in space is within the agent's current
// viewport
public bool CheckIfTargetPositionIsInViewportRange(Vector3 targetPosition) {
// now check if the target position is within bounds of the Agent's
// forward (z) view
Vector3 tmp = m_Camera.transform.position;
if (Vector3.Distance(tmp, targetPosition) > maxVisibleDistance) // + 0.3)
{
errorMessage = "The target position is outside the agent's max visible distance.";
return false;
}
// now make sure that the targetPosition is within the Agent's x/y view,
// restricted by camera
Vector3 vp = m_Camera.WorldToViewportPoint(targetPosition);
if (vp.z < 0 || vp.x > 1.0f || vp.y < 0.0f || vp.y > 1.0f || vp.y < 0.0f) {
errorMessage = "The target position is outside the viewport.";
return false;
}
return true;
}
// moves hand to the x, y, z coordinate, not constrained by any axis, if
// within range
// same as PlaceObjectAtPoint(ServerAction action) but without a server
// action
public bool placeObjectAtPoint(SimObjPhysics t, Vector3 position) {
SimObjPhysics target = null;
// find the object in the scene, disregard visibility
foreach (SimObjPhysics sop in VisibleSimObjs(true)) {
if (sop.objectID == t.objectID) {
target = sop;
}
}
if (target == null) {
return false;
}
// make sure point we are moving the object to is valid
if (!agentManager.sceneBounds.Contains(position)) {
return false;
}
// ok let's get the distance from the simObj to the bottom most part of
// its colliders
Vector3 targetNegY = target.transform.position + new Vector3(0, -1, 0);
BoxCollider b = target.boundingBoxCollider;
b.enabled = true;
Vector3 bottomPoint = b.ClosestPoint(targetNegY);
b.enabled = false;
float distFromSopToBottomPoint = Vector3.Distance(bottomPoint, target.transform.position);
float offset = distFromSopToBottomPoint;
// final position to place on surface
Vector3 finalPos = GetSurfacePointBelowPosition(position) + new Vector3(0, offset, 0);
// check spawn area, if its clear, then place object at finalPos
InstantiatePrefabTest ipt = physicsSceneManager.GetComponent<InstantiatePrefabTest>();
if (ipt.CheckSpawnArea(target, finalPos, target.transform.rotation, false)) {
target.transform.position = finalPos;
return true;
}
return false;
}
// uncomment this to debug draw valid points
// private List<Vector3> validpointlist = new List<Vector3>();
// return a bunch of vector3 points above a target receptacle
// if forceVisible = true, return points regardless of where receptacle is
// if forceVisible = false, only return points that are also within view of
// the Agent camera
// same as GetSpawnCoordinatesAboveReceptacle(Server Action) but takes a sim
// obj phys instead returns a list of vector3 coordinates above a
// receptacle. These coordinates will make up a grid above the receptacle
public List<Vector3> getSpawnCoordinatesAboveReceptacle(SimObjPhysics t) {
SimObjPhysics target = t;
// ok now get spawn points from target
List<Vector3> targetPoints = new List<Vector3>();
targetPoints = target.FindMySpawnPointsFromTopOfTriggerBox();
return targetPoints;
}
// instantiate a target circle, and then place it in a
// "SpawnOnlyOUtsideReceptacle" that is also within camera view If fails,
// return actionFinished(false) and despawn target circle
public virtual void PutObject(ServerAction action) { PlaceHeldObject(action); }
// if you are holding an object, place it on a valid Receptacle
// used for placing objects on receptacles without enclosed restrictions
// (drawers, cabinets, etc) only checks if the object can be placed on top
// of the target receptacle
public void PlaceHeldObject(ServerAction action) {
// check if we are even holding anything
if (ItemInHand == null) {
errorMessage = "Can't place an object if Agent isn't holding anything";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_HELD);
actionFinished(false);
return;
} else {
// Make sure object ID given is actually the item in hand
if (!ItemInHand.transform.name.Equals(action.objectId)) {
errorMessage = "Object ID " + action.objectId + " is not the object currently being held.";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_HELD);
actionFinished(false);
return;
}
}
if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.receptacleObjectId)) {
errorMessage = "Object ID " + action.receptacleObjectId + " appears to be invalid.";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_OBJECT);
actionFinished(false);
return;
}
SimObjPhysics targetReceptacle = physicsSceneManager.ObjectIdToSimObjPhysics[action.receptacleObjectId];
// if receptacle can open, check that it's open before placing. Can't
// place objects in something that is closed!
if (targetReceptacle.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen)) {
CanOpen_Object canOpenObject = targetReceptacle.GetComponent<CanOpen_Object>();
if (canOpenObject != null && !canOpenObject.isOpen) {
errorMessage = "Target openable Receptacle is CLOSED, placement is obstructed until target is opened!";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.OBSTRUCTED);
actionFinished(false);
return;
}
}
VisibilityBools visibilityBools = objectIsCurrentlyVisible(targetReceptacle, maxVisibleDistance);
if (Vector3.Distance(transform.position, FindClosestPoint(transform.position, targetReceptacle)) < maxVisibleDistance &&
!ObjectIsVisibleSimObjOrRoomStructure(targetReceptacle)) {
if (!visibilityBools.inViewportAndVisible && !visibilityBools.notInViewportButNotObstructed) {
errorMessage = "Target " + action.objectId + " is within distance of interaction but obstructed.";
Debug.Log(errorMessage);
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_VISIBLE);
actionFinished(false);
return;
}
if (!visibilityBools.inViewportAndVisible && visibilityBools.notInViewportButNotObstructed) {
errorMessage = "Target " + action.objectId + " is within distance of interaction but not visible.";
Debug.Log(errorMessage);
Debug.Log(string.Format("Agent - X rotation: {0} - Y rotation {1}.", m_Camera.transform.eulerAngles.x, transform.eulerAngles.y));
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_VISIBLE);
actionFinished(false);
return;
}
}
if (!ObjectIsVisibleSimObjOrRoomStructure(targetReceptacle)) {
errorMessage = action.objectId + " is out of reach.";
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.OUT_OF_REACH);
actionFinished(false);
return;
}
if (targetReceptacle == null || !targetReceptacle.GetComponent<SimObjPhysics>()) {
errorMessage = action.receptacleObjectId + " is not interactable.";
this.lastActionStatus = Enum.GetName(typeof(ActionStatus), ActionStatus.NOT_INTERACTABLE);
actionFinished(false);
return;
}
if (!targetReceptacle.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle) || targetReceptacle.GetComponent<StructureObject>()) {