Welcome to mirror list, hosted at ThFree Co, Russian Federation.

material.c « intern « blenkernel « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f3e38d84c331f9e752d7c78a1e30030b5abe6f64 (plain)
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
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
 * All rights reserved.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): none yet.
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file blender/blenkernel/intern/material.c
 *  \ingroup bke
 */


#include <string.h>
#include <math.h>
#include <stddef.h>

#include "MEM_guardedalloc.h"

#include "DNA_anim_types.h"
#include "DNA_curve_types.h"
#include "DNA_group_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_customdata_types.h"
#include "DNA_ID.h"
#include "DNA_meta_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"

#include "BLI_math.h"		
#include "BLI_listbase.h"		
#include "BLI_utildefines.h"
#include "BLI_string.h"

#include "BKE_animsys.h"
#include "BKE_displist.h"
#include "BKE_global.h"
#include "BKE_icons.h"
#include "BKE_image.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_mesh.h"
#include "BKE_node.h"
#include "BKE_curve.h"

#include "GPU_material.h"

/* used in UI and render */
Material defmaterial;

/* called on startup, creator.c */
void init_def_material(void)
{
	init_material(&defmaterial);
}

/* not material itself */
void BKE_material_free(Material *ma)
{
	BKE_material_free_ex(ma, TRUE);
}

/* not material itself */
void BKE_material_free_ex(Material *ma, bool do_id_user)
{
	MTex *mtex;
	int a;
	
	for (a = 0; a < MAX_MTEX; a++) {
		mtex = ma->mtex[a];
		if (do_id_user && mtex && mtex->tex) mtex->tex->id.us--;
		if (mtex) MEM_freeN(mtex);
	}
	
	if (ma->ramp_col) MEM_freeN(ma->ramp_col);
	if (ma->ramp_spec) MEM_freeN(ma->ramp_spec);
	
	BKE_free_animdata((ID *)ma);
	
	if (ma->preview)
		BKE_previewimg_free(&ma->preview);
	BKE_icon_delete((struct ID *)ma);
	ma->id.icon_id = 0;
	
	/* is no lib link block, but material extension */
	if (ma->nodetree) {
		ntreeFreeTree_ex(ma->nodetree, do_id_user);
		MEM_freeN(ma->nodetree);
	}

	if (ma->gpumaterial.first)
		GPU_material_free(ma);
}

void init_material(Material *ma)
{
	ma->r = ma->g = ma->b = ma->ref = 0.8;
	ma->specr = ma->specg = ma->specb = 1.0;
	ma->mirr = ma->mirg = ma->mirb = 1.0;
	ma->spectra = 1.0;
	ma->amb = 1.0;
	ma->alpha = 1.0;
	ma->spec = ma->hasize = 0.5;
	ma->har = 50;
	ma->starc = ma->ringc = 4;
	ma->linec = 12;
	ma->flarec = 1;
	ma->flaresize = ma->subsize = 1.0;
	ma->flareboost = 1;
	ma->seed2 = 6;
	ma->friction = 0.5;
	ma->refrac = 4.0;
	ma->roughness = 0.5;
	ma->param[0] = 0.5;
	ma->param[1] = 0.1;
	ma->param[2] = 0.5;
	ma->param[3] = 0.1;
	ma->rms = 0.1;
	ma->darkness = 1.0;

	ma->strand_sta = ma->strand_end = 1.0f;

	ma->ang = 1.0;
	ma->ray_depth = 2;
	ma->ray_depth_tra = 2;
	ma->fresnel_mir = 0.0;
	ma->fresnel_tra = 0.0;
	ma->fresnel_tra_i = 1.25;
	ma->fresnel_mir_i = 1.25;
	ma->tx_limit = 0.0;
	ma->tx_falloff = 1.0;
	ma->shad_alpha = 1.0f;
	ma->vcol_alpha = 0;
	
	ma->gloss_mir = ma->gloss_tra = 1.0;
	ma->samp_gloss_mir = ma->samp_gloss_tra = 18;
	ma->adapt_thresh_mir = ma->adapt_thresh_tra = 0.005;
	ma->dist_mir = 0.0;
	ma->fadeto_mir = MA_RAYMIR_FADETOSKY;
	
	ma->rampfac_col = 1.0;
	ma->rampfac_spec = 1.0;
	ma->pr_lamp = 3;         /* two lamps, is bits */
	ma->pr_type = MA_SPHERE;

	ma->sss_radius[0] = 1.0f;
	ma->sss_radius[1] = 1.0f;
	ma->sss_radius[2] = 1.0f;
	ma->sss_col[0] = 1.0f;
	ma->sss_col[1] = 1.0f;
	ma->sss_col[2] = 1.0f;
	ma->sss_error = 0.05f;
	ma->sss_scale = 0.1f;
	ma->sss_ior = 1.3f;
	ma->sss_colfac = 1.0f;
	ma->sss_texfac = 0.0f;
	ma->sss_front = 1.0f;
	ma->sss_back = 1.0f;

	ma->vol.density = 1.0f;
	ma->vol.emission = 0.0f;
	ma->vol.scattering = 1.0f;
	ma->vol.reflection = 1.0f;
	ma->vol.transmission_col[0] = ma->vol.transmission_col[1] = ma->vol.transmission_col[2] = 1.0f;
	ma->vol.reflection_col[0] = ma->vol.reflection_col[1] = ma->vol.reflection_col[2] = 1.0f;
	ma->vol.emission_col[0] = ma->vol.emission_col[1] = ma->vol.emission_col[2] = 1.0f;
	ma->vol.density_scale = 1.0f;
	ma->vol.depth_cutoff = 0.01f;
	ma->vol.stepsize_type = MA_VOL_STEP_RANDOMIZED;
	ma->vol.stepsize = 0.2f;
	ma->vol.shade_type = MA_VOL_SHADE_SHADED;
	ma->vol.shadeflag |= MA_VOL_PRECACHESHADING;
	ma->vol.precache_resolution = 50;
	ma->vol.ms_spread = 0.2f;
	ma->vol.ms_diff = 1.f;
	ma->vol.ms_intensity = 1.f;
	
	ma->game.flag = GEMAT_BACKCULL;
	ma->game.alpha_blend = 0;
	ma->game.face_orientation = 0;
	
	ma->mode = MA_TRACEBLE | MA_SHADBUF | MA_SHADOW | MA_RAYBIAS | MA_TANGENT_STR | MA_ZTRANSP;
	ma->shade_flag = MA_APPROX_OCCLUSION;
	ma->preview = NULL;
}

Material *BKE_material_add(Main *bmain, const char *name)
{
	Material *ma;

	ma = BKE_libblock_alloc(bmain, ID_MA, name);
	
	init_material(ma);
	
	return ma;
}

/* XXX keep synced with next function */
Material *BKE_material_copy(Material *ma)
{
	Material *man;
	int a;
	
	man = BKE_libblock_copy(&ma->id);
	
	id_lib_extern((ID *)man->group);
	
	for (a = 0; a < MAX_MTEX; a++) {
		if (ma->mtex[a]) {
			man->mtex[a] = MEM_mallocN(sizeof(MTex), "copymaterial");
			memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex));
			id_us_plus((ID *)man->mtex[a]->tex);
		}
	}
	
	if (ma->ramp_col) man->ramp_col = MEM_dupallocN(ma->ramp_col);
	if (ma->ramp_spec) man->ramp_spec = MEM_dupallocN(ma->ramp_spec);
	
	if (ma->preview) man->preview = BKE_previewimg_copy(ma->preview);

	if (ma->nodetree) {
		man->nodetree = ntreeCopyTree(ma->nodetree);
	}

	BLI_listbase_clear(&man->gpumaterial);
	
	return man;
}

/* XXX (see above) material copy without adding to main dbase */
Material *localize_material(Material *ma)
{
	Material *man;
	int a;
	
	man = BKE_libblock_copy_nolib(&ma->id);

	/* no increment for texture ID users, in previewrender.c it prevents decrement */
	for (a = 0; a < MAX_MTEX; a++) {
		if (ma->mtex[a]) {
			man->mtex[a] = MEM_mallocN(sizeof(MTex), "copymaterial");
			memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex));
		}
	}
	
	if (ma->ramp_col) man->ramp_col = MEM_dupallocN(ma->ramp_col);
	if (ma->ramp_spec) man->ramp_spec = MEM_dupallocN(ma->ramp_spec);
	
	man->preview = NULL;
	
	if (ma->nodetree)
		man->nodetree = ntreeLocalize(ma->nodetree);
	
	BLI_listbase_clear(&man->gpumaterial);
	
	return man;
}

static void extern_local_material(Material *ma)
{
	int i;
	for (i = 0; i < MAX_MTEX; i++) {
		if (ma->mtex[i]) id_lib_extern((ID *)ma->mtex[i]->tex);
	}
}

void BKE_material_make_local(Material *ma)
{
	Main *bmain = G.main;
	Object *ob;
	Mesh *me;
	Curve *cu;
	MetaBall *mb;
	int a, is_local = FALSE, is_lib = FALSE;

	/* - only lib users: do nothing
	 * - only local users: set flag
	 * - mixed: make copy
	 */
	
	if (ma->id.lib == NULL) return;

	/* One local user; set flag and return. */
	if (ma->id.us == 1) {
		id_clear_lib_data(bmain, &ma->id);
		extern_local_material(ma);
		return;
	}

	/* Check which other IDs reference this one to determine if it's used by
	 * lib or local */
	/* test objects */
	ob = bmain->object.first;
	while (ob) {
		if (ob->mat) {
			for (a = 0; a < ob->totcol; a++) {
				if (ob->mat[a] == ma) {
					if (ob->id.lib) is_lib = TRUE;
					else is_local = TRUE;
				}
			}
		}
		ob = ob->id.next;
	}
	/* test meshes */
	me = bmain->mesh.first;
	while (me) {
		if (me->mat) {
			for (a = 0; a < me->totcol; a++) {
				if (me->mat[a] == ma) {
					if (me->id.lib) is_lib = TRUE;
					else is_local = TRUE;
				}
			}
		}
		me = me->id.next;
	}
	/* test curves */
	cu = bmain->curve.first;
	while (cu) {
		if (cu->mat) {
			for (a = 0; a < cu->totcol; a++) {
				if (cu->mat[a] == ma) {
					if (cu->id.lib) is_lib = TRUE;
					else is_local = TRUE;
				}
			}
		}
		cu = cu->id.next;
	}
	/* test mballs */
	mb = bmain->mball.first;
	while (mb) {
		if (mb->mat) {
			for (a = 0; a < mb->totcol; a++) {
				if (mb->mat[a] == ma) {
					if (mb->id.lib) is_lib = TRUE;
					else is_local = TRUE;
				}
			}
		}
		mb = mb->id.next;
	}

	/* Only local users. */
	if (is_local && is_lib == FALSE) {
		id_clear_lib_data(bmain, &ma->id);
		extern_local_material(ma);
	}
	/* Both user and local, so copy. */
	else if (is_local && is_lib) {
		Material *ma_new = BKE_material_copy(ma);

		ma_new->id.us = 0;

		/* Remap paths of new ID using old library as base. */
		BKE_id_lib_local_paths(bmain, ma->id.lib, &ma_new->id);

		/* do objects */
		ob = bmain->object.first;
		while (ob) {
			if (ob->mat) {
				for (a = 0; a < ob->totcol; a++) {
					if (ob->mat[a] == ma) {
						if (ob->id.lib == NULL) {
							ob->mat[a] = ma_new;
							ma_new->id.us++;
							ma->id.us--;
						}
					}
				}
			}
			ob = ob->id.next;
		}
		/* do meshes */
		me = bmain->mesh.first;
		while (me) {
			if (me->mat) {
				for (a = 0; a < me->totcol; a++) {
					if (me->mat[a] == ma) {
						if (me->id.lib == NULL) {
							me->mat[a] = ma_new;
							ma_new->id.us++;
							ma->id.us--;
						}
					}
				}
			}
			me = me->id.next;
		}
		/* do curves */
		cu = bmain->curve.first;
		while (cu) {
			if (cu->mat) {
				for (a = 0; a < cu->totcol; a++) {
					if (cu->mat[a] == ma) {
						if (cu->id.lib == NULL) {
							cu->mat[a] = ma_new;
							ma_new->id.us++;
							ma->id.us--;
						}
					}
				}
			}
			cu = cu->id.next;
		}
		/* do mballs */
		mb = bmain->mball.first;
		while (mb) {
			if (mb->mat) {
				for (a = 0; a < mb->totcol; a++) {
					if (mb->mat[a] == ma) {
						if (mb->id.lib == NULL) {
							mb->mat[a] = ma_new;
							ma_new->id.us++;
							ma->id.us--;
						}
					}
				}
			}
			mb = mb->id.next;
		}
	}
}

/* for curve, mball, mesh types */
void extern_local_matarar(struct Material **matar, short totcol)
{
	short i;
	for (i = 0; i < totcol; i++) {
		id_lib_extern((ID *)matar[i]);
	}
}

Material ***give_matarar(Object *ob)
{
	Mesh *me;
	Curve *cu;
	MetaBall *mb;
	
	if (ob->type == OB_MESH) {
		me = ob->data;
		return &(me->mat);
	}
	else if (ELEM3(ob->type, OB_CURVE, OB_FONT, OB_SURF)) {
		cu = ob->data;
		return &(cu->mat);
	}
	else if (ob->type == OB_MBALL) {
		mb = ob->data;
		return &(mb->mat);
	}
	return NULL;
}

short *give_totcolp(Object *ob)
{
	Mesh *me;
	Curve *cu;
	MetaBall *mb;
	
	if (ob->type == OB_MESH) {
		me = ob->data;
		return &(me->totcol);
	}
	else if (ELEM3(ob->type, OB_CURVE, OB_FONT, OB_SURF)) {
		cu = ob->data;
		return &(cu->totcol);
	}
	else if (ob->type == OB_MBALL) {
		mb = ob->data;
		return &(mb->totcol);
	}
	return NULL;
}

/* same as above but for ID's */
Material ***give_matarar_id(ID *id)
{
	/* ensure we don't try get materials from non-obdata */
	BLI_assert(OB_DATA_SUPPORT_ID(GS(id->name)));

	switch (GS(id->name)) {
		case ID_ME:
			return &(((Mesh *)id)->mat);
			break;
		case ID_CU:
			return &(((Curve *)id)->mat);
			break;
		case ID_MB:
			return &(((MetaBall *)id)->mat);
			break;
	}
	return NULL;
}

short *give_totcolp_id(ID *id)
{
	/* ensure we don't try get materials from non-obdata */
	BLI_assert(OB_DATA_SUPPORT_ID(GS(id->name)));

	switch (GS(id->name)) {
		case ID_ME:
			return &(((Mesh *)id)->totcol);
			break;
		case ID_CU:
			return &(((Curve *)id)->totcol);
			break;
		case ID_MB:
			return &(((MetaBall *)id)->totcol);
			break;
	}
	return NULL;
}

static void material_data_index_remove_id(ID *id, short index)
{
	/* ensure we don't try get materials from non-obdata */
	BLI_assert(OB_DATA_SUPPORT_ID(GS(id->name)));

	switch (GS(id->name)) {
		case ID_ME:
			BKE_mesh_material_index_remove((Mesh *)id, index);
			break;
		case ID_CU:
			BKE_curve_material_index_remove((Curve *)id, index);
			break;
		case ID_MB:
			/* meta-elems don't have materials atm */
			break;
	}
}

static void material_data_index_clear_id(ID *id)
{
	/* ensure we don't try get materials from non-obdata */
	BLI_assert(OB_DATA_SUPPORT_ID(GS(id->name)));

	switch (GS(id->name)) {
		case ID_ME:
			BKE_mesh_material_index_clear((Mesh *)id);
			break;
		case ID_CU:
			BKE_curve_material_index_clear((Curve *)id);
			break;
		case ID_MB:
			/* meta-elems don't have materials atm */
			break;
	}
}

void BKE_material_resize_id(struct ID *id, short totcol, bool do_id_user)
{
	Material ***matar = give_matarar_id(id);
	short *totcolp = give_totcolp_id(id);

	if (matar == NULL) {
		return;
	}

	if (do_id_user && totcol < (*totcolp)) {
		short i;
		for (i = totcol; i < (*totcolp); i++) {
			id_us_min((ID *)(*matar)[i]);
		}
	}

	if (totcol == 0) {
		if (*totcolp) {
			MEM_freeN(*matar);
			*matar = NULL;
		}
	}
	else {
		*matar = MEM_recallocN(*matar, sizeof(void *) * totcol);
	}
	*totcolp = totcol;
}

void BKE_material_append_id(ID *id, Material *ma)
{
	Material ***matar;
	if ((matar = give_matarar_id(id))) {
		short *totcol = give_totcolp_id(id);
		Material **mat = MEM_callocN(sizeof(void *) * ((*totcol) + 1), "newmatar");
		if (*totcol) memcpy(mat, *matar, sizeof(void *) * (*totcol));
		if (*matar) MEM_freeN(*matar);

		*matar = mat;
		(*matar)[(*totcol)++] = ma;

		id_us_plus((ID *)ma);
		test_object_materials(G.main, id);
	}
}

Material *BKE_material_pop_id(ID *id, int index_i, bool update_data)
{
	short index = (short)index_i;
	Material *ret = NULL;
	Material ***matar;
	if ((matar = give_matarar_id(id))) {
		short *totcol = give_totcolp_id(id);
		if (index >= 0 && index < (*totcol)) {
			ret = (*matar)[index];
			id_us_min((ID *)ret);

			if (*totcol <= 1) {
				*totcol = 0;
				MEM_freeN(*matar);
				*matar = NULL;
			}
			else {
				if (index + 1 != (*totcol))
					memmove((*matar) + index, (*matar) + (index + 1), sizeof(void *) * ((*totcol) - (index + 1)));

				(*totcol)--;
				*matar = MEM_reallocN(*matar, sizeof(void *) * (*totcol));
				test_object_materials(G.main, id);
			}

			if (update_data) {
				/* decrease mat_nr index */
				material_data_index_remove_id(id, index);
			}
		}
	}
	
	return ret;
}

void BKE_material_clear_id(struct ID *id, bool update_data)
{
	Material ***matar;
	if ((matar = give_matarar_id(id))) {
		short *totcol = give_totcolp_id(id);
		*totcol = 0;
		if (*matar) {
			MEM_freeN(*matar);
			*matar = NULL;
		}

		if (update_data) {
			/* decrease mat_nr index */
			material_data_index_clear_id(id);
		}
	}
}

Material *give_current_material(Object *ob, short act)
{
	Material ***matarar, *ma;
	short *totcolp;

	if (ob == NULL) return NULL;
	
	/* if object cannot have material, (totcolp == NULL) */
	totcolp = give_totcolp(ob);
	if (totcolp == NULL || ob->totcol == 0) return NULL;
	
	if (act < 0) {
		printf("Negative material index!\n");
	}
	
	/* return NULL for invalid 'act', can happen for mesh face indices */
	if (act > ob->totcol)
		return NULL;
	else if (act <= 0)
		return NULL;

	if (ob->matbits && ob->matbits[act - 1]) {    /* in object */
		ma = ob->mat[act - 1];
	}
	else {                              /* in data */

		/* check for inconsistency */
		if (*totcolp < ob->totcol)
			ob->totcol = *totcolp;
		if (act > ob->totcol) act = ob->totcol;

		matarar = give_matarar(ob);
		
		if (matarar && *matarar) ma = (*matarar)[act - 1];
		else ma = NULL;
		
	}
	
	return ma;
}

ID *material_from(Object *ob, short act)
{

	if (ob == NULL) return NULL;

	if (ob->totcol == 0) return ob->data;
	if (act == 0) act = 1;

	if (ob->matbits[act - 1]) return (ID *)ob;
	else return ob->data;
}

Material *give_node_material(Material *ma)
{
	if (ma && ma->use_nodes && ma->nodetree) {
		bNode *node = nodeGetActiveID(ma->nodetree, ID_MA);

		if (node)
			return (Material *)node->id;
	}

	return NULL;
}

void BKE_material_resize_object(Object *ob, const short totcol, bool do_id_user)
{
	Material **newmatar;
	char *newmatbits;

	if (do_id_user && totcol < ob->totcol) {
		short i;
		for (i = totcol; i < ob->totcol; i++) {
			id_us_min((ID *)ob->mat[i]);
		}
	}

	if (totcol == 0) {
		if (ob->totcol) {
			MEM_freeN(ob->mat);
			MEM_freeN(ob->matbits);
			ob->mat = NULL;
			ob->matbits = NULL;
		}
	}
	else if (ob->totcol < totcol) {
		newmatar = MEM_callocN(sizeof(void *) * totcol, "newmatar");
		newmatbits = MEM_callocN(sizeof(char) * totcol, "newmatbits");
		if (ob->totcol) {
			memcpy(newmatar, ob->mat, sizeof(void *) * ob->totcol);
			memcpy(newmatbits, ob->matbits, sizeof(char) * ob->totcol);
			MEM_freeN(ob->mat);
			MEM_freeN(ob->matbits);
		}
		ob->mat = newmatar;
		ob->matbits = newmatbits;
	}
	/* XXX, why not realloc on shrink? - campbell */

	ob->totcol = totcol;
	if (ob->totcol && ob->actcol == 0) ob->actcol = 1;
	if (ob->actcol > ob->totcol) ob->actcol = ob->totcol;
}

void test_object_materials(Main *bmain, ID *id)
{
	/* make the ob mat-array same size as 'ob->data' mat-array */
	Object *ob;
	short *totcol;

	if (id == NULL || (totcol = give_totcolp_id(id)) == NULL) {
		return;
	}

	for (ob = bmain->object.first; ob; ob = ob->id.next) {
		if (ob->data == id) {
			BKE_material_resize_object(ob, *totcol, false);
		}
	}
}

void assign_material_id(ID *id, Material *ma, short act)
{
	Material *mao, **matar, ***matarar;
	short *totcolp;

	if (act > MAXMAT) return;
	if (act < 1) act = 1;

	/* prevent crashing when using accidentally */
	BLI_assert(id->lib == NULL);
	if (id->lib) return;

	/* test arraylens */

	totcolp = give_totcolp_id(id);
	matarar = give_matarar_id(id);

	if (totcolp == NULL || matarar == NULL) return;

	if (act > *totcolp) {
		matar = MEM_callocN(sizeof(void *) * act, "matarray1");

		if (*totcolp) {
			memcpy(matar, *matarar, sizeof(void *) * (*totcolp));
			MEM_freeN(*matarar);
		}

		*matarar = matar;
		*totcolp = act;
	}

	/* in data */
	mao = (*matarar)[act - 1];
	if (mao) mao->id.us--;
	(*matarar)[act - 1] = ma;

	if (ma)
		id_us_plus((ID *)ma);

	test_object_materials(G.main, id);
}

void assign_material(Object *ob, Material *ma, short act, int assign_type)
{
	Material *mao, **matar, ***matarar;
	short *totcolp;
	char bit = 0;

	if (act > MAXMAT) return;
	if (act < 1) act = 1;
	
	/* prevent crashing when using accidentally */
	BLI_assert(ob->id.lib == NULL);
	if (ob->id.lib) return;
	
	/* test arraylens */
	
	totcolp = give_totcolp(ob);
	matarar = give_matarar(ob);
	
	if (totcolp == NULL || matarar == NULL) return;
	
	if (act > *totcolp) {
		matar = MEM_callocN(sizeof(void *) * act, "matarray1");

		if (*totcolp) {
			memcpy(matar, *matarar, sizeof(void *) * (*totcolp));
			MEM_freeN(*matarar);
		}

		*matarar = matar;
		*totcolp = act;
	}

	/* Determine the object/mesh linking */
	if (assign_type == BKE_MAT_ASSIGN_USERPREF && ob->totcol && ob->actcol) {
		/* copy from previous material */
		bit = ob->matbits[ob->actcol - 1];
	}
	else {
		switch (assign_type) {
			case BKE_MAT_ASSIGN_OBDATA:
				bit = 0;
				break;
			case BKE_MAT_ASSIGN_OBJECT:
				bit = 1;
				break;
			case BKE_MAT_ASSIGN_USERPREF:
			default:
				bit = (U.flag & USER_MAT_ON_OB) ? 1 : 0;
				break;
		}
	}

	if (act > ob->totcol) {
		/* Need more space in the material arrays */
		ob->mat = MEM_recallocN_id(ob->mat, sizeof(void *) * act, "matarray2");
		ob->matbits = MEM_recallocN_id(ob->matbits, sizeof(char) * act, "matbits1");
		ob->totcol = act;
	}
	
	/* do it */

	ob->matbits[act - 1] = bit;
	if (bit == 1) {   /* in object */
		mao = ob->mat[act - 1];
		if (mao) mao->id.us--;
		ob->mat[act - 1] = ma;
	}
	else {  /* in data */
		mao = (*matarar)[act - 1];
		if (mao) mao->id.us--;
		(*matarar)[act - 1] = ma;
	}

	if (ma)
		id_us_plus((ID *)ma);
	test_object_materials(G.main, ob->data);
}

/* XXX - this calls many more update calls per object then are needed, could be optimized */
void assign_matarar(struct Object *ob, struct Material ***matar, short totcol)
{
	int actcol_orig = ob->actcol;
	short i;

	while (object_remove_material_slot(ob)) {}

	/* now we have the right number of slots */
	for (i = 0; i < totcol; i++)
		assign_material(ob, (*matar)[i], i + 1, BKE_MAT_ASSIGN_USERPREF);

	if (actcol_orig > ob->totcol)
		actcol_orig = ob->totcol;

	ob->actcol = actcol_orig;
}


short find_material_index(Object *ob, Material *ma)
{
	Material ***matarar;
	short a, *totcolp;
	
	if (ma == NULL) return 0;
	
	totcolp = give_totcolp(ob);
	matarar = give_matarar(ob);
	
	if (totcolp == NULL || matarar == NULL) return 0;
	
	for (a = 0; a < *totcolp; a++)
		if ((*matarar)[a] == ma)
			break;
	if (a < *totcolp)
		return a + 1;
	return 0;
}

int object_add_material_slot(Object *ob)
{
	if (ob == NULL) return FALSE;
	if (ob->totcol >= MAXMAT) return FALSE;
	
	assign_material(ob, NULL, ob->totcol + 1, BKE_MAT_ASSIGN_USERPREF);
	ob->actcol = ob->totcol;
	return TRUE;
}

static void do_init_render_material(Material *ma, int r_mode, float *amb)
{
	MTex *mtex;
	int a, needuv = 0, needtang = 0;
	
	if (ma->flarec == 0) ma->flarec = 1;

	/* add all texcoflags from mtex, texco and mapto were cleared in advance */
	for (a = 0; a < MAX_MTEX; a++) {
		
		/* separate tex switching */
		if (ma->septex & (1 << a)) continue;

		mtex = ma->mtex[a];
		if (mtex && mtex->tex && (mtex->tex->type | (mtex->tex->use_nodes && mtex->tex->nodetree) )) {
			
			ma->texco |= mtex->texco;
			ma->mapto |= mtex->mapto;

			/* always get derivatives for these textures */
			if (ELEM(mtex->tex->type, TEX_IMAGE, TEX_ENVMAP)) ma->texco |= TEXCO_OSA;
			else if (mtex->texflag & (MTEX_COMPAT_BUMP | MTEX_3TAP_BUMP | MTEX_5TAP_BUMP | MTEX_BICUBIC_BUMP)) ma->texco |= TEXCO_OSA;
			
			if (ma->texco & (TEXCO_ORCO | TEXCO_REFL | TEXCO_NORM | TEXCO_STRAND | TEXCO_STRESS)) needuv = 1;
			else if (ma->texco & (TEXCO_GLOB | TEXCO_UV | TEXCO_OBJECT | TEXCO_SPEED)) needuv = 1;
			else if (ma->texco & (TEXCO_LAVECTOR | TEXCO_VIEW)) needuv = 1;

			if ((ma->mapto & MAP_NORM) && (mtex->normapspace == MTEX_NSPACE_TANGENT))
				needtang = 1;
		}
	}

	if (needtang) ma->mode |= MA_NORMAP_TANG;
	else ma->mode &= ~MA_NORMAP_TANG;
	
	if (ma->mode & (MA_VERTEXCOL | MA_VERTEXCOLP | MA_FACETEXTURE)) {
		needuv = 1;
		if (r_mode & R_OSA) ma->texco |= TEXCO_OSA;     /* for texfaces */
	}
	if (needuv) ma->texco |= NEED_UV;
	
	/* since the raytracer doesnt recalc O structs for each ray, we have to preset them all */
	if (r_mode & R_RAYTRACE) {
		if ((ma->mode & (MA_RAYMIRROR | MA_SHADOW_TRA)) || ((ma->mode & MA_TRANSP) && (ma->mode & MA_RAYTRANSP))) {
			ma->texco |= NEED_UV | TEXCO_ORCO | TEXCO_REFL | TEXCO_NORM;
			if (r_mode & R_OSA) ma->texco |= TEXCO_OSA;
		}
	}
	
	if (amb) {
		ma->ambr = ma->amb * amb[0];
		ma->ambg = ma->amb * amb[1];
		ma->ambb = ma->amb * amb[2];
	}
	/* will become or-ed result of all node modes */
	ma->mode_l = ma->mode;
	ma->mode_l &= ~MA_SHLESS;

	if (ma->strand_surfnor > 0.0f)
		ma->mode_l |= MA_STR_SURFDIFF;

	/* parses the geom+tex nodes */
	if (ma->nodetree && ma->use_nodes)
		ntreeShaderGetTexcoMode(ma->nodetree, r_mode, &ma->texco, &ma->mode_l);

	/* local group override */
	if ((ma->shade_flag & MA_GROUP_LOCAL) && ma->id.lib && ma->group && ma->group->id.lib) {
		Group *group;

		for (group = G.main->group.first; group; group = group->id.next) {
			if (!group->id.lib && strcmp(group->id.name, ma->group->id.name) == 0) {
				ma->group = group;
			}
		}
	}
}

static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode, float *amb)
{
	bNode *node;
	
	for (node = ntree->nodes.first; node; node = node->next) {
		if (node->id) {
			if (GS(node->id->name) == ID_MA) {
				Material *ma = (Material *)node->id;
				if (ma != basemat) {
					do_init_render_material(ma, r_mode, amb);
					basemat->texco |= ma->texco;
					basemat->mode_l |= ma->mode_l & ~(MA_TRANSP | MA_ZTRANSP | MA_RAYTRANSP);
				}
			}
			else if (node->type == NODE_GROUP)
				init_render_nodetree((bNodeTree *)node->id, basemat, r_mode, amb);
		}
	}
}

void init_render_material(Material *mat, int r_mode, float *amb)
{
	
	do_init_render_material(mat, r_mode, amb);
	
	if (mat->nodetree && mat->use_nodes) {
		init_render_nodetree(mat->nodetree, mat, r_mode, amb);
		
		if (!mat->nodetree->execdata)
			mat->nodetree->execdata = ntreeShaderBeginExecTree(mat->nodetree);
	}
}

void init_render_materials(Main *bmain, int r_mode, float *amb)
{
	Material *ma;
	
	/* clear these flags before going over materials, to make sure they
	 * are cleared only once, otherwise node materials contained in other
	 * node materials can go wrong */
	for (ma = bmain->mat.first; ma; ma = ma->id.next) {
		if (ma->id.us) {
			ma->texco = 0;
			ma->mapto = 0;
		}
	}

	/* two steps, first initialize, then or the flags for layers */
	for (ma = bmain->mat.first; ma; ma = ma->id.next) {
		/* is_used flag comes back in convertblender.c */
		ma->flag &= ~MA_IS_USED;
		if (ma->id.us) 
			init_render_material(ma, r_mode, amb);
	}
	
	do_init_render_material(&defmaterial, r_mode, amb);
}

/* only needed for nodes now */
void end_render_material(Material *mat)
{
	if (mat && mat->nodetree && mat->use_nodes) {
		if (mat->nodetree->execdata)
			ntreeShaderEndExecTree(mat->nodetree->execdata);
	}
}

void end_render_materials(Main *bmain)
{
	Material *ma;
	for (ma = bmain->mat.first; ma; ma = ma->id.next)
		if (ma->id.us) 
			end_render_material(ma);
}

static bool material_in_nodetree(bNodeTree *ntree, Material *mat)
{
	bNode *node;

	for (node = ntree->nodes.first; node; node = node->next) {
		if (node->id) {
			if (GS(node->id->name) == ID_MA) {
				if (node->id == (ID *)mat) {
					return 1;
				}
			}
			else if (node->type == NODE_GROUP) {
				if (material_in_nodetree((bNodeTree *)node->id, mat)) {
					return 1;
				}
			}
		}
	}

	return 0;
}

int material_in_material(Material *parmat, Material *mat)
{
	if (parmat == mat)
		return 1;
	else if (parmat->nodetree && parmat->use_nodes)
		return material_in_nodetree(parmat->nodetree, mat);
	else
		return 0;
}


/* ****************** */

/* Update drivers for materials in a nodetree */
static void material_node_drivers_update(Scene *scene, bNodeTree *ntree, float ctime)
{
	bNode *node;

	/* nodetree itself */
	if (ntree->adt && ntree->adt->drivers.first) {
		BKE_animsys_evaluate_animdata(scene, &ntree->id, ntree->adt, ctime, ADT_RECALC_DRIVERS);
	}
	
	/* nodes */
	for (node = ntree->nodes.first; node; node = node->next) {
		if (node->id) {
			if (GS(node->id->name) == ID_MA) {
				material_drivers_update(scene, (Material *)node->id, ctime);
			}
			else if (node->type == NODE_GROUP) {
				material_node_drivers_update(scene, (bNodeTree *)node->id, ctime);
			}
		}
	}
}

/* Calculate all drivers for materials 
 * FIXME: this is really a terrible method which may result in some things being calculated
 * multiple times. However, without proper despgraph support for these things, we are forced
 * into this sort of thing...
 */
void material_drivers_update(Scene *scene, Material *ma, float ctime)
{
	//if (G.f & G_DEBUG)
	//	printf("material_drivers_update(%s, %s)\n", scene->id.name, ma->id.name);
	
	/* Prevent infinite recursion by checking (and tagging the material) as having been visited already
	 * (see BKE_scene_update_tagged()). This assumes ma->id.flag & LIB_DOIT isn't set by anything else
	 * in the meantime... [#32017]
	 */
	if (ma->id.flag & LIB_DOIT)
		return;

	ma->id.flag |= LIB_DOIT;
	
	/* material itself */
	if (ma->adt && ma->adt->drivers.first) {
		BKE_animsys_evaluate_animdata(scene, &ma->id, ma->adt, ctime, ADT_RECALC_DRIVERS);
	}
	
	/* nodes */
	if (ma->nodetree) {
		material_node_drivers_update(scene, ma->nodetree, ctime);
	}

	ma->id.flag &= ~LIB_DOIT;
}

int object_remove_material_slot(Object *ob)
{
	Material *mao, ***matarar;
	Object *obt;
	short *totcolp;
	short a, actcol;
	
	if (ob == NULL || ob->totcol == 0) {
		return FALSE;
	}

	/* this should never happen and used to crash */
	if (ob->actcol <= 0) {
		printf("%s: invalid material index %d, report a bug!\n", __func__, ob->actcol);
		BLI_assert(0);
		return FALSE;
	}

	/* take a mesh/curve/mball as starting point, remove 1 index,
	 * AND with all objects that share the ob->data
	 * 
	 * after that check indices in mesh/curve/mball!!!
	 */
	
	totcolp = give_totcolp(ob);
	matarar = give_matarar(ob);

	if (ELEM(NULL, matarar, *matarar)) {
		return false;
	}

	/* can happen on face selection in editmode */
	if (ob->actcol > ob->totcol) {
		ob->actcol = ob->totcol;
	}
	
	/* we delete the actcol */
	mao = (*matarar)[ob->actcol - 1];
	if (mao) mao->id.us--;
	
	for (a = ob->actcol; a < ob->totcol; a++)
		(*matarar)[a - 1] = (*matarar)[a];
	(*totcolp)--;
	
	if (*totcolp == 0) {
		MEM_freeN(*matarar);
		*matarar = NULL;
	}
	
	actcol = ob->actcol;
	obt = G.main->object.first;
	while (obt) {
	
		if (obt->data == ob->data) {
			
			/* WATCH IT: do not use actcol from ob or from obt (can become zero) */
			mao = obt->mat[actcol - 1];
			if (mao) mao->id.us--;
		
			for (a = actcol; a < obt->totcol; a++) {
				obt->mat[a - 1] = obt->mat[a];
				obt->matbits[a - 1] = obt->matbits[a];
			}
			obt->totcol--;
			if (obt->actcol > obt->totcol) obt->actcol = obt->totcol;
			
			if (obt->totcol == 0) {
				MEM_freeN(obt->mat);
				MEM_freeN(obt->matbits);
				obt->mat = NULL;
				obt->matbits = NULL;
			}
		}
		obt = obt->id.next;
	}

	/* check indices from mesh */
	if (ELEM4(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT)) {
		material_data_index_remove_id((ID *)ob->data, actcol - 1);
		if (ob->curve_cache) {
			BKE_displist_free(&ob->curve_cache->disp);
		}
	}

	return TRUE;
}


/* r_col = current value, col = new value, (fac == 0) is no change */
void ramp_blend(int type, float r_col[3], const float fac, const float col[3])
{
	float tmp, facm = 1.0f - fac;
	
	switch (type) {
		case MA_RAMP_BLEND:
			r_col[0] = facm * (r_col[0]) + fac * col[0];
			r_col[1] = facm * (r_col[1]) + fac * col[1];
			r_col[2] = facm * (r_col[2]) + fac * col[2];
			break;
		case MA_RAMP_ADD:
			r_col[0] += fac * col[0];
			r_col[1] += fac * col[1];
			r_col[2] += fac * col[2];
			break;
		case MA_RAMP_MULT:
			r_col[0] *= (facm + fac * col[0]);
			r_col[1] *= (facm + fac * col[1]);
			r_col[2] *= (facm + fac * col[2]);
			break;
		case MA_RAMP_SCREEN:
			r_col[0] = 1.0f - (facm + fac * (1.0f - col[0])) * (1.0f - r_col[0]);
			r_col[1] = 1.0f - (facm + fac * (1.0f - col[1])) * (1.0f - r_col[1]);
			r_col[2] = 1.0f - (facm + fac * (1.0f - col[2])) * (1.0f - r_col[2]);
			break;
		case MA_RAMP_OVERLAY:
			if (r_col[0] < 0.5f)
				r_col[0] *= (facm + 2.0f * fac * col[0]);
			else
				r_col[0] = 1.0f - (facm + 2.0f * fac * (1.0f - col[0])) * (1.0f - r_col[0]);
			if (r_col[1] < 0.5f)
				r_col[1] *= (facm + 2.0f * fac * col[1]);
			else
				r_col[1] = 1.0f - (facm + 2.0f * fac * (1.0f - col[1])) * (1.0f - r_col[1]);
			if (r_col[2] < 0.5f)
				r_col[2] *= (facm + 2.0f * fac * col[2]);
			else
				r_col[2] = 1.0f - (facm + 2.0f * fac * (1.0f - col[2])) * (1.0f - r_col[2]);
			break;
		case MA_RAMP_SUB:
			r_col[0] -= fac * col[0];
			r_col[1] -= fac * col[1];
			r_col[2] -= fac * col[2];
			break;
		case MA_RAMP_DIV:
			if (col[0] != 0.0f)
				r_col[0] = facm * (r_col[0]) + fac * (r_col[0]) / col[0];
			if (col[1] != 0.0f)
				r_col[1] = facm * (r_col[1]) + fac * (r_col[1]) / col[1];
			if (col[2] != 0.0f)
				r_col[2] = facm * (r_col[2]) + fac * (r_col[2]) / col[2];
			break;
		case MA_RAMP_DIFF:
			r_col[0] = facm * (r_col[0]) + fac * fabsf(r_col[0] - col[0]);
			r_col[1] = facm * (r_col[1]) + fac * fabsf(r_col[1] - col[1]);
			r_col[2] = facm * (r_col[2]) + fac * fabsf(r_col[2] - col[2]);
			break;
		case MA_RAMP_DARK:
			tmp = col[0] + ((1 - col[0]) * facm);
			if (tmp < r_col[0]) r_col[0] = tmp;
			tmp = col[1] + ((1 - col[1]) * facm);
			if (tmp < r_col[1]) r_col[1] = tmp;
			tmp = col[2] + ((1 - col[2]) * facm);
			if (tmp < r_col[2]) r_col[2] = tmp;
			break;
		case MA_RAMP_LIGHT:
			tmp = fac * col[0];
			if (tmp > r_col[0]) r_col[0] = tmp;
			tmp = fac * col[1];
			if (tmp > r_col[1]) r_col[1] = tmp;
			tmp = fac * col[2];
			if (tmp > r_col[2]) r_col[2] = tmp;
			break;
		case MA_RAMP_DODGE:
			if (r_col[0] != 0.0f) {
				tmp = 1.0f - fac * col[0];
				if (tmp <= 0.0f)
					r_col[0] = 1.0f;
				else if ((tmp = (r_col[0]) / tmp) > 1.0f)
					r_col[0] = 1.0f;
				else
					r_col[0] = tmp;
			}
			if (r_col[1] != 0.0f) {
				tmp = 1.0f - fac * col[1];
				if (tmp <= 0.0f)
					r_col[1] = 1.0f;
				else if ((tmp = (r_col[1]) / tmp) > 1.0f)
					r_col[1] = 1.0f;
				else
					r_col[1] = tmp;
			}
			if (r_col[2] != 0.0f) {
				tmp = 1.0f - fac * col[2];
				if (tmp <= 0.0f)
					r_col[2] = 1.0f;
				else if ((tmp = (r_col[2]) / tmp) > 1.0f)
					r_col[2] = 1.0f;
				else
					r_col[2] = tmp;
			}
			break;
		case MA_RAMP_BURN:
			tmp = facm + fac * col[0];

			if (tmp <= 0.0f)
				r_col[0] = 0.0f;
			else if ((tmp = (1.0f - (1.0f - (r_col[0])) / tmp)) < 0.0f)
				r_col[0] = 0.0f;
			else if (tmp > 1.0f)
				r_col[0] = 1.0f;
			else
				r_col[0] = tmp;

			tmp = facm + fac * col[1];
			if (tmp <= 0.0f)
				r_col[1] = 0.0f;
			else if ((tmp = (1.0f - (1.0f - (r_col[1])) / tmp)) < 0.0f)
				r_col[1] = 0.0f;
			else if (tmp > 1.0f)
				r_col[1] = 1.0f;
			else
				r_col[1] = tmp;

			tmp = facm + fac * col[2];
			if (tmp <= 0.0f)
				r_col[2] = 0.0f;
			else if ((tmp = (1.0f - (1.0f - (r_col[2])) / tmp)) < 0.0f)
				r_col[2] = 0.0f;
			else if (tmp > 1.0f)
				r_col[2] = 1.0f;
			else
				r_col[2] = tmp;
			break;
		case MA_RAMP_HUE:
		{
			float rH, rS, rV;
			float colH, colS, colV;
			float tmpr, tmpg, tmpb;
			rgb_to_hsv(col[0], col[1], col[2], &colH, &colS, &colV);
			if (colS != 0) {
				rgb_to_hsv(r_col[0], r_col[1], r_col[2], &rH, &rS, &rV);
				hsv_to_rgb(colH, rS, rV, &tmpr, &tmpg, &tmpb);
				r_col[0] = facm * (r_col[0]) + fac * tmpr;
				r_col[1] = facm * (r_col[1]) + fac * tmpg;
				r_col[2] = facm * (r_col[2]) + fac * tmpb;
			}
			break;
		}
		case MA_RAMP_SAT:
		{
			float rH, rS, rV;
			float colH, colS, colV;
			rgb_to_hsv(r_col[0], r_col[1], r_col[2], &rH, &rS, &rV);
			if (rS != 0) {
				rgb_to_hsv(col[0], col[1], col[2], &colH, &colS, &colV);
				hsv_to_rgb(rH, (facm * rS + fac * colS), rV, r_col + 0, r_col + 1, r_col + 2);
			}
			break;
		}
		case MA_RAMP_VAL:
		{
			float rH, rS, rV;
			float colH, colS, colV;
			rgb_to_hsv(r_col[0], r_col[1], r_col[2], &rH, &rS, &rV);
			rgb_to_hsv(col[0], col[1], col[2], &colH, &colS, &colV);
			hsv_to_rgb(rH, rS, (facm * rV + fac * colV), r_col + 0, r_col + 1, r_col + 2);
			break;
		}
		case MA_RAMP_COLOR:
		{
			float rH, rS, rV;
			float colH, colS, colV;
			float tmpr, tmpg, tmpb;
			rgb_to_hsv(col[0], col[1], col[2], &colH, &colS, &colV);
			if (colS != 0) {
				rgb_to_hsv(r_col[0], r_col[1], r_col[2], &rH, &rS, &rV);
				hsv_to_rgb(colH, colS, rV, &tmpr, &tmpg, &tmpb);
				r_col[0] = facm * (r_col[0]) + fac * tmpr;
				r_col[1] = facm * (r_col[1]) + fac * tmpg;
				r_col[2] = facm * (r_col[2]) + fac * tmpb;
			}
			break;
		}
		case MA_RAMP_SOFT:
		{
			float scr, scg, scb;

			/* first calculate non-fac based Screen mix */
			scr = 1.0f - (1.0f - col[0]) * (1.0f - r_col[0]);
			scg = 1.0f - (1.0f - col[1]) * (1.0f - r_col[1]);
			scb = 1.0f - (1.0f - col[2]) * (1.0f - r_col[2]);

			r_col[0] = facm * (r_col[0]) + fac * (((1.0f - r_col[0]) * col[0] * (r_col[0])) + (r_col[0] * scr));
			r_col[1] = facm * (r_col[1]) + fac * (((1.0f - r_col[1]) * col[1] * (r_col[1])) + (r_col[1] * scg));
			r_col[2] = facm * (r_col[2]) + fac * (((1.0f - r_col[2]) * col[2] * (r_col[2])) + (r_col[2] * scb));
			break;
		}
		case MA_RAMP_LINEAR:
			if (col[0] > 0.5f)
				r_col[0] = r_col[0] + fac * (2.0f * (col[0] - 0.5f));
			else
				r_col[0] = r_col[0] + fac * (2.0f * (col[0]) - 1.0f);
			if (col[1] > 0.5f)
				r_col[1] = r_col[1] + fac * (2.0f * (col[1] - 0.5f));
			else
				r_col[1] = r_col[1] + fac * (2.0f * (col[1]) - 1.0f);
			if (col[2] > 0.5f)
				r_col[2] = r_col[2] + fac * (2.0f * (col[2] - 0.5f));
			else
				r_col[2] = r_col[2] + fac * (2.0f * (col[2]) - 1.0f);
			break;
	}
}

/**
 * \brief copy/paste buffer, if we had a proper py api that would be better
 * \note matcopybuf.nodetree does _NOT_ use ID's
 * \todo matcopybuf.nodetree's  node->id's are NOT validated, this will crash!
 */
static Material matcopybuf;
static short matcopied = 0;

void clear_matcopybuf(void)
{
	memset(&matcopybuf, 0, sizeof(Material));
	matcopied = 0;
}

void free_matcopybuf(void)
{
	int a;

	for (a = 0; a < MAX_MTEX; a++) {
		if (matcopybuf.mtex[a]) {
			MEM_freeN(matcopybuf.mtex[a]);
			matcopybuf.mtex[a] = NULL;
		}
	}

	if (matcopybuf.ramp_col) MEM_freeN(matcopybuf.ramp_col);
	if (matcopybuf.ramp_spec) MEM_freeN(matcopybuf.ramp_spec);

	matcopybuf.ramp_col = NULL;
	matcopybuf.ramp_spec = NULL;

	if (matcopybuf.nodetree) {
		ntreeFreeTree_ex(matcopybuf.nodetree, FALSE);
		MEM_freeN(matcopybuf.nodetree);
		matcopybuf.nodetree = NULL;
	}

	matcopied = 0;
}

void copy_matcopybuf(Material *ma)
{
	int a;
	MTex *mtex;

	if (matcopied)
		free_matcopybuf();

	memcpy(&matcopybuf, ma, sizeof(Material));
	if (matcopybuf.ramp_col) matcopybuf.ramp_col = MEM_dupallocN(matcopybuf.ramp_col);
	if (matcopybuf.ramp_spec) matcopybuf.ramp_spec = MEM_dupallocN(matcopybuf.ramp_spec);

	for (a = 0; a < MAX_MTEX; a++) {
		mtex = matcopybuf.mtex[a];
		if (mtex) {
			matcopybuf.mtex[a] = MEM_dupallocN(mtex);
		}
	}
	matcopybuf.nodetree = ntreeCopyTree_ex(ma->nodetree, FALSE);
	matcopybuf.preview = NULL;
	BLI_listbase_clear(&matcopybuf.gpumaterial);
	matcopied = 1;
}

void paste_matcopybuf(Material *ma)
{
	int a;
	MTex *mtex;
	ID id;

	if (matcopied == 0)
		return;
	/* free current mat */
	if (ma->ramp_col) MEM_freeN(ma->ramp_col);
	if (ma->ramp_spec) MEM_freeN(ma->ramp_spec);
	for (a = 0; a < MAX_MTEX; a++) {
		mtex = ma->mtex[a];
		if (mtex && mtex->tex) mtex->tex->id.us--;
		if (mtex) MEM_freeN(mtex);
	}

	if (ma->nodetree) {
		ntreeFreeTree(ma->nodetree);
		MEM_freeN(ma->nodetree);
	}

	GPU_material_free(ma);

	id = (ma->id);
	memcpy(ma, &matcopybuf, sizeof(Material));
	(ma->id) = id;

	if (matcopybuf.ramp_col) ma->ramp_col = MEM_dupallocN(matcopybuf.ramp_col);
	if (matcopybuf.ramp_spec) ma->ramp_spec = MEM_dupallocN(matcopybuf.ramp_spec);

	for (a = 0; a < MAX_MTEX; a++) {
		mtex = ma->mtex[a];
		if (mtex) {
			ma->mtex[a] = MEM_dupallocN(mtex);
			if (mtex->tex) {
				/* first check this is in main (we may have loaded another file) [#35500] */
				if (BLI_findindex(&G.main->tex, mtex->tex) != -1) {
					id_us_plus((ID *)mtex->tex);
				}
				else {
					ma->mtex[a]->tex = NULL;
				}
			}
		}
	}

	ma->nodetree = ntreeCopyTree_ex(matcopybuf.nodetree, FALSE);
}


/*********************** texface to material convert functions **********************/
/* encode all the TF information into a single int */
static int encode_tfaceflag(MTFace *tf, int convertall)
{
	/* calculate the flag */
	int flag = tf->mode;

	/* options that change the material offline render */
	if (!convertall) {
		flag &= ~TF_OBCOL;
	}

	/* clean flags that are not being converted */
	flag &= ~TF_TEX;
	flag &= ~TF_SHAREDVERT;
	flag &= ~TF_SHAREDCOL;
	flag &= ~TF_CONVERTED;

	/* light tface flag is ignored in GLSL mode */
	flag &= ~TF_LIGHT;
	
	/* 15 is how big the flag can be - hardcoded here and in decode_tfaceflag() */
	flag |= tf->transp << 15;
	
	/* increase 1 so flag 0 is different than no flag yet */
	return flag + 1;
}

/* set the material options based in the tface flag */
static void decode_tfaceflag(Material *ma, int flag, int convertall)
{
	int alphablend;
	GameSettings *game = &ma->game;

	/* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
	flag -= 1;

	alphablend = flag >> 15;  /* encoded in the encode_tfaceflag function */
	(*game).flag = 0;
	
	/* General Material Options */
	if ((flag & TF_DYNAMIC) == 0) (*game).flag    |= GEMAT_NOPHYSICS;
	
	/* Material Offline Rendering Properties */
	if (convertall) {
		if (flag & TF_OBCOL) ma->shade_flag |= MA_OBCOLOR;
	}
	
	/* Special Face Properties */
	if ((flag & TF_TWOSIDE) == 0) (*game).flag |= GEMAT_BACKCULL;
	if (flag & TF_INVISIBLE) (*game).flag |= GEMAT_INVISIBLE;
	if (flag & TF_BMFONT) (*game).flag |= GEMAT_TEXT;
	
	/* Face Orientation */
	if (flag & TF_BILLBOARD) (*game).face_orientation |= GEMAT_HALO;
	else if (flag & TF_BILLBOARD2) (*game).face_orientation |= GEMAT_BILLBOARD;
	else if (flag & TF_SHADOW) (*game).face_orientation |= GEMAT_SHADOW;
	
	/* Alpha Blend */
	if (flag & TF_ALPHASORT && ELEM(alphablend, TF_ALPHA, TF_ADD)) (*game).alpha_blend = GEMAT_ALPHA_SORT;
	else if (alphablend & TF_ALPHA) (*game).alpha_blend = GEMAT_ALPHA;
	else if (alphablend & TF_ADD) (*game).alpha_blend = GEMAT_ADD;
	else if (alphablend & TF_CLIP) (*game).alpha_blend = GEMAT_CLIP;
}

/* boolean check to see if the mesh needs a material */
static int check_tfaceneedmaterial(int flag)
{
	/* check if the flags we have are not deprecated != than default material options
	 * also if only flags are visible and collision see if all objects using this mesh have this option in physics */

	/* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
	flag -= 1;

	/* deprecated flags */
	flag &= ~TF_OBCOL;
	flag &= ~TF_SHAREDVERT;
	flag &= ~TF_SHAREDCOL;

	/* light tface flag is ignored in GLSL mode */
	flag &= ~TF_LIGHT;
	
	/* automatic detected if tex image has alpha */
	flag &= ~(TF_ALPHA << 15);
	/* automatic detected if using texture */
	flag &= ~TF_TEX;

	/* settings for the default NoMaterial */
	if (flag == TF_DYNAMIC)
		return 0;

	else
		return 1;
}

/* return number of digits of an integer */
/* XXX to be optmized or replaced by an equivalent blender internal function */
static int integer_getdigits(int number)
{
	int i = 0;
	if (number == 0) return 1;

	while (number != 0) {
		number = (int)(number / 10);
		i++;
	}
	return i;
}

static void calculate_tface_materialname(char *matname, char *newname, int flag)
{
	/* if flag has only light and collision and material matches those values
	 * you can do strcpy(name, mat_name);
	 * otherwise do: */
	int digits = integer_getdigits(flag);
	/* clamp the old name, remove the MA prefix and add the .TF.flag suffix
	 * e.g. matname = "MALoooooooooooooongName"; newname = "Loooooooooooooon.TF.2" */
	BLI_snprintf(newname, MAX_ID_NAME, "%.*s.TF.%0*d", MAX_ID_NAME - (digits + 5), matname, digits, flag);
}

/* returns -1 if no match */
static short mesh_getmaterialnumber(Mesh *me, Material *ma)
{
	short a;

	for (a = 0; a < me->totcol; a++) {
		if (me->mat[a] == ma) {
			return a;
		}
	}

	return -1;
}

/* append material */
static short mesh_addmaterial(Mesh *me, Material *ma)
{
	BKE_material_append_id(&me->id, NULL);
	me->mat[me->totcol - 1] = ma;

	id_us_plus(&ma->id);

	return me->totcol - 1;
}

static void set_facetexture_flags(Material *ma, Image *image)
{
	if (image) {
		ma->mode |= MA_FACETEXTURE;
		/* we could check if the texture has alpha, but then more meshes sharing the same
		 * material may need it. Let's make it simple. */
		if (BKE_image_has_alpha(image))
			ma->mode |= MA_FACETEXTURE_ALPHA;
	}
}

/* returns material number */
static short convert_tfacenomaterial(Main *main, Mesh *me, MTFace *tf, int flag)
{
	Material *ma;
	char idname[MAX_ID_NAME];
	short mat_nr = -1;
	
	/* new material, the name uses the flag*/
	BLI_snprintf(idname, sizeof(idname), "MAMaterial.TF.%0*d", integer_getdigits(flag), flag);

	if ((ma = BLI_findstring(&main->mat, idname + 2, offsetof(ID, name) + 2))) {
		mat_nr = mesh_getmaterialnumber(me, ma);
		/* assign the material to the mesh */
		if (mat_nr == -1) mat_nr = mesh_addmaterial(me, ma);

		/* if needed set "Face Textures [Alpha]" Material options */
		set_facetexture_flags(ma, tf->tpage);
	}
	/* create a new material */
	else {
		ma = BKE_material_add(main, idname + 2);

		if (ma) {
			printf("TexFace Convert: Material \"%s\" created.\n", idname + 2);
			mat_nr = mesh_addmaterial(me, ma);
			
			/* if needed set "Face Textures [Alpha]" Material options */
			set_facetexture_flags(ma, tf->tpage);

			decode_tfaceflag(ma, flag, 1);
			/* the final decoding will happen after, outside the main loop
			 * for now store the flag into the material and change light/tex/collision
			 * store the flag as a negative number */
			ma->game.flag = -flag;
			id_us_min((ID *)ma);
		}
		else {
			printf("Error: Unable to create Material \"%s\" for Mesh \"%s\".", idname + 2, me->id.name + 2);
		}
	}

	/* set as converted, no need to go bad to this face */
	tf->mode |= TF_CONVERTED;
	return mat_nr;
}

/* Function to fully convert materials */
static void convert_tfacematerial(Main *main, Material *ma)
{
	Mesh *me;
	Material *mat_new;
	MFace *mf;
	MTFace *tf;
	int flag, index;
	int a;
	short mat_nr;
	CustomDataLayer *cdl;
	char idname[MAX_ID_NAME];

	for (me = main->mesh.first; me; me = me->id.next) {
		/* check if this mesh uses this material */
		for (a = 0; a < me->totcol; a++)
			if (me->mat[a] == ma) break;
			
		/* no material found */
		if (a == me->totcol) continue;

		/* get the active tface layer */
		index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
		cdl = (index == -1) ? NULL : &me->fdata.layers[index];
		if (!cdl) continue;

		/* loop over all the faces and stop at the ones that use the material*/
		for (a = 0, mf = me->mface; a < me->totface; a++, mf++) {
			if (me->mat[mf->mat_nr] != ma) continue;

			/* texface data for this face */
			tf = ((MTFace *)cdl->data) + a;
			flag = encode_tfaceflag(tf, 1);

			/* the name of the new material */
			calculate_tface_materialname(ma->id.name, (char *)&idname, flag);

			if ((mat_new = BLI_findstring(&main->mat, idname + 2, offsetof(ID, name) + 2))) {
				/* material already existent, see if the mesh has it */
				mat_nr = mesh_getmaterialnumber(me, mat_new);
				/* material is not in the mesh, add it */
				if (mat_nr == -1) mat_nr = mesh_addmaterial(me, mat_new);
			}
			/* create a new material */
			else {
				mat_new = BKE_material_copy(ma);
				if (mat_new) {
					/* rename the material*/
					BLI_strncpy(mat_new->id.name, idname, sizeof(mat_new->id.name));
					id_us_min((ID *)mat_new);

					mat_nr = mesh_addmaterial(me, mat_new);
					decode_tfaceflag(mat_new, flag, 1);
				}
				else {
					printf("Error: Unable to create Material \"%s\" for Mesh \"%s.", idname + 2, me->id.name + 2);
					mat_nr = mf->mat_nr;
					continue;
				}
			}
			
			/* if the material has a texture but no texture channel
			 * set "Face Textures [Alpha]" Material options 
			 * actually we need to run it always, because of old behavior
			 * of using face texture if any texture channel was present (multitex) */
			//if ((!mat_new->mtex[0]) && (!mat_new->mtex[0]->tex))
			set_facetexture_flags(mat_new, tf->tpage);

			/* set the material number to the face*/
			mf->mat_nr = mat_nr;
		}
		/* remove material from mesh */
		for (a = 0; a < me->totcol; ) {
			if (me->mat[a] == ma) {
				BKE_material_pop_id(&me->id, a, true);
			}
			else {
				a++;
			}
		}
	}
}


#define MAT_BGE_DISPUTED -99999

int do_version_tface(Main *main)
{
	Mesh *me;
	Material *ma;
	MFace *mf;
	MTFace *tf;
	CustomDataLayer *cdl;
	int a;
	int flag;
	int index;
	
	/* Operator in help menu has been removed for 2.7x */
	int fileload = 1;

	/* sometimes mesh has no materials but will need a new one. In those
	 * cases we need to ignore the mf->mat_nr and only look at the face
	 * mode because it can be zero as uninitialized or the 1st created material
	 */
	int nomaterialslots;

	/* alert to user to check the console */
	int nowarning = 1;

	/* mark all the materials to conversion with a flag
	 * if there is tface create a complete flag for that storing in flag
	 * if there is tface and flag > 0: creates a new flag based on this face
	 * if flags are different set flag to -1  
	 */
	
	/* 1st part: marking mesh materials to update */
	for (me = main->mesh.first; me; me = me->id.next) {
		if (me->id.lib) continue;

		/* get the active tface layer */
		index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
		cdl = (index == -1) ? NULL : &me->fdata.layers[index];
		if (!cdl) continue;

		nomaterialslots = (me->totcol == 0 ? 1 : 0);
		
		/* loop over all the faces*/
		for (a = 0, mf = me->mface; a < me->totface; a++, mf++) {
			/* texface data for this face */
			tf = ((MTFace *)cdl->data) + a;

			/* conversion should happen only once */
			if (fileload)
				tf->mode &= ~TF_CONVERTED;
			else {
				if ((tf->mode & TF_CONVERTED)) continue;
				else tf->mode |= TF_CONVERTED;
			}
			
			/* no material slots */
			if (nomaterialslots) {
				flag = encode_tfaceflag(tf, 1);
				
				/* create/find a new material and assign to the face */
				if (check_tfaceneedmaterial(flag)) {
					mf->mat_nr = convert_tfacenomaterial(main, me, tf, flag);
				}
				/* else mark them as no-material to be reverted to 0 later */
				else {
					mf->mat_nr = -1;
				}
			}
			else if (mf->mat_nr < me->totcol) {
				ma = me->mat[mf->mat_nr];
				
				/* no material create one if necessary */
				if (!ma) {
					/* find a new material and assign to the face */
					flag = encode_tfaceflag(tf, 1);

					/* create/find a new material and assign to the face */
					if (check_tfaceneedmaterial(flag))
						mf->mat_nr = convert_tfacenomaterial(main, me, tf, flag);

					continue;
				}

				/* we can't read from this if it comes from a library,
				 * at doversion time: direct_link might not have happened on it,
				 * so ma->mtex is not pointing to valid memory yet.
				 * later we could, but it's better not */
				else if (ma->id.lib)
					continue;
				
				/* material already marked as disputed */
				else if (ma->game.flag == MAT_BGE_DISPUTED)
					continue;

				/* found a material */
				else {
					flag = encode_tfaceflag(tf, ((fileload) ? 0 : 1));

					/* first time changing this material */
					if (ma->game.flag == 0)
						ma->game.flag = -flag;
			
					/* mark material as disputed */
					else if (ma->game.flag != -flag) {
						ma->game.flag = MAT_BGE_DISPUTED;
						continue;
					}
			
					/* material ok so far */
					else {
						ma->game.flag = -flag;
						
						/* some people uses multitexture with TexFace by creating a texture
						 * channel which not necessarily the tf->tpage image. But the game engine
						 * was enabling it. Now it's required to set "Face Texture [Alpha] in the
						 * material settings. */
						if (!fileload)
							set_facetexture_flags(ma, tf->tpage);
					}
				}
			}
			else {
				continue;
			}
		}

		/* if we didn't have material slot and now we do, we need to
		 * make sure the materials are correct */
		if (nomaterialslots) {
			if (me->totcol > 0) {
				for (a = 0, mf = me->mface; a < me->totface; a++, mf++) {
					if (mf->mat_nr == -1) {
						/* texface data for this face */
						tf = ((MTFace *)cdl->data) + a;
						mf->mat_nr = convert_tfacenomaterial(main, me, tf, encode_tfaceflag(tf, 1));
					}
				}
			}
			else {
				for (a = 0, mf = me->mface; a < me->totface; a++, mf++) {
					mf->mat_nr = 0;
				}
			}
		}

	}
	
	/* 2nd part - conversion */
	/* skip library files */

	/* we shouldn't loop through the materials created in the loop. make the loop stop at its original length) */
	for (ma = main->mat.first, a = 0; ma; ma = ma->id.next, a++) {
		if (ma->id.lib) continue;

		/* disputed material */
		if (ma->game.flag == MAT_BGE_DISPUTED) {
			ma->game.flag = 0;
			if (fileload) {
				printf("Warning: material \"%s\" skipped.\n", ma->id.name + 2);
				nowarning = 0;
			}
			else {
				convert_tfacematerial(main, ma);
			}
			continue;
		}
	
		/* no conflicts in this material - 90% of cases
		 * convert from tface system to material */
		else if (ma->game.flag < 0) {
			decode_tfaceflag(ma, -(ma->game.flag), 1);

			/* material is good make sure all faces using
			 * this material are set to converted */
			if (fileload) {
				for (me = main->mesh.first; me; me = me->id.next) {
					/* check if this mesh uses this material */
					for (a = 0; a < me->totcol; a++)
						if (me->mat[a] == ma) break;
						
					/* no material found */
					if (a == me->totcol) continue;
			
					/* get the active tface layer */
					index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
					cdl = (index == -1) ? NULL : &me->fdata.layers[index];
					if (!cdl) continue;
			
					/* loop over all the faces and stop at the ones that use the material*/
					for (a = 0, mf = me->mface; a < me->totface; a++, mf++) {
						if (me->mat[mf->mat_nr] == ma) {
							/* texface data for this face */
							tf = ((MTFace *)cdl->data) + a;
							tf->mode |= TF_CONVERTED;
						}
					}
				}
			}
		}
		/* material is not used by faces with texface
		 * set the default flag - do it only once */
		else {
			if (fileload) {
				ma->game.flag = GEMAT_BACKCULL;
			}
		}
	}

	return nowarning;
}