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
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
|
/*
* 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 OpenSimulator 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.
*/
//#define USE_DRAWSTUFF
//#define SPAM
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System.Diagnostics;
using log4net;
using Nini.Config;
using OdeAPI;
#if USE_DRAWSTUFF
using ODEDrawstuff;
#endif
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using OpenMetaverse;
namespace OpenSim.Region.Physics.OdePlugin
{
public enum StatusIndicators : int
{
Generic = 0,
Start = 1,
End = 2
}
public struct sCollisionData
{
public uint ColliderLocalId;
public uint CollidedWithLocalId;
public int NumberOfCollisions;
public int CollisionType;
public int StatusIndicator;
public int lastframe;
}
[Flags]
public enum CollisionCategories : int
{
Disabled = 0,
Geom = 0x00000001,
Body = 0x00000002,
Space = 0x00000004,
Character = 0x00000008,
Land = 0x00000010,
Water = 0x00000020,
Wind = 0x00000040,
Sensor = 0x00000080,
Selected = 0x00000100
}
/// <summary>
/// Material type for a primitive
/// </summary>
public enum Material : int
{
/// <summary></summary>
Stone = 0,
/// <summary></summary>
Metal = 1,
/// <summary></summary>
Glass = 2,
/// <summary></summary>
Wood = 3,
/// <summary></summary>
Flesh = 4,
/// <summary></summary>
Plastic = 5,
/// <summary></summary>
Rubber = 6,
light = 7 // compatibility with old viewers
}
public enum changes : int
{
Add = 0, // arg null. finishs the prim creation. should be used internally only ( to remove later ?)
Remove,
Link, // arg AuroraODEPrim new parent prim or null to delink. Makes the prim part of a object with prim parent as root
// or removes from a object if arg is null
DeLink,
Position, // arg Vector3 new position in world coords. Changes prim position. Prim must know if it is root or child
Orientation, // arg Quaternion new orientation in world coords. Changes prim position. Prim must know it it is root or child
PosOffset, // not in use
// arg Vector3 new position in local coords. Changes prim position in object
OriOffset, // not in use
// arg Vector3 new position in local coords. Changes prim position in object
Velocity,
AngVelocity,
Acceleration,
Force,
Torque,
AddForce,
AddAngForce,
AngLock,
Size,
Shape,
CollidesWater,
VolumeDtc,
Physical,
Selected,
disabled,
building,
VehicleType,
VehicleFloatParam,
VehicleVectorParam,
VehicleRotationParam,
VehicleFlags,
Null //keep this last used do dim the methods array. does nothing but pulsing the prim
}
public struct ODEchangeitem
{
public PhysicsActor actor;
public OdeCharacter character;
public changes what;
public Object arg;
}
public class OdeScene : PhysicsScene
{
private readonly ILog m_log;
// private Dictionary<string, sCollisionData> m_storedCollisions = new Dictionary<string, sCollisionData>();
private int threadid = 0;
private Random fluidRandomizer = new Random(Environment.TickCount);
const d.ContactFlags comumContactFlags = d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM |d.ContactFlags.Approx1 | d.ContactFlags.Bounce;
const float comumContactERP = 0.6f;
const float comumSoftContactERP = 0.1f;
const float comumContactCFM = 0.0001f;
float frictionScale = 1.0f;
float frictionMovementMult = 0.3f;
float TerrainBounce = 0.3f;
float TerrainFriction = 0.3f;
public float AvatarBounce = 0.3f;
public float AvatarFriction = 0;// 0.9f * 0.5f;
private const uint m_regionWidth = Constants.RegionSize;
private const uint m_regionHeight = Constants.RegionSize;
public float ODE_STEPSIZE = 0.020f;
private float metersInSpace = 25.6f;
private float m_timeDilation = 1.0f;
public float gravityx = 0f;
public float gravityy = 0f;
public float gravityz = -9.8f;
private float waterlevel = 0f;
private int framecount = 0;
internal IntPtr WaterGeom;
public float avPIDD = 3200f; // make it visible
public float avPIDP = 1400f; // make it visible
private float avCapRadius = 0.37f;
private float avDensity = 3f;
private float avMovementDivisorWalk = 1.3f;
private float avMovementDivisorRun = 0.8f;
private float minimumGroundFlightOffset = 3f;
public float maximumMassObject = 10000.01f;
public bool meshSculptedPrim = true;
public bool forceSimplePrimMeshing = false;
public float meshSculptLOD = 32;
public float MeshSculptphysicalLOD = 16;
public float geomDefaultDensity = 10.000006836f;
public int geomContactPointsStartthrottle = 3;
public int geomUpdatesPerThrottledUpdate = 15;
public float bodyPIDD = 35f;
public float bodyPIDG = 25;
public int geomCrossingFailuresBeforeOutofbounds = 6;
public int bodyFramesAutoDisable = 20;
private float[] _watermap;
private bool m_filterCollisions = true;
private d.NearCallback nearCallback;
private readonly HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
private readonly HashSet<OdePrim> _prims = new HashSet<OdePrim>();
private readonly HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
private readonly Object _taintedCharacterLock = new Object();
private readonly HashSet<OdeCharacter> _taintedCharacterH = new HashSet<OdeCharacter>(); // faster verification of repeated character taints
private readonly Queue<OdeCharacter> _taintedCharacterQ = new Queue<OdeCharacter>(); // character taints
public OpenSim.Framework.LocklessQueue<ODEchangeitem> ChangesQueue = new OpenSim.Framework.LocklessQueue<ODEchangeitem>();
/// <summary>
/// A list of actors that should receive collision events.
/// </summary>
private readonly List<PhysicsActor> _collisionEventPrim = new List<PhysicsActor>();
private readonly HashSet<OdeCharacter> _badCharacter = new HashSet<OdeCharacter>();
public Dictionary<IntPtr, String> geom_name_map = new Dictionary<IntPtr, String>();
public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
private float contactsurfacelayer = 0.002f;
private int contactsPerCollision = 80;
internal IntPtr ContactgeomsArray = IntPtr.Zero;
private IntPtr GlobalContactsArray = IntPtr.Zero;
const int maxContactsbeforedeath = 4000;
private volatile int m_global_contactcount = 0;
private readonly IntPtr contactgroup;
public ContactData[] m_materialContactsData = new ContactData[8];
private readonly DoubleDictionary<Vector3, IntPtr, IntPtr> RegionTerrain = new DoubleDictionary<Vector3, IntPtr, IntPtr>();
private readonly Dictionary<IntPtr, float[]> TerrainHeightFieldHeights = new Dictionary<IntPtr, float[]>();
private readonly Dictionary<IntPtr, GCHandle> TerrainHeightFieldHeightsHandlers = new Dictionary<IntPtr, GCHandle>();
private int m_physicsiterations = 10;
private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
private readonly PhysicsActor PANull = new NullPhysicsActor();
private float step_time = 0.0f;
public IntPtr world;
private uint obj2LocalID = 0;
private OdeCharacter cc1;
private OdePrim cp1;
private OdeCharacter cc2;
private OdePrim cp2;
// split the spaces acording to contents type
// ActiveSpace contains characters and active prims
// StaticSpace contains land and other that is mostly static in enviroment
// this can contain subspaces, like the grid in staticspace
// as now space only contains this 2 top spaces
public IntPtr TopSpace; // the global space
public IntPtr ActiveSpace; // space for active prims
public IntPtr StaticSpace; // space for the static things around
// some speedup variables
private int spaceGridMaxX;
private int spaceGridMaxY;
private float spacesPerMeter;
// split static geometry collision into a grid as before
private IntPtr[,] staticPrimspace;
private Object OdeLock;
private static Object SimulationLock;
public IMesher mesher;
private IConfigSource m_config;
public bool physics_logging = false;
public int physics_logging_interval = 0;
public bool physics_logging_append_existing_logfile = false;
private Vector3 m_worldOffset = Vector3.Zero;
public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
private PhysicsScene m_parentScene = null;
private ODERayCastRequestManager m_rayCastManager;
/* maybe needed if ode uses tls
private void checkThread()
{
int th = Thread.CurrentThread.ManagedThreadId;
if(th != threadid)
{
threadid = th;
d.AllocateODEDataForThread(~0U);
}
}
*/
/// <summary>
/// Initiailizes the scene
/// Sets many properties that ODE requires to be stable
/// These settings need to be tweaked 'exactly' right or weird stuff happens.
/// </summary>
public OdeScene(string sceneIdentifier)
{
m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.ToString() + "." + sceneIdentifier);
// checkThread();
Name = sceneIdentifier;
OdeLock = new Object();
SimulationLock = new Object();
nearCallback = near;
m_rayCastManager = new ODERayCastRequestManager(this);
lock (OdeLock)
{
// Create the world and the first space
try
{
world = d.WorldCreate();
TopSpace = d.HashSpaceCreate(IntPtr.Zero);
// now the major subspaces
ActiveSpace = d.HashSpaceCreate(TopSpace);
StaticSpace = d.HashSpaceCreate(TopSpace);
}
catch
{
// i must RtC#FM
}
d.HashSpaceSetLevels(TopSpace, -2, 8); // cell sizes from .25 to 256 ?? need check what this really does
d.HashSpaceSetLevels(ActiveSpace, -2, 8);
d.HashSpaceSetLevels(StaticSpace, -2, 8);
// demote to second level
d.SpaceSetSublevel(ActiveSpace, 1);
d.SpaceSetSublevel(StaticSpace, 1);
contactgroup = d.JointGroupCreate(0);
//contactgroup
d.WorldSetAutoDisableFlag(world, false);
#if USE_DRAWSTUFF
Thread viewthread = new Thread(new ParameterizedThreadStart(startvisualization));
viewthread.Start();
#endif
}
_watermap = new float[258 * 258];
}
#if USE_DRAWSTUFF
public void startvisualization(object o)
{
ds.Functions fn;
fn.version = ds.VERSION;
fn.start = new ds.CallbackFunction(start);
fn.step = new ds.CallbackFunction(step);
fn.command = new ds.CallbackFunction(command);
fn.stop = null;
fn.path_to_textures = "./textures";
string[] args = new string[0];
ds.SimulationLoop(args.Length, args, 352, 288, ref fn);
}
#endif
// Initialize the mesh plugin
// public override void Initialise(IMesher meshmerizer, IConfigSource config, RegionInfo region )
public override void Initialise(IMesher meshmerizer, IConfigSource config)
{
// checkThread();
mesher = meshmerizer;
m_config = config;
// m_log.WarnFormat("ODE configuration: {0}", d.GetConfiguration("ODE"));
/*
if (region != null)
{
WorldExtents.X = region.RegionSizeX;
WorldExtents.Y = region.RegionSizeY;
}
*/
// Defaults
avPIDD = 2200.0f;
avPIDP = 900.0f;
int contactsPerCollision = 80;
if (m_config != null)
{
IConfig physicsconfig = m_config.Configs["ODEPhysicsSettings"];
if (physicsconfig != null)
{
gravityx = physicsconfig.GetFloat("world_gravityx", 0f);
gravityy = physicsconfig.GetFloat("world_gravityy", 0f);
gravityz = physicsconfig.GetFloat("world_gravityz", -9.8f);
metersInSpace = physicsconfig.GetFloat("meters_in_small_space", 29.9f);
contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", contactsurfacelayer);
ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", 0.020f);
m_physicsiterations = physicsconfig.GetInt("world_internal_steps_without_collisions", 10);
avDensity = physicsconfig.GetFloat("av_density", avDensity);
avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f);
avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f);
avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f);
contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80);
geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 3);
geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15);
geomCrossingFailuresBeforeOutofbounds = physicsconfig.GetInt("geom_crossing_failures_before_outofbounds", 5);
geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", 10.000006836f);
bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", 20);
bodyPIDD = physicsconfig.GetFloat("body_pid_derivative", 35f);
bodyPIDG = physicsconfig.GetFloat("body_pid_gain", 25f);
forceSimplePrimMeshing = physicsconfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
meshSculptedPrim = physicsconfig.GetBoolean("mesh_sculpted_prim", true);
meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f);
MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f);
m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false);
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
avPIDD = physicsconfig.GetFloat("av_pid_derivative_linux", 2200.0f);
avPIDP = physicsconfig.GetFloat("av_pid_proportional_linux", 900.0f);
}
else
{
avPIDD = physicsconfig.GetFloat("av_pid_derivative_win", 2200.0f);
avPIDP = physicsconfig.GetFloat("av_pid_proportional_win", 900.0f);
}
physics_logging = physicsconfig.GetBoolean("physics_logging", false);
physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", 3f);
maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", 10000.01f);
}
}
ContactgeomsArray = Marshal.AllocHGlobal(contactsPerCollision * d.ContactGeom.unmanagedSizeOf);
GlobalContactsArray = GlobalContactsArray = Marshal.AllocHGlobal(maxContactsbeforedeath * d.Contact.unmanagedSizeOf);
m_materialContactsData[(int)Material.Stone].mu = frictionScale * 0.8f;
m_materialContactsData[(int)Material.Stone].bounce = 0.4f;
m_materialContactsData[(int)Material.Metal].mu = frictionScale * 0.3f;
m_materialContactsData[(int)Material.Metal].bounce = 0.4f;
m_materialContactsData[(int)Material.Glass].mu = frictionScale * 0.2f;
m_materialContactsData[(int)Material.Glass].bounce = 0.7f;
m_materialContactsData[(int)Material.Wood].mu = frictionScale * 0.6f;
m_materialContactsData[(int)Material.Wood].bounce = 0.5f;
m_materialContactsData[(int)Material.Flesh].mu = frictionScale * 0.9f;
m_materialContactsData[(int)Material.Flesh].bounce = 0.3f;
m_materialContactsData[(int)Material.Plastic].mu = frictionScale * 0.4f;
m_materialContactsData[(int)Material.Plastic].bounce = 0.7f;
m_materialContactsData[(int)Material.Rubber].mu = frictionScale * 0.9f;
m_materialContactsData[(int)Material.Rubber].bounce = 0.95f;
m_materialContactsData[(int)Material.light].mu = 0.0f;
m_materialContactsData[(int)Material.light].bounce = 0.0f;
TerrainFriction *= frictionScale;
// AvatarFriction *= frictionScale;
// Set the gravity,, don't disable things automatically (we set it explicitly on some things)
d.WorldSetGravity(world, gravityx, gravityy, gravityz);
d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
d.WorldSetLinearDamping(world, 0.001f);
d.WorldSetAngularDamping(world, 0.001f);
d.WorldSetAngularDampingThreshold(world, 0f);
d.WorldSetLinearDampingThreshold(world, 0f);
d.WorldSetMaxAngularSpeed(world, 256f);
d.WorldSetCFM(world,1e-6f); // a bit harder than default
//d.WorldSetCFM(world, 1e-4f); // a bit harder than default
d.WorldSetERP(world, 0.6f); // higher than original
// Set how many steps we go without running collision testing
// This is in addition to the step size.
// Essentially Steps * m_physicsiterations
d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
d.WorldSetContactMaxCorrectingVel(world, 100.0f);
spacesPerMeter = 1 / metersInSpace;
spaceGridMaxX = (int)(WorldExtents.X * spacesPerMeter);
spaceGridMaxY = (int)(WorldExtents.Y * spacesPerMeter);
staticPrimspace = new IntPtr[spaceGridMaxX, spaceGridMaxY];
// create all spaces now
int i, j;
IntPtr newspace;
for (i = 0; i < spaceGridMaxX; i++)
for (j = 0; j < spaceGridMaxY; j++)
{
newspace = d.HashSpaceCreate(StaticSpace);
d.GeomSetCategoryBits(newspace, (int)CollisionCategories.Space);
waitForSpaceUnlock(newspace);
d.SpaceSetSublevel(newspace, 2);
d.HashSpaceSetLevels(newspace, -2, 8);
staticPrimspace[i, j] = newspace;
}
// let this now be real maximum values
spaceGridMaxX--;
spaceGridMaxY--;
}
internal void waitForSpaceUnlock(IntPtr space)
{
//if (space != IntPtr.Zero)
//while (d.SpaceLockQuery(space)) { } // Wait and do nothing
}
#region Collision Detection
// sets a global contact for a joint for contactgeom , and base contact description)
private IntPtr CreateContacJoint(ref d.ContactGeom contactGeom, float mu, float bounce, bool softerp)
{
if (GlobalContactsArray == IntPtr.Zero || m_global_contactcount >= maxContactsbeforedeath)
return IntPtr.Zero;
d.Contact newcontact = new d.Contact();
newcontact.geom.depth = contactGeom.depth;
newcontact.geom.g1 = contactGeom.g1;
newcontact.geom.g2 = contactGeom.g2;
newcontact.geom.pos = contactGeom.pos;
newcontact.geom.normal = contactGeom.normal;
newcontact.geom.side1 = contactGeom.side1;
newcontact.geom.side2 = contactGeom.side2;
// this needs bounce also
newcontact.surface.mode = comumContactFlags;
newcontact.surface.mu = mu;
newcontact.surface.bounce = bounce;
newcontact.surface.soft_cfm = comumContactCFM;
if (softerp)
newcontact.surface.soft_erp = comumSoftContactERP;
else
newcontact.surface.soft_erp = comumContactERP;
IntPtr contact = new IntPtr(GlobalContactsArray.ToInt64() + (Int64)(m_global_contactcount * d.Contact.unmanagedSizeOf));
Marshal.StructureToPtr(newcontact, contact, true);
return d.JointCreateContactPtr(world, contactgroup, contact);
}
/// <summary>
/// This is our near callback. A geometry is near a body
/// </summary>
/// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
/// <param name="g1">a geometry or space</param>
/// <param name="g2">another geometry or space</param>
///
private bool GetCurContactGeom(int index, ref d.ContactGeom newcontactgeom)
{
if (ContactgeomsArray == IntPtr.Zero || index >= contactsPerCollision)
return false;
IntPtr contactptr = new IntPtr(ContactgeomsArray.ToInt64() + (Int64)(index * d.ContactGeom.unmanagedSizeOf));
newcontactgeom = (d.ContactGeom)Marshal.PtrToStructure(contactptr, typeof(d.ContactGeom));
return true;
}
private void near(IntPtr space, IntPtr g1, IntPtr g2)
{
// no lock here! It's invoked from within Simulate(), which is thread-locked
if (m_global_contactcount >= maxContactsbeforedeath)
return;
// Test if we're colliding a geom with a space.
// If so we have to drill down into the space recursively
if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
return;
if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
{
// We'll be calling near recursivly if one
// of them is a space to find all of the
// contact points in the space
try
{
d.SpaceCollide2(g1, g2, IntPtr.Zero, nearCallback);
}
catch (AccessViolationException)
{
m_log.Warn("[PHYSICS]: Unable to collide test a space");
return;
}
//here one should check collisions of geoms inside a space
// but on each space we only should have geoms that not colide amoung each other
// so we don't dig inside spaces
return;
}
// get geom bodies to check if we already a joint contact
// guess this shouldn't happen now
IntPtr b1 = d.GeomGetBody(g1);
IntPtr b2 = d.GeomGetBody(g2);
// d.GeomClassID id = d.GeomGetClass(g1);
// Figure out how many contact points we have
int count = 0;
try
{
// Colliding Geom To Geom
// This portion of the function 'was' blatantly ripped off from BoxStack.cs
if (g1 == g2)
return; // Can't collide with yourself
if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
return;
count = d.CollidePtr(g1, g2, (contactsPerCollision & 0xffff), ContactgeomsArray, d.ContactGeom.unmanagedSizeOf);
}
catch (SEHException)
{
m_log.Error("[PHYSICS]: The Operating system shut down ODE because of corrupt memory. This could be a result of really irregular terrain. If this repeats continuously, restart using Basic Physics and terrain fill your terrain. Restarting the sim.");
// ode.drelease(world);
base.TriggerPhysicsBasedRestart();
}
catch (Exception e)
{
m_log.WarnFormat("[PHYSICS]: Unable to collide test an object: {0}", e.Message);
return;
}
// id contacts done
if (count == 0)
return;
// try get physical actors
PhysicsActor p1;
PhysicsActor p2;
if (!actor_name_map.TryGetValue(g1, out p1))
{
p1 = PANull;
}
if (!actor_name_map.TryGetValue(g2, out p2))
{
p2 = PANull;
}
// update actors collision score
if (p1.CollisionScore >= float.MaxValue - count)
p1.CollisionScore = 0;
p1.CollisionScore += count;
if (p2.CollisionScore >= float.MaxValue - count)
p2.CollisionScore = 0;
p2.CollisionScore += count;
// get first contact
d.ContactGeom curContact = new d.ContactGeom();
if (!GetCurContactGeom(0, ref curContact))
return;
// for now it's the one with max depth
ContactPoint maxDepthContact = new ContactPoint(
new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
curContact.depth
);
// do volume detection case
if (
(p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect) ||
(p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect))
{
collision_accounting_events(p1, p2, maxDepthContact);
return;
}
// big messy collision analises
float mu = 0;
float bounce = 0;
ContactData contactdata1;
ContactData contactdata2;
bool erpSoft = false;
String name = null;
bool dop1foot = false;
bool dop2foot = false;
bool ignore = false;
switch (p1.PhysicsActorType)
{
case (int)ActorTypes.Agent:
switch (p2.PhysicsActorType)
{
case (int)ActorTypes.Agent:
contactdata1 = p1.ContactData;
contactdata2 = p2.ContactData;
bounce = contactdata1.bounce * contactdata2.bounce;
mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
if ((Math.Abs(p2.Velocity.X - p1.Velocity.X) > 0.1f || Math.Abs(p2.Velocity.Y - p1.Velocity.Y) > 0.1f))
mu *= frictionMovementMult;
p1.CollidingObj = true;
p2.CollidingObj = true;
break;
case (int)ActorTypes.Prim:
contactdata1 = p1.ContactData;
contactdata2 = p2.ContactData;
bounce = contactdata1.bounce * contactdata2.bounce;
mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
if ((Math.Abs(p2.Velocity.X - p1.Velocity.X) > 0.1f || Math.Abs(p2.Velocity.Y - p1.Velocity.Y) > 0.1f))
mu *= frictionMovementMult;
if (p2.Velocity.LengthSquared() > 0.0f)
p2.CollidingObj = true;
dop1foot = true;
break;
default:
ignore=true; // avatar to terrain and water ignored
break;
}
break;
case (int)ActorTypes.Prim:
switch (p2.PhysicsActorType)
{
case (int)ActorTypes.Agent:
contactdata1 = p1.ContactData;
contactdata2 = p2.ContactData;
bounce = contactdata1.bounce * contactdata2.bounce;
mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
if ((Math.Abs(p2.Velocity.X - p1.Velocity.X) > 0.1f || Math.Abs(p2.Velocity.Y - p1.Velocity.Y) > 0.1f))
mu *= frictionMovementMult;
dop2foot = true;
if (p1.Velocity.LengthSquared() > 0.0f)
p1.CollidingObj = true;
break;
case (int)ActorTypes.Prim:
if ((p1.Velocity - p2.Velocity).LengthSquared() > 0.0f)
{
p1.CollidingObj = true;
p2.CollidingObj = true;
}
contactdata1 = p1.ContactData;
contactdata2 = p2.ContactData;
bounce = contactdata1.bounce * contactdata2.bounce;
erpSoft = true;
mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
if ((Math.Abs(p2.Velocity.X - p1.Velocity.X) > 0.1f || Math.Abs(p2.Velocity.Y - p1.Velocity.Y) > 0.1f))
mu *= frictionMovementMult;
break;
default:
if (geom_name_map.TryGetValue(g2, out name))
{
if (name == "Terrain")
{
erpSoft = true;
contactdata1 = p1.ContactData;
bounce = contactdata1.bounce * TerrainBounce;
mu = (float)Math.Sqrt(contactdata1.mu * TerrainFriction);
if (Math.Abs(p1.Velocity.X) > 0.1f || Math.Abs(p1.Velocity.Y) > 0.1f)
mu *= frictionMovementMult;
p1.CollidingGround = true;
}
else if (name == "Water")
{
erpSoft = true;
}
}
else
ignore=true;
break;
}
break;
default:
if (geom_name_map.TryGetValue(g1, out name))
{
if (name == "Terrain")
{
if (p2.PhysicsActorType == (int)ActorTypes.Prim)
{
erpSoft = true;
p2.CollidingGround = true;
contactdata2 = p2.ContactData;
bounce = contactdata2.bounce * TerrainBounce;
mu = (float)Math.Sqrt(contactdata2.mu * TerrainFriction);
if (Math.Abs(p2.Velocity.X) > 0.1f || Math.Abs(p2.Velocity.Y) > 0.1f)
mu *= frictionMovementMult;
}
else
ignore = true;
}
else if (name == "Water" &&
(p2.PhysicsActorType == (int)ActorTypes.Prim || p2.PhysicsActorType == (int)ActorTypes.Agent))
{
erpSoft = true;
}
}
else
ignore = true;
break;
}
if (ignore)
return;
IntPtr Joint;
int i = 0;
while(true)
{
if (dop1foot && (p1.Position.Z - curContact.pos.Z) > (p1.Size.Z - avCapRadius) * 0.5f)
p1.IsColliding = true;
if (dop2foot && (p2.Position.Z - curContact.pos.Z) > (p2.Size.Z - avCapRadius) * 0.5f)
p2.IsColliding = true;
Joint = CreateContacJoint(ref curContact, mu, bounce, erpSoft);
d.JointAttach(Joint, b1, b2);
if (++m_global_contactcount >= maxContactsbeforedeath)
break;
if(++i >= count)
break;
if (!GetCurContactGeom(i, ref curContact))
break;
if (curContact.depth > maxDepthContact.PenetrationDepth)
{
maxDepthContact.Position.X = curContact.pos.X;
maxDepthContact.Position.Y = curContact.pos.Y;
maxDepthContact.Position.Z = curContact.pos.Z;
maxDepthContact.SurfaceNormal.X = curContact.normal.X;
maxDepthContact.SurfaceNormal.Y = curContact.normal.Y;
maxDepthContact.SurfaceNormal.Z = curContact.normal.Z;
maxDepthContact.PenetrationDepth = curContact.depth;
}
}
collision_accounting_events(p1, p2, maxDepthContact);
/*
if (notskipedcount > geomContactPointsStartthrottle)
{
// If there are more then 3 contact points, it's likely
// that we've got a pile of objects, so ...
// We don't want to send out hundreds of terse updates over and over again
// so lets throttle them and send them again after it's somewhat sorted out.
this needs checking so out for now
if (b1 != IntPtr.Zero)
p1.ThrottleUpdates = true;
if (b2 != IntPtr.Zero)
p2.ThrottleUpdates = true;
}
*/
}
private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
{
// obj1LocalID = 0;
//returncollisions = false;
obj2LocalID = 0;
//ctype = 0;
//cStartStop = 0;
if (!(p2.SubscribedEvents() || p1.SubscribedEvents()))
return;
switch ((ActorTypes)p1.PhysicsActorType)
{
case ActorTypes.Agent:
cc1 = (OdeCharacter)p1;
switch ((ActorTypes)p2.PhysicsActorType)
{
case ActorTypes.Agent:
cc2 = (OdeCharacter)p2;
obj2LocalID = cc2.m_localID;
if (p2.SubscribedEvents())
cc2.AddCollisionEvent(cc1.m_localID, contact);
break;
case ActorTypes.Prim:
if (p2 is OdePrim)
{
cp2 = (OdePrim)p2;
obj2LocalID = cp2.m_localID;
if (p2.SubscribedEvents())
cp2.AddCollisionEvent(cc1.m_localID, contact);
}
break;
case ActorTypes.Ground:
case ActorTypes.Unknown:
default:
obj2LocalID = 0;
break;
}
if (p1.SubscribedEvents())
{
contact.SurfaceNormal = -contact.SurfaceNormal;
cc1.AddCollisionEvent(obj2LocalID, contact);
}
break;
case ActorTypes.Prim:
if (p1 is OdePrim)
{
cp1 = (OdePrim)p1;
// obj1LocalID = cp2.m_localID;
switch ((ActorTypes)p2.PhysicsActorType)
{
case ActorTypes.Agent:
if (p2 is OdeCharacter)
{
cc2 = (OdeCharacter)p2;
obj2LocalID = cc2.m_localID;
if (p2.SubscribedEvents())
cc2.AddCollisionEvent(cp1.m_localID, contact);
}
break;
case ActorTypes.Prim:
if (p2 is OdePrim)
{
cp2 = (OdePrim)p2;
obj2LocalID = cp2.m_localID;
if (p2.SubscribedEvents())
cp2.AddCollisionEvent(cp1.m_localID, contact);
}
break;
case ActorTypes.Ground:
case ActorTypes.Unknown:
default:
obj2LocalID = 0;
break;
}
if (p1.SubscribedEvents())
{
contact.SurfaceNormal = -contact.SurfaceNormal;
cp1.AddCollisionEvent(obj2LocalID, contact);
}
}
break;
}
}
/// <summary>
/// This is our collision testing routine in ODE
/// </summary>
/// <param name="timeStep"></param>
private void collision_optimized()
{
// _perloopContact.Clear();
// clear characts IsColliding until we do it some other way
lock (_characters)
{
foreach (OdeCharacter chr in _characters)
{
// this are odd checks if they are needed something is wrong elsewhere
// keep for now
if (chr == null)
continue;
if (chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero)
continue;
chr.IsColliding = false;
// chr.CollidingGround = false; not done here
chr.CollidingObj = false;
}
}
// now let ode do its job
// colide active things amoung them
int st = Util.EnvironmentTickCount();
int ta;
int ts;
try
{
d.SpaceCollide(ActiveSpace, IntPtr.Zero, nearCallback);
}
catch (AccessViolationException)
{
m_log.Warn("[PHYSICS]: Unable to Active space collide");
}
ta = Util.EnvironmentTickCountSubtract(st);
// then active things with static enviroment
try
{
d.SpaceCollide2(ActiveSpace,StaticSpace, IntPtr.Zero, nearCallback);
}
catch (AccessViolationException)
{
m_log.Warn("[PHYSICS]: Unable to Active to static space collide");
}
ts = Util.EnvironmentTickCountSubtract(st);
// _perloopContact.Clear();
}
#endregion
public float GetTerrainHeightAtXY(float x, float y)
{
// assumes 1m size grid and constante size square regions
// region offset in mega position
int offsetX = ((int)(x / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
int offsetY = ((int)(y / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
IntPtr heightFieldGeom = IntPtr.Zero;
// get region map
if (!RegionTerrain.TryGetValue(new Vector3(offsetX, offsetY, 0), out heightFieldGeom))
return 0f;
if (heightFieldGeom == IntPtr.Zero)
return 0f;
if (!TerrainHeightFieldHeights.ContainsKey(heightFieldGeom))
return 0f;
// TerrainHeightField for ODE as offset 1m
x += 1f - offsetX;
y += 1f - offsetY;
// make position fit into array
if (x < 0)
x = 0;
if (y < 0)
y = 0;
// integer indexs
int ix;
int iy;
// interpolators offset
float dx;
float dy;
int regsize = (int)Constants.RegionSize + 2; // map size see setterrain
// we still have square fixed size regions
// also flip x and y because of how map is done for ODE fliped axis
// so ix,iy,dx and dy are inter exchanged
if (x < regsize - 1)
{
iy = (int)x;
dy = x - (float)iy;
}
else // out world use external height
{
iy = regsize - 1;
dy = 0;
}
if (y < regsize - 1)
{
ix = (int)y;
dx = y - (float)ix;
}
else
{
ix = regsize - 1;
dx = 0;
}
float h0;
float h1;
float h2;
iy *= regsize;
iy += ix; // all indexes have iy + ix
float[] heights = TerrainHeightFieldHeights[heightFieldGeom];
if ((dx + dy) <= 1.0f)
{
h0 = ((float)heights[iy]); // 0,0 vertice
h1 = (((float)heights[iy + 1]) - h0) * dx; // 1,0 vertice minus 0,0
h2 = (((float)heights[iy + regsize]) - h0) * dy; // 0,1 vertice minus 0,0
}
else
{
h0 = ((float)heights[iy + regsize + 1]); // 1,1 vertice
h1 = (((float)heights[iy + 1]) - h0) * (1 - dy); // 1,1 vertice minus 1,0
h2 = (((float)heights[iy + regsize]) - h0) * (1 - dx); // 1,1 vertice minus 0,1
}
return h0 + h1 + h2;
}
/// <summary>
/// Add actor to the list that should receive collision events in the simulate loop.
/// </summary>
/// <param name="obj"></param>
public void AddCollisionEventReporting(PhysicsActor obj)
{
lock (_collisionEventPrim)
{
if (!_collisionEventPrim.Contains(obj))
_collisionEventPrim.Add(obj);
}
}
/// <summary>
/// Remove actor from the list that should receive collision events in the simulate loop.
/// </summary>
/// <param name="obj"></param>
public void RemoveCollisionEventReporting(PhysicsActor obj)
{
lock (_collisionEventPrim)
{
if (_collisionEventPrim.Contains(obj))
_collisionEventPrim.Remove(obj);
}
}
#region Add/Remove Entities
public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
{
Vector3 pos;
pos.X = position.X;
pos.Y = position.Y;
pos.Z = position.Z;
OdeCharacter newAv = new OdeCharacter(avName, this, pos, size, avPIDD, avPIDP, avCapRadius, avDensity, avMovementDivisorWalk, avMovementDivisorRun);
newAv.Flying = isFlying;
newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
return newAv;
}
public void AddCharacter(OdeCharacter chr)
{
lock (_characters)
{
if (!_characters.Contains(chr))
{
_characters.Add(chr);
if (chr.bad)
m_log.DebugFormat("[PHYSICS] Added BAD actor {0} to characters list", chr.m_uuid);
}
}
}
public void RemoveCharacter(OdeCharacter chr)
{
lock (_characters)
{
if (_characters.Contains(chr))
{
_characters.Remove(chr);
}
}
}
public void BadCharacter(OdeCharacter chr)
{
lock (_badCharacter)
{
if (!_badCharacter.Contains(chr))
_badCharacter.Add(chr);
}
}
public override void RemoveAvatar(PhysicsActor actor)
{
//m_log.Debug("[PHYSICS]:ODELOCK");
((OdeCharacter) actor).Destroy();
}
private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
PrimitiveBaseShape pbs, bool isphysical, uint localID)
{
Vector3 pos = position;
Vector3 siz = size;
Quaternion rot = rotation;
OdePrim newPrim;
lock (OdeLock)
{
newPrim = new OdePrim(name, this, pos, siz, rot, pbs, isphysical);
lock (_prims)
_prims.Add(newPrim);
}
newPrim.LocalID = localID;
return newPrim;
}
public void addActivePrim(OdePrim activatePrim)
{
// adds active prim.. (ones that should be iterated over in collisions_optimized
lock (_activeprims)
{
if (!_activeprims.Contains(activatePrim))
_activeprims.Add(activatePrim);
//else
// m_log.Warn("[PHYSICS]: Double Entry in _activeprims detected, potential crash immenent");
}
}
public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
{
#if SPAM
m_log.DebugFormat("[PHYSICS]: Adding physics actor to {0}", primName);
#endif
return AddPrim(primName, position, size, rotation, pbs, isPhysical, localid);
}
public override float TimeDilation
{
get { return m_timeDilation; }
}
public override bool SupportsNINJAJoints
{
get { return false; }
}
public void remActivePrim(OdePrim deactivatePrim)
{
lock (_activeprims)
{
_activeprims.Remove(deactivatePrim);
}
}
public override void RemovePrim(PhysicsActor prim)
{
// As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
// removed in the next physics simulate pass.
if (prim is OdePrim)
{
// lock (OdeLock)
{
OdePrim p = (OdePrim)prim;
p.setPrimForRemoval();
}
}
}
/// <summary>
/// This is called from within simulate but outside the locked portion
/// We need to do our own locking here
/// (Note: As of 20110801 this no longer appears to be true - this is being called within lock (odeLock) in
/// Simulate() -- justincc).
///
/// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
///
/// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
/// that the space was using.
/// </summary>
/// <param name="prim"></param>
public void RemovePrimThreadLocked(OdePrim prim)
{
//Console.WriteLine("RemovePrimThreadLocked " + prim.m_primName);
lock (prim)
{
RemoveCollisionEventReporting(prim);
lock (_prims)
_prims.Remove(prim);
}
}
#endregion
#region Space Separation Calculation
/// <summary>
/// Called when a static prim moves or becomes static
/// Places the prim in a space one the static sub-spaces grid
/// </summary>
/// <param name="geom">the pointer to the geom that moved</param>
/// <param name="pos">the position that the geom moved to</param>
/// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
/// <returns>a pointer to the new space it's in</returns>
public IntPtr MoveGeomToStaticSpace(IntPtr geom, Vector3 pos, IntPtr currentspace)
{
// moves a prim into another static sub-space or from another space into a static sub-space
// Called ODEPrim so
// it's already in locked space.
if (geom == IntPtr.Zero) // shouldn't happen
return IntPtr.Zero;
// get the static sub-space for current position
IntPtr newspace = calculateSpaceForGeom(pos);
if (newspace == currentspace) // if we are there all done
return newspace;
// else remove it from its current space
if (currentspace != IntPtr.Zero && d.SpaceQuery(currentspace, geom))
{
if (d.GeomIsSpace(currentspace))
{
waitForSpaceUnlock(currentspace);
d.SpaceRemove(currentspace, geom);
}
else
{
m_log.Info("[Physics]: Invalid or empty Space passed to 'MoveGeomToStaticSpace':" + currentspace +
" Geom:" + geom);
}
}
else // odd currentspace is null or doesn't contain the geom? lets try the geom ideia of current space
{
currentspace = d.GeomGetSpace(geom);
if (currentspace != IntPtr.Zero)
{
if (d.GeomIsSpace(currentspace))
{
waitForSpaceUnlock(currentspace);
d.SpaceRemove(currentspace, geom);
}
}
}
// put the geom in the newspace
waitForSpaceUnlock(newspace);
d.SpaceAdd(newspace, geom);
// let caller know this newspace
return newspace;
}
/// <summary>
/// Calculates the space the prim should be in by its position
/// </summary>
/// <param name="pos"></param>
/// <returns>a pointer to the space. This could be a new space or reused space.</returns>
public IntPtr calculateSpaceForGeom(Vector3 pos)
{
int x, y;
x = (int)(pos.X * spacesPerMeter);
if (x < 0)
x = 0;
else if (x > spaceGridMaxX)
x = spaceGridMaxX;
y = (int)(pos.Y * spacesPerMeter);
if (y < 0)
y = 0;
else if (y >spaceGridMaxY)
y = spaceGridMaxY;
IntPtr tmpSpace = staticPrimspace[x, y];
return tmpSpace;
}
#endregion
/// <summary>
/// Routine to figure out if we need to mesh this prim with our mesher
/// </summary>
/// <param name="pbs"></param>
/// <returns></returns>
public bool needsMeshing(PrimitiveBaseShape pbs)
{
// most of this is redundant now as the mesher will return null if it cant mesh a prim
// but we still need to check for sculptie meshing being enabled so this is the most
// convenient place to do it for now...
// //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
// //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
int iPropertiesNotSupportedDefault = 0;
if (pbs.SculptEntry)
{
if(!meshSculptedPrim)
return false;
}
// if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim
if (!forceSimplePrimMeshing && !pbs.SculptEntry)
{
if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
|| (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
&& pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
{
if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
&& pbs.ProfileHollow == 0
&& pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
&& pbs.PathBegin == 0 && pbs.PathEnd == 0
&& pbs.PathTaperX == 0 && pbs.PathTaperY == 0
&& pbs.PathScaleX == 100 && pbs.PathScaleY == 100
&& pbs.PathShearX == 0 && pbs.PathShearY == 0)
{
#if SPAM
m_log.Warn("NonMesh");
#endif
return false;
}
}
}
// following code doesn't give meshs to boxes and spheres ever
// and it's odd.. so for now just return true if asked to force meshs
// hopefully mesher will fail if doesn't suport so things still get basic boxes
if (forceSimplePrimMeshing)
return true;
if (pbs.ProfileHollow != 0)
iPropertiesNotSupportedDefault++;
if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
iPropertiesNotSupportedDefault++;
if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
iPropertiesNotSupportedDefault++;
if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
iPropertiesNotSupportedDefault++;
if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
iPropertiesNotSupportedDefault++;
if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
iPropertiesNotSupportedDefault++;
if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
iPropertiesNotSupportedDefault++;
if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
iPropertiesNotSupportedDefault++;
if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
iPropertiesNotSupportedDefault++;
// test for torus
if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
{
if (pbs.PathCurve == (byte)Extrusion.Curve1)
{
iPropertiesNotSupportedDefault++;
}
}
else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
{
if (pbs.PathCurve == (byte)Extrusion.Straight)
{
iPropertiesNotSupportedDefault++;
}
// ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
else if (pbs.PathCurve == (byte)Extrusion.Curve1)
{
iPropertiesNotSupportedDefault++;
}
}
else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
{
if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
{
iPropertiesNotSupportedDefault++;
}
}
else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
{
if (pbs.PathCurve == (byte)Extrusion.Straight)
{
iPropertiesNotSupportedDefault++;
}
else if (pbs.PathCurve == (byte)Extrusion.Curve1)
{
iPropertiesNotSupportedDefault++;
}
}
if (pbs.SculptEntry && meshSculptedPrim)
iPropertiesNotSupportedDefault++;
if (iPropertiesNotSupportedDefault == 0)
{
#if SPAM
m_log.Warn("NonMesh");
#endif
return false;
}
#if SPAM
m_log.Debug("Mesh");
#endif
return true;
}
/// <summary>
/// Called to queue a change to a actor
/// to use in place of old taint mechanism so changes do have a time sequence
/// </summary>
public void AddChange(PhysicsActor actor, changes what, Object arg)
{
ODEchangeitem item = new ODEchangeitem();
item.actor = actor;
item.what = what;
item.arg = arg;
ChangesQueue.Enqueue(item);
}
/// <summary>
/// Called after our prim properties are set Scale, position etc.
/// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
/// This assures us that we have no race conditions
/// </summary>
/// <param name="prim"></param>
public override void AddPhysicsActorTaint(PhysicsActor prim)
{
if (prim is OdePrim)
{
/* OdePrim taintedprim = ((OdePrim) prim);
lock (_taintedPrimLock)
{
if (!(_taintedPrimH.Contains(taintedprim)))
{
_taintedPrimH.Add(taintedprim); // HashSet for searching
_taintedPrimQ.Enqueue(taintedprim); // List for ordered readout
}
}
*/
return;
}
else if (prim is OdeCharacter)
{
OdeCharacter taintedchar = ((OdeCharacter)prim);
lock (_taintedCharacterLock)
{
if (!(_taintedCharacterH.Contains(taintedchar)))
{
_taintedCharacterH.Add(taintedchar);
_taintedCharacterQ.Enqueue(taintedchar);
if (taintedchar.bad)
m_log.DebugFormat("[PHYSICS]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
}
}
}
}
/// <summary>
/// This is our main simulate loop
/// It's thread locked by a Mutex in the scene.
/// It holds Collisions, it instructs ODE to step through the physical reactions
/// It moves the objects around in memory
/// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
/// </summary>
/// <param name="timeStep"></param>
/// <returns></returns>
public override float Simulate(float timeStep)
{
int statstart;
int statchanges = 0;
int statchmove = 0;
int statactmove = 0;
int statray = 0;
int statcol = 0;
int statstep = 0;
int statmovchar = 0;
int statmovprim;
int totjcontact = 0;
// acumulate time so we can reduce error
step_time += timeStep;
if (step_time < ODE_STEPSIZE)
return 0;
if (framecount >= int.MaxValue)
framecount = 0;
framecount++;
int curphysiteractions = m_physicsiterations;
if (step_time >= m_SkipFramesAtms)
{
// if in trouble reduce step resolution
curphysiteractions /= 2;
}
int nodeframes = 0;
// checkThread();
lock (SimulationLock)
{
// adjust number of iterations per step
try
{
d.WorldSetQuickStepNumIterations(world, curphysiteractions);
}
catch (StackOverflowException)
{
m_log.Error("[PHYSICS]: The operating system wasn't able to allocate enough memory for the simulation. Restarting the sim.");
// ode.drelease(world);
base.TriggerPhysicsBasedRestart();
}
while (step_time >= ODE_STEPSIZE && nodeframes < 10) //limit number of steps so we don't say here for ever
{
try
{
statstart = Util.EnvironmentTickCount();
// clear pointer/counter to contacts to pass into joints
m_global_contactcount = 0;
ODEchangeitem item;
if(ChangesQueue.Count >0)
{
int ttmpstart = Util.EnvironmentTickCount();
int ttmp;
int ttmp2;
while(ChangesQueue.Dequeue(out item))
{
if (item.actor != null)
{
try
{
if (item.actor is OdeCharacter)
((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
RemovePrimThreadLocked((OdePrim)item.actor);
}
catch
{
m_log.Warn("[PHYSICS]: doChange failed for a actor");
};
}
ttmp = Util.EnvironmentTickCountSubtract(ttmpstart);
if (ttmp > 20)
break;
}
ttmp2 = Util.EnvironmentTickCountSubtract(ttmpstart);
if (ttmp2 > 50)
ttmp2 = 0;
}
statchanges += Util.EnvironmentTickCountSubtract(statstart);
// Move characters
lock (_characters)
{
List<OdeCharacter> defects = new List<OdeCharacter>();
foreach (OdeCharacter actor in _characters)
{
if (actor != null)
actor.Move(ODE_STEPSIZE, defects);
}
if (defects.Count != 0)
{
foreach (OdeCharacter defect in defects)
{
RemoveCharacter(defect);
}
}
}
statchmove += Util.EnvironmentTickCountSubtract(statstart);
// Move other active objects
lock (_activeprims)
{
foreach (OdePrim aprim in _activeprims)
{
aprim.CollisionScore = 0;
aprim.IsColliding = false;
aprim.Move();
}
}
statactmove += Util.EnvironmentTickCountSubtract(statstart);
//if ((framecount % m_randomizeWater) == 0)
// randomizeWater(waterlevel);
m_rayCastManager.ProcessQueuedRequests();
statray += Util.EnvironmentTickCountSubtract(statstart);
collision_optimized();
statcol += Util.EnvironmentTickCountSubtract(statstart);
lock (_collisionEventPrim)
{
foreach (PhysicsActor obj in _collisionEventPrim)
{
if (obj == null)
continue;
switch ((ActorTypes)obj.PhysicsActorType)
{
case ActorTypes.Agent:
OdeCharacter cobj = (OdeCharacter)obj;
cobj.AddCollisionFrameTime((int)(ODE_STEPSIZE*1000.0f));
cobj.SendCollisions();
break;
case ActorTypes.Prim:
OdePrim pobj = (OdePrim)obj;
pobj.SendCollisions();
break;
}
}
}
d.WorldQuickStep(world, ODE_STEPSIZE);
statstep += Util.EnvironmentTickCountSubtract(statstart);
d.JointGroupEmpty(contactgroup);
totjcontact += m_global_contactcount;
//ode.dunlock(world);
}
catch (Exception e)
{
m_log.ErrorFormat("[PHYSICS]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
// ode.dunlock(world);
}
step_time -= ODE_STEPSIZE;
nodeframes++;
}
statstart = Util.EnvironmentTickCount();
lock (_characters)
{
foreach (OdeCharacter actor in _characters)
{
if (actor != null)
{
if (actor.bad)
m_log.WarnFormat("[PHYSICS]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
actor.UpdatePositionAndVelocity();
}
}
}
lock (_badCharacter)
{
if (_badCharacter.Count > 0)
{
foreach (OdeCharacter chr in _badCharacter)
{
RemoveCharacter(chr);
}
_badCharacter.Clear();
}
}
statmovchar = Util.EnvironmentTickCountSubtract(statstart);
lock (_activeprims)
{
{
foreach (OdePrim actor in _activeprims)
{
if (actor.IsPhysical)
{
actor.UpdatePositionAndVelocity((float)nodeframes * ODE_STEPSIZE);
}
}
}
}
statmovprim = Util.EnvironmentTickCountSubtract(statstart);
int nactivegeoms = d.SpaceGetNumGeoms(ActiveSpace);
int nstaticgeoms = d.SpaceGetNumGeoms(StaticSpace);
int ntopgeoms = d.SpaceGetNumGeoms(TopSpace);
int nbodies = d.NTotalBodies;
int ngeoms = d.NTotalGeoms;
// Finished with all sim stepping. If requested, dump world state to file for debugging.
// TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
// TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
{
string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
if (physics_logging_append_existing_logfile)
{
string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
TextWriter fwriter = File.AppendText(fname);
fwriter.WriteLine(header);
fwriter.Close();
}
d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
}
// think time dilation is not a physics issue alone.. but ok let's fake something
if (step_time < ODE_STEPSIZE) // we did the required loops
m_timeDilation = 1.0f;
else
{ // we didn't forget the lost ones and let user know something
m_timeDilation = 1 - step_time / timeStep;
if (m_timeDilation < 0)
m_timeDilation = 0;
step_time = 0;
}
}
// return nodeframes * ODE_STEPSIZE; // return real simulated time
return 1000 * nodeframes; // return steps for now * 1000 to keep core happy
}
/// <summary>
public override void GetResults()
{
}
public override bool IsThreaded
{
// for now we won't be multithreaded
get { return (false); }
}
#region ODE Specific Terrain Fixes
public float[] ResizeTerrain512NearestNeighbour(float[] heightMap)
{
float[] returnarr = new float[262144];
float[,] resultarr = new float[(int)WorldExtents.X, (int)WorldExtents.Y];
// Filling out the array into its multi-dimensional components
for (int y = 0; y < WorldExtents.Y; y++)
{
for (int x = 0; x < WorldExtents.X; x++)
{
resultarr[y, x] = heightMap[y * (int)WorldExtents.Y + x];
}
}
// Resize using Nearest Neighbour
// This particular way is quick but it only works on a multiple of the original
// The idea behind this method can be described with the following diagrams
// second pass and third pass happen in the same loop really.. just separated
// them to show what this does.
// First Pass
// ResultArr:
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// Second Pass
// ResultArr2:
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// Third pass fills in the blanks
// ResultArr2:
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// X,Y = .
// X+1,y = ^
// X,Y+1 = *
// X+1,Y+1 = #
// Filling in like this;
// .*
// ^#
// 1st .
// 2nd *
// 3rd ^
// 4th #
// on single loop.
float[,] resultarr2 = new float[512, 512];
for (int y = 0; y < WorldExtents.Y; y++)
{
for (int x = 0; x < WorldExtents.X; x++)
{
resultarr2[y * 2, x * 2] = resultarr[y, x];
if (y < WorldExtents.Y)
{
resultarr2[(y * 2) + 1, x * 2] = resultarr[y, x];
}
if (x < WorldExtents.X)
{
resultarr2[y * 2, (x * 2) + 1] = resultarr[y, x];
}
if (x < WorldExtents.X && y < WorldExtents.Y)
{
resultarr2[(y * 2) + 1, (x * 2) + 1] = resultarr[y, x];
}
}
}
//Flatten out the array
int i = 0;
for (int y = 0; y < 512; y++)
{
for (int x = 0; x < 512; x++)
{
if (resultarr2[y, x] <= 0)
returnarr[i] = 0.0000001f;
else
returnarr[i] = resultarr2[y, x];
i++;
}
}
return returnarr;
}
public float[] ResizeTerrain512Interpolation(float[] heightMap)
{
float[] returnarr = new float[262144];
float[,] resultarr = new float[512,512];
// Filling out the array into its multi-dimensional components
for (int y = 0; y < 256; y++)
{
for (int x = 0; x < 256; x++)
{
resultarr[y, x] = heightMap[y * 256 + x];
}
}
// Resize using interpolation
// This particular way is quick but it only works on a multiple of the original
// The idea behind this method can be described with the following diagrams
// second pass and third pass happen in the same loop really.. just separated
// them to show what this does.
// First Pass
// ResultArr:
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// 1,1,1,1,1,1
// Second Pass
// ResultArr2:
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// ,,,,,,,,,,
// 1,,1,,1,,1,,1,,1,
// Third pass fills in the blanks
// ResultArr2:
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// 1,1,1,1,1,1,1,1,1,1,1,1
// X,Y = .
// X+1,y = ^
// X,Y+1 = *
// X+1,Y+1 = #
// Filling in like this;
// .*
// ^#
// 1st .
// 2nd *
// 3rd ^
// 4th #
// on single loop.
float[,] resultarr2 = new float[512,512];
for (int y = 0; y < (int)Constants.RegionSize; y++)
{
for (int x = 0; x < (int)Constants.RegionSize; x++)
{
resultarr2[y*2, x*2] = resultarr[y, x];
if (y < (int)Constants.RegionSize)
{
if (y + 1 < (int)Constants.RegionSize)
{
if (x + 1 < (int)Constants.RegionSize)
{
resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x] +
resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
}
else
{
resultarr2[(y*2) + 1, x*2] = ((resultarr[y, x] + resultarr[y + 1, x])/2);
}
}
else
{
resultarr2[(y*2) + 1, x*2] = resultarr[y, x];
}
}
if (x < (int)Constants.RegionSize)
{
if (x + 1 < (int)Constants.RegionSize)
{
if (y + 1 < (int)Constants.RegionSize)
{
resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
}
else
{
resultarr2[y*2, (x*2) + 1] = ((resultarr[y, x] + resultarr[y, x + 1])/2);
}
}
else
{
resultarr2[y*2, (x*2) + 1] = resultarr[y, x];
}
}
if (x < (int)Constants.RegionSize && y < (int)Constants.RegionSize)
{
if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize))
{
resultarr2[(y*2) + 1, (x*2) + 1] = ((resultarr[y, x] + resultarr[y + 1, x] +
resultarr[y, x + 1] + resultarr[y + 1, x + 1])/4);
}
else
{
resultarr2[(y*2) + 1, (x*2) + 1] = resultarr[y, x];
}
}
}
}
//Flatten out the array
int i = 0;
for (int y = 0; y < 512; y++)
{
for (int x = 0; x < 512; x++)
{
if (Single.IsNaN(resultarr2[y, x]) || Single.IsInfinity(resultarr2[y, x]))
{
m_log.Warn("[PHYSICS]: Non finite heightfield element detected. Setting it to 0");
resultarr2[y, x] = 0;
}
returnarr[i] = resultarr2[y, x];
i++;
}
}
return returnarr;
}
#endregion
public override void SetTerrain(float[] heightMap)
{
if (m_worldOffset != Vector3.Zero && m_parentScene != null)
{
if (m_parentScene is OdeScene)
{
((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
}
}
else
{
SetTerrain(heightMap, m_worldOffset);
}
}
public override void CombineTerrain(float[] heightMap, Vector3 pOffset)
{
SetTerrain(heightMap, pOffset);
}
public void SetTerrain(float[] heightMap, Vector3 pOffset)
{
float[] _heightmap;
_heightmap = new float[(((int)Constants.RegionSize + 2) * ((int)Constants.RegionSize + 2))];
uint heightmapWidth = Constants.RegionSize + 2;
uint heightmapHeight = Constants.RegionSize + 2;
uint heightmapWidthSamples;
uint heightmapHeightSamples;
heightmapWidthSamples = (uint)Constants.RegionSize + 2;
heightmapHeightSamples = (uint)Constants.RegionSize + 2;
const float scale = 1.0f;
const float offset = 0.0f;
const float thickness = 10f;
const int wrap = 0;
int regionsize = (int) Constants.RegionSize + 2;
float hfmin = float.MaxValue;
float hfmax = float.MinValue;
float val;
int xx;
int yy;
int maxXXYY = regionsize - 3;
// flipping map adding one margin all around so things don't fall in edges
int xt = 0;
xx = 0;
for (int x = 0; x < heightmapWidthSamples; x++)
{
if (x > 1 && xx < maxXXYY)
xx++;
yy = 0;
for (int y = 0; y < heightmapHeightSamples; y++)
{
if (y > 1 && y < maxXXYY)
yy += (int)Constants.RegionSize;
val = heightMap[yy + xx];
_heightmap[xt + y] = val;
if (hfmin > val)
hfmin = val;
if (hfmax < val)
hfmax = val;
}
xt += regionsize;
}
lock (OdeLock)
{
IntPtr GroundGeom = IntPtr.Zero;
if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
{
RegionTerrain.Remove(pOffset);
if (GroundGeom != IntPtr.Zero)
{
if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
{
TerrainHeightFieldHeightsHandlers[GroundGeom].Free();
TerrainHeightFieldHeightsHandlers.Remove(GroundGeom);
TerrainHeightFieldHeights.Remove(GroundGeom);
}
d.SpaceRemove(StaticSpace, GroundGeom);
d.GeomDestroy(GroundGeom);
}
}
IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
GCHandle _heightmaphandler = GCHandle.Alloc(_heightmap, GCHandleType.Pinned);
d.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmaphandler.AddrOfPinnedObject(), 0, heightmapWidth , heightmapHeight,
(int)heightmapWidthSamples, (int)heightmapHeightSamples, scale,
offset, thickness, wrap);
d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
GroundGeom = d.CreateHeightfield(StaticSpace, HeightmapData, 1);
if (GroundGeom != IntPtr.Zero)
{
d.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
d.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
}
geom_name_map[GroundGeom] = "Terrain";
d.Matrix3 R = new d.Matrix3();
Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
q1 = q1 * q2;
Vector3 v3;
float angle;
q1.GetAxisAngle(out v3, out angle);
d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
d.GeomSetRotation(GroundGeom, ref R);
d.GeomSetPosition(GroundGeom, pOffset.X + (float)Constants.RegionSize * 0.5f - 0.5f, pOffset.Y + (float)Constants.RegionSize * 0.5f - 0.5f, 0);
IntPtr testGround = IntPtr.Zero;
if (RegionTerrain.TryGetValue(pOffset, out testGround))
{
RegionTerrain.Remove(pOffset);
}
RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
// TerrainHeightFieldHeights.Add(GroundGeom, ODElandMap);
TerrainHeightFieldHeights.Add(GroundGeom, _heightmap);
TerrainHeightFieldHeightsHandlers.Add(GroundGeom, _heightmaphandler);
}
}
public override void DeleteTerrain()
{
}
public float GetWaterLevel()
{
return waterlevel;
}
public override bool SupportsCombining()
{
return true;
}
/*
public override void UnCombine(PhysicsScene pScene)
{
IntPtr localGround = IntPtr.Zero;
// float[] localHeightfield;
bool proceed = false;
List<IntPtr> geomDestroyList = new List<IntPtr>();
lock (OdeLock)
{
if (RegionTerrain.TryGetValue(Vector3.Zero, out localGround))
{
foreach (IntPtr geom in TerrainHeightFieldHeights.Keys)
{
if (geom == localGround)
{
// localHeightfield = TerrainHeightFieldHeights[geom];
proceed = true;
}
else
{
geomDestroyList.Add(geom);
}
}
if (proceed)
{
m_worldOffset = Vector3.Zero;
WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
m_parentScene = null;
foreach (IntPtr g in geomDestroyList)
{
// removingHeightField needs to be done or the garbage collector will
// collect the terrain data before we tell ODE to destroy it causing
// memory corruption
if (TerrainHeightFieldHeights.ContainsKey(g))
{
// float[] removingHeightField = TerrainHeightFieldHeights[g];
TerrainHeightFieldHeights.Remove(g);
if (RegionTerrain.ContainsKey(g))
{
RegionTerrain.Remove(g);
}
d.GeomDestroy(g);
//removingHeightField = new float[0];
}
}
}
else
{
m_log.Warn("[PHYSICS]: Couldn't proceed with UnCombine. Region has inconsistant data.");
}
}
}
}
*/
public override void SetWaterLevel(float baseheight)
{
waterlevel = baseheight;
randomizeWater(waterlevel);
}
public void randomizeWater(float baseheight)
{
const uint heightmapWidth = m_regionWidth + 2;
const uint heightmapHeight = m_regionHeight + 2;
const uint heightmapWidthSamples = m_regionWidth + 2;
const uint heightmapHeightSamples = m_regionHeight + 2;
const float scale = 1.0f;
const float offset = 0.0f;
const float thickness = 2.9f;
const int wrap = 0;
for (int i = 0; i < (258 * 258); i++)
{
_watermap[i] = (baseheight-0.1f) + ((float)fluidRandomizer.Next(1,9) / 10f);
// m_log.Info((baseheight - 0.1f) + ((float)fluidRandomizer.Next(1, 9) / 10f));
}
lock (OdeLock)
{
if (WaterGeom != IntPtr.Zero)
{
d.SpaceRemove(StaticSpace, WaterGeom);
}
IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
d.GeomHeightfieldDataBuildSingle(HeightmapData, _watermap, 0, heightmapWidth, heightmapHeight,
(int)heightmapWidthSamples, (int)heightmapHeightSamples, scale,
offset, thickness, wrap);
d.GeomHeightfieldDataSetBounds(HeightmapData, m_regionWidth, m_regionHeight);
WaterGeom = d.CreateHeightfield(StaticSpace, HeightmapData, 1);
if (WaterGeom != IntPtr.Zero)
{
d.GeomSetCategoryBits(WaterGeom, (int)(CollisionCategories.Water));
d.GeomSetCollideBits(WaterGeom, (int)(CollisionCategories.Space));
}
geom_name_map[WaterGeom] = "Water";
d.Matrix3 R = new d.Matrix3();
Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
q1 = q1 * q2;
Vector3 v3;
float angle;
q1.GetAxisAngle(out v3, out angle);
d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
d.GeomSetRotation(WaterGeom, ref R);
d.GeomSetPosition(WaterGeom, 128, 128, 0);
}
}
public override void Dispose()
{
m_rayCastManager.Dispose();
m_rayCastManager = null;
lock (OdeLock)
{
lock (_prims)
{
foreach (OdePrim prm in _prims)
{
RemovePrim(prm);
}
}
if (ContactgeomsArray != IntPtr.Zero)
Marshal.FreeHGlobal(ContactgeomsArray);
if (GlobalContactsArray != IntPtr.Zero)
Marshal.FreeHGlobal(GlobalContactsArray);
d.WorldDestroy(world);
//d.CloseODE();
}
}
public override Dictionary<uint, float> GetTopColliders()
{
Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
int cnt = 0;
lock (_prims)
{
foreach (OdePrim prm in _prims)
{
if (prm.CollisionScore > 0)
{
returncolliders.Add(prm.m_localID, prm.CollisionScore);
cnt++;
prm.CollisionScore = 0f;
if (cnt > 25)
{
break;
}
}
}
}
return returncolliders;
}
public override bool SupportsRayCast()
{
return true;
}
public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
{
if (retMethod != null)
{
m_rayCastManager.QueueRequest(position, direction, length, retMethod);
}
}
public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
{
if (retMethod != null)
{
m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
}
}
// don't like this
public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
{
ContactResult[] ourResults = null;
RayCallback retMethod = delegate(List<ContactResult> results)
{
ourResults = new ContactResult[results.Count];
results.CopyTo(ourResults, 0);
};
int waitTime = 0;
m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
while (ourResults == null && waitTime < 1000)
{
Thread.Sleep(1);
waitTime++;
}
if (ourResults == null)
return new List<ContactResult>();
return new List<ContactResult>(ourResults);
}
public override void RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
{
if (retMethod != null && actor !=null)
{
IntPtr geom;
if (actor is OdePrim)
geom = ((OdePrim)actor).prim_geom;
else if (actor is OdeCharacter)
geom = ((OdePrim)actor).prim_geom;
else
return;
if (geom == IntPtr.Zero)
return;
m_rayCastManager.QueueRequest(geom, position, direction, length, retMethod);
}
}
public override void RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
{
if (retMethod != null && actor != null)
{
IntPtr geom;
if (actor is OdePrim)
geom = ((OdePrim)actor).prim_geom;
else if (actor is OdeCharacter)
geom = ((OdePrim)actor).prim_geom;
else
return;
if (geom == IntPtr.Zero)
return;
m_rayCastManager.QueueRequest(geom,position, direction, length, Count, retMethod);
}
}
// don't like this
public override List<ContactResult> RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, int Count)
{
if (actor != null)
{
IntPtr geom;
if (actor is OdePrim)
geom = ((OdePrim)actor).prim_geom;
else if (actor is OdeCharacter)
geom = ((OdePrim)actor).prim_geom;
else
return new List<ContactResult>();
if (geom == IntPtr.Zero)
return new List<ContactResult>();
ContactResult[] ourResults = null;
RayCallback retMethod = delegate(List<ContactResult> results)
{
ourResults = new ContactResult[results.Count];
results.CopyTo(ourResults, 0);
};
int waitTime = 0;
m_rayCastManager.QueueRequest(geom,position, direction, length, Count, retMethod);
while (ourResults == null && waitTime < 1000)
{
Thread.Sleep(1);
waitTime++;
}
if (ourResults == null)
return new List<ContactResult>();
return new List<ContactResult>(ourResults);
}
return new List<ContactResult>();
}
#if USE_DRAWSTUFF
// Keyboard callback
public void command(int cmd)
{
IntPtr geom;
d.Mass mass;
d.Vector3 sides = new d.Vector3(d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f);
Char ch = Char.ToLower((Char)cmd);
switch ((Char)ch)
{
case 'w':
try
{
Vector3 rotate = (new Vector3(1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
xyz.X += rotate.X; xyz.Y += rotate.Y; xyz.Z += rotate.Z;
ds.SetViewpoint(ref xyz, ref hpr);
}
catch (ArgumentException)
{ hpr.X = 0; }
break;
case 'a':
hpr.X++;
ds.SetViewpoint(ref xyz, ref hpr);
break;
case 's':
try
{
Vector3 rotate2 = (new Vector3(-1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
xyz.X += rotate2.X; xyz.Y += rotate2.Y; xyz.Z += rotate2.Z;
ds.SetViewpoint(ref xyz, ref hpr);
}
catch (ArgumentException)
{ hpr.X = 0; }
break;
case 'd':
hpr.X--;
ds.SetViewpoint(ref xyz, ref hpr);
break;
case 'r':
xyz.Z++;
ds.SetViewpoint(ref xyz, ref hpr);
break;
case 'f':
xyz.Z--;
ds.SetViewpoint(ref xyz, ref hpr);
break;
case 'e':
xyz.Y++;
ds.SetViewpoint(ref xyz, ref hpr);
break;
case 'q':
xyz.Y--;
ds.SetViewpoint(ref xyz, ref hpr);
break;
}
}
public void step(int pause)
{
ds.SetColor(1.0f, 1.0f, 0.0f);
ds.SetTexture(ds.Texture.Wood);
lock (_prims)
{
foreach (OdePrim prm in _prims)
{
//IntPtr body = d.GeomGetBody(prm.prim_geom);
if (prm.prim_geom != IntPtr.Zero)
{
d.Vector3 pos;
d.GeomCopyPosition(prm.prim_geom, out pos);
//d.BodyCopyPosition(body, out pos);
d.Matrix3 R;
d.GeomCopyRotation(prm.prim_geom, out R);
//d.BodyCopyRotation(body, out R);
d.Vector3 sides = new d.Vector3();
sides.X = prm.Size.X;
sides.Y = prm.Size.Y;
sides.Z = prm.Size.Z;
ds.DrawBox(ref pos, ref R, ref sides);
}
}
}
ds.SetColor(1.0f, 0.0f, 0.0f);
lock (_characters)
{
foreach (OdeCharacter chr in _characters)
{
if (chr.Shell != IntPtr.Zero)
{
IntPtr body = d.GeomGetBody(chr.Shell);
d.Vector3 pos;
d.GeomCopyPosition(chr.Shell, out pos);
//d.BodyCopyPosition(body, out pos);
d.Matrix3 R;
d.GeomCopyRotation(chr.Shell, out R);
//d.BodyCopyRotation(body, out R);
ds.DrawCapsule(ref pos, ref R, chr.Size.Z, 0.35f);
d.Vector3 sides = new d.Vector3();
sides.X = 0.5f;
sides.Y = 0.5f;
sides.Z = 0.5f;
ds.DrawBox(ref pos, ref R, ref sides);
}
}
}
}
public void start(int unused)
{
ds.SetViewpoint(ref xyz, ref hpr);
}
#endif
}
}
|