aboutsummaryrefslogtreecommitdiff
path: root/mayaPlug/shaveRender.cpp
blob: a005cf239316e359467a2fa1d25d1db583b249c7 (plain) (blame)
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
// Shave and a Haircut
// (c) 2019 Epic Games
// US Patent 6720962

#include <maya/MAngle.h>
#include <maya/MAnimControl.h>
#include <maya/MColorArray.h>
#include <maya/MDagPath.h>
#include <maya/MDGMessage.h>
#include <maya/MFileIO.h>
#include <maya/MFnCamera.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnLight.h>
#include <maya/MFnMesh.h>
#include <maya/MFnSpotLight.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MIntArray.h>
#include <maya/MItDag.h>
#include <maya/MItDependencyNodes.h>
#include <maya/MMatrix.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MPoint.h>
#include <maya/MSelectionList.h>
#include <maya/MString.h>
#include <maya/MStringArray.h>
#include <maya/MVector.h>

#include "shaveCheckObjectVisibility.h"
#include "shaveDebug.h"
#include "shaveGlobals.h"
#include "shaveHairShape.h"
#include "shaveIO.h"
#include "shaveMaya.h"
#include "shaveMayaRenderer.h"
#include "shaveObjExporter.h"
#include "shaveRender.h"
#include "shaveRenderCallback.h"
#include "shaveRenderer.h"
#include "shaveSDK.h"
#include "shaveTextureStore.h"
#include "shaveUtil.h"
#include "shaveVertexShader.h"
#include "shaveVrayRenderer.h"
#include "shaveXPM.h"


#ifndef M_PI
#define M_PI 3.14159926535
#endif

bool	shaveRenderCancelled = false;
bool	shaveEnableProgressBar = true;


//
// Static class members.
//
bool					shaveRender::mCallbacksSet = false;
bool					shaveRender::mExportActive = false;
unsigned				shaveRender::mExportFileCompression = 0;
unsigned				shaveRender::mExportFileFramePadding = 0;
MString					shaveRender::mExportFileName = "";
bool					shaveRender::mExportFilePerFrame = false;

shaveConstant::FileNameFormat
		shaveRender::mExportFileNameFormat = shaveConstant::kNoFileNameFormat;

shaveGlobals::Globals	shaveRender::mFrameGlobals;

shaveConstant::RenderMode	shaveRender::mHairRenderMode = shaveConstant::kNoRender;
MObjectArray			shaveRender::mHiddenNodes;
bool					shaveRender::mRenderInstances = true;

bool					shaveRender::mNeedVertexColours = false;
shaveConstant::ShadowSource
						shaveRender::mNormalShadows = shaveConstant::kNoShadows;

shaveRenderer*			shaveRender::mRenderer = NULL;
shaveRender::RenderState shaveRender::mRenderState = shaveRender::kRenderNone;
shaveRender::SceneInfo	shaveRender::mSceneInfo;
MObjectArray			shaveRender::mTemplatedNodes;

MCallbackId				shaveRender::mAfterFrameRenderCallback;
MCallbackId				shaveRender::mAfterRenderCallback;
MCallbackId				shaveRender::mBeforeFrameRenderCallback;
MCallbackId				shaveRender::mBeforeRenderCallback;
MCallbackId				shaveRender::mRenderInterruptedCallback;
MCallbackId				shaveRender::mTimeChangeCallback;
shaveRenderCallback*	shaveRender::mShaveCallback = NULL;

//
// Normally, 'mFirstFrame' will be set true in renderStart() and false in
// frameEnd().  This ensures that it will be true during the first frame
// and false during subsequent frames within the same render.
//
// However, Shave API calls don't go through renderStart() and frameEnd().
// Since the Shave API currently just does a single frame at a time,
// 'mFirstFrame' should always be true.
//
bool					shaveRender::mFirstFrame = true;


void shaveRender::initSceneInfo(float currentFrame, bool allocateBuffers)
{
	if (mFrameGlobals.verbose) cerr << "setting up render." << endl;

	static int MBAAQ[] = {1,3,8,15,23};

	shaveRenderCallback::setGeomRender(false);

	mSceneInfo.shaveRenderPixels	= NULL;
	mSceneInfo.shaveZBuffer			= NULL;

	if (allocateBuffers)
	{
		mSceneInfo.shaveRenderPixels = (Pixel*)malloc(
											(shaveMaya::imageWidth+1) *
											(shaveMaya::imageHeight+1) *
											sizeof(Pixel)
										);

		if (!mSceneInfo.shaveRenderPixels)
		{
			MGlobal::displayError(
				"Shave Render: not enough memory available for pixel buffer."
			);

			shaveRenderCancelled = true;

			return;
		}

		mSceneInfo.shaveZBuffer = (float *)malloc(
										(shaveMaya::imageWidth+1) *
										(shaveMaya::imageHeight+1) *\
										sizeof(float)
									);

		if (!mSceneInfo.shaveZBuffer)
		{
			MGlobal::displayError(
				"Shave Render: not enough memory available for depth buffer."
			);

			shaveRenderCancelled = true;

			return;
		}
	}

	mSceneInfo.aa					= MBAAQ[renderQualityGlob];
	mSceneInfo.currentFrame			= currentFrame;
	mSceneInfo.haveTracedLights		= false;
	mSceneInfo.height				= shaveMaya::imageHeight;
	mSceneInfo.shaveTraceInitialized= false;
	mSceneInfo.width				= shaveMaya::imageWidth;

	return;
}


void shaveRender::doShadows()
{
	//
	// Note that here we check doHairShadowsGlob rather than checking the
	// hair and instance shadow sources.  This is because even if all the
	// shadow sources are set to kNoShadows, if doHairShadowsGlob is true
	// then we still want self-shadowing.
	//
	if (doHairShadowsGlob)
	{
		int renderReturnVal = 0;

		shadowRender = true;

		if (nativeIlluminationGlob)
		{
			//
			// With native illumination, Maya will be rendering the shadows
			// for those objects which are actually in the scene, so Shave
			// doesn't have to.
			//
			// The only use that SHAVErender_shadows() makes of the WFTYPEs
			// that we pass down to it is to render shadows for the
			// geometry that they contain.  So by passing down empty
			// WFTYPEs, we can prevent it from redoing the shadows which
			// Maya has already done.
			//
			WFTYPE	empty;

			init_geomWF(&empty);

			renderReturnVal = SHAVErender_shadows(&empty, &empty, 1, 1);
		}
		else
		{
			renderReturnVal = SHAVErender_shadows(
								&mSceneInfo.shutterOpenShadowScene,
								(shaveMaya::doMotionBlur ?
									&mSceneInfo.shutterCloseShadowScene :
									&mSceneInfo.shutterOpenShadowScene),
								1,
								1
							);
		}

		//
		// If there were any traced lights, then the shadow render will have
		// called SHAVEtrace_init.  It's an expensive operation, so let's
		// set a flag so that we know not to do it in other places, such as
		// where we set up for reflections and refractions.
		//
		mSceneInfo.shaveTraceInitialized |= mSceneInfo.haveTracedLights;

		if (shaveRenderCancelled)
		{
			MGlobal::displayInfo("Shave render cancelled by user.");
		}
		else if (renderReturnVal != 0)
		{
			cerr << "Shave light render failed, return value is "
				 << renderReturnVal << endl;

			shaveRenderCancelled = true;
		}
		else if (mFrameGlobals.verbose)
		{
			cerr << "Done with Shave light render." << endl;
		}

		shadowRender = false;

		MGlobal::executeCommand("shave_closeProgressBar()");
	}

	return;
}


void shaveRender::bufferRender(
	shaveConstant::ShutterState shutter,
	const MDagPath& cameraPath,
	float frame,
	bool needBuffers,
	bool doShadowRender,
	bool doCameraRender,
	bool doOcclusions
)
{
	//
	// Do the initialization on shutter open so that everything's there for
	// the rest of the render.
	//
	if (((shutter == shaveConstant::kShutterOpen)
		|| (shutter == shaveConstant::kShutterBoth))
	&&	!shaveRenderCancelled)
	{
		initSceneInfo(frame, needBuffers);
	}

	//
	// If this is shutter close, then the actual frame time will be the
	// average of the current frame and what was saved into
	// mSceneInfo.currentFrame on shutter open.  So calculate the real frame
	// time.
	//
	if (shutter == shaveConstant::kShutterClose)
		mSceneInfo.currentFrame = (mSceneInfo.currentFrame + frame) / 2.0f;

	if (!shaveRenderCancelled
	&&	(doCameraRender || doShadowRender || doOcclusions))
	{
		buildOcclusionLists(shutter);
	}

	if (!shaveRenderCancelled) doCamera(cameraPath, shutter, mSceneInfo);

	//
	// Lights are not motion-blurred, so we only do them on shutter open.
	//
	if (((shutter == shaveConstant::kShutterOpen)
		|| (shutter == shaveConstant::kShutterBoth))
	&&	!shaveRenderCancelled)
	{
		doLights();
	}

	//
	// Shadows & rendering are done on shutter close.
	//
	if ((shutter == shaveConstant::kShutterClose)
		|| (shutter == shaveConstant::kShutterBoth))
	{
		if (!shaveRenderCancelled && doShadowRender)
			doShadows();

		if (!shaveRenderCancelled && doCameraRender)
		{
			if (renderCameraView(cameraPath) != 0)
				shaveRenderCancelled = true;
		}
	}

	//
	// If something went wrong, clean up.  Otherwise cleanup will be done
	// by shaveRenderCallback::renderCallback(), once it's through with the
	// compositing.
	//
	if (shaveRenderCancelled)
	{
		bufferRenderCleanup();
	}

	return;
}


void shaveRender::bufferRenderCleanup()
{
	mSceneInfo.bufferValid = false;

	if (mSceneInfo.shaveRenderPixels)
	{
		free(mSceneInfo.shaveRenderPixels);
		mSceneInfo.shaveRenderPixels = NULL;
	}

	if (mSceneInfo.shaveZBuffer)
	{
		free(mSceneInfo.shaveZBuffer);
		mSceneInfo.shaveZBuffer = NULL;
	}

	SHAVEclear_stack();

	return;
}


void shaveRender::geomRender(MObjectArray& shaveHairShapes)
{
	//
	// Let shaveRenderCallback know that this is a geom render.
	//
	shaveRenderCallback::setGeomRender(true);

	//
	// This code used to only set up texture lookups if there were vertex
	// shaders in the scene, the logic being that they would need updated
	// vertex colours.  However, we still need to evaluate things such as
	// cutlength and density which might be textured.  So we need to do the
	// lookups *every* time.
	//
#ifdef PER_NODE_TEXLOOKUP
	initTexInfoLookup2(shaveHairShapes, "", mFrameGlobals.verbose);
#else
	initTexInfoLookup(shaveHairShapes, "", mFrameGlobals.verbose);
#endif
	//
	// Force each shaveHairShape to update its outputMesh.  This is needed for
	// two reasons:
	//
	// 1) When motion blur is off and we're rendering just a single frame,
	//    the last time change will have occurred just prior to
	//    renderStart().  So the outputMeshes won't have been updated since
	//    renderStart() set the mRenderAllNormalHairs/mRenderAllInstanceHairs
	//    flags, which will affect the output meshes.
	//
	// 2) We just now built the proper texture lookup for this frame, so
	//    the meshes need to pick up new values from that.
	//
	// %%% We could optimize this by only doing the loop below if motion
	//     blur is off and this is the first frame to be rendered, or if
	//     mNeedVertexColours is true.
	//
	unsigned int	i;
	unsigned int	numShaveNodes = shaveHairShapes.length();

	for (i = 0; i < numShaveNodes; i++)
	{
		MFnDependencyNode	nodeFn(shaveHairShapes[i]);
		shaveHairShape*		theShaveNode = (shaveHairShape*)nodeFn.userNode();

		//
		// Simply grabbing the hairNode will cause the output mesh to
		// recompute.
		//
		theShaveNode->getHairNode();
	}

	//
	// NOTE:	We no longer need the texture lookup tables at this point
	//			because any info we needed from them is now embedded in the
	//			output meshes built by the getHairNode() calls in the loop
	//			above.  So it's not a problem if someone else now calls
	//			initTexInfoLookup() with a different set of shaveHairShapes.
	//

	return;
}


//
// Called at the start of each frame render.  Note that for normal Maya
// renders we get called from a callback, but some renderers might call
// us via the shaveRender MEL command.
//
void shaveRender::frameStart(void * clientData)
{
    //
    // We don't support IPR.
    //
    if (isIPRActive()) return;

	mRenderState = kRenderingFrame;
	mSceneInfo.bufferValid = false;
	shaveRenderCancelled = false;

	//	We are transitioning from using a bunch of global variables to
	//	using a shaveGlobals::Globals instance to pass around the
	//	shaveGlobals values for the frame. During the transition period we
	//	have to continue to support both.
	shaveGlobals::getGlobals();
	saveFrameGlobals();

	shaveMaya::getRenderGlobals();

	SHAVEset_verbose(mFrameGlobals.verbose ? 1 : 0);
	SHAVEclear_stack();

	//
	// Do renderer-specific setup.
	//
	if (mRenderer) mRenderer->frameStart(mFrameGlobals);

	return;
}


//
// Called at the end of each frame render.  Note that for normal Maya
// renders we get called from a callback but some renderers might call
// us via the shaveRender MEL command.
//
void shaveRender::frameEnd(void * clientData)
{
    //
    // We don't support IPR.
    //
    if (isIPRActive()) return;

	//
	// Do renderer-specific cleanup.
	//
	if (mRenderer) mRenderer->frameEnd(mFrameGlobals);

	if (shaveHairShape::getNumShaveNodes() > 0)
	{
		SHAVEclear_stack();
	}

	mRenderState = kRendering;
	mFirstFrame = false;

	return;
}




/*************************************************************************
 * LIGHTS
 *************************************************************************/
void shaveRender::doLights()
{
	MStatus					st;

	MDagPath				lightPath;
	MTransformationMatrix	lightWorldMatrix;
	MVector					lightTranslation;
	double					rot[3];
	VERT					shaveDirection;

	MTransformationMatrix::RotationOrder order = MTransformationMatrix::kXYZ;

	//
	// Get our lights
	//
	shaveUtil::buildLightList();

	//
	// Loop through lights, register them with Shave
	//
	unsigned	i;
	unsigned	length = (unsigned int)shaveUtil::globalLightList.size();

	for (i = 0; i < length; i++)
	{
	    lightPath = shaveUtil::globalLightList[i].path;

	    MFnLight    lightFn(lightPath);
		MColor		lightColor = lightFn.color (&st);
		float		lightIntensity = lightFn.intensity(&st);

		if (nativeIlluminationGlob)
		{
			lightColor = MColor(1,1,1);
			lightIntensity = 1;
		}

		//
		// Look for the per-light shadow parameters.  Use defaults if
		// this light doesn't have the parameters.
		//
		MPlug	plug;
		float	shadowFuzz = 8.0f;
		short	shadowQuality = shaveGlobals::kHighShadowQuality;
		int		shadowRes = 450;
		bool	shadowTrace = false;

		if (lightPath.hasFn(MFn::kSpotLight)) shadowRes = 600;

		plug = lightFn.findPlug("shaveShadowFuzz", &st);
		if (st) plug.getValue(shadowFuzz);

		plug = lightFn.findPlug("shaveShadowResolution", &st);
		if (st) plug.getValue(shadowRes);

		plug = lightFn.findPlug("shaveShadowTrace", &st);
		if (st) plug.getValue(shadowTrace);

		//
		// Get the position of the light, in World space. 
		//
		lightWorldMatrix = lightPath.inclusiveMatrix();
		lightTranslation = lightWorldMatrix.translation(MSpace::kWorld);

		VERT shaveLightPosition;
		shaveLightPosition.x = (float)lightTranslation.x;
		shaveLightPosition.y = (float)lightTranslation.y;
		shaveLightPosition.z = (float)lightTranslation.z; 

		MColor	shadowColour = lightFn.shadowColor();

		//
		// Handle spotlights.
		//
		if (lightPath.hasFn(MFn::kSpotLight))
		{
			//
			//  DIRECTION VECTOR
			//
			lightWorldMatrix.getRotation(rot, order);

			MVector mayaDirectionVector = MVector::zAxis.rotateBy(rot, order);

			shaveDirection.x = (float) -mayaDirectionVector.x;
			shaveDirection.y = (float) -mayaDirectionVector.y;
			shaveDirection.z = (float) -mayaDirectionVector.z;

			//
			// UP VECTOR
			//
			MVector mayaUpVector = MVector::yAxis.rotateBy(rot, order);

			VERT	shaveUpVector;
			shaveUpVector.x = (float) mayaUpVector.x;
			shaveUpVector.y = (float) mayaUpVector.y;
			shaveUpVector.z = (float) mayaUpVector.z;

			//
			// Cone Angle
			//
			const float		kRad2degrees = (float)(180.0 / M_PI); 
			MFnSpotLight	spotFn(lightPath);

			float lightConeAngle = (float)
					(spotFn.coneAngle() + spotFn.penumbraAngle() * 2.0);
			lightConeAngle = ((float)lightConeAngle) * kRad2degrees;

			Matrix shaveLightMatrix;
	 
			SHAVEmake_view_matrix(
				shaveLightMatrix,
				shaveUpVector,
				shaveDirection,
				shaveLightPosition,
				lightConeAngle
			); 
			
			shaveUtil::globalLightList[i].minId =
				SHAVEadd_light(
					lightColor.r*lightIntensity,
					lightColor.g*lightIntensity,
					lightColor.b*lightIntensity,
					shaveLightMatrix,
					shaveLightPosition,
					shadowRes,
					shadowRes,
					1.0,
					lightConeAngle,
					shadowFuzz,
					shadowQuality,
					(float)shadowColour.r,
					(float)shadowColour.g,
					(float)shadowColour.b,
					(shadowTrace ? 1 : 0),
					0.01f
				);
			shaveUtil::globalLightList[i].maxId = shaveUtil::globalLightList[i].minId;
		}
		//
		// Handle all other light types.
		//
		else
		{
			shaveUtil::globalLightList[i].minId =
				SHAVEadd_point_light(
					lightColor.r*lightIntensity,
					lightColor.g*lightIntensity,
					lightColor.b*lightIntensity,
					shaveLightPosition,
					shadowRes,
					shadowRes,
					shadowFuzz,
					shadowQuality,
					(float)shadowColour.r,
					(float)shadowColour.g,
					(float)shadowColour.b,
					(shadowTrace ? 1 : 0),
					0.01f
				);

			//
			// Internally, Shave generates 6 lights for each non-spotlight
			// we register using the above function.
			//
			shaveUtil::globalLightList[i].maxId = shaveUtil::globalLightList[i].minId + 5;
		}

		//
		// Keep track of if we have any traced lights.
		//
		if (shadowTrace) mSceneInfo.haveTracedLights = true;
	}

	return;
}


/*************************************************************************
 * CAMERA
 *
 * A *LOT* of voodoo here. Maya Z and Shave Z are opposites. So we flip
 * it on our end. This affects the handed-ness of rotations along
 * X and Y (but not Z). Maya's FOV is horizontal, Shave's camera is vertical.
 * Maya has the concept of a camera's viewing fustrum (aspect, FOV) being 
 * different than the rendering (globals) fustrum. This is because Maya looks
 * at the FILM aperture (width & height) for calculating its camera FOV and
 * aspect, while Shave uses the rendering globals. Can't we all just get along?
 *************************************************************************/



/*************************************************************************
 * SCENE GEOMETRY
 *************************************************************************/
void shaveRender::buildOcclusionLists(shaveConstant::ShutterState shutter)
{
	static bool	firstTime = true;

	if (firstTime)
	{
		init_geomWF(&mSceneInfo.shutterOpenCamScene);
		init_geomWF(&mSceneInfo.shutterCloseCamScene);
		init_geomWF(&mSceneInfo.shutterOpenShadowScene);
		init_geomWF(&mSceneInfo.shutterCloseShadowScene);
		firstTime = false;
	}

	static MDagPathArray	camOcclusions;
	static MDagPathArray	shadowOcclusions;
	shaveObjTranslator		x;

	if ((shutter == shaveConstant::kShutterOpen)
		|| (shutter == shaveConstant::kShutterBoth))
	{
		camOcclusions.clear();
		shadowOcclusions.clear();

		//
		// When doing 2D compositing, we ignore transparency: the user must
		// switch to 3D if zie wants to see hair through glass.
		//
		bool			ignoreTransparency = doShaveComp2dGlob;
		unsigned int	i;
		MStringArray	occlusionNames;
		MDagPath		occlusionPath;
		MSelectionList	tmpSel;

		if (shaveSceneObjectsGlob == "all")
		{
			MGlobal::executeCommand("ls -g", occlusionNames);

			for (i = 0; i < occlusionNames.length(); i++)
			{
				tmpSel.clear();
				tmpSel.add(occlusionNames[i]);
				tmpSel.getDagPath(0, occlusionPath);

				//
				// If native illumination is on, then we only do
				// occlusions for the cam pass, not the shadow pass.
				//
				if (nativeIlluminationGlob)
				{
					if (areObjectAndParentsVisible(
							occlusionPath, true, false, ignoreTransparency)) 
					{
						camOcclusions.append(occlusionPath);
					}
				}
				else
				{
					//
					// For shadows, we ignore transparency and primary
					// visibility.
					//
					if (areObjectAndParentsVisible(
							occlusionPath, true, true, true))
					{
						shadowOcclusions.append(occlusionPath);

						//
						// For the cam pass, we don't want objects whose
						// primary visibility is off or which have any
						// transparency to be treated as occlusions.
						//
						if (areObjectAndParentsVisible(
							occlusionPath, true, false, ignoreTransparency)) 
						{
							camOcclusions.append(occlusionPath);
						}
					}
				}
			}
		}
		else
		{
			shaveSceneObjectsGlob.split(' ', occlusionNames);

			for (i = 0; i < occlusionNames.length(); i++)
			{
				tmpSel.clear();
				tmpSel.add(occlusionNames[i]);
				tmpSel.getDagPath(0, occlusionPath);

				camOcclusions.append(occlusionPath);

				if (!nativeIlluminationGlob)
					shadowOcclusions.append(occlusionPath);
			}
		}

		if (mFrameGlobals.verbose) cerr << "built occlusion list." << endl;

		x.exportOcclusion(camOcclusions, &mSceneInfo.shutterOpenCamScene);

		if (!nativeIlluminationGlob)
		{
			x.exportOcclusion(
				shadowOcclusions, &mSceneInfo.shutterOpenShadowScene
			);
		}
	}

	//
	// If there's no motion blur then shutter open and close are identical
	// and we can just use the same data for both.  So we only need to
	// gather occlusions for shutter close if motion blur is on.
	//
	if ((shaveMaya::doMotionBlur)
	&&	((shutter == shaveConstant::kShutterClose)
		|| (shutter == shaveConstant::kShutterBoth)))
	{
		x.exportOcclusion(camOcclusions, &mSceneInfo.shutterCloseCamScene);

		if (!nativeIlluminationGlob)
		{
			x.exportOcclusion(
				shadowOcclusions, &mSceneInfo.shutterCloseShadowScene
			);
		}
	}

	return;
}
 

/*
 * Modify our color projection map (for hair-to-object shadows) with the
 * color of the light. I thought intensity would also need to be
 * multiplied in, but I was wrong.
 */
void shaveRender::doColorCorrection (MColor colorMod, short mapWidth, short mapHeight, unsigned char* mapBuffer)
{

	for (int x=0; x < mapWidth*mapHeight*4; x += 4)
	{
		// RED
		mapBuffer[x+0] = (unsigned char) ((float) mapBuffer[x+0] * colorMod.r );
		//GREEN
		mapBuffer[x+1] = (unsigned char) ((float) mapBuffer[x+1] * colorMod.g );
		//BLUE
		mapBuffer[x+2] = (unsigned char) ((float) mapBuffer[x+2] * colorMod.b );
	}

}

/*
 * Correct black levels, to control hair-on-skin shadow density.
 */
void shaveRender::doDensityCorrection (float density, short mapWidth, short mapHeight, unsigned char* mapBuffer)
{
	/*
	 * Tint values towards white.
	 * Density range is 0.0-1.0
	 */
	for (int x=0; x < mapWidth*mapHeight*4; x += 4)
	{ 
		mapBuffer[x+0] = (unsigned char)
						((float)mapBuffer[x+0] * density + 255.*(1.0-density)); 

		mapBuffer[x+1] = (unsigned char)
						((float)mapBuffer[x+1] * density + 255.*(1.0-density)); 

		mapBuffer[x+2] = (unsigned char)
						((float)mapBuffer[x+2] * density + 255.*(1.0-density)); 
	} 
}


//
// Called at the start of a render of a group of one or more frames.  Note
// that for normal Maya renders we get called from a callback but some
// renderers may call us via the shaveRender MEL command.
//
void shaveRender::renderStart(void* clientData)
{
	//
	// We don't support IPR.
	//
	if (isIPRActive()) return;

	//
	// If a render crashes (e.g. due to insufficient memory) Maya won't
	// send us the renderEnd event.  So let's make sure that there isn't
	// anything lying around from a previous render.
	//
	bufferRenderCleanup();

	mRenderState = kRendering;
	mFirstFrame = true;

	//
	// Make sure we start out with a fresh renderer instance.
	//
	if (mRenderer != NULL)
	{
		delete mRenderer;
		mRenderer = NULL;
	}

	getRenderer();

	//
	// Make sure that the display nodes are all in the same render layer as
	// at least on of their growth surfaces.
	//
	MGlobal::executeCommand("shave_assignRenderLayers");


	//*******************************************************************
	//
	//					Get The Shave Nodes
	//
	//*******************************************************************

	shaveGlobals::getGlobals();

	MObjectArray	shaveHairShapes;
	shaveUtil::getShaveNodes(shaveHairShapes);

	unsigned int	numShaveNodes = shaveHairShapes.length();


	//*******************************************************************
	//
	//					Get The Render Modes
	//
	//*******************************************************************

	mHairRenderMode = mRenderer->getFilteredRenderMode(
						shaveHairShapes, &mRenderInstances
					);

	//
	// Go no further if there's nothing to render.
	//
	if ((mHairRenderMode == shaveConstant::kNoRender) && !mRenderInstances)
	{
		delete mRenderer;
		mRenderer = NULL;

		return;
	}


	//*******************************************************************
	//
	//					Determine Shadow Sources
	//
	//*******************************************************************

	//
	// Let's figure out where our shadows are coming from.
	//
	mNormalShadows = mRenderer->getShadowSource();


	//*******************************************************************
	//
	//					Set Templating & Visibility
	//
	//*******************************************************************

	//
	// We may not want display geometry showing up in the render, or we
	// might only want it showing up in secondary effects, such as shadows,
	// so ask the renderer what we should do with it.
	//
	// Note that we need to do it now, before the first call to frameStart,
	// because we want the full geometry available at the start of the
	// render, when the renderer does its automatic clipping plane
	// calculations.  Otherwise it might end up clipping some of our
	// geometry later on.
	//
	bool	hairPrimaryVisibility;
	bool	hairSecondaryVisibility;
	bool	instancePrimaryVisibility;
	bool	instanceSecondaryVisibility;

	mRenderer->getGeomVisibility(
		hairPrimaryVisibility,
		hairSecondaryVisibility,
		instancePrimaryVisibility,
		instanceSecondaryVisibility
	);

	unsigned int	i;
	bool			shouldBeTemplated;
	bool			shouldBeVisible;

	mHiddenNodes.clear();
	mTemplatedNodes.clear();

	for (i = 0; i < numShaveNodes; i++)
	{
		//
		// Find the shaveHairShape's display node.
		//
		MFnDependencyNode	nodeFn(shaveHairShapes[i]);
		shaveHairShape*			nodePtr = (shaveHairShape*)nodeFn.userNode();

		MObject	displayNode = nodePtr->getDisplayShape();

		if (!displayNode.isNull())
		{
			//
			// Set the display node's templating, as appropriate.
			//
			nodeFn.setObject(displayNode);

			if (nodePtr->isInstanced())
			{
				shouldBeVisible = instancePrimaryVisibility;
				shouldBeTemplated = (!instancePrimaryVisibility
								  && !instanceSecondaryVisibility);
			}
			else
			{
				shouldBeVisible = hairPrimaryVisibility;
				shouldBeTemplated = (!hairPrimaryVisibility
								  && !hairSecondaryVisibility);
			}

			bool	isTemplated = false;
			bool	isVisible = false;
			MPlug	plug;

			plug = nodeFn.findPlug("template");
			plug.getValue(isTemplated);

			if (isTemplated != shouldBeTemplated)
			{
				plug.setValue(shouldBeTemplated);
				mTemplatedNodes.append(displayNode);
			}

			//
			// If the display node is not templated we may still need to
			// adjust its primary visibility.
			//
			if (!shouldBeTemplated)
			{
				plug = nodeFn.findPlug("primaryVisibility");
				plug.getValue(isVisible);

				if (isVisible != shouldBeVisible)
				{
					plug.setValue(shouldBeVisible);
					mHiddenNodes.append(displayNode);
				}
			}
		}

		//
		// Let the shaveHairShape know about the new render state.
		//
		MPlug	renderStatePlug(
					shaveHairShapes[i], shaveHairShape::renderStateAttr
				);

		renderStatePlug.setValue(mRenderState);
	}


	//*******************************************************************
	//
	//			Set Up Vertex Shaders
	//
	//*******************************************************************

	//
	// If we're using geometry for hair, for shadows, or for instances,
	// then we'll need to create/update vertex shaders for those shaveHairShapes
	// with their geom shader override turned on.
	//
	if ((mHairRenderMode == shaveConstant::kGeometryRender)
	||	(mNormalShadows == shaveConstant::kMayaGeomShadows)
	||	mRenderInstances)
	{
		MGlobal::executeCommand("shave_prepareVertexShaders");
	}

	//
	// Do we need to set up vertex colours?
	//
	mNeedVertexColours = mRenderer->needVertexColours();


	//*******************************************************************
	//
	//			Turn Off Automatic Clipping Planes
	//
	//*******************************************************************

	//
	// Automatic clipping planes cause us all kinds of problems because
	// they're evaluated before frameStart() gets called, which means that
	// any geometry created on a per-frame basis (e.g. the camera's render
	// cone) may end up getting clipped.
	//
	// So let's just turn it off.  We turn it off on all cameras just in
	// case the render camera changes in mid-sequence.
	//
	mSceneInfo.autoClipCameras.clear();

	if (numShaveNodes > 0)
	{
		MItDag			dagIter(MItDag::kDepthFirst, MFn::kCamera);
		AutoClipInfo	camInfo;

		camInfo.nearClipChanged = false;
		camInfo.farClipChanged = false;

		for (; !dagIter.isDone(); dagIter.next())
		{
			dagIter.getPath(camInfo.cameraPath);

			MFnCamera	cameraFn(camInfo.cameraPath);
			MPlug		plug = cameraFn.findPlug("bestFitClippingPlanes");
			bool		autoClipOn;

			plug.getValue(autoClipOn);

			if (autoClipOn)
			{
				plug.setValue(false);

				camInfo.origNearClip = cameraFn.nearClippingPlane();
				camInfo.origFarClip = cameraFn.farClippingPlane();

				//
				//	We shouldn't be doing this here since we don't know
				//	the render cam yet, but Joe doesn't want to pay to do
				//	it properly, so we're stuck with issuing spurious
				//	warnings.
				//
				if (!cameraFn.isOrtho())
				{
					float diff;

					diff = (float)(camInfo.origFarClip - camInfo.origNearClip);

					if (diff == camInfo.origFarClip)
					{
						MGlobal::displayWarning(
							"Shave does not support autoclip.  The clipping"
							" range is larger than Maya can support.  Your"
							" surfaces may appear black as a result."
						);
					}
				}

				mSceneInfo.autoClipCameras.push_front(camInfo);
			}
		}
	}

	//
	// Do any renderer-specific setup.
	//
	mRenderer->renderStart();

	//
	// Setup up a callback for time changes.
	//
	mTimeChangeCallback = MDGMessage::addForceUpdateCallback(timeChanged);

	return;
}


//
// Called at the end of a render of a group of one or more frames.  Note
// that for normal Maya renders we get called from a callback but some
// renderers may call us via the shaveRender MEL command.
//
void shaveRender::renderEnd(void* clientData)
{
	//
	// We don't support IPR.
	//
	if (isIPRActive()) return;

	mRenderState = kRenderNone;

	//
	// If there's nothing to render, then there's nothing to undo.
	//
	if ((mHairRenderMode == shaveConstant::kNoRender) && !mRenderInstances)
	{
		return;
	}

	MDGMessage::removeCallback(mTimeChangeCallback);

	//
	// Do renderer-specific cleanup.
	//
	if (mRenderer) mRenderer->renderEnd();

	//
	// Restore automatic clipping planes to those cameras which had them
	// turned on.
	//
	MPlug				plug;
	AutoClipListIter	iter;

	for (iter = mSceneInfo.autoClipCameras.begin();
		 iter != mSceneInfo.autoClipCameras.end();
		 iter++)
	{
		MFnCamera	cameraFn(iter->cameraPath);

		if (iter->nearClipChanged)
			cameraFn.setNearClippingPlane(iter->origNearClip);

		if (iter->farClipChanged)
			cameraFn.setFarClippingPlane(iter->origFarClip);

		//
		// If we turn the camera's auto clipping back on right now, either
		// by setting its plug or executing a 'setAttr' command, then for
		// some reason Maya will reset both of the camera's clipping planes
		// to 0.1.
		//
		// But if we do it as a deferred command, then it retains the
		// clipping planes.
		//
		// Just more of the magic of Maya...
		//
		MGlobal::executeCommand(
			MString("evalDeferred \"setAttr ")
			+ iter->cameraPath.fullPathName()
			+ ".bestFitClippingPlanes true \""
		);
	}

	mSceneInfo.autoClipCameras.clear();

	shaveGlobals::getGlobals();

	//
	// Remove any vertex shaders we set up.
	//
	if ((mHairRenderMode == shaveConstant::kGeometryRender)
	||	(mNormalShadows == shaveConstant::kMayaGeomShadows)
	||	mRenderInstances)
	{
		MGlobal::executeCommand("shave_destroyVertexShaders");
	}

	//
	// Toggle the templating of any display nodes which we changed,
	// back to their original settings.
	//
	unsigned int	i;
	unsigned int	numTemplatedNodes = mTemplatedNodes.length();

	for (i = 0; i < numTemplatedNodes; i++)
	{
		MFnDependencyNode	nodeFn(mTemplatedNodes[i]);
		MPlug				plug = nodeFn.findPlug("template");
		bool				isTemplated;

		plug.getValue(isTemplated);
		plug.setValue(!isTemplated);
	}

	mTemplatedNodes.clear();

	//
	// Toggle the primary visibility of any display nodes which we changed,
	// back to their original settings.
	//
	unsigned int	numHiddenNodes = mHiddenNodes.length();

	for (i = 0; i < numHiddenNodes; i++)
	{
		MFnDependencyNode	nodeFn(mHiddenNodes[i]);
		MPlug				plug = nodeFn.findPlug("primaryVisibility");
		bool				isHidden;

		plug.getValue(isHidden);
		plug.setValue(!isHidden);
	}

	mHiddenNodes.clear();

	//
	// Reset the first frame flag to true for the sake of Shave API calls.
	//
	// See the initialization of 'mFirstFrame' near the top of this file
	// for more details on why we do this here.
	//
	mFirstFrame = true;

	//
	// Let the shaveHairShapes know about the new render state.
	//
	MObjectArray	shaveHairShapes;
	shaveUtil::getShaveNodes(shaveHairShapes);

	unsigned int	numShaveNodes = shaveHairShapes.length();

	for (i = 0; i < numShaveNodes; i++)
	{
		MPlug	plug(shaveHairShapes[i], shaveHairShape::renderStateAttr);

		plug.setValue(mRenderState);
	}

	//
	// Get rid of the renderer instance.
	//
	delete mRenderer;
	mRenderer = NULL;

	return;
}


void shaveRender::renderInterrupted(void* clientData)
{
	//
	// We don't support IPR.
	//
	if (isIPRActive()) return;

	if (mRenderer) mRenderer->renderInterrupted();

	if (mRenderState == kRendering)
		renderEnd(NULL);
	else if (mRenderState != kRenderNone)
	{
		frameEnd(NULL);
		renderEnd(NULL);
	}

	return;
}


void shaveRender::setupCallbacks()
{
	if (!mCallbacksSet)
	{
		mBeforeRenderCallback =
				MSceneMessage::addCallback(
					MSceneMessage::kBeforeSoftwareRender,
					renderStart
				);

		mAfterRenderCallback =
				MSceneMessage::addCallback(
					MSceneMessage::kAfterSoftwareRender,
					renderEnd
				);

		mBeforeFrameRenderCallback =
				MSceneMessage::addCallback(
					MSceneMessage::kBeforeSoftwareFrameRender,
					frameStart
				);

		mAfterFrameRenderCallback =
				MSceneMessage::addCallback(
					MSceneMessage::kAfterSoftwareFrameRender,
					frameEnd
				);

		mRenderInterruptedCallback =
				MSceneMessage::addCallback(
					MSceneMessage::kSoftwareRenderInterrupted,
					renderInterrupted
				);

		mCallbacksSet = true;
	}
}


void shaveRender::cleanupCallbacks()
{
	if (mCallbacksSet)
	{
		MSceneMessage::removeCallback(mBeforeRenderCallback);
		MSceneMessage::removeCallback(mAfterRenderCallback);
		MSceneMessage::removeCallback(mBeforeFrameRenderCallback);
		MSceneMessage::removeCallback(mAfterFrameRenderCallback);
		MSceneMessage::removeCallback(mRenderInterruptedCallback);

		mCallbacksSet = false;
	}
}


//	vlad|15Apr2010
//
bool shaveRender::rendererIsVray()
{
	MStatus			status;
	int				isVray = false;

	status = MGlobal::executeCommand("shave_rendererIsVray", isVray);

	return (status && isVray);
}

bool shaveRender::rendererIsPrMan()
{
	MStatus			status;
	int isPrMan = 0;
	status = MGlobal::executeCommand("shave_curRendererIsPrMan", isPrMan);

	return (status && isPrMan);
}


int shaveRender::renderCameraView(const MDagPath& cameraPath)
{
	int renderReturnVal = 0;

	shaveGlobals::getGlobals();

	SceneInfo* shaveData = getSceneInfo();

	if (doShaveCompsGlob || keepHairRenderFilesGlob)
	{
		shadowRender = false;

		SHAVEcalibrate(0.0f, -.05f);
//			SHAVEcalibrate(-.25f,0.0f);

		if (shaveMaya::doMotionBlur)
		{
			renderReturnVal = SHAVErender_cam(
								&mSceneInfo.shutterOpenCamScene, 
								&mSceneInfo.shutterCloseCamScene,
								mSceneInfo.aa, 
								(unsigned char*)mSceneInfo.shaveRenderPixels,
								mSceneInfo.shaveZBuffer,
								0,
								0,
								mSceneInfo.width-1,
								mSceneInfo.height-1,
								mSceneInfo.width,
								mSceneInfo.height,
								3
							);
		}
		else
		{
			renderReturnVal = SHAVErender_camNOBLUR(
								&mSceneInfo.shutterOpenCamScene, 
								&mSceneInfo.shutterOpenCamScene, 
								mSceneInfo.aa, 
								(unsigned char*)mSceneInfo.shaveRenderPixels,
								mSceneInfo.shaveZBuffer,
								0,
								0,
								mSceneInfo.width-1,
								mSceneInfo.height-1,
								mSceneInfo.width,
								mSceneInfo.height,
								3
							);
		}

		if (mFrameGlobals.verbose)
			cerr << "Pixel render returned: " << renderReturnVal << endl;

		//
		// Did this camera have automatic clipping planes on?
		//
		AutoClipListIter	iter;

		for (iter = mSceneInfo.autoClipCameras.begin();
			 iter != mSceneInfo.autoClipCameras.end();
			 iter++)
		{
			if (iter->cameraPath == cameraPath) break;
		}

		if (iter != mSceneInfo.autoClipCameras.end())
		{
			//
			// Find the min and max depth values in the image.
			//
			bool		gotDepth = false;
			int			i;
			int			numPixels = mSceneInfo.height * mSceneInfo.width;
			float		depth;
			float		minDepth = 0.0f;
			float		maxDepth = 0.0f;

			for (i = 0; i < numPixels; i++)
			{
				depth = mSceneInfo.shaveZBuffer[i];

				if (depth != SHAVE_FAR_CLIP)
				{
					if (!gotDepth)
					{
						minDepth = maxDepth = depth;
						gotDepth = true;
					}
					else if (depth < minDepth)
						minDepth = depth;
					else if (depth > maxDepth)
						maxDepth = depth;
				}
			}

			if (gotDepth)
			{
				//
				// We want to make sure that the camera's clipping planes
				// catch all of our generated pixels.  So if a pixel lies
				// outside of the volume bounded by the near and far
				// clipping planes, then we will need to move them so that
				// the pixel is included.
				//
				// Shave's depths represent linear distance from the
				// camera while Maya's clip values are the Z coordinates of
				// the clipping planes in camera space.
				//
				// Now let's look at two points in camera space: [0, 0, 5]
				// and [4, 2, 4].  The first point is 5 units away from the
				// camera while the second point is 6 units away from the
				// camera.  So the first point is closer to the camera.
				//
				// However, if we set Maya's near clipping plane to a value
				// of 5, it will still clip the second point.  That's
				// because while the second point is farther from the
				// camera than the first, it is still closer along the
				// camera's Z-axis, and that's what counts when clipping.
				// The camera does not clip at a uniform distance but
				// rather at a uniform Z coordinate, which means that the
				// clipping distance increases the further you get from the
				// camera's Z-axis.
				//
				// To do the job properly, we should convert each non-empty
				// Shave pixel to a camera-space position, then find the
				// one with the lowest Z coord. However, that's a bit
				// expensive in terms of computation, so instead we'll
				// cheat a bit.
				//
				// The points on the clipping plane which are most distant
				// from the camera are at the far corners of the plane.  If
				// we pull the near clipping plane in so that even those
				// corner points are as close as the minimum depth in
				// Shave's depth buffer, then we'll be guaranteed that our
				// nearest pixel doesn't get clipped.
				//
				// For the far clipping plane, our job is easier.  We want
				// to push the far clipping plane out until its point
				// nearest the camera is at least as far away as Shave's
				// largest depth value.  The point nearest the camera on
				// the far clipping plane is directly along the Z-axis.  So
				// we can just move the far clipping plane to Shave's max
				// depth value and that will work.
				//
				// I call all of this "cheating" because we'll frequently
				// end up pulling the near clipping plane in closer to the
				// camera, and pushing the far plane farther from the
				// camera, than we really need to.  But it's unlikely that
				// anyone will care.  If they do, then we can switch to the
				// full-blown approach.
				//

				//
				// The first step is to get the camera's near and far
				// clipping planes.
				//
				MFnCamera	cameraFn(cameraPath);
				double		nearClip = cameraFn.nearClippingPlane();
				double		farClip = cameraFn.farClippingPlane();

				//
				// If Shave's max depth is greater than the camera's far
				// clip, then reset the clip.
				//
				if (maxDepth > farClip)
				{
					cameraFn.setFarClippingPlane((double)maxDepth);
					iter->farClipChanged = true;
				}

				//
				// For the near clipping plane, find a corner of the
				// frustum.
				//
				MPoint	frustumCorners[4];

				cameraFn.getFilmFrustum(1.0, frustumCorners);

				//
				// Turn it into a normalized vector.
				//
				MVector	vec(
							frustumCorners[0].x,
							frustumCorners[0].y,
							frustumCorners[0].z
						);

				vec.normalize();

				//
				// Multiply it by our minimum depth value.  This will give
				// us the position vector for a corner point at the minimum
				// depth.
				//
				vec *= minDepth;

				//
				// If the resulting z-coord is smaller than the near clip
				// value, then set the near clip to the z-coord value.
				//
				if (vec.z < nearClip)
				{
					cameraFn.setNearClippingPlane((double)vec.z);
					iter->nearClipChanged = true;
				}
			}
		}

		shaveData->bufferValid = true;
	}

	MGlobal::executeCommand("shave_closeProgressBar()");

	if (keepHairRenderFilesGlob)
	{
		MString	outFilename;
		int		intFrame;

		if (mSceneInfo.currentFrame < 0)
			intFrame = (int)(mSceneInfo.currentFrame - 0.5f);
		else
			intFrame = (int)(mSceneInfo.currentFrame + 0.5f);

		outFilename = hairFileNameGlob + ".";
		outFilename += intFrame;
		outFilename += ".tga";

		if (mFrameGlobals.verbose) {
#if defined(OSMac_) && (MAYA_API_VERSION >= 201600) && (MAYA_API_VERSION < 201700)
			cerr << "Outputting to " << outFilename.asChar() << endl;
#else
			cerr << "Outputting to " << outFilename << endl;
#endif
		}

		SHAVEwrite_targa(
			(char *)outFilename.asChar(),
			(short)mSceneInfo.width,
			(short)mSceneInfo.height,
			(unsigned char*)mSceneInfo.shaveRenderPixels
		);
	}

	return renderReturnVal;
}


void shaveRender::doCamera(
		const MDagPath& camPath,
		shaveConstant::ShutterState shutter,
		shaveRender::SceneInfo& shaveData
)
{
	Matrix	camvm;
	MVector	mayaUpVector, mayaDirectionVector;
	double	rotationVector[3];
	VERT	shaveUpVector, shaveDirection, shavePosition;
	MVector	unitDirectionVector(0., 0., 1.);
	MVector	unitUpVector(0., 1., 0.);

	MTransformationMatrix::RotationOrder order = MTransformationMatrix::kXYZ;

	MTransformationMatrix	camWorldMatrix = camPath.inclusiveMatrix();
	MFnCamera				fnCamera(camPath);

	//
	// Get MAYA camera translation and rotation info
	//
	MVector translation = camWorldMatrix.translation(MSpace::kWorld);

	camWorldMatrix.getRotation(rotationVector, order);

	//
	// Set SHAVE camera position in World space
	//
	shavePosition.x = (float) translation.x;
	shavePosition.y = (float) translation.y; 
	shavePosition.z = (float) translation.z;
	
	//
	// UP VECTOR
	//
	mayaUpVector = unitUpVector.rotateBy(rotationVector, order);
	shaveUpVector.x = (float) mayaUpVector.x;
	shaveUpVector.y = (float) mayaUpVector.y;
	shaveUpVector.z = (float) mayaUpVector.z;

	//
	//  DIRECTION VECTOR
	//
	mayaDirectionVector = unitDirectionVector.rotateBy(rotationVector, order);
	shaveDirection.x = (float) -mayaDirectionVector.x;
	shaveDirection.y = (float) -mayaDirectionVector.y;
	shaveDirection.z = (float) -mayaDirectionVector.z;

	//
	// FIELD OF VIEW
	//
	float	pixelAspect = mRenderer ? mRenderer->getPixelAspect() : 1.0f;
	double	hfovagain, vfovagain;

	portFieldOfView(
		shaveMaya::imageWidth,
		shaveMaya::imageHeight,
		pixelAspect,
		hfovagain,
		vfovagain,
		fnCamera
	);

	const float rad2degrees = (180.0f / (float)M_PI); 

	vfovagain *= rad2degrees;

	if (mFrameGlobals.verbose)
	{
#if 0
#ifdef OSMac_
		//
		// Panther broke cerr somehow so that it crashes if you use it on
		// non-zero float or double values.  So let's try our old pal
		// stderr, instead.
		//
		if (stderr) fprintf(stderr, "pixel aspect is: %f\n", pixelAspect);
#else
		cerr << "pixel aspect is: " << pixelAspect << endl;
#endif
#endif
	}

	SHAVEmake_view_matrix(
		camvm, shaveUpVector, shaveDirection, shavePosition, (float)vfovagain
	);


	/*
	 * Register the camera with Shave
	 */
	if ((shutter == shaveConstant::kShutterOpen)
	||	(shutter == shaveConstant::kShutterBoth))
	{		
		SHAVEset_cameraOPEN(
			camvm,
			shavePosition,
			shaveData.width,
			shaveData.height,
			pixelAspect,
			(float)vfovagain,
			0.01f
		);	
	}

	if ((shutter == shaveConstant::kShutterClose)
	||	(shutter == shaveConstant::kShutterBoth))
	{
		SHAVEset_cameraCLOSE(camvm, shavePosition);
	}

	return;
}


void shaveRender::computeViewingFrustum(
		double		image_aspect,
        double&		left,
        double&		right,
        double&		bottom,
        double&		top,
		MFnCamera&	cam
)
{
    double film_aspect = cam.aspectRatio();
    double aperture_x = cam.horizontalFilmAperture();
    double aperture_y = cam.verticalFilmAperture();
    double offset_x = cam.horizontalFilmOffset();
    double offset_y = cam.verticalFilmOffset();
    double focal_to_near = cam.nearClippingPlane() /
						   (cam.focalLength() * MM_TO_INCH);
// 88360

    focal_to_near *= cam.cameraScale();

    double scale_x = 1.0;
    double scale_y = 1.0;
    double translate_x = 0.0;
    double translate_y = 0.0;

	switch (cam.filmFit()) {
		case MFnCamera::kFillFilmFit:
			//	In Fill mode we want to keep the entire image within the
			//	viewing frustum. If the image's aspect ratio is greater
			//	than that of the film then we'll do a horizontal fit,
			//	otherwise we'll do a vertical fit.
			if (image_aspect > film_aspect)
				scale_y = film_aspect / image_aspect;
			else
				scale_x = image_aspect / film_aspect;
		break;
 
		case MFnCamera::kHorizontalFilmFit:
			scale_y = film_aspect / image_aspect;
 
			if (scale_y > 1.0)
			{
				translate_y = cam.filmFitOffset() *
					(aperture_y - (aperture_y * scale_y)) / 2.0;
			}
		break;
 
		case MFnCamera::kVerticalFilmFit:
			scale_x = image_aspect / film_aspect;

			if (scale_x > 1.0)
			{
				translate_x = cam.filmFitOffset() *
					(aperture_x - (aperture_x * scale_x)) / 2.0;
			}
		break;
 
		case MFnCamera::kOverscanFilmFit:
			//	In Overscan mode we allow the edges of the image to extend
			//	beyond the viewing frustum.  If the image's aspect ratio is
			//	greater than that of the film then we'll do a vertical fit,
			//	allowing the left and right edges to extend beyond the
			//	frustum.  Otherwise we'll do a horizontal fit, allowing the
			//	top and bottom edges to extend beyond the frustum.
			if (image_aspect > film_aspect)
				scale_x = image_aspect / film_aspect;
			else
				scale_y = film_aspect / image_aspect;
		break;

		case MFnCamera::kInvalid:
		break;
    }
    

    left   = focal_to_near * (-.5*aperture_x*scale_x+offset_x+translate_x);
    right  = focal_to_near * ( .5*aperture_x*scale_x+offset_x+translate_x);
    bottom = focal_to_near * (-.5*aperture_y*scale_y+offset_y+translate_y);
    top    = focal_to_near * ( .5*aperture_y*scale_y+offset_y+translate_y);
}


void shaveRender::portFieldOfView(
		int port_width,
		int port_height,
		double pixelAspect,
		double& horizontal,
		double& vertical,
		MFnCamera& fnCamera
)
{
    double left, right, bottom, top;
    double aspect =  pixelAspect * (double)port_width / (double)port_height;
    computeViewingFrustum(aspect,left,right,bottom,top,fnCamera);

    double neardb = fnCamera.nearClippingPlane();
    horizontal = atan(((right - left) * 0.5) / neardb) * 2.0;
    vertical = atan(((top - bottom) * 0.5) / neardb) * 2.0;
}


void shaveRender::buildHairStack(
	MObjectArray& shaveHairShapes, shaveConstant::ShutterState shutter
)
{
	unsigned int	i;
	unsigned int	numShaveNodes = shaveHairShapes.length();

	//
	// Register the hair nodes.
	//
		if ((shutter == shaveConstant::kShutterOpen)
		||	(shutter == shaveConstant::kShutterBoth))
			SHAVEclear_stack();

	for (i = 0; i < numShaveNodes; i++)
	{
		MFnDependencyNode	nodeFn(shaveHairShapes[i]);
		shaveHairShape*		hairShape = (shaveHairShape*)nodeFn.userNode();
		SHAVENODE*			hairNode = hairShape->getHairNode();

		hairShape->setStackIndex(i);

		if ((shutter == shaveConstant::kShutterOpen)
		||	(shutter == shaveConstant::kShutterBoth))
		{
			//
			// Remove any old UV sets and add the current ones.
			// Note that this *must* be done on the add_hairOPEN call:
			// add_hairCLOSE is too late.
			//
			hairShape->removeShaveUVSets();
			hairShape->addShaveUVSets();
			SHAVEadd_hairOPEN2(hairNode, (int)i);
		}

		if ((shutter == shaveConstant::kShutterClose)
		||	(shutter == shaveConstant::kShutterBoth))
		{
			SHAVEadd_hairCLOSE2(hairNode, (int)i);
		}
	}

	SHAVEset_stack_max(numShaveNodes);

	return;
}


void shaveRender::clearHairStack(MObjectArray& shaveHairShapes)
{
	unsigned int	i;
	unsigned int	numShaveNodes = shaveHairShapes.length();

	//
	// Remove the UV sets from the nodes, so that they don't waste mem.
	//
	for (i = 0; i < numShaveNodes; i++)
	{
		MFnDependencyNode	nodeFn(shaveHairShapes[i]);
		shaveHairShape*		hairShape = (shaveHairShape*)nodeFn.userNode();

		hairShape->removeShaveUVSets();
	}

	SHAVEclear_stack();

	return;
}


void shaveRender::timeChanged(MTime& newTime, void* clientData)
{
	if (mRenderer) mRenderer->timeChange(newTime);

	return;
}


MStatus shaveRender::renderSwatch(
	MObject shaveHairShapeObj, unsigned int res, MString fileName
)
{
	unsigned char*		image = new unsigned char[res*res*4];
	float*				zbuff = new float[res*res];

	MFnDependencyNode	nodeFn(shaveHairShapeObj);
	shaveHairShape*		theShaveNode = (shaveHairShape*)nodeFn.userNode();
	SHAVENODE*			hairNode = theShaveNode->getHairNode();

	theShaveNode->makeCurrent();

	//
	// Let's not have the progress bar for such a short render.
	//
	shaveRenderCancelled = false;
	shaveEnableProgressBar = false;
	SHAVErender_swatch(image, zbuff, res, &hairNode->shavep);
	shaveEnableProgressBar = true;

	delete [] zbuff;

	bool	success = shaveXPM::write(res, res, image, fileName);

	delete [] image;

	if (!success) return MS::kFailure;

	return MS::kSuccess;
}


MStatus shaveRender::getShutterTimes(float& shutterOpen, float& shutterClose)
{
	//
	// Get the current render camera.
	//
	MDagPath		cameraPath = getRenderCamPath();

	if (!cameraPath.isValid()) return MS::kUnknownParameter;

	//
	// Get the camera's shutter angle.
	//
	MFnCamera	cameraFn(cameraPath);
	MAngle		shutterAngle(cameraFn.shutterAngle(), MAngle::kRadians);

	//
	// Calculate the amount of slider time needed for blurring.
	//
	float	frameDelta = (float)
			(shutterAngle.asDegrees()/360.0 * shaveMaya::motionBlurByFrame/2.0);

	float	midFrame = 0.0f;
	//if(rendererIsVray())
	//{
	//	double open = 0.0;
	//	double close = 0.0;
	//	MGlobal::executeCommand("eval(\"shaveVrayShader -q -shutterOpen\")",open);
	//	MGlobal::executeCommand("eval(\"shaveVrayShader -q -shutterClose\")",close);
	//	shutterOpen = open;
	//	shutterClose= close;
	//}
	//else
	//{
		midFrame = (float)MAnimControl::currentTime().value();
		shutterOpen = midFrame - frameDelta;
		shutterClose = midFrame + frameDelta;
	//}
	MGlobal::displayInfo(MString(" sutterOpen ") + shutterOpen + MString(" shutterClose ") + shutterClose);

	return MS::kSuccess;
}


MStatus shaveRender::renderToDRAFile(
	SHAVE_RENDER_HOST	renderHost,
	const MString&		fileName,
	int					voxelResolution,
	bool				includeOcclusions
)
{
	MStatus			st;
	bool			mustFreeRenderer = false;
	MObjectArray	shaveHairShapes;
	float			shutterOpen = 0.0f;
	float			shutterClose = 0.0f;

	shaveGlobals::getGlobals();

	if (mRenderer == NULL)
	{
		getRenderer();
		mustFreeRenderer = true;
	}

	mRenderer->getRenderableShaveNodesByRenderMode(NULL, &shaveHairShapes);

	bool	doMotionBlur = shaveMaya::doMotionBlur;

	if (doMotionBlur)
	{
		st = getShutterTimes(shutterOpen, shutterClose);
		if (!st) doMotionBlur = false;
	}

	MGlobal::displayInfo(MString("blur ") + doMotionBlur + MString("sutterOpen ") + shutterOpen + MString(" shutterClose ") + shutterClose);

	st = renderToDRAFile(
			renderHost,
			fileName,
			voxelResolution,
			shaveHairShapes,
			doMotionBlur,
			shutterOpen,
			shutterClose,
			true,
			includeOcclusions
		);

	if (mustFreeRenderer)
	{
		delete mRenderer;
		mRenderer = NULL;
	}

	return st;
}


MStatus shaveRender::renderToDRAFile(
	SHAVE_RENDER_HOST	renderHost,
	const MString&		fileName,
	int					voxelResolution,
	MObjectArray		shaveHairShapes,
	bool				doMotionBlur,
	float				shutterOpen,
	float				shutterClose,
	bool				updateTextureCache,
	bool				includeOcclusions
)
{
	bool	mustFreeRenderer = false;
	MStatus	st;

	if (shaveHairShapes.length() == 0) return MS::kNotFound;

	saveFrameGlobals();
	shaveMaya::getRenderGlobals();

	SHAVEset_verbose(mFrameGlobals.verbose ? 1 : 0);
	SHAVEclear_stack();

	SHAVEset_tile_limit(
		mFrameGlobals.tileMemoryLimit, mFrameGlobals.transparencyDepth
	);

	if (mRenderer == NULL)
	{
		getRenderer();
		mustFreeRenderer = true;
	}

	mHairRenderMode = mRenderer->getFilteredRenderMode(
						shaveHairShapes, &mRenderInstances
					);
	mNormalShadows = mRenderer->getShadowSource();

	//
	// Build the texture lookup tables.
	//
	if (updateTextureCache)
#ifdef PER_NODE_TEXLOOKUP
		initTexInfoLookup2(shaveHairShapes, "", mFrameGlobals.verbose);
#else
		initTexInfoLookup(shaveHairShapes, "", mFrameGlobals.verbose);
#endif

	//
	// Do everything except the camera renders, as we won't be needing the
	// rendered images.
	//
	shaveRenderCancelled = false;
	mSceneInfo.bufferValid = false;

	MDagPath	cameraPath = getRenderCamPath();

	

	if (doMotionBlur)
	{
		//if(rendererIsVray())	//vlad|15Apr2010
		//{
		//	shutterOpen += 0.5;
		//	shutterClose += 0.5;
		//}

		float curFrame = (float)MAnimControl::currentTime().as(MTime::uiUnit());

		if (curFrame != shutterOpen) shaveUtil::setFrame(shutterOpen);

		buildHairStack(shaveHairShapes, shaveConstant::kShutterOpen);

		bufferRender(
			shaveConstant::kShutterOpen,
			cameraPath,
			shutterOpen,
			false,
			false,
			false,
			includeOcclusions
		);

		shaveUtil::setFrame(shutterClose);
		buildHairStack(shaveHairShapes, shaveConstant::kShutterClose);

		bufferRender(
			shaveConstant::kShutterClose,
			cameraPath,
			shutterClose,
			false,
			false,
			false,
			includeOcclusions
		);
	}
	else
	{
		//MTime ct = MAnimControl::currentTime();
		//if(rendererIsVray())	//vlad|15Apr2010
		//{
		//	shaveUtil::setFrame((ct + 1.0).value());
		//}
		buildHairStack(shaveHairShapes, shaveConstant::kShutterBoth);

		bufferRender(
			shaveConstant::kShutterBoth,
			cameraPath,
			shutterClose,
			false,
			false,
			false,
			includeOcclusions
		);
		//if(rendererIsVray())	//vlad|15Apr2010
		//{
		//	shaveUtil::setFrame(ct.value());
		//}
	}

#if OCCLUSIONS_IN_DRA
	if (includeOcclusions)
	{
		shaveUtil::setWFTYPEVelocities(
			&mSceneInfo.shutterOpenCamScene, &mSceneInfo.shutterCloseCamScene
		);

		SHAVEadd_occlusions(&mSceneInfo.shutterOpenCamScene);
	}
#endif

	//
	// Export the current Shave state to a DRA file.
	//
	SHAVEset_render_host(renderHost);
	SHAVEmult_vox_size(mFrameGlobals.voxelScaling);
	SHAVEexport_archive((char*)fileName.asChar(), voxelResolution);

#if OCCLUSIONS_IN_DRA
	if (includeOcclusions)
	{
		free_geomWF(&mSceneInfo.shutterOpenCamScene);
		free_geomWF(&mSceneInfo.shutterCloseCamScene);
	}
#endif

	clearHairStack(shaveHairShapes);

	if (mustFreeRenderer)
	{
		delete mRenderer;
		mRenderer = NULL;
	}

	return MS::kSuccess;
}


MDagPath shaveRender::getRenderCamPath()
{
	//
	// We have a dandy MEL proc which determines the current render camera
	// for us, so let's use it.
	//
	MString		cameraName;
	MGlobal::executeCommand("shave_getRenderCamera()", cameraName);

	MDagPath		cameraPath;
	MSelectionList	list;

	list.add(cameraName);
	list.getDagPath(0, cameraPath);

	return cameraPath;
}


MString shaveRender::getRenderModeName(shaveConstant::RenderMode mode)
{
	//
	// Yes, it would be nice to switch to some kind of dynamic registration
	// system rather than these hard-coded strings, but that's not likely
	// to happen unless we start supporting a new renderer, or I have a lot
	// of idle time on my hands.
	//
	switch (mode)
	{
		case shaveConstant::kNoRender:
			return "None";

		case shaveConstant::kBufferRender:
			return "Buffer";

		case shaveConstant::kGeometryRender:
			return "Geometry";

		default:
		break;
	}

	return "";
}


//
// The caller must not free the returned renderer.
//
shaveRenderer* shaveRender::getRenderer()
{
	//
	// If we're in the middle of a render, then return the existing
	// renderer (if there is one), otherwise return a new renderer.
	//
	if (mRenderState == kRenderNone)
	{
		if (mRenderer != NULL)
		{
			delete mRenderer;
			mRenderer = NULL;
		}
	}

	if (mRenderer == NULL)
	{
#ifdef USE_VRAY
		if(rendererIsVray())				//vlad|16Apr2010
			mRenderer = new shaveVrayRenderer;	
		else
#endif
			mRenderer = new shaveMayaRenderer;

		///I do not see tha rpman case is trapped here -- vald|19Jan2012
		//int isPrMan = 0;
		//status = MGlobal::executeCommand("shave_curRendererIsPrMan", isPrMan);
		//if(isPrMan)
		//{
		//}
	}

	return mRenderer;
}


bool shaveRender::isIPRActive()
{
	bool	isActive = false;

	MGlobal::executeCommand("shave_isIPRActive", isActive);

	return isActive;
}


void shaveRender::exportEnd()
{
	mExportActive = false;

	//
	// Let the MEL scripts know that the export is over.
	//
	MGlobal::executeCommand("shave_exportEnd");

	//
	// Clear out the export filename info.
	//
	mExportFileFramePadding = 0;
	mExportFileNameFormat = shaveConstant::kNoFileNameFormat;
	mExportFileName = "";
	mExportFilePerFrame = false;
	mExportFileCompression = 0;
}


void shaveRender::exportStart()
{
	//
	// The caller didn't give us a name for the export file, so let's see
	// if Maya can.
	//
	exportStart(MFileIO::beforeExportFilename());
}


void shaveRender::exportStart(MString fileName)
{
	//  These parameters were used for special handling of Mental Ray. We
    //  no longer support Mental Ray and none of the renderers we do
    //  support have need of these, so we just set them to default values
    //  for now.
	//
	bool							filePerFrame = false;
	shaveConstant::FileNameFormat	nameFormat = shaveConstant::kNoFileNameFormat;
	unsigned						framePadding = 0;
	unsigned						compression = 0;

	exportStart(fileName, filePerFrame, nameFormat, framePadding, compression);
}


void shaveRender::exportStart(
		MString							exportFile,
		bool							filePerFrame,
		shaveConstant::FileNameFormat	nameFormat,
		unsigned						framePadding,
		unsigned						compression
)
{
	mExportFileFramePadding = framePadding;
	mExportFileName = exportFile;
	mExportFileNameFormat = nameFormat;
	mExportFilePerFrame = filePerFrame;
	mExportFileCompression = compression;

	mExportActive = true;

	//
	// Let the MEL scripts know that an export has started.
	//
	MGlobal::executeCommand("shave_exportStart");
}


void shaveRender::getExportFileInfo(
		MString&						exportFile,
		bool&							filePerFrame,
		shaveConstant::FileNameFormat&	nameFormat,
		unsigned&						framePadding,
		unsigned&						compression
)
{
	exportFile = mExportFileName;
	filePerFrame = mExportFilePerFrame;
	nameFormat = mExportFileNameFormat;
	framePadding = mExportFileFramePadding;
	compression = mExportFileCompression;

	return;
}

void shaveRender::vrayKeyFrame()
{
	if (mRenderer) 
	{
#ifdef USE_VRAY
		if(rendererIsVray())
		{
			shaveVrayRenderer* vr = static_cast<shaveVrayRenderer*>( mRenderer );
			vr->vrayKeyframeCallback();
		}
#endif
	}
}

///////////////////////
//void shaveRender::shutterOpen()
//{
//	shaveGlobals::getGlobals();
//	saveFrameGlobals();
//
//	shaveMaya::getRenderGlobals();
//
//	SHAVEset_verbose(mFrameGlobals.verbose ? 1 : 0);
//	SHAVEclear_stack();
//
//	MTime	curTime = MAnimControl::currentTime();
//	float	frame = (float)curTime.as(MTime::uiUnit());
//	MGlobal::displayInfo(MString("shutter open: ") + frame);
//
//	bool mustFreeRenderer = false;
//	if (mRenderer == NULL)
//	{
//		getRenderer();
//		mustFreeRenderer = true;
//	}
//
//	MObjectArray	shaveHairShapes;
//	mRenderer->getRenderableShaveNodes(shaveHairShapes);
//	MGlobal::displayInfo(MString("num nodes: ") + shaveHairShapes.length() );
//	buildHairStack(shaveHairShapes, shaveConstant::kShutterOpen);
//
//	//if(mustFreeRenderer)
//	//{
//	//	delete mRenderer;
//	//	mRenderer = NULL;
//	//}
//	MGlobal::displayInfo("shaveRender::shutterOpen - OK");
//
//}
//void shaveRender::shutterClose()
//{
//	shaveGlobals::getGlobals();
//	saveFrameGlobals();
//
//	shaveMaya::getRenderGlobals();
//
//	MTime	curTime = MAnimControl::currentTime();
//	float	frame = (float)curTime.as(MTime::uiUnit());
//	MGlobal::displayInfo(MString("shutter close: ") + frame);
//	
//	
//	//bool mustFreeRenderer = false;
//	//if (mRenderer == NULL)
//	//{
//	//	getRenderer();
//	//	mustFreeRenderer = true;
//	//}
//	MObjectArray	shaveHairShapes;
//	mRenderer->getRenderableShaveNodes(shaveHairShapes);
//	buildHairStack(shaveHairShapes, shaveConstant::kShutterClose);
//
//	//if(mustFreeRenderer)
//	//{
//	//	delete mRenderer;
//	//	mRenderer = NULL;
//	//}
//}
//void shaveRender::shutterExport(MString fileName)
//{
//	SHAVEmult_vox_size(mFrameGlobals.voxelScaling);
//	SHAVEexport_archive((char*)fileName.asChar(), voxelResolutionGlob);
//
//	//bool mustFreeRenderer = false;
//	//if (mRenderer == NULL)
//	//{
//	//	getRenderer();
//	//	mustFreeRenderer = true;
//	//}
//	MObjectArray	shaveHairShapes;
//	mRenderer->getRenderableShaveNodes(shaveHairShapes);
//	clearHairStack(shaveHairShapes);
//
//	//if(mustFreeRenderer)
//	//{
//	if(mRenderer)
//	{
//		delete mRenderer;
//		mRenderer = NULL;
//	}
//	//}
//}