Skip to content
Snippets Groups Projects
export_fbx.py 114 KiB
Newer Older
# ##### 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.
#
# ##### END GPL LICENSE BLOCK #####

# <pep8 compliant>

# Script copyright (C) Campbell Barton

"""
This script is an exporter to the FBX file format.

http://wiki.blender.org/index.php/Scripts/Manual/Export/autodesk_fbx
"""

import os
import time
import math  # math.pi
import shutil  # for file copying

import bpy
from mathutils import Vector, Euler, Matrix


# XXX not used anymore, images are copied one at a time
def copy_images(dest_dir, textures):
    import shutil

    if not dest_dir.endswith(os.sep):
        dest_dir += os.sep

    image_paths = set()
    for tex in textures:
        image_paths.add(bpy.path.abspath(tex.filepath))

    # Now copy images
    copyCount = 0
    for image_path in image_paths:
        if Blender.sys.exists(image_path):
            # Make a name for the target path.
            dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1]
            if not Blender.sys.exists(dest_image_path):  # Image isnt already there
                print("\tCopying %r > %r" % (image_path, dest_image_path))
                try:
                    shutil.copy(image_path, dest_image_path)
                    copyCount += 1
                except:
                    print("\t\tWarning, file failed to copy, skipping.")

    print('\tCopied %d images' % copyCount)


# I guess FBX uses degrees instead of radians (Arystan).
# Call this function just before writing to FBX.
# 180 / math.pi == 57.295779513
def tuple_rad_to_deg(eul):
    return eul[0] * 57.295779513, eul[1] * 57.295779513, eul[2] * 57.295779513

# def strip_path(p):
# 	return p.split('\\')[-1].split('/')[-1]

# Used to add the scene name into the filepath without using odd chars
sane_name_mapping_ob = {}
sane_name_mapping_mat = {}
sane_name_mapping_tex = {}
sane_name_mapping_take = {}
sane_name_mapping_group = {}

# Make sure reserved names are not used
sane_name_mapping_ob['Scene'] = 'Scene_'
sane_name_mapping_ob['blend_root'] = 'blend_root_'


def increment_string(t):
    name = t
    num = ''
    while name and name[-1].isdigit():
        num = name[-1] + num
        name = name[:-1]
    if num:
        return '%s%d' % (name, int(num) + 1)
    else:
        return name + '_0'


# todo - Disallow the name 'Scene' and 'blend_root' - it will bugger things up.
def sane_name(data, dct):
    #if not data: return None

    if type(data) == tuple:  # materials are paired up with images
        data, other = data
        use_other = True
    else:
        other = None
        use_other = False

    name = data.name if data else None
    orig_name = name

    if other:
        orig_name_other = other.name
        name = '%s #%s' % (name, orig_name_other)
    else:
        orig_name_other = None

    # dont cache, only ever call once for each data type now,
    # so as to avoid namespace collision between types - like with objects <-> bones
    #try:		return dct[name]
    #except:		pass

    if not name:
        name = 'unnamed'  # blank string, ASKING FOR TROUBLE!
    else:

        name = bpy.path.clean_name(name)  # use our own

    while name in iter(dct.values()):
        name = increment_string(name)

    if use_other:  # even if other is None - orig_name_other will be a string or None
        dct[orig_name, orig_name_other] = name
    else:
        dct[orig_name] = name

    return name


def sane_obname(data):
    return sane_name(data, sane_name_mapping_ob)


def sane_matname(data):
    return sane_name(data, sane_name_mapping_mat)


def sane_texname(data):
    return sane_name(data, sane_name_mapping_tex)


def sane_takename(data):
    return sane_name(data, sane_name_mapping_take)


def sane_groupname(data):
    return sane_name(data, sane_name_mapping_group)

# def derived_paths(fname_orig, basepath, FORCE_CWD=False):
# 	'''
# 	fname_orig - blender path, can be relative
# 	basepath - fname_rel will be relative to this
# 	FORCE_CWD - dont use the basepath, just add a ./ to the filepath.
# 		use when we know the file will be in the basepath.
# 	'''
# 	fname = bpy.path.abspath(fname_orig)
# # 	fname = Blender.sys.expandpath(fname_orig)
# 	fname_strip = os.path.basename(fname)
# # 	fname_strip = strip_path(fname)
# 	if FORCE_CWD:
# 		fname_rel = '.' + os.sep + fname_strip
# 	else:
# 		fname_rel = bpy.path.relpath(fname, basepath)
# # 		fname_rel = Blender.sys.relpath(fname, basepath)
# 	if fname_rel.startswith('//'): fname_rel = '.' + os.sep + fname_rel[2:]
# 	return fname, fname_strip, fname_rel


def mat4x4str(mat):
    return '%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f' % tuple([f for v in mat for f in v])


# XXX not used
# duplicated in OBJ exporter
def getVertsFromGroup(me, group_index):
    ret = []

    for i, v in enumerate(me.vertices):
        for g in v.groups:
            if g.group == group_index:
                ret.append((i, g.weight))

        return ret


# ob must be OB_MESH
def BPyMesh_meshWeight2List(ob, me):
    ''' Takes a mesh and return its group names and a list of lists, one list per vertex.
    aligning the each vert list with the group names, each list contains float value for the weight.
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
    These 2 lists can be modified and then used with list2MeshWeight to apply the changes.
    '''

    # Clear the vert group.
    groupNames = [g.name for g in ob.vertex_groups]
    len_groupNames = len(groupNames)

    if not len_groupNames:
        # no verts? return a vert aligned empty list
        return [[] for i in range(len(me.vertices))], []
    else:
        vWeightList = [[0.0] * len_groupNames for i in range(len(me.vertices))]

    for i, v in enumerate(me.vertices):
        for g in v.groups:
            vWeightList[i][g.group] = g.weight

    return groupNames, vWeightList


def meshNormalizedWeights(ob, me):
    try:  # account for old bad BPyMesh
        groupNames, vWeightList = BPyMesh_meshWeight2List(ob, me)
    except:
        return [], []

    if not groupNames:
        return [], []

    for i, vWeights in enumerate(vWeightList):
        tot = 0.0
        for w in vWeights:
            tot += w

        if tot:
            for j, w in enumerate(vWeights):
                vWeights[j] = w / tot

    return groupNames, vWeightList

header_comment = \
'''; FBX 6.1.0 project file
; Created by Blender FBX Exporter
; for support mail: ideasman42@gmail.com
; ----------------------------------------------------

'''


# This func can be called with just the filepath
def save(operator, context, filepath="",
        GLOBAL_MATRIX=None,
        EXP_OBS_SELECTED=True,
        EXP_MESH=True,
        EXP_MESH_APPLY_MOD=True,
        EXP_ARMATURE=True,
        EXP_LAMP=True,
        EXP_CAMERA=True,
        EXP_EMPTY=True,
        EXP_IMAGE_COPY=False,
        ANIM_ENABLE=True,
        ANIM_OPTIMIZE=True,
        ANIM_OPTIMIZE_PRECISSION=6,
        ANIM_ACTION_ALL=False,
        BATCH_ENABLE=False,
        BATCH_GROUP=True,
        BATCH_FILE_PREFIX='',
        BATCH_OWN_DIR=False
    ):

    #XXX, missing arg
    batch_objects = None

    # testing
    mtx_x90 = Matrix.Rotation(math.pi / 2.0, 3, 'X')  # used
    mtx4_z90 = Matrix.Rotation(math.pi / 2.0, 4, 'Z')

    if GLOBAL_MATRIX is None:
        GLOBAL_MATRIX = Matrix()

    if bpy.ops.object.mode_set.poll():
        bpy.ops.object.mode_set(mode='OBJECT')

    # ----------------- Batch support!
    if BATCH_ENABLE:
        fbxpath = filepath

        # get the path component of filepath
        tmp_exists = bpy.utils.exists(fbxpath)

        if tmp_exists != 2:  # a file, we want a path
            fbxpath = os.path.dirname(fbxpath)
# 			while fbxpath and fbxpath[-1] not in ('/', '\\'):
# 				fbxpath = fbxpath[:-1]
            if not fbxpath:
                # XXX
                print('Error%t|Directory does not exist!')
# 				Draw.PupMenu('Error%t|Directory does not exist!')
                return

            tmp_exists = bpy.utils.exists(fbxpath)

        if tmp_exists != 2:
            # XXX
            print('Error%t|Directory does not exist!')
# 			Draw.PupMenu('Error%t|Directory does not exist!')
            return

        if not fbxpath.endswith(os.sep):
            fbxpath += os.sep
        del tmp_exists

        if BATCH_GROUP:
            data_seq = bpy.data.groups
        else:
            data_seq = bpy.data.scenes

        # call this function within a loop with BATCH_ENABLE == False
        orig_sce = context.scene

        new_fbxpath = fbxpath  # own dir option modifies, we need to keep an original
        for data in data_seq:  # scene or group
            newname = BATCH_FILE_PREFIX + bpy.path.clean_name(data.name)

            if BATCH_OWN_DIR:
                new_fbxpath = fbxpath + newname + os.sep
                # path may already exist
                # TODO - might exist but be a file. unlikely but should probably account for it.

                if bpy.utils.exists(new_fbxpath) == 0:
# 				if Blender.sys.exists(new_fbxpath) == 0:
                    os.mkdir(new_fbxpath)

            filepath = new_fbxpath + newname + '.fbx'

            print('\nBatch exporting %s as...\n\t%r' % (data, filepath))

            # XXX don't know what to do with this, probably do the same? (Arystan)
            if BATCH_GROUP:  # group
                # group, so objects update properly, add a dummy scene.
                scene = bpy.data.scenes.new()
                scene.Layers = (1 << 20) - 1
                bpy.data.scenes.active = scene
                for ob_base in data.objects:
                    scene.objects.link(ob_base)

                scene.update(1)

                # TODO - BUMMER! Armatures not in the group wont animate the mesh

            else:  # scene
                data_seq.active = data

            # Call self with modified args
            # Dont pass batch options since we already usedt them
            write(filepath, data.objects,
                context,
                False,
                EXP_MESH,
                EXP_MESH_APPLY_MOD,
                EXP_ARMATURE,
                EXP_LAMP,
                EXP_CAMERA,
                EXP_EMPTY,
                EXP_IMAGE_COPY,
                GLOBAL_MATRIX,
                ANIM_ENABLE,
                ANIM_OPTIMIZE,
                ANIM_OPTIMIZE_PRECISSION,
                ANIM_ACTION_ALL
            )

            if BATCH_GROUP:
                # remove temp group scene
                bpy.data.scenes.unlink(scene)

        bpy.data.scenes.active = orig_sce

        return  # so the script wont run after we have batch exported.

    # end batch support

    # Use this for working out paths relative to the export location
    basepath = os.path.dirname(filepath) or '.'
    basepath += os.sep
# 	basepath = Blender.sys.dirname(filepath)

    # ----------------------------------------------
    # storage classes
    class my_bone_class(object):
        __slots__ = ("blenName",
                     "blenBone",
                     "blenMeshes",
                     "restMatrix",
                     "parent",
                     "blenName",
                     "fbxName",
                     "fbxArm",
                     "__pose_bone",
                     "__anim_poselist")

        def __init__(self, blenBone, fbxArm):

            # This is so 2 armatures dont have naming conflicts since FBX bones use object namespace
            self.fbxName = sane_obname(blenBone)

            self.blenName = blenBone.name
            self.blenBone = blenBone
            self.blenMeshes = {}					# fbxMeshObName : mesh
            self.fbxArm = fbxArm
            self.restMatrix = blenBone.matrix_local
# 			self.restMatrix =		blenBone.matrix['ARMATURESPACE']

            # not used yet
            # self.restMatrixInv =	self.restMatrix.copy().invert()
            # self.restMatrixLocal =	None # set later, need parent matrix

            self.parent = None

            # not public
            pose = fbxArm.blenObject.pose
            self.__pose_bone = pose.bones[self.blenName]

            # store a list if matricies here, (poseMatrix, head, tail)
            # {frame:posematrix, frame:posematrix, ...}
            self.__anim_poselist = {}

        '''
        def calcRestMatrixLocal(self):
            if self.parent:
                self.restMatrixLocal = self.restMatrix * self.parent.restMatrix.copy().invert()
            else:
                self.restMatrixLocal = self.restMatrix.copy()
        '''
        def setPoseFrame(self, f):
            # cache pose info here, frame must be set beforehand

            # Didnt end up needing head or tail, if we do - here it is.
            '''
            self.__anim_poselist[f] = (\
                self.__pose_bone.poseMatrix.copy(),\
                self.__pose_bone.head.copy(),\
                self.__pose_bone.tail.copy() )
            '''

            self.__anim_poselist[f] = self.__pose_bone.matrix.copy()

        # get pose from frame.
        def getPoseMatrix(self, f):  # ----------------------------------------------
            return self.__anim_poselist[f]
        '''
        def getPoseHead(self, f):
            #return self.__pose_bone.head.copy()
            return self.__anim_poselist[f][1].copy()
        def getPoseTail(self, f):
            #return self.__pose_bone.tail.copy()
            return self.__anim_poselist[f][2].copy()
        '''
        # end

        def getAnimParRelMatrix(self, frame):
            #arm_mat = self.fbxArm.matrixWorld
            #arm_mat = self.fbxArm.parRelMatrix()
            if not self.parent:
                #return mtx4_z90 * (self.getPoseMatrix(frame) * arm_mat) # dont apply arm matrix anymore
                return self.getPoseMatrix(frame) * mtx4_z90
            else:
                #return (mtx4_z90 * ((self.getPoseMatrix(frame) * arm_mat)))  *  (mtx4_z90 * (self.parent.getPoseMatrix(frame) * arm_mat)).invert()
                return (self.parent.getPoseMatrix(frame) * mtx4_z90).invert() * ((self.getPoseMatrix(frame)) * mtx4_z90)

        # we need thes because cameras and lights modified rotations
        def getAnimParRelMatrixRot(self, frame):
            return self.getAnimParRelMatrix(frame)

        def flushAnimData(self):
            self.__anim_poselist.clear()

    class my_object_generic(object):
        __slots__ = ("fbxName",
                     "blenObject",
                     "blenData",
                     "origData",
                     "blenTextures",
                     "blenMaterials",
                     "blenMaterialList",
                     "blenAction",
                     "blenActionList",
                     "fbxGroupNames",
                     "fbxParent",
                     "fbxBoneParent",
                     "fbxBones",
                     "fbxArm",
                     "matrixWorld",
                     "__anim_poselist",
                     )

        # Other settings can be applied for each type - mesh, armature etc.
        def __init__(self, ob, matrixWorld=None):
            self.fbxName = sane_obname(ob)
            self.blenObject = ob
            self.fbxGroupNames = []
            self.fbxParent = None  # set later on IF the parent is in the selection.
            if matrixWorld:
                self.matrixWorld = GLOBAL_MATRIX * matrixWorld
            else:
                self.matrixWorld = GLOBAL_MATRIX * ob.matrix_world

            self.__anim_poselist = {}  # we should only access this

        def parRelMatrix(self):
            if self.fbxParent:
                return self.fbxParent.matrixWorld.copy().invert() * self.matrixWorld
            else:
                return self.matrixWorld

        def setPoseFrame(self, f, fake=False):
            if fake:
                # annoying, have to clear GLOBAL_MATRIX
                self.__anim_poselist[f] = self.matrixWorld * GLOBAL_MATRIX.copy().invert()
            else:
                self.__anim_poselist[f] = self.blenObject.matrix_world.copy()

        def getAnimParRelMatrix(self, frame):
            if self.fbxParent:
                #return (self.__anim_poselist[frame] * self.fbxParent.__anim_poselist[frame].copy().invert() ) * GLOBAL_MATRIX
                return (GLOBAL_MATRIX * self.fbxParent.__anim_poselist[frame]).invert() * (GLOBAL_MATRIX * self.__anim_poselist[frame])
            else:
                return GLOBAL_MATRIX * self.__anim_poselist[frame]

        def getAnimParRelMatrixRot(self, frame):
            obj_type = self.blenObject.type
            if self.fbxParent:
                matrix_rot = ((GLOBAL_MATRIX * self.fbxParent.__anim_poselist[frame]).invert() * (GLOBAL_MATRIX * self.__anim_poselist[frame])).rotation_part()
            else:
                matrix_rot = (GLOBAL_MATRIX * self.__anim_poselist[frame]).rotation_part()

            # Lamps need to be rotated
            if obj_type == 'LAMP':
                matrix_rot = matrix_rot * mtx_x90
            elif obj_type == 'CAMERA':
                y = Vector((0.0, 1.0, 0.0)) * matrix_rot
                matrix_rot = Matrix.Rotation(math.pi / 2.0, 3, y) * matrix_rot

            return matrix_rot

    # ----------------------------------------------

    print('\nFBX export starting... %r' % filepath)
    start_time = time.clock()
    try:
        file = open(filepath, 'w', encoding='utf8')
    except:
        return False

    scene = context.scene
    world = scene.world

    # ---------------------------- Write the header first
    file.write(header_comment)
    if time:
        curtime = time.localtime()[0:6]
    else:
        curtime = (0, 0, 0, 0, 0, 0)
    #
    file.write(\
'''FBXHeaderExtension:  {
    FBXHeaderVersion: 1003
    FBXVersion: 6100
    CreationTimeStamp:  {
        Version: 1000
        Year: %.4i
        Month: %.2i
        Day: %.2i
        Hour: %.2i
        Minute: %.2i
        Second: %.2i
        Millisecond: 0
    }
    Creator: "FBX SDK/FBX Plugins build 20070228"
    OtherFlags:  {
        FlagPLE: 0
    }
}''' % (curtime))

    file.write('\nCreationTime: "%.4i-%.2i-%.2i %.2i:%.2i:%.2i:000"' % curtime)
    file.write('\nCreator: "Blender version %s"' % bpy.app.version_string)

    pose_items = []  # list of (fbxName, matrix) to write pose data for, easier to collect allong the way

    # --------------- funcs for exporting
    def object_tx(ob, loc, matrix, matrix_mod=None):
        '''
        Matrix mod is so armature objects can modify their bone matricies
        '''
        if isinstance(ob, bpy.types.Bone):
# 		if isinstance(ob, Blender.Types.BoneType):

            # we know we have a matrix
            # matrix = mtx4_z90 * (ob.matrix['ARMATURESPACE'] * matrix_mod)
            matrix = ob.matrix_local * mtx4_z90  # dont apply armature matrix anymore
# 			matrix = mtx4_z90 * ob.matrix['ARMATURESPACE'] # dont apply armature matrix anymore

            parent = ob.parent
            if parent:
                #par_matrix = mtx4_z90 * (parent.matrix['ARMATURESPACE'] * matrix_mod)
                par_matrix = parent.matrix_local * mtx4_z90  # dont apply armature matrix anymore
# 				par_matrix = mtx4_z90 * parent.matrix['ARMATURESPACE'] # dont apply armature matrix anymore
                matrix = par_matrix.copy().invert() * matrix

            loc, rot, scale = matrix.decompose()
            matrix_rot = rot.to_matrix()

            loc = tuple(loc)
            rot = tuple(rot.to_euler())  # quat -> euler
            scale = tuple(scale)
        else:
            # This is bad because we need the parent relative matrix from the fbx parent (if we have one), dont use anymore
            #if ob and not matrix: matrix = ob.matrix_world * GLOBAL_MATRIX
            if ob and not matrix:
                raise Exception("error: this should never happen!")

            matrix_rot = matrix
            #if matrix:
            #	matrix = matrix_scale * matrix

            if matrix:
                loc, rot, scale = matrix.decompose()
                matrix_rot = rot.to_matrix()

                # Lamps need to be rotated
                if ob and ob.type == 'LAMP':
                    matrix_rot = matrix_rot * mtx_x90
                elif ob and ob.type == 'CAMERA':
                    y = Vector((0.0, 1.0, 0.0)) * matrix_rot
                    matrix_rot = Matrix.Rotation(math.pi / 2.0, 3, y) * matrix_rot
                # else do nothing.

                loc = tuple(loc)
                rot = tuple(matrix_rot.to_euler())
                scale = tuple(scale)
            else:
                if not loc:
                    loc = 0.0, 0.0, 0.0
                scale = 1.0, 1.0, 1.0
                rot = 0.0, 0.0, 0.0

        return loc, rot, scale, matrix, matrix_rot

    def write_object_tx(ob, loc, matrix, matrix_mod=None):
        '''
        We have loc to set the location if non blender objects that have a location

        matrix_mod is only used for bones at the moment
        '''
        loc, rot, scale, matrix, matrix_rot = object_tx(ob, loc, matrix, matrix_mod)

        file.write('\n\t\t\tProperty: "Lcl Translation", "Lcl Translation", "A+",%.15f,%.15f,%.15f' % loc)
        file.write('\n\t\t\tProperty: "Lcl Rotation", "Lcl Rotation", "A+",%.15f,%.15f,%.15f' % tuple_rad_to_deg(rot))
# 		file.write('\n\t\t\tProperty: "Lcl Rotation", "Lcl Rotation", "A+",%.15f,%.15f,%.15f' % rot)
        file.write('\n\t\t\tProperty: "Lcl Scaling", "Lcl Scaling", "A+",%.15f,%.15f,%.15f' % scale)
        return loc, rot, scale, matrix, matrix_rot

    def write_object_props(ob=None, loc=None, matrix=None, matrix_mod=None):
        # if the type is 0 its an empty otherwise its a mesh
        # only difference at the moment is one has a color
        file.write('''
        Properties60:  {
            Property: "QuaternionInterpolate", "bool", "",0
            Property: "Visibility", "Visibility", "A+",1''')

        loc, rot, scale, matrix, matrix_rot = write_object_tx(ob, loc, matrix, matrix_mod)

        # Rotation order, note, for FBX files Iv loaded normal order is 1
        # setting to zero.
        # eEULER_XYZ = 0
        # eEULER_XZY
        # eEULER_YZX
        # eEULER_YXZ
        # eEULER_ZXY
        # eEULER_ZYX

        file.write('''
            Property: "RotationOffset", "Vector3D", "",0,0,0
            Property: "RotationPivot", "Vector3D", "",0,0,0
            Property: "ScalingOffset", "Vector3D", "",0,0,0
            Property: "ScalingPivot", "Vector3D", "",0,0,0
            Property: "TranslationActive", "bool", "",0
            Property: "TranslationMin", "Vector3D", "",0,0,0
            Property: "TranslationMax", "Vector3D", "",0,0,0
            Property: "TranslationMinX", "bool", "",0
            Property: "TranslationMinY", "bool", "",0
            Property: "TranslationMinZ", "bool", "",0
            Property: "TranslationMaxX", "bool", "",0
            Property: "TranslationMaxY", "bool", "",0
            Property: "TranslationMaxZ", "bool", "",0
            Property: "RotationOrder", "enum", "",0
            Property: "RotationSpaceForLimitOnly", "bool", "",0
            Property: "AxisLen", "double", "",10
            Property: "PreRotation", "Vector3D", "",0,0,0
            Property: "PostRotation", "Vector3D", "",0,0,0
            Property: "RotationActive", "bool", "",0
            Property: "RotationMin", "Vector3D", "",0,0,0
            Property: "RotationMax", "Vector3D", "",0,0,0
            Property: "RotationMinX", "bool", "",0
            Property: "RotationMinY", "bool", "",0
            Property: "RotationMinZ", "bool", "",0
            Property: "RotationMaxX", "bool", "",0
            Property: "RotationMaxY", "bool", "",0
            Property: "RotationMaxZ", "bool", "",0
            Property: "RotationStiffnessX", "double", "",0
            Property: "RotationStiffnessY", "double", "",0
            Property: "RotationStiffnessZ", "double", "",0
            Property: "MinDampRangeX", "double", "",0
            Property: "MinDampRangeY", "double", "",0
            Property: "MinDampRangeZ", "double", "",0
            Property: "MaxDampRangeX", "double", "",0
            Property: "MaxDampRangeY", "double", "",0
            Property: "MaxDampRangeZ", "double", "",0
            Property: "MinDampStrengthX", "double", "",0
            Property: "MinDampStrengthY", "double", "",0
            Property: "MinDampStrengthZ", "double", "",0
            Property: "MaxDampStrengthX", "double", "",0
            Property: "MaxDampStrengthY", "double", "",0
            Property: "MaxDampStrengthZ", "double", "",0
            Property: "PreferedAngleX", "double", "",0
            Property: "PreferedAngleY", "double", "",0
            Property: "PreferedAngleZ", "double", "",0
            Property: "InheritType", "enum", "",0
            Property: "ScalingActive", "bool", "",0
            Property: "ScalingMin", "Vector3D", "",1,1,1
            Property: "ScalingMax", "Vector3D", "",1,1,1
            Property: "ScalingMinX", "bool", "",0
            Property: "ScalingMinY", "bool", "",0
            Property: "ScalingMinZ", "bool", "",0
            Property: "ScalingMaxX", "bool", "",0
            Property: "ScalingMaxY", "bool", "",0
            Property: "ScalingMaxZ", "bool", "",0
            Property: "GeometricTranslation", "Vector3D", "",0,0,0
            Property: "GeometricRotation", "Vector3D", "",0,0,0
            Property: "GeometricScaling", "Vector3D", "",1,1,1
            Property: "LookAtProperty", "object", ""
            Property: "UpVectorProperty", "object", ""
            Property: "Show", "bool", "",1
            Property: "NegativePercentShapeSupport", "bool", "",1
            Property: "DefaultAttributeIndex", "int", "",0''')
        if ob and not isinstance(ob, bpy.types.Bone):
            # Only mesh objects have color
            file.write('\n\t\t\tProperty: "Color", "Color", "A",0.8,0.8,0.8')
            file.write('\n\t\t\tProperty: "Size", "double", "",100')
            file.write('\n\t\t\tProperty: "Look", "enum", "",1')

        return loc, rot, scale, matrix, matrix_rot

    # -------------------------------------------- Armatures
    #def write_bone(bone, name, matrix_mod):
    def write_bone(my_bone):
        file.write('\n\tModel: "Model::%s", "Limb" {' % my_bone.fbxName)
        file.write('\n\t\tVersion: 232')

        #poseMatrix = write_object_props(my_bone.blenBone, None, None, my_bone.fbxArm.parRelMatrix())[3]
        poseMatrix = write_object_props(my_bone.blenBone)[3]  # dont apply bone matricies anymore
        pose_items.append((my_bone.fbxName, poseMatrix))

        # file.write('\n\t\t\tProperty: "Size", "double", "",%.6f' % ((my_bone.blenData.head['ARMATURESPACE'] - my_bone.blenData.tail['ARMATURESPACE']) * my_bone.fbxArm.parRelMatrix()).length)
        file.write('\n\t\t\tProperty: "Size", "double", "",1')

        #((my_bone.blenData.head['ARMATURESPACE'] * my_bone.fbxArm.matrixWorld) - (my_bone.blenData.tail['ARMATURESPACE'] * my_bone.fbxArm.parRelMatrix())).length)

        """
        file.write('\n\t\t\tProperty: "LimbLength", "double", "",%.6f' %\
            ((my_bone.blenBone.head['ARMATURESPACE'] - my_bone.blenBone.tail['ARMATURESPACE']) * my_bone.fbxArm.parRelMatrix()).length)
        """

        file.write('\n\t\t\tProperty: "LimbLength", "double", "",%.6f' %
                   (my_bone.blenBone.head_local - my_bone.blenBone.tail_local).length)
# 			(my_bone.blenBone.head['ARMATURESPACE'] - my_bone.blenBone.tail['ARMATURESPACE']).length)

        #file.write('\n\t\t\tProperty: "LimbLength", "double", "",1')
        file.write('\n\t\t\tProperty: "Color", "ColorRGB", "",0.8,0.8,0.8')
        file.write('\n\t\t\tProperty: "Color", "Color", "A",0.8,0.8,0.8')
        file.write('\n\t\t}')
        file.write('\n\t\tMultiLayer: 0')
        file.write('\n\t\tMultiTake: 1')
        file.write('\n\t\tShading: Y')
        file.write('\n\t\tCulling: "CullingOff"')
        file.write('\n\t\tTypeFlags: "Skeleton"')
        file.write('\n\t}')

    def write_camera_switch():
        file.write('''
    Model: "Model::Camera Switcher", "CameraSwitcher" {
        Version: 232''')

        write_object_props()
        file.write('''
            Property: "Color", "Color", "A",0.8,0.8,0.8
            Property: "Camera Index", "Integer", "A+",100
        }
        MultiLayer: 0
        MultiTake: 1
        Hidden: "True"
        Shading: W
        Culling: "CullingOff"
        Version: 101
        Name: "Model::Camera Switcher"
        CameraId: 0
        CameraName: 100
        CameraIndexName:
    }''')

    def write_camera_dummy(name, loc, near, far, proj_type, up):
        file.write('\n\tModel: "Model::%s", "Camera" {' % name)
        file.write('\n\t\tVersion: 232')
        write_object_props(None, loc)

        file.write('\n\t\t\tProperty: "Color", "Color", "A",0.8,0.8,0.8')
        file.write('\n\t\t\tProperty: "Roll", "Roll", "A+",0')
        file.write('\n\t\t\tProperty: "FieldOfView", "FieldOfView", "A+",40')
        file.write('\n\t\t\tProperty: "FieldOfViewX", "FieldOfView", "A+",1')
        file.write('\n\t\t\tProperty: "FieldOfViewY", "FieldOfView", "A+",1')
        file.write('\n\t\t\tProperty: "OpticalCenterX", "Real", "A+",0')
        file.write('\n\t\t\tProperty: "OpticalCenterY", "Real", "A+",0')
        file.write('\n\t\t\tProperty: "BackgroundColor", "Color", "A+",0.63,0.63,0.63')
        file.write('\n\t\t\tProperty: "TurnTable", "Real", "A+",0')
        file.write('\n\t\t\tProperty: "DisplayTurnTableIcon", "bool", "",1')
        file.write('\n\t\t\tProperty: "Motion Blur Intensity", "Real", "A+",1')
        file.write('\n\t\t\tProperty: "UseMotionBlur", "bool", "",0')
        file.write('\n\t\t\tProperty: "UseRealTimeMotionBlur", "bool", "",1')
        file.write('\n\t\t\tProperty: "ResolutionMode", "enum", "",0')
        file.write('\n\t\t\tProperty: "ApertureMode", "enum", "",2')
        file.write('\n\t\t\tProperty: "GateFit", "enum", "",0')
        file.write('\n\t\t\tProperty: "FocalLength", "Real", "A+",21.3544940948486')
        file.write('\n\t\t\tProperty: "CameraFormat", "enum", "",0')
        file.write('\n\t\t\tProperty: "AspectW", "double", "",320')
        file.write('\n\t\t\tProperty: "AspectH", "double", "",200')
        file.write('\n\t\t\tProperty: "PixelAspectRatio", "double", "",1')
        file.write('\n\t\t\tProperty: "UseFrameColor", "bool", "",0')
        file.write('\n\t\t\tProperty: "FrameColor", "ColorRGB", "",0.3,0.3,0.3')
        file.write('\n\t\t\tProperty: "ShowName", "bool", "",1')
        file.write('\n\t\t\tProperty: "ShowGrid", "bool", "",1')
        file.write('\n\t\t\tProperty: "ShowOpticalCenter", "bool", "",0')
        file.write('\n\t\t\tProperty: "ShowAzimut", "bool", "",1')
        file.write('\n\t\t\tProperty: "ShowTimeCode", "bool", "",0')
        file.write('\n\t\t\tProperty: "NearPlane", "double", "",%.6f' % near)
        file.write('\n\t\t\tProperty: "FarPlane", "double", "",%.6f' % far)
        file.write('\n\t\t\tProperty: "FilmWidth", "double", "",0.816')
        file.write('\n\t\t\tProperty: "FilmHeight", "double", "",0.612')
        file.write('\n\t\t\tProperty: "FilmAspectRatio", "double", "",1.33333333333333')
        file.write('\n\t\t\tProperty: "FilmSqueezeRatio", "double", "",1')
        file.write('\n\t\t\tProperty: "FilmFormatIndex", "enum", "",4')
        file.write('\n\t\t\tProperty: "ViewFrustum", "bool", "",1')
        file.write('\n\t\t\tProperty: "ViewFrustumNearFarPlane", "bool", "",0')
        file.write('\n\t\t\tProperty: "ViewFrustumBackPlaneMode", "enum", "",2')
        file.write('\n\t\t\tProperty: "BackPlaneDistance", "double", "",100')
        file.write('\n\t\t\tProperty: "BackPlaneDistanceMode", "enum", "",0')
        file.write('\n\t\t\tProperty: "ViewCameraToLookAt", "bool", "",1')
        file.write('\n\t\t\tProperty: "LockMode", "bool", "",0')
        file.write('\n\t\t\tProperty: "LockInterestNavigation", "bool", "",0')
        file.write('\n\t\t\tProperty: "FitImage", "bool", "",0')
        file.write('\n\t\t\tProperty: "Crop", "bool", "",0')
        file.write('\n\t\t\tProperty: "Center", "bool", "",1')
        file.write('\n\t\t\tProperty: "KeepRatio", "bool", "",1')
        file.write('\n\t\t\tProperty: "BackgroundMode", "enum", "",0')
        file.write('\n\t\t\tProperty: "BackgroundAlphaTreshold", "double", "",0.5')
        file.write('\n\t\t\tProperty: "ForegroundTransparent", "bool", "",1')
        file.write('\n\t\t\tProperty: "DisplaySafeArea", "bool", "",0')
        file.write('\n\t\t\tProperty: "SafeAreaDisplayStyle", "enum", "",1')
        file.write('\n\t\t\tProperty: "SafeAreaAspectRatio", "double", "",1.33333333333333')
        file.write('\n\t\t\tProperty: "Use2DMagnifierZoom", "bool", "",0')
        file.write('\n\t\t\tProperty: "2D Magnifier Zoom", "Real", "A+",100')
        file.write('\n\t\t\tProperty: "2D Magnifier X", "Real", "A+",50')
        file.write('\n\t\t\tProperty: "2D Magnifier Y", "Real", "A+",50')
        file.write('\n\t\t\tProperty: "CameraProjectionType", "enum", "",%i' % proj_type)
        file.write('\n\t\t\tProperty: "UseRealTimeDOFAndAA", "bool", "",0')
        file.write('\n\t\t\tProperty: "UseDepthOfField", "bool", "",0')
        file.write('\n\t\t\tProperty: "FocusSource", "enum", "",0')
        file.write('\n\t\t\tProperty: "FocusAngle", "double", "",3.5')
        file.write('\n\t\t\tProperty: "FocusDistance", "double", "",200')
        file.write('\n\t\t\tProperty: "UseAntialiasing", "bool", "",0')
        file.write('\n\t\t\tProperty: "AntialiasingIntensity", "double", "",0.77777')
        file.write('\n\t\t\tProperty: "UseAccumulationBuffer", "bool", "",0')
        file.write('\n\t\t\tProperty: "FrameSamplingCount", "int", "",7')
        file.write('\n\t\t}')
        file.write('\n\t\tMultiLayer: 0')
        file.write('\n\t\tMultiTake: 0')
        file.write('\n\t\tHidden: "True"')
        file.write('\n\t\tShading: Y')
        file.write('\n\t\tCulling: "CullingOff"')
        file.write('\n\t\tTypeFlags: "Camera"')
        file.write('\n\t\tGeometryVersion: 124')
        file.write('\n\t\tPosition: %.6f,%.6f,%.6f' % loc)
        file.write('\n\t\tUp: %i,%i,%i' % up)
        file.write('\n\t\tLookAt: 0,0,0')
        file.write('\n\t\tShowInfoOnMoving: 1')
        file.write('\n\t\tShowAudio: 0')
        file.write('\n\t\tAudioColor: 0,1,0')
        file.write('\n\t\tCameraOrthoZoom: 1')
        file.write('\n\t}')

    def write_camera_default():
        # This sucks but to match FBX converter its easier to
        # write the cameras though they are not needed.
        write_camera_dummy('Producer Perspective', (0, 71.3, 287.5), 10, 4000, 0, (0, 1, 0))
        write_camera_dummy('Producer Top', (0, 4000, 0), 1, 30000, 1, (0, 0, -1))
        write_camera_dummy('Producer Bottom', (0, -4000, 0), 1, 30000, 1, (0, 0, -1))
        write_camera_dummy('Producer Front', (0, 0, 4000), 1, 30000, 1, (0, 1, 0))
        write_camera_dummy('Producer Back', (0, 0, -4000), 1, 30000, 1, (0, 1, 0))
        write_camera_dummy('Producer Right', (4000, 0, 0), 1, 30000, 1, (0, 1, 0))
        write_camera_dummy('Producer Left', (-4000, 0, 0), 1, 30000, 1, (0, 1, 0))

    def write_camera(my_cam):
        '''
        Write a blender camera
        '''
        render = scene.render
        width = render.resolution_x
        height = render.resolution_y
        aspect = width / height

        data = my_cam.blenObject.data

        file.write('\n\tModel: "Model::%s", "Camera" {' % my_cam.fbxName)
        file.write('\n\t\tVersion: 232')
        loc, rot, scale, matrix, matrix_rot = write_object_props(my_cam.blenObject, None, my_cam.parRelMatrix())

        file.write('\n\t\t\tProperty: "Roll", "Roll", "A+",0')
        file.write('\n\t\t\tProperty: "FieldOfView", "FieldOfView", "A+",%.6f' % math.degrees(data.angle))
        file.write('\n\t\t\tProperty: "FieldOfViewX", "FieldOfView", "A+",1')
        file.write('\n\t\t\tProperty: "FieldOfViewY", "FieldOfView", "A+",1')
        # file.write('\n\t\t\tProperty: "FocalLength", "Real", "A+",14.0323972702026')
        file.write('\n\t\t\tProperty: "OpticalCenterX", "Real", "A+",%.6f' % data.shift_x)  # not sure if this is in the correct units?
        file.write('\n\t\t\tProperty: "OpticalCenterY", "Real", "A+",%.6f' % data.shift_y)  # ditto
        file.write('\n\t\t\tProperty: "BackgroundColor", "Color", "A+",0,0,0')
        file.write('\n\t\t\tProperty: "TurnTable", "Real", "A+",0')
        file.write('\n\t\t\tProperty: "DisplayTurnTableIcon", "bool", "",1')
        file.write('\n\t\t\tProperty: "Motion Blur Intensity", "Real", "A+",1')
        file.write('\n\t\t\tProperty: "UseMotionBlur", "bool", "",0')
        file.write('\n\t\t\tProperty: "UseRealTimeMotionBlur", "bool", "",1')
        file.write('\n\t\t\tProperty: "ResolutionMode", "enum", "",0')
        file.write('\n\t\t\tProperty: "ApertureMode", "enum", "",2')
        file.write('\n\t\t\tProperty: "GateFit", "enum", "",2')
        file.write('\n\t\t\tProperty: "CameraFormat", "enum", "",0')
        file.write('\n\t\t\tProperty: "AspectW", "double", "",%i' % width)
        file.write('\n\t\t\tProperty: "AspectH", "double", "",%i' % height)

        '''Camera aspect ratio modes.
            0 If the ratio mode is eWINDOW_SIZE, both width and height values aren't relevant.
            1 If the ratio mode is eFIXED_RATIO, the height value is set to 1.0 and the width value is relative to the height value.
            2 If the ratio mode is eFIXED_RESOLUTION, both width and height values are in pixels.
            3 If the ratio mode is eFIXED_WIDTH, the width value is in pixels and the height value is relative to the width value.
            4 If the ratio mode is eFIXED_HEIGHT, the height value is in pixels and the width value is relative to the height value.

        Definition at line 234 of file kfbxcamera.h. '''

        file.write('\n\t\t\tProperty: "PixelAspectRatio", "double", "",2')

        file.write('\n\t\t\tProperty: "UseFrameColor", "bool", "",0')
        file.write('\n\t\t\tProperty: "FrameColor", "ColorRGB", "",0.3,0.3,0.3')
        file.write('\n\t\t\tProperty: "ShowName", "bool", "",1')
        file.write('\n\t\t\tProperty: "ShowGrid", "bool", "",1')
        file.write('\n\t\t\tProperty: "ShowOpticalCenter", "bool", "",0')
        file.write('\n\t\t\tProperty: "ShowAzimut", "bool", "",1')
        file.write('\n\t\t\tProperty: "ShowTimeCode", "bool", "",0')
        file.write('\n\t\t\tProperty: "NearPlane", "double", "",%.6f' % data.clip_start)
        file.write('\n\t\t\tProperty: "FarPlane", "double", "",%.6f' % data.clip_end)
        file.write('\n\t\t\tProperty: "FilmWidth", "double", "",1.0')
        file.write('\n\t\t\tProperty: "FilmHeight", "double", "",1.0')
        file.write('\n\t\t\tProperty: "FilmAspectRatio", "double", "",%.6f' % aspect)
        file.write('\n\t\t\tProperty: "FilmSqueezeRatio", "double", "",1')
        file.write('\n\t\t\tProperty: "FilmFormatIndex", "enum", "",0')
        file.write('\n\t\t\tProperty: "ViewFrustum", "bool", "",1')
        file.write('\n\t\t\tProperty: "ViewFrustumNearFarPlane", "bool", "",0')
        file.write('\n\t\t\tProperty: "ViewFrustumBackPlaneMode", "enum", "",2')
        file.write('\n\t\t\tProperty: "BackPlaneDistance", "double", "",100')
        file.write('\n\t\t\tProperty: "BackPlaneDistanceMode", "enum", "",0')
        file.write('\n\t\t\tProperty: "ViewCameraToLookAt", "bool", "",1')
        file.write('\n\t\t\tProperty: "LockMode", "bool", "",0')
        file.write('\n\t\t\tProperty: "LockInterestNavigation", "bool", "",0')
        file.write('\n\t\t\tProperty: "FitImage", "bool", "",0')
        file.write('\n\t\t\tProperty: "Crop", "bool", "",0')
        file.write('\n\t\t\tProperty: "Center", "bool", "",1')
        file.write('\n\t\t\tProperty: "KeepRatio", "bool", "",1')
        file.write('\n\t\t\tProperty: "BackgroundMode", "enum", "",0')
        file.write('\n\t\t\tProperty: "BackgroundAlphaTreshold", "double", "",0.5')
        file.write('\n\t\t\tProperty: "ForegroundTransparent", "bool", "",1')
        file.write('\n\t\t\tProperty: "DisplaySafeArea", "bool", "",0')
        file.write('\n\t\t\tProperty: "SafeAreaDisplayStyle", "enum", "",1')
        file.write('\n\t\t\tProperty: "SafeAreaAspectRatio", "double", "",%.6f' % aspect)
        file.write('\n\t\t\tProperty: "Use2DMagnifierZoom", "bool", "",0')
        file.write('\n\t\t\tProperty: "2D Magnifier Zoom", "Real", "A+",100')
        file.write('\n\t\t\tProperty: "2D Magnifier X", "Real", "A+",50')
        file.write('\n\t\t\tProperty: "2D Magnifier Y", "Real", "A+",50')
        file.write('\n\t\t\tProperty: "CameraProjectionType", "enum", "",0')
        file.write('\n\t\t\tProperty: "UseRealTimeDOFAndAA", "bool", "",0')
        file.write('\n\t\t\tProperty: "UseDepthOfField", "bool", "",0')
        file.write('\n\t\t\tProperty: "FocusSource", "enum", "",0')
        file.write('\n\t\t\tProperty: "FocusAngle", "double", "",3.5')
        file.write('\n\t\t\tProperty: "FocusDistance", "double", "",200')
        file.write('\n\t\t\tProperty: "UseAntialiasing", "bool", "",0')
        file.write('\n\t\t\tProperty: "AntialiasingIntensity", "double", "",0.77777')
        file.write('\n\t\t\tProperty: "UseAccumulationBuffer", "bool", "",0')
        file.write('\n\t\t\tProperty: "FrameSamplingCount", "int", "",7')

        file.write('\n\t\t}')
        file.write('\n\t\tMultiLayer: 0')
        file.write('\n\t\tMultiTake: 0')
        file.write('\n\t\tShading: Y')
        file.write('\n\t\tCulling: "CullingOff"')
        file.write('\n\t\tTypeFlags: "Camera"')
        file.write('\n\t\tGeometryVersion: 124')
        file.write('\n\t\tPosition: %.6f,%.6f,%.6f' % loc)
        file.write('\n\t\tUp: %.6f,%.6f,%.6f' % tuple(Vector((0.0, 1.0, 0.0)) * matrix_rot))
        file.write('\n\t\tLookAt: %.6f,%.6f,%.6f' % tuple(Vector((0.0, 0.0, -1.0)) * matrix_rot))

        #file.write('\n\t\tUp: 0,0,0' )
        #file.write('\n\t\tLookAt: 0,0,0' )

        file.write('\n\t\tShowInfoOnMoving: 1')
        file.write('\n\t\tShowAudio: 0')
        file.write('\n\t\tAudioColor: 0,1,0')
        file.write('\n\t\tCameraOrthoZoom: 1')
        file.write('\n\t}')

    def write_light(my_light):
        light = my_light.blenObject.data
        file.write('\n\tModel: "Model::%s", "Light" {' % my_light.fbxName)
        file.write('\n\t\tVersion: 232')

        write_object_props(my_light.blenObject, None, my_light.parRelMatrix())

        # Why are these values here twice?????? - oh well, follow the holy sdk's output

        # Blender light types match FBX's, funny coincidence, we just need to
        # be sure that all unsupported types are made into a point light
        #ePOINT,
        #eDIRECTIONAL
        #eSPOT
        light_type_items = {'POINT': 0, 'SUN': 1, 'SPOT': 2, 'HEMI': 3, 'AREA': 4}
        light_type = light_type_items[light.type]

        if light_type > 2:
            light_type = 1  # hemi and area lights become directional

# 		mode = light.mode
        if light.shadow_method == 'RAY_SHADOW' or light.shadow_method == 'BUFFER_SHADOW':
# 		if mode & Blender.Lamp.Modes.RayShadow or mode & Blender.Lamp.Modes.Shadows:
            do_shadow = 1
        else:
            do_shadow = 0

        if light.use_only_shadow or (not light.use_diffuse and not light.use_specular):
# 		if mode & Blender.Lamp.Modes.OnlyShadow or (mode & Blender.Lamp.Modes.NoDiffuse and mode & Blender.Lamp.Modes.NoSpecular):
            do_light = 0
        else:
            do_light = 1

        scale = abs(GLOBAL_MATRIX.scale_part()[0])  # scale is always uniform in this case

        file.write('\n\t\t\tProperty: "LightType", "enum", "",%i' % light_type)
        file.write('\n\t\t\tProperty: "CastLightOnObject", "bool", "",1')
        file.write('\n\t\t\tProperty: "DrawVolumetricLight", "bool", "",1')
        file.write('\n\t\t\tProperty: "DrawGroundProjection", "bool", "",1')
        file.write('\n\t\t\tProperty: "DrawFrontFacingVolumetricLight", "bool", "",0')
        file.write('\n\t\t\tProperty: "GoboProperty", "object", ""')
        file.write('\n\t\t\tProperty: "Color", "Color", "A+",1,1,1')
        file.write('\n\t\t\tProperty: "Intensity", "Intensity", "A+",%.2f' % (min(light.energy * 100.0, 200.0)))  # clamp below 200
        if light.type == 'SPOT':
            file.write('\n\t\t\tProperty: "Cone angle", "Cone angle", "A+",%.2f' % math.degrees(light.spot_size))
        file.write('\n\t\t\tProperty: "Fog", "Fog", "A+",50')
        file.write('\n\t\t\tProperty: "Color", "Color", "A",%.2f,%.2f,%.2f' % tuple(light.color))

        file.write('\n\t\t\tProperty: "Intensity", "Intensity", "A+",%.2f' % (min(light.energy * 100.0, 200.0)))  # clamp below 200

        file.write('\n\t\t\tProperty: "Fog", "Fog", "A+",50')
        file.write('\n\t\t\tProperty: "LightType", "enum", "",%i' % light_type)
        file.write('\n\t\t\tProperty: "CastLightOnObject", "bool", "",%i' % do_light)
        file.write('\n\t\t\tProperty: "DrawGroundProjection", "bool", "",1')
        file.write('\n\t\t\tProperty: "DrawFrontFacingVolumetricLight", "bool", "",0')
        file.write('\n\t\t\tProperty: "DrawVolumetricLight", "bool", "",1')
        file.write('\n\t\t\tProperty: "GoboProperty", "object", ""')
        file.write('\n\t\t\tProperty: "DecayType", "enum", "",0')
        file.write('\n\t\t\tProperty: "DecayStart", "double", "",%.2f' % light.distance)
        file.write('\n\t\t\tProperty: "EnableNearAttenuation", "bool", "",0')
        file.write('\n\t\t\tProperty: "NearAttenuationStart", "double", "",0')
        file.write('\n\t\t\tProperty: "NearAttenuationEnd", "double", "",0')
        file.write('\n\t\t\tProperty: "EnableFarAttenuation", "bool", "",0')
        file.write('\n\t\t\tProperty: "FarAttenuationStart", "double", "",0')
        file.write('\n\t\t\tProperty: "FarAttenuationEnd", "double", "",0')
        file.write('\n\t\t\tProperty: "CastShadows", "bool", "",%i' % do_shadow)
        file.write('\n\t\t\tProperty: "ShadowColor", "ColorRGBA", "",0,0,0,1')
        file.write('\n\t\t}')
        file.write('\n\t\tMultiLayer: 0')
        file.write('\n\t\tMultiTake: 0')
        file.write('\n\t\tShading: Y')
        file.write('\n\t\tCulling: "CullingOff"')
        file.write('\n\t\tTypeFlags: "Light"')
        file.write('\n\t\tGeometryVersion: 124')
        file.write('\n\t}')

    # matrixOnly is not used at the moment
    def write_null(my_null=None, fbxName=None, matrixOnly=None):
        # ob can be null
        if not fbxName:
            fbxName = my_null.fbxName

        file.write('\n\tModel: "Model::%s", "Null" {' % fbxName)
        file.write('\n\t\tVersion: 232')

        # only use this for the root matrix at the moment
        if matrixOnly:
            poseMatrix = write_object_props(None, None, matrixOnly)[3]

        else:  # all other Null's
            if my_null:
                poseMatrix = write_object_props(my_null.blenObject, None, my_null.parRelMatrix())[3]
            else:
                poseMatrix = write_object_props()[3]

        pose_items.append((fbxName, poseMatrix))

        file.write('''
        }
        MultiLayer: 0
        MultiTake: 1
        Shading: Y
        Culling: "CullingOff"
        TypeFlags: "Null"
    }''')

    # Material Settings
    if world:
        world_amb = world.ambient_color[:]
    else:
        world_amb = 0.0, 0.0, 0.0  # default value

    def write_material(matname, mat):
        file.write('\n\tMaterial: "Material::%s", "" {' % matname)

        # Todo, add more material Properties.
        if mat:
            mat_cold = tuple(mat.diffuse_color)
            mat_cols = tuple(mat.specular_color)
            #mat_colm = tuple(mat.mirCol) # we wont use the mirror color
            mat_colamb = world_amb

            mat_dif = mat.diffuse_intensity
            mat_amb = mat.ambient
            mat_hard = (float(mat.specular_hardness) - 1.0) / 5.10
            mat_spec = mat.specular_intensity / 2.0
            mat_alpha = mat.alpha
            mat_emit = mat.emit
            mat_shadeless = mat.use_shadeless
            if mat_shadeless:
                mat_shader = 'Lambert'
            else:
                if mat.diffuse_shader == 'LAMBERT':
                    mat_shader = 'Lambert'
                else:
                    mat_shader = 'Phong'
        else:
            mat_cols = mat_cold = 0.8, 0.8, 0.8
            mat_colamb = 0.0, 0.0, 0.0
            # mat_colm
            mat_dif = 1.0
            mat_amb = 0.5
            mat_hard = 20.0
            mat_spec = 0.2
            mat_alpha = 1.0
            mat_emit = 0.0
            mat_shadeless = False
            mat_shader = 'Phong'

        file.write('\n\t\tVersion: 102')
        file.write('\n\t\tShadingModel: "%s"' % mat_shader.lower())
        file.write('\n\t\tMultiLayer: 0')

        file.write('\n\t\tProperties60:  {')
        file.write('\n\t\t\tProperty: "ShadingModel", "KString", "", "%s"' % mat_shader)
        file.write('\n\t\t\tProperty: "MultiLayer", "bool", "",0')
        file.write('\n\t\t\tProperty: "EmissiveColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_cold)  # emit and diffuse color are he same in blender
        file.write('\n\t\t\tProperty: "EmissiveFactor", "double", "",%.4f' % mat_emit)

        file.write('\n\t\t\tProperty: "AmbientColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_colamb)
        file.write('\n\t\t\tProperty: "AmbientFactor", "double", "",%.4f' % mat_amb)
        file.write('\n\t\t\tProperty: "DiffuseColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_cold)
        file.write('\n\t\t\tProperty: "DiffuseFactor", "double", "",%.4f' % mat_dif)
        file.write('\n\t\t\tProperty: "Bump", "Vector3D", "",0,0,0')
        file.write('\n\t\t\tProperty: "TransparentColor", "ColorRGB", "",1,1,1')
        file.write('\n\t\t\tProperty: "TransparencyFactor", "double", "",%.4f' % (1.0 - mat_alpha))
        if not mat_shadeless:
            file.write('\n\t\t\tProperty: "SpecularColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_cols)
            file.write('\n\t\t\tProperty: "SpecularFactor", "double", "",%.4f' % mat_spec)
            file.write('\n\t\t\tProperty: "ShininessExponent", "double", "",80.0')
            file.write('\n\t\t\tProperty: "ReflectionColor", "ColorRGB", "",0,0,0')
            file.write('\n\t\t\tProperty: "ReflectionFactor", "double", "",1')
        file.write('\n\t\t\tProperty: "Emissive", "ColorRGB", "",0,0,0')
        file.write('\n\t\t\tProperty: "Ambient", "ColorRGB", "",%.1f,%.1f,%.1f' % mat_colamb)
        file.write('\n\t\t\tProperty: "Diffuse", "ColorRGB", "",%.1f,%.1f,%.1f' % mat_cold)
        if not mat_shadeless:
            file.write('\n\t\t\tProperty: "Specular", "ColorRGB", "",%.1f,%.1f,%.1f' % mat_cols)
            file.write('\n\t\t\tProperty: "Shininess", "double", "",%.1f' % mat_hard)
        file.write('\n\t\t\tProperty: "Opacity", "double", "",%.1f' % mat_alpha)
        if not mat_shadeless:
            file.write('\n\t\t\tProperty: "Reflectivity", "double", "",0')

        file.write('\n\t\t}')
        file.write('\n\t}')

    def copy_image(image):
        fn = bpy.path.abspath(image.filepath)
        fn_strip = os.path.basename(fn)

        if EXP_IMAGE_COPY:
            rel = fn_strip
            fn_abs_dest = os.path.join(basepath, fn_strip)
            if not os.path.exists(fn_abs_dest):
                shutil.copy(fn, fn_abs_dest)
        elif bpy.path.is_subdir(fn, basepath):
            rel = os.path.relpath(fn, basepath)
        else:
            rel = fn

        return (rel, fn_strip)

    # tex is an Image (Arystan)
    def write_video(texname, tex):
        # Same as texture really!
        file.write('\n\tVideo: "Video::%s", "Clip" {' % texname)

        file.write('''
        Type: "Clip"
        Properties60:  {
            Property: "FrameRate", "double", "",0
            Property: "LastFrame", "int", "",0
            Property: "Width", "int", "",0
            Property: "Height", "int", "",0''')
        if tex:
            fname_rel, fname_strip = copy_image(tex)
# 			fname, fname_strip, fname_rel = derived_paths(tex.filepath, basepath, EXP_IMAGE_COPY)
        else:
            fname = fname_strip = fname_rel = ''

        file.write('\n\t\t\tProperty: "Path", "charptr", "", "%s"' % fname_strip)

        file.write('''
            Property: "StartFrame", "int", "",0
            Property: "StopFrame", "int", "",0
            Property: "PlaySpeed", "double", "",1
            Property: "Offset", "KTime", "",0
            Property: "InterlaceMode", "enum", "",0
            Property: "FreeRunning", "bool", "",0
            Property: "Loop", "bool", "",0
            Property: "AccessMode", "enum", "",0
        }
        UseMipMap: 0''')

        file.write('\n\t\tFilename: "%s"' % fname_strip)
        if fname_strip:
            fname_strip = '/' + fname_strip
        file.write('\n\t\tRelativeFilename: "%s"' % fname_rel)  # make relative
        file.write('\n\t}')

    def write_texture(texname, tex, num):
        # if tex is None then this is a dummy tex
        file.write('\n\tTexture: "Texture::%s", "TextureVideoClip" {' % texname)
        file.write('\n\t\tType: "TextureVideoClip"')
        file.write('\n\t\tVersion: 202')
        # TODO, rare case _empty_ exists as a name.
        file.write('\n\t\tTextureName: "Texture::%s"' % texname)

        file.write('''
        Properties60:  {
            Property: "Translation", "Vector", "A+",0,0,0
            Property: "Rotation", "Vector", "A+",0,0,0
            Property: "Scaling", "Vector", "A+",1,1,1''')
        file.write('\n\t\t\tProperty: "Texture alpha", "Number", "A+",%i' % num)

        # WrapModeU/V 0==rep, 1==clamp, TODO add support
        file.write('''
            Property: "TextureTypeUse", "enum", "",0
            Property: "CurrentTextureBlendMode", "enum", "",1
            Property: "UseMaterial", "bool", "",0
            Property: "UseMipMap", "bool", "",0
            Property: "CurrentMappingType", "enum", "",0
            Property: "UVSwap", "bool", "",0''')

        file.write('\n\t\t\tProperty: "WrapModeU", "enum", "",%i' % tex.use_clamp_x)
        file.write('\n\t\t\tProperty: "WrapModeV", "enum", "",%i' % tex.use_clamp_y)

        file.write('''
            Property: "TextureRotationPivot", "Vector3D", "",0,0,0
            Property: "TextureScalingPivot", "Vector3D", "",0,0,0
            Property: "VideoProperty", "object", ""
        }''')

        file.write('\n\t\tMedia: "Video::%s"' % texname)

        if tex:
            fname_rel, fname_strip = copy_image(tex)
# 			fname, fname_strip, fname_rel = derived_paths(tex.filepath, basepath, EXP_IMAGE_COPY)
        else:
            fname = fname_strip = fname_rel = ''

        file.write('\n\t\tFileName: "%s"' % fname_strip)
        file.write('\n\t\tRelativeFilename: "%s"' % fname_rel)  # need some make relative command

        file.write('''
        ModelUVTranslation: 0,0
        ModelUVScaling: 1,1
        Texture_Alpha_Source: "None"
        Cropping: 0,0,0,0
    }''')

    def write_deformer_skin(obname):
        '''
        Each mesh has its own deformer
        '''
        file.write('\n\tDeformer: "Deformer::Skin %s", "Skin" {' % obname)
        file.write('''
        Version: 100
        MultiLayer: 0
        Type: "Skin"
        Properties60:  {
        }
        Link_DeformAcuracy: 50
    }''')

    # in the example was 'Bip01 L Thigh_2'
    def write_sub_deformer_skin(my_mesh, my_bone, weights):

        '''
        Each subdeformer is spesific to a mesh, but the bone it links to can be used by many sub-deformers
        So the SubDeformer needs the mesh-object name as a prefix to make it unique

        Its possible that there is no matching vgroup in this mesh, in that case no verts are in the subdeformer,
        a but silly but dosnt really matter
        '''
        file.write('\n\tDeformer: "SubDeformer::Cluster %s %s", "Cluster" {' % (my_mesh.fbxName, my_bone.fbxName))

        file.write('''
        Version: 100
        MultiLayer: 0
        Type: "Cluster"
        Properties60:  {
            Property: "SrcModel", "object", ""
            Property: "SrcModelReference", "object", ""
        }
        UserData: "", ""''')

        # Support for bone parents
        if my_mesh.fbxBoneParent:
            if my_mesh.fbxBoneParent == my_bone:
                # TODO - this is a bit lazy, we could have a simple write loop
                # for this case because all weights are 1.0 but for now this is ok
                # Parent Bones arent used all that much anyway.
                vgroup_data = [(j, 1.0) for j in range(len(my_mesh.blenData.vertices))]
            else:
                # This bone is not a parent of this mesh object, no weights
                vgroup_data = []

        else:
            # Normal weight painted mesh
            if my_bone.blenName in weights[0]:
                # Before we used normalized wright list
                #vgroup_data = me.getVertsFromGroup(bone.name, 1)
                group_index = weights[0].index(my_bone.blenName)
                vgroup_data = [(j, weight[group_index]) for j, weight in enumerate(weights[1]) if weight[group_index]]
            else:
                vgroup_data = []

        file.write('\n\t\tIndexes: ')

        i = -1
        for vg in vgroup_data:
            if i == -1:
                file.write('%i' % vg[0])
                i = 0
            else:
                if i == 23:
                    file.write('\n\t\t')
                    i = 0
                file.write(',%i' % vg[0])
            i += 1

        file.write('\n\t\tWeights: ')
        i = -1
        for vg in vgroup_data:
            if i == -1:
                file.write('%.8f' % vg[1])
                i = 0
            else:
                if i == 38:
                    file.write('\n\t\t')
                    i = 0
                file.write(',%.8f' % vg[1])
            i += 1

        if my_mesh.fbxParent:
            # TODO FIXME, this case is broken in some cases. skinned meshes just shouldnt have parents where possible!
            m = (my_mesh.matrixWorld.copy().invert() * my_bone.fbxArm.matrixWorld.copy() * my_bone.restMatrix) * mtx4_z90
        else:
            # Yes! this is it...  - but dosnt work when the mesh is a.
            m = (my_mesh.matrixWorld.copy().invert() * my_bone.fbxArm.matrixWorld.copy() * my_bone.restMatrix) * mtx4_z90

        #m = mtx4_z90 * my_bone.restMatrix
        matstr = mat4x4str(m)
        matstr_i = mat4x4str(m.invert())

        file.write('\n\t\tTransform: %s' % matstr_i)  # THIS IS __NOT__ THE GLOBAL MATRIX AS DOCUMENTED :/
        file.write('\n\t\tTransformLink: %s' % matstr)
        file.write('\n\t}')

    def write_mesh(my_mesh):

        me = my_mesh.blenData

        # if there are non NULL materials on this mesh
        do_materials = bool(my_mesh.blenMaterials)
        do_textures = bool(my_mesh.blenTextures)
        do_uvs = bool(me.uv_textures)

        file.write('\n\tModel: "Model::%s", "Mesh" {' % my_mesh.fbxName)
        file.write('\n\t\tVersion: 232')  # newline is added in write_object_props

        # convert into lists once.
        me_vertices = me.vertices[:]
        me_edges = me.edges[:]
        me_faces = me.faces[:]

        poseMatrix = write_object_props(my_mesh.blenObject, None, my_mesh.parRelMatrix())[3]
        pose_items.append((my_mesh.fbxName, poseMatrix))

        file.write('\n\t\t}')
        file.write('\n\t\tMultiLayer: 0')
        file.write('\n\t\tMultiTake: 1')
        file.write('\n\t\tShading: Y')
        file.write('\n\t\tCulling: "CullingOff"')

        # Write the Real Mesh data here
        file.write('\n\t\tVertices: ')
        i = -1

        for v in me_vertices:
            if i == -1:
                file.write('%.6f,%.6f,%.6f' % v.co[:])
                i = 0
            else:
                if i == 7:
                    file.write('\n\t\t')
                    i = 0
                file.write(',%.6f,%.6f,%.6f' % v.co[:])
            i += 1

        file.write('\n\t\tPolygonVertexIndex: ')
        i = -1
        for f in me_faces:
            fi = f.vertices[:]

            # last index XORd w. -1 indicates end of face
            if i == -1:
                if len(fi) == 3:
                    file.write('%i,%i,%i' % (fi[0], fi[1], fi[2] ^ -1))
                else:
                    file.write('%i,%i,%i,%i' % (fi[0], fi[1], fi[2], fi[3] ^ -1))
                i = 0
            else:
                if i == 13:
                    file.write('\n\t\t')
                    i = 0
                if len(fi) == 3:
                    file.write(',%i,%i,%i' % (fi[0], fi[1], fi[2] ^ -1))
                else:
                    file.write(',%i,%i,%i,%i' % (fi[0], fi[1], fi[2], fi[3] ^ -1))
            i += 1

        # write loose edges as faces.
        for ed in me_edges:
            if ed.is_loose:
                ed_val = ed.vertices[:]
                ed_val = ed_val[0], ed_val[-1] ^ -1

                if i == -1:
                    file.write('%i,%i' % ed_val)
                    i = 0
                else:
                    if i == 13:
                        file.write('\n\t\t')
                        i = 0
                    file.write(',%i,%i' % ed_val)
            i += 1

        file.write('\n\t\tEdges: ')
        i = -1
        for ed in me_edges:
                if i == -1:
                    file.write('%i,%i' % (ed.vertices[0], ed.vertices[1]))
                    i = 0
                else:
                    if i == 13:
                        file.write('\n\t\t')
                        i = 0
                    file.write(',%i,%i' % (ed.vertices[0], ed.vertices[1]))
                i += 1

        file.write('\n\t\tGeometryVersion: 124')

        file.write('''
        LayerElementNormal: 0 {
            Version: 101
            Name: ""
            MappingInformationType: "ByVertice"
            ReferenceInformationType: "Direct"
            Normals: ''')

        i = -1
        for v in me_vertices:
            if i == -1:
                file.write('%.15f,%.15f,%.15f' % v.normal[:])
                i = 0
            else:
                if i == 2:
                    file.write('\n\t\t\t ')
                    i = 0
                file.write(',%.15f,%.15f,%.15f' % v.normal[:])
            i += 1
        file.write('\n\t\t}')

        # Write Face Smoothing
        file.write('''
        LayerElementSmoothing: 0 {
            Version: 102
            Name: ""
            MappingInformationType: "ByPolygon"
            ReferenceInformationType: "Direct"
            Smoothing: ''')

        i = -1
        for f in me_faces:
            if i == -1:
                file.write('%i' % f.use_smooth)
                i = 0
            else:
                if i == 54:
                    file.write('\n\t\t\t ')
                    i = 0
                file.write(',%i' % f.use_smooth)
            i += 1

        file.write('\n\t\t}')

        # Write Edge Smoothing
        file.write('''
        LayerElementSmoothing: 0 {
            Version: 101
            Name: ""
            MappingInformationType: "ByEdge"
            ReferenceInformationType: "Direct"
            Smoothing: ''')

        i = -1
        for ed in me_edges:
            if i == -1:
                file.write('%i' % (ed.use_edge_sharp))
                i = 0
            else:
                if i == 54:
                    file.write('\n\t\t\t ')
                    i = 0
                file.write(',%i' % (ed.use_edge_sharp))
            i += 1

        file.write('\n\t\t}')

        # Write VertexColor Layers
        # note, no programs seem to use this info :/
        collayers = []
        if len(me.vertex_colors):
            collayers = me.vertex_colors
            for colindex, collayer in enumerate(collayers):
                file.write('\n\t\tLayerElementColor: %i {' % colindex)
                file.write('\n\t\t\tVersion: 101')
                file.write('\n\t\t\tName: "%s"' % collayer.name)

                file.write('''
            MappingInformationType: "ByPolygonVertex"
            ReferenceInformationType: "IndexToDirect"
            Colors: ''')

                i = -1
                ii = 0  # Count how many Colors we write

                for fi, cf in enumerate(collayer.data):
                    if len(me_faces[fi].vertices) == 4:
                        colors = cf.color1[:], cf.color2[:], cf.color3[:], cf.color4[:]
                    else:
                        colors = cf.color1[:], cf.color2[:], cf.color3[:]

                    for col in colors:
                        if i == -1:
                            file.write('%.4f,%.4f,%.4f,1' % col)
                            i = 0
                        else:
                            if i == 7:
                                file.write('\n\t\t\t\t')
                                i = 0
                            file.write(',%.4f,%.4f,%.4f,1' % col)
                        i += 1
                        ii += 1  # One more Color

                file.write('\n\t\t\tColorIndex: ')
                i = -1
                for j in range(ii):
                    if i == -1:
                        file.write('%i' % j)
                        i = 0
                    else:
                        if i == 55:
                            file.write('\n\t\t\t\t')
                            i = 0
                        file.write(',%i' % j)
                    i += 1

                file.write('\n\t\t}')

        # Write UV and texture layers.
        uvlayers = []
        if do_uvs:
            uvlayers = me.uv_textures
            uvlayer_orig = me.uv_textures.active
            for uvindex, uvlayer in enumerate(me.uv_textures):
                file.write('\n\t\tLayerElementUV: %i {' % uvindex)
                file.write('\n\t\t\tVersion: 101')
                file.write('\n\t\t\tName: "%s"' % uvlayer.name)

                file.write('''
            MappingInformationType: "ByPolygonVertex"
            ReferenceInformationType: "IndexToDirect"
            UV: ''')

                i = -1
                ii = 0  # Count how many UVs we write

                for uf in uvlayer.data:
                    # workaround, since uf.uv iteration is wrong atm
                    for uv in uf.uv:
                        if i == -1:
                            file.write('%.6f,%.6f' % uv[:])
                            i = 0
                        else:
                            if i == 7:
                                file.write('\n\t\t\t ')
                                i = 0
                            file.write(',%.6f,%.6f' % uv[:])
                        i += 1
                        ii += 1  # One more UV

                file.write('\n\t\t\tUVIndex: ')
                i = -1
                for j in range(ii):
                    if i == -1:
                        file.write('%i' % j)
                        i = 0
                    else:
                        if i == 55:
                            file.write('\n\t\t\t\t')
                            i = 0
                        file.write(',%i' % j)
                    i += 1

                file.write('\n\t\t}')

                if do_textures:
                    file.write('\n\t\tLayerElementTexture: %i {' % uvindex)
                    file.write('\n\t\t\tVersion: 101')
                    file.write('\n\t\t\tName: "%s"' % uvlayer.name)

                    if len(my_mesh.blenTextures) == 1:
                        file.write('\n\t\t\tMappingInformationType: "AllSame"')
                    else:
                        file.write('\n\t\t\tMappingInformationType: "ByPolygon"')

                    file.write('\n\t\t\tReferenceInformationType: "IndexToDirect"')
                    file.write('\n\t\t\tBlendMode: "Translucent"')
                    file.write('\n\t\t\tTextureAlpha: 1')
                    file.write('\n\t\t\tTextureId: ')

                    if len(my_mesh.blenTextures) == 1:
                        file.write('0')
                    else:
                        texture_mapping_local = {None: -1}

                        i = 0  # 1 for dummy
                        for tex in my_mesh.blenTextures:
                            if tex:  # None is set above
                                texture_mapping_local[tex] = i
                                i += 1

                        i = -1
                        for f in uvlayer.data:
                            img_key = f.image

                            if i == -1:
                                i = 0
                                file.write('%s' % texture_mapping_local[img_key])
                            else:
                                if i == 55:
                                    file.write('\n			 ')
                                    i = 0

                                file.write(',%s' % texture_mapping_local[img_key])
                            i += 1

                else:
                    file.write('''
        LayerElementTexture: 0 {
            Version: 101
            Name: ""
            MappingInformationType: "NoMappingInformation"
            ReferenceInformationType: "IndexToDirect"
            BlendMode: "Translucent"
            TextureAlpha: 1
            TextureId: ''')
                file.write('\n\t\t}')

        # Done with UV/textures.
        if do_materials:
            file.write('\n\t\tLayerElementMaterial: 0 {')
            file.write('\n\t\t\tVersion: 101')
            file.write('\n\t\t\tName: ""')

            if len(my_mesh.blenMaterials) == 1:
                file.write('\n\t\t\tMappingInformationType: "AllSame"')
            else:
                file.write('\n\t\t\tMappingInformationType: "ByPolygon"')

            file.write('\n\t\t\tReferenceInformationType: "IndexToDirect"')
            file.write('\n\t\t\tMaterials: ')

            if len(my_mesh.blenMaterials) == 1:
                file.write('0')
            else:
                # Build a material mapping for this
                material_mapping_local = {}  # local-mat & tex : global index.

                for j, mat_tex_pair in enumerate(my_mesh.blenMaterials):
                    material_mapping_local[mat_tex_pair] = j

                len_material_mapping_local = len(material_mapping_local)

                mats = my_mesh.blenMaterialList

                if me.uv_textures.active:
                    uv_faces = me.uv_textures.active.data
                else:
                    uv_faces = [None] * len(me_faces)

                i = -1
                for f, uf in zip(me_faces, uv_faces):
# 				for f in me_faces:
                    try:
                        mat = mats[f.material_index]
                    except:
                        mat = None

                    if do_uvs:
                        tex = uf.image  # WARNING - MULTI UV LAYER IMAGES NOT SUPPORTED :/
                    else:
                        tex = None

                    if i == -1:
                        i = 0
                        file.write('%s' % (material_mapping_local[mat, tex]))  # None for mat or tex is ok
                    else:
                        if i == 55:
                            file.write('\n\t\t\t\t')
                            i = 0

                        file.write(',%s' % (material_mapping_local[mat, tex]))
                    i += 1

            file.write('\n\t\t}')

        file.write('''
        Layer: 0 {
            Version: 100
            LayerElement:  {
                Type: "LayerElementNormal"
                TypedIndex: 0
            }''')

        if do_materials:
            file.write('''
            LayerElement:  {
                Type: "LayerElementMaterial"
                TypedIndex: 0
            }''')

        # Always write this
        if do_textures:
            file.write('''
            LayerElement:  {
                Type: "LayerElementTexture"
                TypedIndex: 0
            }''')

        if me.vertex_colors:
            file.write('''
            LayerElement:  {
                Type: "LayerElementColor"
                TypedIndex: 0
            }''')

        if do_uvs:  # same as me.faceUV
            file.write('''
            LayerElement:  {
                Type: "LayerElementUV"
                TypedIndex: 0
            }''')

        file.write('\n\t\t}')

        if len(uvlayers) > 1:
            for i in range(1, len(uvlayers)):

                file.write('\n\t\tLayer: %i {' % i)
                file.write('\n\t\t\tVersion: 100')

                file.write('''
            LayerElement:  {
                Type: "LayerElementUV"''')

                file.write('\n\t\t\t\tTypedIndex: %i' % i)
                file.write('\n\t\t\t}')

                if do_textures:

                    file.write('''
            LayerElement:  {
                Type: "LayerElementTexture"''')

                    file.write('\n\t\t\t\tTypedIndex: %i' % i)
                    file.write('\n\t\t\t}')

                file.write('\n\t\t}')

        if len(collayers) > 1:
            # Take into account any UV layers
            layer_offset = 0
            if uvlayers:
                layer_offset = len(uvlayers) - 1

            for i in range(layer_offset, len(collayers) + layer_offset):
                file.write('\n\t\tLayer: %i {' % i)
                file.write('\n\t\t\tVersion: 100')

                file.write('''
            LayerElement:  {
                Type: "LayerElementColor"''')

                file.write('\n\t\t\t\tTypedIndex: %i' % i)
                file.write('\n\t\t\t}')
                file.write('\n\t\t}')
        file.write('\n\t}')

    def write_group(name):
        file.write('\n\tGroupSelection: "GroupSelection::%s", "Default" {' % name)

        file.write('''
        Properties60:  {
            Property: "MultiLayer", "bool", "",0
            Property: "Pickable", "bool", "",1
            Property: "Transformable", "bool", "",1
            Property: "Show", "bool", "",1
        }
        MultiLayer: 0
    }''')

    # add meshes here to clear because they are not used anywhere.
    meshes_to_clear = []

    ob_meshes = []
    ob_lights = []
    ob_cameras = []
    # in fbx we export bones as children of the mesh
    # armatures not a part of a mesh, will be added to ob_arms
    ob_bones = []
    ob_arms = []
    ob_null = []  # emptys

    # List of types that have blender objects (not bones)
    ob_all_typegroups = [ob_meshes, ob_lights, ob_cameras, ob_arms, ob_null]

    groups = []  # blender groups, only add ones that have objects in the selections
    materials = {}  # (mat, image) keys, should be a set()
    textures = {}  # should be a set()

    tmp_ob_type = ob_type = None  # incase no objects are exported, so as not to raise an error

    # if EXP_OBS_SELECTED is false, use sceens objects
    if not batch_objects:
        if EXP_OBS_SELECTED:
            tmp_objects = context.selected_objects
        else:
            tmp_objects = scene.objects
    else:
        tmp_objects = batch_objects

    if EXP_ARMATURE:
        # This is needed so applying modifiers dosnt apply the armature deformation, its also needed
        # ...so mesh objects return their rest worldspace matrix when bone-parents are exported as weighted meshes.
        # set every armature to its rest, backup the original values so we done mess up the scene
        ob_arms_orig_rest = [arm.pose_position for arm in bpy.data.armatures]

        for arm in bpy.data.armatures:
            arm.pose_position = 'REST'

        if ob_arms_orig_rest:
            for ob_base in bpy.data.objects:
                if ob_base.type == 'ARMATURE':
                    ob_base.update()

            # This causes the makeDisplayList command to effect the mesh
            scene.frame_set(scene.frame_current)

    for ob_base in tmp_objects:

        # ignore dupli children
        if ob_base.parent and ob_base.parent.dupli_type != 'NONE':
            continue

        obs = [(ob_base, ob_base.matrix_world)]
        if ob_base.dupli_type != 'NONE':
            ob_base.create_dupli_list(scene)
            obs = [(dob.object, dob.matrix) for dob in ob_base.dupli_list]

        for ob, mtx in obs:
# 		for ob, mtx in BPyObject.getDerivedObjects(ob_base):
            tmp_ob_type = ob.type
            if tmp_ob_type == 'CAMERA':
                if EXP_CAMERA:
                    ob_cameras.append(my_object_generic(ob, mtx))
            elif tmp_ob_type == 'LAMP':
                if EXP_LAMP:
                    ob_lights.append(my_object_generic(ob, mtx))
            elif tmp_ob_type == 'ARMATURE':
                if EXP_ARMATURE:
                    # TODO - armatures dont work in dupligroups!
                    if ob not in ob_arms:
                        ob_arms.append(ob)
                    # ob_arms.append(ob) # replace later. was "ob_arms.append(sane_obname(ob), ob)"
            elif tmp_ob_type == 'EMPTY':
                if EXP_EMPTY:
                    ob_null.append(my_object_generic(ob, mtx))
            elif EXP_MESH:
                origData = True
                if tmp_ob_type != 'MESH':
                    try:
                        me = ob.create_mesh(scene, True, 'PREVIEW')
                    except:
                        me = None

                    if me:
                        meshes_to_clear.append(me)
                        mats = me.materials
                        origData = False
                else:
                    # Mesh Type!
                    if EXP_MESH_APPLY_MOD:
                        me = ob.create_mesh(scene, True, 'PREVIEW')

                        # print ob, me, me.getVertGroupNames()
                        meshes_to_clear.append(me)
                        origData = False
                        mats = me.materials
                    else:
                        me = ob.data
                        mats = me.materials

# 						# Support object colors
# 						tmp_colbits = ob.colbits
# 						if tmp_colbits:
# 							tmp_ob_mats = ob.getMaterials(1) # 1 so we get None's too.
# 							for i in xrange(16):
# 								if tmp_colbits & (1<<i):
# 									mats[i] = tmp_ob_mats[i]
# 							del tmp_ob_mats
# 						del tmp_colbits

                if me:
# 					# This WILL modify meshes in blender if EXP_MESH_APPLY_MOD is disabled.
# 					# so strictly this is bad. but only in rare cases would it have negative results
# 					# say with dupliverts the objects would rotate a bit differently
# 					if EXP_MESH_HQ_NORMALS:
# 						BPyMesh.meshCalcNormals(me) # high quality normals nice for realtime engines.

                    texture_mapping_local = {}
                    material_mapping_local = {}
                    if me.uv_textures:
                        for uvlayer in me.uv_textures:
                            for f, uf in zip(me.faces, uvlayer.data):
                                tex = uf.image
                                textures[tex] = texture_mapping_local[tex] = None

                                try:
                                    mat = mats[f.material_index]
                                except:
                                    mat = None

                                materials[mat, tex] = material_mapping_local[mat, tex] = None  # should use sets, wait for blender 2.5

                    else:
                        for mat in mats:
                            # 2.44 use mat.lib too for uniqueness
                            materials[mat, None] = material_mapping_local[mat, None] = None
                        else:
                            materials[None, None] = None

                    if EXP_ARMATURE:
                        armob = ob.find_armature()
                        blenParentBoneName = None

                        # parent bone - special case
                        if (not armob) and ob.parent and ob.parent.type == 'ARMATURE' and \
                                ob.parent_type == 'BONE':
                            armob = ob.parent
                            blenParentBoneName = ob.parent_bone

                        if armob and armob not in ob_arms:
                            ob_arms.append(armob)

                        # Warning for scaled, mesh objects with armatures
                        if abs(ob.scale[0] - 1.0) > 0.05 or abs(ob.scale[1] - 1.0) > 0.05 or abs(ob.scale[1] - 1.0) > 0.05:
                            operator.report('WARNING', "Object '%s' has a scale of (%.3f, %.3f, %.3f), Armature deformation will not work as expected!, Apply Scale to fix." % ((ob.name,) + tuple(ob.scale)))

                    else:
                        blenParentBoneName = armob = None

                    my_mesh = my_object_generic(ob, mtx)
                    my_mesh.blenData = me
                    my_mesh.origData = origData
                    my_mesh.blenMaterials = list(material_mapping_local.keys())
                    my_mesh.blenMaterialList = mats
                    my_mesh.blenTextures = list(texture_mapping_local.keys())

                    # if only 1 null texture then empty the list
                    if len(my_mesh.blenTextures) == 1 and my_mesh.blenTextures[0] is None:
                        my_mesh.blenTextures = []

                    my_mesh.fbxArm = armob  # replace with my_object_generic armature instance later
                    my_mesh.fbxBoneParent = blenParentBoneName  # replace with my_bone instance later

                    ob_meshes.append(my_mesh)

        # not forgetting to free dupli_list
        if ob_base.dupli_list:
            ob_base.free_dupli_list()

    if EXP_ARMATURE:
        # now we have the meshes, restore the rest arm position
        for i, arm in enumerate(bpy.data.armatures):
            arm.pose_position = ob_arms_orig_rest[i]

        if ob_arms_orig_rest:
            for ob_base in bpy.data.objects:
                if ob_base.type == 'ARMATURE':
                    ob_base.update()
            # This causes the makeDisplayList command to effect the mesh
            scene.frame_set(scene.frame_current)

    del tmp_ob_type, tmp_objects

    # now we have collected all armatures, add bones
    for i, ob in enumerate(ob_arms):

        ob_arms[i] = my_arm = my_object_generic(ob)

        my_arm.fbxBones = []
        my_arm.blenData = ob.data
        if ob.animation_data:
            my_arm.blenAction = ob.animation_data.action
        else:
            my_arm.blenAction = None
# 		my_arm.blenAction =		ob.action
        my_arm.blenActionList = []

        # fbxName, blenderObject, my_bones, blenderActions
        #ob_arms[i] = fbxArmObName, ob, arm_my_bones, (ob.action, [])

        for bone in my_arm.blenData.bones:
            my_bone = my_bone_class(bone, my_arm)
            my_arm.fbxBones.append(my_bone)
            ob_bones.append(my_bone)

    # add the meshes to the bones and replace the meshes armature with own armature class
    #for obname, ob, mtx, me, mats, arm, armname in ob_meshes:
    for my_mesh in ob_meshes:
        # Replace
        # ...this could be sped up with dictionary mapping but its unlikely for
        # it ever to be a bottleneck - (would need 100+ meshes using armatures)
        if my_mesh.fbxArm:
            for my_arm in ob_arms:
                if my_arm.blenObject == my_mesh.fbxArm:
                    my_mesh.fbxArm = my_arm
                    break

        for my_bone in ob_bones:

            # The mesh uses this bones armature!
            if my_bone.fbxArm == my_mesh.fbxArm:
                if my_bone.blenBone.use_deform:
                    my_bone.blenMeshes[my_mesh.fbxName] = me

                # parent bone: replace bone names with our class instances
                # my_mesh.fbxBoneParent is None or a blender bone name initialy, replacing if the names match.
                if my_mesh.fbxBoneParent == my_bone.blenName:
                    my_mesh.fbxBoneParent = my_bone

    bone_deformer_count = 0  # count how many bones deform a mesh
    my_bone_blenParent = None
    for my_bone in ob_bones:
        my_bone_blenParent = my_bone.blenBone.parent
        if my_bone_blenParent:
            for my_bone_parent in ob_bones:
                # Note 2.45rc2 you can compare bones normally
                if my_bone_blenParent.name == my_bone_parent.blenName and my_bone.fbxArm == my_bone_parent.fbxArm:
                    my_bone.parent = my_bone_parent
                    break

        # Not used at the moment
        # my_bone.calcRestMatrixLocal()
        bone_deformer_count += len(my_bone.blenMeshes)

    del my_bone_blenParent

    # Build blenObject -> fbxObject mapping
    # this is needed for groups as well as fbxParenting
    bpy.data.objects.tag(False)

    # using a list of object names for tagging (Arystan)

    tmp_obmapping = {}
    for ob_generic in ob_all_typegroups:
        for ob_base in ob_generic:
            ob_base.blenObject.tag = True
            tmp_obmapping[ob_base.blenObject] = ob_base

    # Build Groups from objects we export
    for blenGroup in bpy.data.groups:
        fbxGroupName = None
        for ob in blenGroup.objects:
            if ob.tag:
                if fbxGroupName is None:
                    fbxGroupName = sane_groupname(blenGroup)
                    groups.append((fbxGroupName, blenGroup))

                tmp_obmapping[ob].fbxGroupNames.append(fbxGroupName)  # also adds to the objects fbxGroupNames

    groups.sort()  # not really needed

    # Assign parents using this mapping
    for ob_generic in ob_all_typegroups:
        for my_ob in ob_generic:
            parent = my_ob.blenObject.parent
            if parent and parent.tag:  # does it exist and is it in the mapping
                my_ob.fbxParent = tmp_obmapping[parent]

    del tmp_obmapping
    # Finished finding groups we use

    materials = [(sane_matname(mat_tex_pair), mat_tex_pair) for mat_tex_pair in materials.keys()]
    textures = [(sane_texname(tex), tex) for tex in textures.keys()  if tex]
    materials.sort()  # sort by name
    textures.sort()

    camera_count = 8
    file.write('''

; Object definitions
;------------------------------------------------------------------

Definitions:  {
    Version: 100
    Count: %i''' % (\
        1 + 1 + camera_count + \
        len(ob_meshes) + \
        len(ob_lights) + \
        len(ob_cameras) + \
        len(ob_arms) + \
        len(ob_null) + \
        len(ob_bones) + \
        bone_deformer_count + \
        len(materials) + \
        (len(textures) * 2)))  # add 1 for the root model 1 for global settings

    del bone_deformer_count

    file.write('''
    ObjectType: "Model" {
        Count: %i
    }''' % (\
Loading
Loading full blame...