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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#region References
using System;
using System.Collections.Generic;
using MonoXnaCompactMaths;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using XnaDevRu.BulletX;
using XnaDevRu.BulletX.Dynamics;
using Nini.Config;
using AxiomQuaternion = Axiom.Math.Quaternion;
#endregion
namespace OpenSim.Region.Physics.BulletXPlugin
{
/// <summary>
/// BulletXConversions are called now BulletXMaths
/// This Class converts objects and types for BulletX and give some operations
/// </summary>
public class BulletXMaths
{
//private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Vector3
public static Vector3 PhysicsVectorToXnaVector3(PhysicsVector physicsVector)
{
return new Vector3(physicsVector.X, physicsVector.Y, physicsVector.Z);
}
public static PhysicsVector XnaVector3ToPhysicsVector(Vector3 xnaVector3)
{
return new PhysicsVector(xnaVector3.X, xnaVector3.Y, xnaVector3.Z);
}
//Quaternion
public static Quaternion AxiomQuaternionToXnaQuaternion(AxiomQuaternion axiomQuaternion)
{
return new Quaternion(axiomQuaternion.x, axiomQuaternion.y, axiomQuaternion.z, axiomQuaternion.w);
}
public static AxiomQuaternion XnaQuaternionToAxiomQuaternion(Quaternion xnaQuaternion)
{
return new AxiomQuaternion(xnaQuaternion.W, xnaQuaternion.X, xnaQuaternion.Y, xnaQuaternion.Z);
}
//Next methods are extracted from XnaDevRu.BulletX(See 3rd party license):
//- SetRotation (class MatrixOperations)
//- GetRotation (class MatrixOperations)
//- GetElement (class MathHelper)
//- SetElement (class MathHelper)
internal static void SetRotation(ref Matrix m, Quaternion q)
{
float d = q.LengthSquared();
float s = 2f/d;
float xs = q.X*s, ys = q.Y*s, zs = q.Z*s;
float wx = q.W*xs, wy = q.W*ys, wz = q.W*zs;
float xx = q.X*xs, xy = q.X*ys, xz = q.X*zs;
float yy = q.Y*ys, yz = q.Y*zs, zz = q.Z*zs;
m = new Matrix(1 - (yy + zz), xy - wz, xz + wy, 0,
xy + wz, 1 - (xx + zz), yz - wx, 0,
xz - wy, yz + wx, 1 - (xx + yy), 0,
m.M41, m.M42, m.M43, 1);
}
internal static Quaternion GetRotation(Matrix m)
{
Quaternion q = new Quaternion();
float trace = m.M11 + m.M22 + m.M33;
if (trace > 0)
{
float s = (float) Math.Sqrt(trace + 1);
q.W = s*0.5f;
s = 0.5f/s;
q.X = (m.M32 - m.M23)*s;
q.Y = (m.M13 - m.M31)*s;
q.Z = (m.M21 - m.M12)*s;
}
else
{
int i = m.M11 < m.M22
?
(m.M22 < m.M33 ? 2 : 1)
:
(m.M11 < m.M33 ? 2 : 0);
int j = (i + 1)%3;
int k = (i + 2)%3;
float s = (float) Math.Sqrt(GetElement(m, i, i) - GetElement(m, j, j) - GetElement(m, k, k) + 1);
SetElement(ref q, i, s*0.5f);
s = 0.5f/s;
q.W = (GetElement(m, k, j) - GetElement(m, j, k))*s;
SetElement(ref q, j, (GetElement(m, j, i) + GetElement(m, i, j))*s);
SetElement(ref q, k, (GetElement(m, k, i) + GetElement(m, i, k))*s);
}
return q;
}
internal static float SetElement(ref Quaternion q, int index, float value)
{
switch (index)
{
case 0:
q.X = value;
break;
case 1:
q.Y = value;
break;
case 2:
q.Z = value;
break;
case 3:
q.W = value;
break;
}
return 0;
}
internal static float GetElement(Matrix mat, int row, int col)
{
switch (row)
{
case 0:
switch (col)
{
case 0:
return mat.M11;
case 1:
return mat.M12;
case 2:
return mat.M13;
}
break;
case 1:
switch (col)
{
case 0:
return mat.M21;
case 1:
return mat.M22;
case 2:
return mat.M23;
}
break;
case 2:
switch (col)
{
case 0:
return mat.M31;
case 1:
return mat.M32;
case 2:
return mat.M33;
}
break;
}
return 0;
}
}
/// <summary>
/// PhysicsPlugin Class for BulletX
/// </summary>
public class BulletXPlugin : IPhysicsPlugin
{
private BulletXScene _mScene;
public BulletXPlugin()
{
}
public bool Init()
{
return true;
}
public PhysicsScene GetScene()
{
if (_mScene == null)
{
_mScene = new BulletXScene();
}
return (_mScene);
}
public string GetName()
{
return ("modified_BulletX"); //Changed!! "BulletXEngine" To "modified_BulletX"
}
public void Dispose()
{
}
}
// Class to detect and debug collisions
// Mainly used for debugging purposes
internal class CollisionDispatcherLocal : CollisionDispatcher
{
private BulletXScene relatedScene;
public CollisionDispatcherLocal(BulletXScene s)
: base()
{
relatedScene = s;
}
public override bool NeedsCollision(CollisionObject bodyA, CollisionObject bodyB)
{
RigidBody rb;
BulletXCharacter bxcA = null;
BulletXPrim bxpA = null;
Type t = bodyA.GetType();
if (t == typeof (RigidBody))
{
rb = (RigidBody) bodyA;
relatedScene._characters.TryGetValue(rb, out bxcA);
relatedScene._prims.TryGetValue(rb, out bxpA);
}
// String nameA;
// if (bxcA != null)
// nameA = bxcA._name;
// else if (bxpA != null)
// nameA = bxpA._name;
// else
// nameA = "null";
BulletXCharacter bxcB = null;
BulletXPrim bxpB = null;
t = bodyB.GetType();
if (t == typeof (RigidBody))
{
rb = (RigidBody) bodyB;
relatedScene._characters.TryGetValue(rb, out bxcB);
relatedScene._prims.TryGetValue(rb, out bxpB);
}
// String nameB;
// if (bxcB != null)
// nameB = bxcB._name;
// else if (bxpB != null)
// nameB = bxpB._name;
// else
// nameB = "null";
bool needsCollision;// = base.NeedsCollision(bodyA, bodyB);
int c1 = 3;
int c2 = 3;
////////////////////////////////////////////////////////
//BulletX Mesh Collisions
//added by Jed zhu
//data: May 07,2005
////////////////////////////////////////////////////////
#region BulletXMeshCollisions Fields
if (bxcA != null && bxpB != null)
c1 = Collision(bxcA, bxpB);
if (bxpA != null && bxcB != null)
c2 = Collision(bxcB, bxpA);
if (c1 < 2)
needsCollision = (c1 > 0) ? true : false;
else if (c2 < 2)
needsCollision = (c2 > 0) ? true : false;
else
needsCollision = base.NeedsCollision(bodyA, bodyB);
#endregion
//m_log.DebugFormat("[BulletX]: A collision was detected between {0} and {1} --> {2}", nameA, nameB,
//needsCollision);
return needsCollision;
}
//added by jed zhu
//calculas the collision between the Prim and Actor
//
private int Collision(BulletXCharacter actorA, BulletXPrim primB)
{
int[] indexBase;
Vector3[] vertexBase;
Vector3 vNormal;
// Vector3 vP1;
// Vector3 vP2;
// Vector3 vP3;
IMesh mesh = primB.GetMesh();
float fdistance;
if (primB == null)
return 3;
if (mesh == null)
return 2;
if (actorA == null)
return 3;
int iVertexCount = mesh.getVertexList().Count;
int iIndexCount = mesh.getIndexListAsInt().Length;
if (iVertexCount == 0)
return 3;
if (iIndexCount == 0)
return 3;
lock (BulletXScene.BulletXLock)
{
indexBase = mesh.getIndexListAsInt();
vertexBase = new Vector3[iVertexCount];
for (int i = 0; i < iVertexCount; i++)
{
PhysicsVector v = mesh.getVertexList()[i];
if (v != null) // Note, null has special meaning. See meshing code for details
vertexBase[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
else
vertexBase[i] = Vector3.Zero;
}
for (int ix = 0; ix < iIndexCount; ix += 3)
{
int ia = indexBase[ix + 0];
int ib = indexBase[ix + 1];
int ic = indexBase[ix + 2];
//
Vector3 v1 = vertexBase[ib] - vertexBase[ia];
Vector3 v2 = vertexBase[ic] - vertexBase[ia];
Vector3.Cross(ref v1, ref v2, out vNormal);
Vector3.Normalize(ref vNormal, out vNormal);
fdistance = Vector3.Dot(vNormal, vertexBase[ia]) + 0.50f;
if (preCheckCollision(actorA, vNormal, fdistance) == 1)
{
if (CheckCollision(actorA, ia, ib, ic, vNormal, vertexBase) == 1)
{
//PhysicsVector v = actorA.Position;
//Vector3 v3 = BulletXMaths.PhysicsVectorToXnaVector3(v);
//Vector3 vp = vNormal * (fdistance - Vector3.Dot(vNormal, v3) + 0.2f);
//actorA.Position += BulletXMaths.XnaVector3ToPhysicsVector(vp);
return 1;
}
}
}
}
return 0;
}
//added by jed zhu
//return value 1: need second check
//return value 0: no need check
private int preCheckCollision(BulletXActor actA, Vector3 vNormal, float fDist)
{
float fstartSide;
PhysicsVector v = actA.Position;
Vector3 v3 = BulletXMaths.PhysicsVectorToXnaVector3(v);
fstartSide = Vector3.Dot(vNormal, v3) - fDist;
if (fstartSide > 0) return 0;
else return 1;
}
//added by jed zhu
private int CheckCollision(BulletXActor actA, int ia, int ib, int ic, Vector3 vNormal, Vector3[] vertBase)
{
Vector3 perPlaneNormal;
float fPerPlaneDist;
PhysicsVector v = actA.Position;
Vector3 v3 = BulletXMaths.PhysicsVectorToXnaVector3(v);
//check AB
Vector3 v1;
v1 = vertBase[ib] - vertBase[ia];
Vector3.Cross(ref vNormal, ref v1, out perPlaneNormal);
Vector3.Normalize(ref perPlaneNormal, out perPlaneNormal);
if (Vector3.Dot((vertBase[ic] - vertBase[ia]), perPlaneNormal) < 0)
perPlaneNormal = -perPlaneNormal;
fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ia]) - 0.50f;
if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) < 0)
return 0;
fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ic]) + 0.50f;
if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) > 0)
return 0;
//check BC
v1 = vertBase[ic] - vertBase[ib];
Vector3.Cross(ref vNormal, ref v1, out perPlaneNormal);
Vector3.Normalize(ref perPlaneNormal, out perPlaneNormal);
if (Vector3.Dot((vertBase[ia] - vertBase[ib]), perPlaneNormal) < 0)
perPlaneNormal = -perPlaneNormal;
fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ib]) - 0.50f;
if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) < 0)
return 0;
fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ia]) + 0.50f;
if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) > 0)
return 0;
//check CA
v1 = vertBase[ia] - vertBase[ic];
Vector3.Cross(ref vNormal, ref v1, out perPlaneNormal);
Vector3.Normalize(ref perPlaneNormal, out perPlaneNormal);
if (Vector3.Dot((vertBase[ib] - vertBase[ic]), perPlaneNormal) < 0)
perPlaneNormal = -perPlaneNormal;
fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ic]) - 0.50f;
if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) < 0)
return 0;
fPerPlaneDist = Vector3.Dot(perPlaneNormal, vertBase[ib]) + 0.50f;
if ((Vector3.Dot(perPlaneNormal, v3) - fPerPlaneDist) > 0)
return 0;
return 1;
}
}
/// <summary>
/// PhysicsScene Class for BulletX
/// </summary>
public class BulletXScene : PhysicsScene
{
#region BulletXScene Fields
public DiscreteDynamicsWorld ddWorld;
private CollisionDispatcher cDispatcher;
private OverlappingPairCache opCache;
private SequentialImpulseConstraintSolver sicSolver;
public static Object BulletXLock = new Object();
private const int minXY = 0;
private const int minZ = 0;
private const int maxXY = (int)Constants.RegionSize;
private const int maxZ = 4096;
private const int maxHandles = 32766; //Why? I don't know
private const float gravity = 9.8f;
private const float heightLevel0 = 77.0f;
private const float heightLevel1 = 200.0f;
private const float lowGravityFactor = 0.2f;
//OpenSim calls Simulate 10 times per seconds. So FPS = "Simulate Calls" * simulationSubSteps = 100 FPS
private const int simulationSubSteps = 10;
//private float[] _heightmap;
private BulletXPlanet _simFlatPlanet;
internal Dictionary<RigidBody, BulletXCharacter> _characters = new Dictionary<RigidBody, BulletXCharacter>();
internal Dictionary<RigidBody, BulletXPrim> _prims = new Dictionary<RigidBody, BulletXPrim>();
public IMesher mesher;
// private IConfigSource m_config;
public static float Gravity
{
get { return gravity; }
}
public static float HeightLevel0
{
get { return heightLevel0; }
}
public static float HeightLevel1
{
get { return heightLevel1; }
}
public static float LowGravityFactor
{
get { return lowGravityFactor; }
}
public static int MaxXY
{
get { return maxXY; }
}
public static int MaxZ
{
get { return maxZ; }
}
private List<RigidBody> _forgottenRigidBodies = new List<RigidBody>();
internal string is_ex_message = "Can't remove rigidBody!: ";
#endregion
public BulletXScene()
{
cDispatcher = new CollisionDispatcherLocal(this);
Vector3 worldMinDim = new Vector3((float) minXY, (float) minXY, (float) minZ);
Vector3 worldMaxDim = new Vector3((float) maxXY, (float) maxXY, (float) maxZ);
opCache = new AxisSweep3(worldMinDim, worldMaxDim, maxHandles);
sicSolver = new SequentialImpulseConstraintSolver();
lock (BulletXLock)
{
ddWorld = new DiscreteDynamicsWorld(cDispatcher, opCache, sicSolver);
ddWorld.Gravity = new Vector3(0, 0, -gravity);
}
//this._heightmap = new float[65536];
}
public override void Initialise(IMesher meshmerizer, IConfigSource config)
{
mesher = meshmerizer;
// m_config = config;
}
public override void Dispose()
{
}
public override Dictionary<uint, float> GetTopColliders()
{
Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
return returncolliders;
}
public override void SetWaterLevel(float baseheight)
{
}
public override PhysicsActor AddAvatar(string avName, PhysicsVector position, PhysicsVector size)
{
PhysicsVector pos = new PhysicsVector();
pos.X = position.X;
pos.Y = position.Y;
pos.Z = position.Z + 20;
BulletXCharacter newAv = null;
lock (BulletXLock)
{
newAv = new BulletXCharacter(avName, this, pos);
_characters.Add(newAv.RigidBody, newAv);
}
return newAv;
}
public override void RemoveAvatar(PhysicsActor actor)
{
if (actor is BulletXCharacter)
{
lock (BulletXLock)
{
try
{
ddWorld.RemoveRigidBody(((BulletXCharacter) actor).RigidBody);
}
catch (Exception ex)
{
BulletXMessage(is_ex_message + ex.Message, true);
((BulletXCharacter) actor).RigidBody.ActivationState = ActivationState.DisableSimulation;
AddForgottenRigidBody(((BulletXCharacter) actor).RigidBody);
}
_characters.Remove(((BulletXCharacter) actor).RigidBody);
}
GC.Collect();
}
}
public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
PhysicsVector size, AxiomQuaternion rotation)
{
return AddPrimShape(primName, pbs, position, size, rotation, false);
}
public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
PhysicsVector size, AxiomQuaternion rotation, bool isPhysical)
{
PhysicsActor result;
switch (pbs.ProfileShape)
{
case ProfileShape.Square:
/// support simple box & hollow box now; later, more shapes
if (pbs.ProfileHollow == 0)
{
result = AddPrim(primName, position, size, rotation, null, null, isPhysical);
}
else
{
IMesh mesh = mesher.CreateMesh(primName, pbs, size, 32f);
result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical);
}
break;
default:
result = AddPrim(primName, position, size, rotation, null, null, isPhysical);
break;
}
return result;
}
public PhysicsActor AddPrim(String name, PhysicsVector position, PhysicsVector size, AxiomQuaternion rotation,
IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
{
BulletXPrim newPrim = null;
lock (BulletXLock)
{
newPrim = new BulletXPrim(name, this, position, size, rotation, mesh, pbs, isPhysical);
_prims.Add(newPrim.RigidBody, newPrim);
}
return newPrim;
}
public override void RemovePrim(PhysicsActor prim)
{
if (prim is BulletXPrim)
{
lock (BulletXLock)
{
try
{
ddWorld.RemoveRigidBody(((BulletXPrim) prim).RigidBody);
}
catch (Exception ex)
{
BulletXMessage(is_ex_message + ex.Message, true);
((BulletXPrim) prim).RigidBody.ActivationState = ActivationState.DisableSimulation;
AddForgottenRigidBody(((BulletXPrim) prim).RigidBody);
}
_prims.Remove(((BulletXPrim) prim).RigidBody);
}
GC.Collect();
}
}
public override void AddPhysicsActorTaint(PhysicsActor prim)
{
}
public override float Simulate(float timeStep)
{
float fps = 0;
lock (BulletXLock)
{
//Try to remove garbage
RemoveForgottenRigidBodies();
//End of remove
MoveAllObjects(timeStep);
fps = (timeStep*simulationSubSteps);
ddWorld.StepSimulation(timeStep, simulationSubSteps, timeStep);
//Extra Heightmap Validation: BulletX's HeightFieldTerrain somestimes doesn't work so fine.
ValidateHeightForAll();
//End heightmap validation.
UpdateKineticsForAll();
}
return fps;
}
private void MoveAllObjects(float timeStep)
{
foreach (BulletXCharacter actor in _characters.Values)
{
actor.Move(timeStep);
}
}
private void ValidateHeightForAll()
{
float _height;
foreach (BulletXCharacter actor in _characters.Values)
{
//_height = HeightValue(actor.RigidBodyPosition);
_height = _simFlatPlanet.HeightValue(actor.RigidBodyPosition);
actor.ValidateHeight(_height);
//if (_simFlatPlanet.heightIsNotValid(actor.RigidBodyPosition, out _height)) actor.ValidateHeight(_height);
}
foreach (BulletXPrim prim in _prims.Values)
{
//_height = HeightValue(prim.RigidBodyPosition);
_height = _simFlatPlanet.HeightValue(prim.RigidBodyPosition);
prim.ValidateHeight(_height);
//if (_simFlatPlanet.heightIsNotValid(prim.RigidBodyPosition, out _height)) prim.ValidateHeight(_height);
}
//foreach (BulletXCharacter actor in _characters)
//{
// actor.ValidateHeight(0);
//}
//foreach (BulletXPrim prim in _prims)
//{
// prim.ValidateHeight(0);
//}
}
private void UpdateKineticsForAll()
{
//UpdatePosition > UpdateKinetics.
//Not only position will be updated, also velocity cause acceleration.
foreach (BulletXCharacter actor in _characters.Values)
{
actor.UpdateKinetics();
}
foreach (BulletXPrim prim in _prims.Values)
{
prim.UpdateKinetics();
}
//if (this._simFlatPlanet!=null) this._simFlatPlanet.Restore();
}
public override void GetResults()
{
}
public override bool IsThreaded
{
get
{
return (false); // for now we won't be multithreaded
}
}
public override void SetTerrain(float[] heightMap)
{
////As the same as ODE, heightmap (x,y) must be swapped for BulletX
//for (int i = 0; i < 65536; i++)
//{
// // this._heightmap[i] = (double)heightMap[i];
// // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
// int x = i & 0xff;
// int y = i >> 8;
// this._heightmap[i] = heightMap[x * 256 + y];
//}
//float[] swappedHeightMap = new float[65536];
////As the same as ODE, heightmap (x,y) must be swapped for BulletX
//for (int i = 0; i < 65536; i++)
//{
// // this._heightmap[i] = (double)heightMap[i];
// // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
// int x = i & 0xff;
// int y = i >> 8;
// swappedHeightMap[i] = heightMap[x * 256 + y];
//}
DeleteTerrain();
//There is a BulletXLock inside the constructor of BulletXPlanet
//this._simFlatPlanet = new BulletXPlanet(this, swappedHeightMap);
_simFlatPlanet = new BulletXPlanet(this, heightMap);
//this._heightmap = heightMap;
}
public override void DeleteTerrain()
{
if (_simFlatPlanet != null)
{
lock (BulletXLock)
{
try
{
ddWorld.RemoveRigidBody(_simFlatPlanet.RigidBody);
}
catch (Exception ex)
{
BulletXMessage(is_ex_message + ex.Message, true);
_simFlatPlanet.RigidBody.ActivationState = ActivationState.DisableSimulation;
AddForgottenRigidBody(_simFlatPlanet.RigidBody);
}
}
_simFlatPlanet = null;
GC.Collect();
BulletXMessage("Terrain erased!", false);
}
//this._heightmap = null;
}
internal void AddForgottenRigidBody(RigidBody forgottenRigidBody)
{
_forgottenRigidBodies.Add(forgottenRigidBody);
}
private void RemoveForgottenRigidBodies()
{
RigidBody forgottenRigidBody;
int nRigidBodies = _forgottenRigidBodies.Count;
for (int i = nRigidBodies - 1; i >= 0; i--)
{
forgottenRigidBody = _forgottenRigidBodies[i];
try
{
ddWorld.RemoveRigidBody(forgottenRigidBody);
_forgottenRigidBodies.Remove(forgottenRigidBody);
BulletXMessage("Forgotten Rigid Body Removed", false);
}
catch (Exception ex)
{
BulletXMessage("Can't remove forgottenRigidBody!: " + ex.Message, false);
}
}
GC.Collect();
}
internal static void BulletXMessage(string message, bool isWarning)
{
PhysicsPluginManager.PhysicsPluginMessage("[Modified BulletX]:\t" + message, isWarning);
}
//temp
//private float HeightValue(MonoXnaCompactMaths.Vector3 position)
//{
// int li_x, li_y;
// float height;
// li_x = (int)Math.Round(position.X); if (li_x < 0) li_x = 0;
// li_y = (int)Math.Round(position.Y); if (li_y < 0) li_y = 0;
// height = this._heightmap[li_y * 256 + li_x];
// if (height < 0) height = 0;
// else if (height > maxZ) height = maxZ;
// return height;
//}
}
/// <summary>
/// Generic Physics Actor for BulletX inherit from PhysicActor
/// </summary>
public class BulletXActor : PhysicsActor
{
protected bool flying = false;
protected bool _physical = false;
protected PhysicsVector _position;
protected PhysicsVector _velocity;
protected PhysicsVector _size;
protected PhysicsVector _acceleration;
protected AxiomQuaternion _orientation;
protected PhysicsVector m_rotationalVelocity = PhysicsVector.Zero;
protected RigidBody rigidBody;
protected int m_PhysicsActorType;
private Boolean iscolliding = false;
internal string _name;
public BulletXActor(String name)
{
_name = name;
}
public override bool Stopped
{
get { return false; }
}
public override PhysicsVector Position
{
get { return _position; }
set
{
lock (BulletXScene.BulletXLock)
{
_position = value;
Translate();
}
}
}
public override PhysicsVector RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override PhysicsVector Velocity
{
get { return _velocity; }
set
{
lock (BulletXScene.BulletXLock)
{
//Static objects don' have linear velocity
if (_physical)
{
_velocity = value;
Speed();
}
else
{
_velocity = new PhysicsVector();
}
}
}
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override PhysicsVector Size
{
get { return _size; }
set
{
lock (BulletXScene.BulletXLock)
{
_size = value;
}
}
}
public override PhysicsVector Force
{
get { return PhysicsVector.Zero; }
}
public override PhysicsVector CenterOfMass
{
get { return PhysicsVector.Zero; }
}
public override PhysicsVector GeometricCenter
{
get { return PhysicsVector.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override PhysicsVector Acceleration
{
get { return _acceleration; }
}
public override AxiomQuaternion Orientation
{
get { return _orientation; }
set
{
lock (BulletXScene.BulletXLock)
{
_orientation = value;
ReOrient();
}
}
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(PhysicsVector axis)
{
}
public override float Mass
{
get { return ActorMass; }
}
public virtual float ActorMass
{
get { return 0; }
}
public override int PhysicsActorType
{
get { return (int) m_PhysicsActorType; }
set { m_PhysicsActorType = value; }
}
public RigidBody RigidBody
{
get { return rigidBody; }
}
public Vector3 RigidBodyPosition
{
get { return rigidBody.CenterOfMassPosition; }
}
public override bool IsPhysical
{
get { return _physical; }
set { _physical = value; }
}
public override bool Flying
{
get { return flying; }
set { flying = value; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public virtual void SetAcceleration(PhysicsVector accel)
{
lock (BulletXScene.BulletXLock)
{
_acceleration = accel;
}
}
public override bool Kinematic
{
get { return false; }
set { }
}
public override void AddForce(PhysicsVector force, bool pushforce)
{
}
public override void SetMomentum(PhysicsVector momentum)
{
}
internal virtual void ValidateHeight(float heighmapPositionValue)
{
}
internal virtual void UpdateKinetics()
{
}
#region Methods for updating values of RigidBody
protected internal void Translate()
{
Translate(_position);
}
protected internal void Translate(PhysicsVector _newPos)
{
Vector3 _translation;
_translation = BulletXMaths.PhysicsVectorToXnaVector3(_newPos) - rigidBody.CenterOfMassPosition;
rigidBody.Translate(_translation);
}
protected internal void Speed()
{
Speed(_velocity);
}
protected internal void Speed(PhysicsVector _newSpeed)
{
Vector3 _speed;
_speed = BulletXMaths.PhysicsVectorToXnaVector3(_newSpeed);
rigidBody.LinearVelocity = _speed;
}
protected internal void ReOrient()
{
ReOrient(_orientation);
}
protected internal void ReOrient(AxiomQuaternion _newOrient)
{
Quaternion _newOrientation;
_newOrientation = BulletXMaths.AxiomQuaternionToXnaQuaternion(_newOrient);
Matrix _comTransform = rigidBody.CenterOfMassTransform;
BulletXMaths.SetRotation(ref _comTransform, _newOrientation);
rigidBody.CenterOfMassTransform = _comTransform;
}
protected internal void ReSize()
{
ReSize(_size);
}
protected internal virtual void ReSize(PhysicsVector _newSize)
{
}
public virtual void ScheduleTerseUpdate()
{
base.RequestPhysicsterseUpdate();
}
#endregion
public override void CrossingFailure()
{
}
public override PhysicsVector PIDTarget { set { return; } }
public override bool PIDActive { set { return; } }
public override float PIDTau { set { return; } }
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
/// <summary>
/// PhysicsActor Character Class for BulletX
/// </summary>
public class BulletXCharacter : BulletXActor
{
public BulletXCharacter(BulletXScene parent_scene, PhysicsVector pos)
: this(String.Empty, parent_scene, pos)
{
}
public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos)
: this(avName, parent_scene, pos, new PhysicsVector(), new PhysicsVector(), new PhysicsVector(),
AxiomQuaternion.Identity)
{
}
public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
PhysicsVector size, PhysicsVector acceleration, AxiomQuaternion orientation)
: base(avName)
{
//This fields will be removed. They're temporal
float _sizeX = 0.5f;
float _sizeY = 0.5f;
float _sizeZ = 1.6f;
//.
_position = pos;
_velocity = velocity;
_size = size;
//---
_size.X = _sizeX;
_size.Y = _sizeY;
_size.Z = _sizeZ;
//.
_acceleration = acceleration;
_orientation = orientation;
_physical = true;
float _mass = 50.0f; //This depends of avatar's dimensions
//For RigidBody Constructor. The next values might change
float _linearDamping = 0.0f;
float _angularDamping = 0.0f;
float _friction = 0.5f;
float _restitution = 0.0f;
Matrix _startTransform = Matrix.Identity;
Matrix _centerOfMassOffset = Matrix.Identity;
lock (BulletXScene.BulletXLock)
{
_startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
//CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(1.0f, 1.0f, 1.60f));
//For now, like ODE, collisionShape = sphere of radious = 1.0
CollisionShape _collisionShape = new SphereShape(1.0f);
DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
Vector3 _localInertia = new Vector3();
_collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
rigidBody =
new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
_friction, _restitution);
//rigidBody.ActivationState = ActivationState.DisableDeactivation;
//It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
Vector3 _vDebugTranslation;
_vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
rigidBody.Translate(_vDebugTranslation);
parent_scene.ddWorld.AddRigidBody(rigidBody);
}
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
public override PhysicsVector Position
{
get { return base.Position; }
set { base.Position = value; }
}
public override PhysicsVector Velocity
{
get { return base.Velocity; }
set { base.Velocity = value; }
}
public override PhysicsVector Size
{
get { return base.Size; }
set { base.Size = value; }
}
public override PhysicsVector Acceleration
{
get { return base.Acceleration; }
}
public override AxiomQuaternion Orientation
{
get { return base.Orientation; }
set { base.Orientation = value; }
}
public override bool Flying
{
get { return base.Flying; }
set { base.Flying = value; }
}
public override bool IsColliding
{
get { return base.IsColliding; }
set { base.IsColliding = value; }
}
public override bool Kinematic
{
get { return base.Kinematic; }
set { base.Kinematic = value; }
}
public override void SetAcceleration(PhysicsVector accel)
{
base.SetAcceleration(accel);
}
public override void AddForce(PhysicsVector force, bool pushforce)
{
base.AddForce(force, pushforce);
}
public override void SetMomentum(PhysicsVector momentum)
{
base.SetMomentum(momentum);
}
internal void Move(float timeStep)
{
Vector3 vec = new Vector3();
//At this point it's supossed that:
//_velocity == rigidBody.LinearVelocity
vec.X = _velocity.X;
vec.Y = _velocity.Y;
vec.Z = _velocity.Z;
if ((vec.X != 0.0f) || (vec.Y != 0.0f) || (vec.Z != 0.0f)) rigidBody.Activate();
if (flying)
{
//Antigravity with movement
if (_position.Z <= BulletXScene.HeightLevel0)
{
vec.Z += BulletXScene.Gravity*timeStep;
}
//Lowgravity with movement
else if ((_position.Z > BulletXScene.HeightLevel0)
&& (_position.Z <= BulletXScene.HeightLevel1))
{
vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
}
//Lowgravity with...
else if (_position.Z > BulletXScene.HeightLevel1)
{
if (vec.Z > 0) //no movement
vec.Z = BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
else
vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
}
}
rigidBody.LinearVelocity = vec;
}
//This validation is very basic
internal override void ValidateHeight(float heighmapPositionValue)
{
if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
{
Matrix m = rigidBody.WorldTransform;
Vector3 v3 = m.Translation;
v3.Z = heighmapPositionValue + _size.Z/2.0f;
m.Translation = v3;
rigidBody.WorldTransform = m;
//When an Avie touch the ground it's vertical velocity it's reduced to ZERO
Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
}
}
internal override void UpdateKinetics()
{
_position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
_velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
//Orientation it seems that it will be the default.
ReOrient();
}
}
/// <summary>
/// PhysicsActor Prim Class for BulletX
/// </summary>
public class BulletXPrim : BulletXActor
{
//Density it will depends of material.
//For now all prims have the same density, all prims are made of water. Be water my friend! :D
private const float _density = 1000.0f;
private BulletXScene _parent_scene;
private PhysicsVector m_prev_position = new PhysicsVector(0, 0, 0);
private bool m_lastUpdateSent = false;
//added by jed zhu
private IMesh _mesh;
public IMesh GetMesh() { return _mesh; }
public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector size,
AxiomQuaternion rotation, IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
: this(
primName, parent_scene, pos, new PhysicsVector(), size, new PhysicsVector(), rotation, mesh, pbs,
isPhysical)
{
}
public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
PhysicsVector size,
PhysicsVector acceleration, AxiomQuaternion rotation, IMesh mesh, PrimitiveBaseShape pbs,
bool isPhysical)
: base(primName)
{
if ((size.X == 0) || (size.Y == 0) || (size.Z == 0)) throw new Exception("Size 0");
if (rotation.Norm == 0f) rotation = AxiomQuaternion.Identity;
_position = pos;
_physical = isPhysical;
_velocity = _physical ? velocity : new PhysicsVector();
_size = size;
_acceleration = acceleration;
_orientation = rotation;
_parent_scene = parent_scene;
CreateRigidBody(parent_scene, mesh, pos, size);
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Prim; }
set { return; }
}
public override PhysicsVector Position
{
get { return base.Position; }
set { base.Position = value; }
}
public override PhysicsVector Velocity
{
get { return base.Velocity; }
set { base.Velocity = value; }
}
public override PhysicsVector Size
{
get { return _size; }
set
{
lock (BulletXScene.BulletXLock)
{
_size = value;
ReSize();
}
}
}
public override PhysicsVector Acceleration
{
get { return base.Acceleration; }
}
public override AxiomQuaternion Orientation
{
get { return base.Orientation; }
set { base.Orientation = value; }
}
public override float ActorMass
{
get
{
//For now all prims are boxes
return (_physical ? 1 : 0)*_density*_size.X*_size.Y*_size.Z;
}
}
public override bool IsPhysical
{
get { return base.IsPhysical; }
set
{
base.IsPhysical = value;
if (value)
{
//---
PhysicsPluginManager.PhysicsPluginMessage("Physical - Recreate", true);
//---
ReCreateRigidBody(_size);
}
else
{
//---
PhysicsPluginManager.PhysicsPluginMessage("Physical - SetMassProps", true);
//---
rigidBody.SetMassProps(Mass, new Vector3());
}
}
}
public override bool Flying
{
get { return base.Flying; }
set { base.Flying = value; }
}
public override bool IsColliding
{
get { return base.IsColliding; }
set { base.IsColliding = value; }
}
public override bool Kinematic
{
get { return base.Kinematic; }
set { base.Kinematic = value; }
}
public override void SetAcceleration(PhysicsVector accel)
{
lock (BulletXScene.BulletXLock)
{
_acceleration = accel;
}
}
public override void AddForce(PhysicsVector force, bool pushforce)
{
base.AddForce(force,pushforce);
}
public override void SetMomentum(PhysicsVector momentum)
{
base.SetMomentum(momentum);
}
internal override void ValidateHeight(float heighmapPositionValue)
{
if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
{
Matrix m = rigidBody.WorldTransform;
Vector3 v3 = m.Translation;
v3.Z = heighmapPositionValue + _size.Z/2.0f;
m.Translation = v3;
rigidBody.WorldTransform = m;
//When a Prim touch the ground it's vertical velocity it's reduced to ZERO
//Static objects don't have linear velocity
if (_physical)
Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
}
}
internal override void UpdateKinetics()
{
if (_physical) //Updates properties. Prim updates its properties physically
{
_position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
_velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
_orientation = BulletXMaths.XnaQuaternionToAxiomQuaternion(rigidBody.Orientation);
if ((Math.Abs(m_prev_position.X - _position.X) < 0.03)
&& (Math.Abs(m_prev_position.Y - _position.Y) < 0.03)
&& (Math.Abs(m_prev_position.Z - _position.Z) < 0.03))
{
if (!m_lastUpdateSent)
{
_velocity = new PhysicsVector(0, 0, 0);
base.ScheduleTerseUpdate();
m_lastUpdateSent = true;
}
}
else
{
m_lastUpdateSent = false;
base.ScheduleTerseUpdate();
}
m_prev_position = _position;
}
else //Doesn't updates properties. That's a cancel
{
Translate();
//Speed(); //<- Static objects don't have linear velocity
ReOrient();
}
}
#region Methods for updating values of RigidBody
protected internal void CreateRigidBody(BulletXScene parent_scene, IMesh mesh, PhysicsVector pos,
PhysicsVector size)
{
//For RigidBody Constructor. The next values might change
float _linearDamping = 0.0f;
float _angularDamping = 0.0f;
float _friction = 1.0f;
float _restitution = 0.0f;
Matrix _startTransform = Matrix.Identity;
Matrix _centerOfMassOffset = Matrix.Identity;
//added by jed zhu
_mesh = mesh;
lock (BulletXScene.BulletXLock)
{
_startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
//For now all prims are boxes
CollisionShape _collisionShape;
if (mesh == null)
{
_collisionShape = new BoxShape(BulletXMaths.PhysicsVectorToXnaVector3(size)/2.0f);
}
else
{
int iVertexCount = mesh.getVertexList().Count;
int[] indices = mesh.getIndexListAsInt();
Vector3[] v3Vertices = new Vector3[iVertexCount];
for (int i = 0; i < iVertexCount; i++)
{
PhysicsVector v = mesh.getVertexList()[i];
if (v != null) // Note, null has special meaning. See meshing code for details
v3Vertices[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
else
v3Vertices[i] = Vector3.Zero;
}
TriangleIndexVertexArray triMesh = new TriangleIndexVertexArray(indices, v3Vertices);
_collisionShape = new TriangleMeshShape(triMesh);
}
DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
Vector3 _localInertia = new Vector3();
if (_physical) _collisionShape.CalculateLocalInertia(Mass, out _localInertia); //Always when mass > 0
rigidBody =
new RigidBody(Mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
_friction, _restitution);
//rigidBody.ActivationState = ActivationState.DisableDeactivation;
//It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
Vector3 _vDebugTranslation;
_vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
rigidBody.Translate(_vDebugTranslation);
//---
parent_scene.ddWorld.AddRigidBody(rigidBody);
}
}
protected internal void ReCreateRigidBody(PhysicsVector size)
{
//There is a bug when trying to remove a rigidBody that is colliding with something..
try
{
_parent_scene.ddWorld.RemoveRigidBody(rigidBody);
}
catch (Exception ex)
{
BulletXScene.BulletXMessage(_parent_scene.is_ex_message + ex.Message, true);
rigidBody.ActivationState = ActivationState.DisableSimulation;
_parent_scene.AddForgottenRigidBody(rigidBody);
}
CreateRigidBody(_parent_scene, null, _position, size);
// Note, null for the meshing definitely is wrong. It's here for the moment to apease the compiler
if (_physical) Speed(); //Static objects don't have linear velocity
ReOrient();
GC.Collect();
}
protected internal override void ReSize(PhysicsVector _newSize)
{
//I wonder to know how to resize with a simple instruction in BulletX. It seems that for now there isn't
//so i have to do it manually. That's recreating rigidbody
ReCreateRigidBody(_newSize);
}
#endregion
}
/// <summary>
/// This Class manage a HeighField as a RigidBody. This is for to be added in the BulletXScene
/// </summary>
internal class BulletXPlanet
{
private PhysicsVector _staticPosition;
// private PhysicsVector _staticVelocity;
// private AxiomQuaternion _staticOrientation;
private float _mass;
// private BulletXScene _parentscene;
internal float[] _heightField;
private RigidBody _flatPlanet;
internal RigidBody RigidBody
{
get { return _flatPlanet; }
}
internal BulletXPlanet(BulletXScene parent_scene, float[] heightField)
{
_staticPosition = new PhysicsVector(BulletXScene.MaxXY/2, BulletXScene.MaxXY/2, 0);
// _staticVelocity = new PhysicsVector();
// _staticOrientation = AxiomQuaternion.Identity;
_mass = 0; //No active
// _parentscene = parent_scene;
_heightField = heightField;
float _linearDamping = 0.0f;
float _angularDamping = 0.0f;
float _friction = 0.5f;
float _restitution = 0.0f;
Matrix _startTransform = Matrix.Identity;
Matrix _centerOfMassOffset = Matrix.Identity;
lock (BulletXScene.BulletXLock)
{
try
{
_startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(_staticPosition);
CollisionShape _collisionShape =
new HeightfieldTerrainShape(BulletXScene.MaxXY, BulletXScene.MaxXY, _heightField,
(float) BulletXScene.MaxZ, 2, true, false);
DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
Vector3 _localInertia = new Vector3();
//_collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
_flatPlanet =
new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping,
_angularDamping, _friction, _restitution);
//It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
Vector3 _vDebugTranslation;
_vDebugTranslation = _startTransform.Translation - _flatPlanet.CenterOfMassPosition;
_flatPlanet.Translate(_vDebugTranslation);
parent_scene.ddWorld.AddRigidBody(_flatPlanet);
}
catch (Exception ex)
{
BulletXScene.BulletXMessage(ex.Message, true);
}
}
BulletXScene.BulletXMessage("BulletXPlanet created.", false);
}
internal float HeightValue(Vector3 position)
{
int li_x, li_y;
float height;
li_x = (int) Math.Round(position.X);
if (li_x < 0) li_x = 0;
if (li_x >= BulletXScene.MaxXY) li_x = BulletXScene.MaxXY - 1;
li_y = (int) Math.Round(position.Y);
if (li_y < 0) li_y = 0;
if (li_y >= BulletXScene.MaxXY) li_y = BulletXScene.MaxXY - 1;
height = ((HeightfieldTerrainShape) _flatPlanet.CollisionShape).getHeightFieldValue(li_x, li_y);
if (height < 0) height = 0;
else if (height > BulletXScene.MaxZ) height = BulletXScene.MaxZ;
return height;
}
}
}
|