/*
Copyright (c) 2007 Trent Waddington

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <math.h>

FILE *fout, *fskel;

#pragma pack(1)

typedef enum {
    rwNONE = 0,
    rwDATA = 1,
    rwSTRING = 2,
    rwEXTENSION = 3,
    rwTEXTURE = 6,
    rwMATERIAL = 7,
    rwMATERIALLIST = 8,
    rwFRAMELIST = 14,
    rwGEOMETRY = 15,
    rwCLUMP = 16,
    rwATOMIC = 20,
    rwGEOMETRYLIST = 26,
    rwMATERIALSPLIT = 1294,
    rwFRAME = 39056126,
} section_type;

typedef struct {
    section_type kind;
    unsigned int size;
    unsigned short unkn;
    unsigned short version;
} section_header;

const char *section_type_string(section_type kind)
{
    switch(kind) {
        case rwDATA:
            return "rwDATA";
        case rwSTRING:
            return "rwSTRING";
        case rwEXTENSION:
            return "rwEXTENSION";
        case rwTEXTURE:
            return "rwTEXTURE";
        case rwMATERIAL:
            return "rwMATERIAL";
        case rwMATERIALLIST:
            return "rwMATERIALLIST";
        case rwFRAMELIST:
            return "rwFRAMELIST";
        case rwGEOMETRY:
            return "rwGEOMETRY";
        case rwCLUMP:
            return "rwCLUMP";
        case rwATOMIC:
            return "rwATOMIC";
        case rwGEOMETRYLIST:
            return "rwGEOMETRYLIST";
        case rwMATERIALSPLIT:
            return "rwMATERIALSPLIT";
        case rwFRAME:
            return "rwFRAME";
    }

    static char tmp[100];
    sprintf(tmp, "unknown %i", kind);
    return tmp;
}

void indent(int ind)
{
    int i;
    for (i = 0; i < ind; i++)
        printf("   ");
}

void dump_int(section_header *h, int ind)
{
    indent(ind);
    int *data = (int *)(h + 1);
    printf("%i\n", *data);
}

std::vector<std::string> meshnames;

void dump_frame(section_header *h, int ind)
{
    std::string n;
    indent(ind);
    char *data = (char *)(h + 1);
    printf("\"");
    unsigned int i;
    bool terminated = false;
    for (i = 0; i < h->size; i++)
        if (data[i] == 0) {
            printf("\\0");
            terminated = true;
        } else {
            printf("%c", data[i]);
            if (!terminated)
                n.append(1, data[i]);
        }
    printf("\"\n");

    meshnames.push_back(n);
}

typedef struct {
    float rot[3][3];
    float xyz[3];
    int parent;
    int unkn;
} frame_data;
std::vector<frame_data> frames;

void dump_frame_list(section_header *h, int ind)
{
    char *data = (char *)(h + 1);
    frame_data *frame = (frame_data *)(data + 4);
    int i;
    for (i = 0; i < *(int *)data; i++) {
        indent(ind);
        printf("(%f %f %f / %f %f %f / %f %f %f) (%f %f %f) %i %i\n",
            frame[i].rot[0][0], frame[i].rot[0][1], frame[i].rot[0][2],
            frame[i].rot[1][0], frame[i].rot[1][1], frame[i].rot[1][2],
            frame[i].rot[2][0], frame[i].rot[2][1], frame[i].rot[2][2],
            frame[i].xyz[0], frame[i].xyz[1], frame[i].xyz[2], frame[i].parent,
            frame[i].unkn);
        frames.push_back(frame[i]);
    }
}

typedef struct {
    unsigned short flags;
    unsigned short unkn;
    unsigned int triangle_count;
    unsigned int vertex_count;
    unsigned int morph_target_count;
} geometry_header;

typedef struct {
    float ambient;
    float diffuse;
    float specular;
} geometry_lighting;

#define rwOBJECT_VERTEX_UV 4
#define rwOBJECT_VERTEX_COLOR 8
#define rwOBJECT_VERTEX_NORMAL 16
geometry_header *geom_hdr;
struct face {
    int v1, v2, v3;
};
std::vector<struct face> faces;
struct texcood {
    float u, v;
};
std::vector<struct texcood> texcoods;
struct pos {
    float x, y, z;
};
std::vector<struct pos> vertexes;
struct norm {
    float x, y, z;
}; 
std::vector<struct norm> normals;
std::vector<std::string> materials;
std::vector<int> splits_for_name;
std::vector<std::string> submeshnames;

void dump_geometry(section_header *h, int ind)
{
    unsigned int i;
    unsigned char *data = (unsigned char *)(h + 1);
    unsigned char *odata = data;
    geometry_header *g = (geometry_header *)data;
    geom_hdr = g;
    faces.clear();
    texcoods.clear();
    normals.clear();
    materials.clear();

    indent(ind);
    printf("flags: %02x\n", g->flags);
    indent(ind);
    printf("unkn: %02x\n", g->unkn);
    indent(ind);
    printf("triangle count: %i\n", g->triangle_count);
    indent(ind);
    printf("vertex count: %i\n", g->vertex_count);
    indent(ind);
    printf("morph target count: %i\n", g->morph_target_count);
    assert(sizeof(geometry_header) == 16);
    data += sizeof(geometry_header);
    
    {  // seems to always be present
        indent(ind);
        geometry_lighting *l = (geometry_lighting *)data;
        printf("lighting %f %f %f\n", l->ambient, l->diffuse, l->specular);
        assert(sizeof(geometry_lighting) == 12);
        data += sizeof(geometry_lighting);
    }

    if (g->flags & rwOBJECT_VERTEX_COLOR) {
        indent(ind);
        printf("colors:\n");
        for (i = 0; i < g->vertex_count; i++) {
            indent(ind + 1);
            printf("%i %i %i %i\n", data[i * 4],     data[i * 4 + 1], 
                                    data[i * 4 + 2], data[i * 4 + 3]);
        }
        data += g->vertex_count * 4;
    }

    assert(g->flags & rwOBJECT_VERTEX_UV);
    if (g->flags & rwOBJECT_VERTEX_UV) {
        indent(ind);
        printf("texture mapping:\n");
        float *f = (float *)data;
        texcoods.resize(g->vertex_count);
        for (i = 0; i < g->vertex_count; i++) {
            indent(ind + 1);
            printf("%f %f\n", f[i * 2], f[i * 2 + 1]);
            texcoods[i].u = f[i * 2];
            texcoods[i].v = f[i * 2 + 1];
        }
        data += g->vertex_count * 4 * 2;
    }
    
    indent(ind);
    printf("faces:\n");
    faces.resize(g->triangle_count);
    for (i = 0; i < g->triangle_count; i++) {
        indent(ind + 1);
        short *v = (short *)data;
        printf("2:%i 1:%i flags:%08x 3:%i\n", v[i * 4],     v[i * 4 + 1], 
                                              v[i * 4 + 2], v[i * 4 + 3]);
    
        faces[i].v1 = v[i * 4 + 1];
        faces[i].v2 = v[i * 4];
        faces[i].v3 = v[i * 4 + 3];
    }
    data += g->triangle_count * 4 * 2;

    {
        indent(ind);
        float *f = (float *)data;
        printf("bounding sphere: (%f %f %f) %f\n", f[0], f[1], f[2], f[3]);
        data += 4 * 4;

        indent(ind);
        int *v = (int *)data;
        printf("has position %i has normals %i\n", v[0], v[1]);
        data += 8;
    }

    indent(ind);
    printf("vertexes:\n");
    vertexes.resize(g->vertex_count);
    for (i = 0; i < g->vertex_count; i++) {
        indent(ind + 1);
        float *f = (float *)data;
        printf("%f %f %f\n", f[i * 3], f[i * 3 + 1], f[i * 3 + 2]);
        vertexes[i].x = f[i * 3];
        vertexes[i].y = f[i * 3 + 1];
        vertexes[i].z = f[i * 3 + 2];
    }
    data += g->vertex_count * 4 * 3;
    
    if (g->flags & rwOBJECT_VERTEX_NORMAL) {
        indent(ind);
        printf("normals:\n");
        normals.resize(g->vertex_count);
        for (i = 0; i < g->vertex_count; i++) {
            indent(ind + 1);
            float *f = (float *)data;
            printf("%f %f %f\n", f[i * 3], f[i * 3 + 1], f[i * 3 + 2]);
            
            normals[i].x = f[i * 3];
            normals[i].y = f[i * 3 + 1];
            normals[i].z = f[i * 3 + 2];

        }
        data += g->vertex_count * 4 * 3;
    }

    assert(data - odata == h->size);
}

typedef struct {
    int unkn1;
    int unkn2;
    int unkn3;
    int texture_count;
} material_header;

void dump_material(section_header *h, int ind)
{
    unsigned char *data = (unsigned char *)(h + 1);
    unsigned char *odata = data;
    material_header *m = (material_header *)data;
    indent(ind);
    printf("unkn1: %08x\n", m->unkn1);
    indent(ind);
    printf("unkn2: %08x\n", m->unkn2);
    indent(ind);
    printf("unkn3: %08x\n", m->unkn3);
    indent(ind);
    printf("texure count: %i\n", m->texture_count);
    
    data += sizeof(material_header);

    if (data - odata != h->size) {
        float *f = (float *)data;
        indent(ind);
        printf("unknown: %f %f %f\n", f[0], f[1], f[2]);
        data += 4 * 3;
    }

    assert(data - odata == h->size);
}

std::map<int, int> geometry_to_frame;

void dump_atomic(section_header *h, int ind)
{
    unsigned char *data = (unsigned char *)(h + 1);
    unsigned int *v = (unsigned int *)data;
    indent(ind);
    printf("frame index: %i\n", v[0]); 
    indent(ind);
    printf("geometry index: %i\n", v[1]); 
    geometry_to_frame[v[1]] = v[0];
}

void dump_data(section_header *h, int ind)
{
    indent(ind);
    unsigned char *data = (unsigned char *)(h + 1);
    unsigned int i;
    for (i = 0; i < h->size; i++)
        printf("%02x ", data[i]);
    printf("\n");
}

void add_material_string(section_header *h, int ind)
{
    std::string m = "";

    indent(ind);
    char *data = (char *)(h + 1);
    printf("\"");
    unsigned int i;
    bool seenzero = false;
    for (i = 0; i < h->size; i++)
        if (data[i] == 0) {
            printf("\\0");
            seenzero = true;
        } else {
            printf("%c", data[i]);
            if (!seenzero)
                m.append(1, data[i]);
        }
    printf("\"\n");
    if (m != "") {
        materials.push_back(m);
    }
}

void dump_string(section_header *h, int ind)
{
    indent(ind);
    char *data = (char *)(h + 1);
    printf("\"");
    unsigned int i;
    for (i = 0; i < h->size; i++)
        if (data[i] == 0)
            printf("\\0");
        else
            printf("%c", data[i]);
    printf("\"\n");
}

void dump_material_split(section_header *h, int ind)
{
    char *data = (char *)(h + 1);
    char *odata = data;
    int *v = (int *)data;

    indent(ind);
    printf("triangle strip: %i\n", v[0]);
    indent(ind);
    printf("split count: %i\n", v[1]);
    indent(ind);
    printf("face count: %i\n", v[2]);
    data += 4 * 3;

    std::vector<std::set<int> > splits;
    std::vector<int> split_material;
    int num_splits = v[1];
    int i;
    splits.resize(num_splits);
    split_material.resize(num_splits);
    for (i = 0; i < num_splits; i++) {
        int *vn = (int *)data;
        indent(ind);
        printf("face index: %i\n", vn[0]);
        indent(ind);
        printf("material index: %i\n", vn[1]);
        split_material[i] = vn[1];
        int j;
        for (j = 0; j < vn[0]; j++) {
            indent(ind);
            printf("vertex: %i\n", vn[2 + j]);
            splits[i].insert(vn[2 + j]);
        }
        data += 4 * (2 + vn[0]);
    }

    assert(data - odata == h->size);
    static unsigned int mesh_count = 0;
    assert(mesh_count < meshnames.size());
    std::string meshname = meshnames[mesh_count++];

    splits_for_name.push_back(num_splits);

    for (int j = 0; j < num_splits; j++) {
        unsigned int mat = split_material[j];
        if (mat >= materials.size()) {
            materials.resize(mat + 1);
            materials[mat] = "white64";
        }
        assert(mat < materials.size());
        submeshnames.push_back(meshname);
        fprintf(fout, "\t\t<submesh material=\"%s\" usesharedvertices=\"false\" use32bitindexes=\"false\">\n", materials[mat].c_str());

		bool change = true;
		while (change) {
			change = false;
			for (unsigned int i = 0; i < geom_hdr->triangle_count; i++) {
				if (splits[j].find(faces[i].v1) != splits[j].end()) {
					if (splits[j].find(faces[i].v2) == splits[j].end()) {
						splits[j].insert(faces[i].v2);
						change = true;
					}
					if (splits[j].find(faces[i].v3) == splits[j].end()) {
						splits[j].insert(faces[i].v3);
						change = true;
					}
				}
			}
		}

        int num_faces = 0;
        for (unsigned int i = 0; i < geom_hdr->triangle_count; i++) {
            if (splits[j].find(faces[i].v1) != splits[j].end()) {
                assert(splits[j].find(faces[i].v2) != splits[j].end());
                assert(splits[j].find(faces[i].v3) != splits[j].end());
                num_faces++;
            }
        }
            
        fprintf(fout, "\t\t\t<faces count=\"%i\">\n", num_faces);

        std::map<int, int> vertex_map;
        int count = 0;
        for (std::set<int>::iterator it = splits[j].begin(); it != splits[j].end(); it++)
            vertex_map[*it] = count++;

        for (unsigned int i = 0; i < geom_hdr->triangle_count; i++) {
            if (splits[j].find(faces[i].v1) != splits[j].end()) {
                assert(splits[j].find(faces[i].v2) != splits[j].end());
                assert(splits[j].find(faces[i].v3) != splits[j].end());
                fprintf(fout, "\t\t\t\t<face v1=\"%i\" v2=\"%i\" v3=\"%i\" />\n", 
                                vertex_map[faces[i].v1], 
                                vertex_map[faces[i].v2], 
                                vertex_map[faces[i].v3]);
            }
        }

        fprintf(fout, "\t\t\t</faces>\n");

        fprintf(fout, "\t\t\t<geometry vertexcount=\"%i\">\n", count);
        fprintf(fout, "\t\t\t\t<vertexbuffer positions=\"true\" normals=\"%s\" colours_diffuse=\"false\" texture_coords=\"1\" texture_coords_dimensions_0=\"2\">\n", normals.size() ? "true" : "false");

        for (std::map<int, int>::iterator it = vertex_map.begin(); it != vertex_map.end(); it++) {
                int i = (*it).first;
                fprintf(fout, "\t\t\t\t\t<vertex>\n");
                fprintf(fout, "\t\t\t\t\t\t<position x=\"%f\" y=\"%f\" z=\"%f\" />\n",
                           vertexes[i].x, vertexes[i].y, vertexes[i].z);
                if (normals.size()) 
                    fprintf(fout, "\t\t\t\t\t\t<normal x=\"%f\" y=\"%f\" z=\"%f\" />\n",
                           normals[i].x, normals[i].y, normals[i].z);
                fprintf(fout, "\t\t\t\t\t\t<texcoord u=\"%f\" v=\"%f\" />\n",
                           texcoods[i].u, texcoods[i].v);
                fprintf(fout, "\t\t\t\t\t</vertex>\n");
        }

        fprintf(fout, "\t\t\t\t</vertexbuffer>\n");
        fprintf(fout, "\t\t\t</geometry>\n");

        if (fskel) {
            fprintf(fout, "\t\t\t<boneassignments>\n");
            // shouldn't need this, if we're doing atomic processing correct
            //int bone_trans[16] = { 16, 10, 15, 14, 11, 13, 12, 9, 2, 8, 3, 7, 6, 4, 5, 1 };
            size_t bone = splits_for_name.size() - 1;
            for (int i = 0; i < count; i++)
                fprintf(fout, "\t\t\t\t<vertexboneassignment vertexindex=\"%i\" boneindex=\"%i\" weight=\"1\" />\n", i, bone);
            fprintf(fout, "\t\t\t</boneassignments>\n");
        }

        fprintf(fout, "\t\t</submesh>\n");
    }
}

void dump_section(section_header *h, int ind, section_type parent)
{
    indent(ind);
    printf("%s (%i bytes) (version %i)\n", section_type_string(h->kind), 
                                           h->size, h->version);
    switch(h->kind) {
        case rwDATA:
            switch(parent) {
                case rwCLUMP:
                    dump_int(h, ind + 1);
                    break;
                case rwFRAMELIST:
                    dump_frame_list(h, ind + 1);
                    break;
                case rwGEOMETRY:
                    dump_geometry(h, ind + 1);
                    break;
                case rwGEOMETRYLIST:
                    dump_int(h, ind + 1);
                    break;
                case rwMATERIALLIST:
                    dump_int(h, ind + 1);
                    break;
                case rwMATERIAL:
                    dump_material(h, ind + 1);
                    break;
                case rwATOMIC:
                    dump_atomic(h, ind + 1);
                    break;
                default:
                    dump_data(h, ind + 1);
            }
            break;
        case rwSTRING:
            switch(parent) {
                case rwTEXTURE:
                    add_material_string(h, ind + 1);
                    break;
                default:
                    dump_string(h, ind + 1);
            }
            break;
        case rwFRAME:
            dump_frame(h, ind + 1);
            break;
        case rwMATERIALSPLIT:
            dump_material_split(h, ind + 1);
            break;
        case rwEXTENSION:
        case rwTEXTURE:
        case rwMATERIAL:
        case rwMATERIALLIST:
        case rwFRAMELIST:
        case rwGEOMETRY:
        case rwCLUMP:
        case rwATOMIC:
        case rwGEOMETRYLIST:
        {
            section_header *ch = h + 1;
            while ((size_t)ch < (size_t)(h + 1) + h->size) {
                dump_section(ch, ind + 1, h->kind);
                ch = (section_header *)((size_t)(ch + 1) + ch->size);
            }
        }
    }
}

typedef float Real;
typedef float Radian;
class Vector3 {
public:
    float x, y, z;
};

typedef float Matrix3[3][3];

class Quaternion {
public:
    float x, y, z, w;

void FromRotationMatrix (const Matrix3& kRot)
{
    Real fTrace = kRot[0][0]+kRot[1][1]+kRot[2][2];
    Real fRoot;
   
    if ( fTrace > 0.0 )
    {
        // |w| > 1/2, may as well choose w > 1/2
        fRoot = sqrt(fTrace + 1.0f);  // 2w
        w = 0.5f*fRoot;
        fRoot = 0.5f/fRoot;  // 1/(4w)
        x = (kRot[2][1]-kRot[1][2])*fRoot;
        y = (kRot[0][2]-kRot[2][0])*fRoot;
        z = (kRot[1][0]-kRot[0][1])*fRoot;
    }
    else
    {
        // |w| <= 1/2
        static size_t s_iNext[3] = { 1, 2, 0 };
        size_t i = 0;
        if ( kRot[1][1] > kRot[0][0] )
            i = 1;
        if ( kRot[2][2] > kRot[i][i] )
            i = 2;
        size_t j = s_iNext[i];
        size_t k = s_iNext[j];
        
        fRoot = sqrt(kRot[i][i]-kRot[j][j]-kRot[k][k] + 1.0f);
        Real* apkQuat[3] = { &x, &y, &z };
        *apkQuat[i] = 0.5f*fRoot;
        fRoot = 0.5f/fRoot;
        w = (kRot[k][j]-kRot[j][k])*fRoot;
        *apkQuat[j] = (kRot[j][i]+kRot[i][j])*fRoot;
        *apkQuat[k] = (kRot[k][i]+kRot[i][k])*fRoot;
    }
}

void ToAngleAxis (Radian& rfAngle, Vector3& rkAxis) const
{
    // The quaternion representing the rotation is
    //   q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)

    float fSqrLength = x*x+y*y+z*z;
    if ( fSqrLength > 0.0f )
    {
        rfAngle = 2.0f*acos(w);
        float fInvLength = 1.0f/sqrt(fSqrLength);
        rkAxis.x = x*fInvLength;
        rkAxis.y = y*fInvLength;
        rkAxis.z = z*fInvLength;
    }
    else
    {
        // angle is 0 (mod 2*pi), so any axis will do
        rfAngle = 0.0f;
        rkAxis.x = 1.0f;
        rkAxis.y = 0.0f;
        rkAxis.z = 0.0f;
    }
}

};

struct keyframe
{
    struct pos trans;
    Quaternion rot;
    float time;
};

struct track
{
    std::string name;
    std::vector<struct keyframe> keyframes;
};

struct animation
{
    std::string name;
    std::vector<struct track> tracks;
};

std::vector<struct animation> animations;

int dumpanims(unsigned char *data, int ind)
{
    int size = 0;
    int i;
    while (*data == 0) {
        size++; 
        data++;
    }
    for (i = 0; i < 4; i++)
        assert((data[i] >= 'A' && data[i] <= 'Z') || 
               (data[i] >= '0' && data[i] <= '9'));
    int dsize = *(int*)(data + 4);
    size += dsize;
    char tag[5];
    memcpy(tag, data, 4);
    tag[4] = 0;
    indent(ind);
    printf("%s %i\n", tag, size);
    
    if (!strcmp(tag, "ANPK") || !strcmp(tag, "DGAN") || !strcmp(tag, "CPAN")) {
        int bytes = 0;
        do 
            bytes += dumpanims(data + 8 + bytes, ind + 1);
        while (bytes < dsize);
    } else if (!strcmp(tag, "NAME")) {
        indent(ind + 1);
        printf("%s\n", data + 8);
        struct animation a;
        a.name = (char *)data + 8;
        a.tracks.clear();
        animations.push_back(a);
    } else if (!strcmp(tag, "ANIM")) {
        indent(ind + 1);
        printf("%s\n", data + 8);
        struct track t;
        t.name = (char *)data + 8;
        t.keyframes.clear();
        animations[animations.size() - 1].tracks.push_back(t);
        // TODO: seems to be more data, 0x30 worth
    } else if (!strcmp(tag, "KRT0")) {
        assert((size % (4 * 8)) == 0);
        float *f = (float *)(data + 8);
        for (i = 0; i < size / 4 / 8; i++) {
            indent(ind + 1);
            printf("rot=(%f %f %f %f) trans=(%f %f %f) time=%f\n", 
                f[i * 8], f[i * 8 + 1], f[i * 8 + 2], f[i * 8 + 3],
                f[i * 8 + 4], f[i * 8 + 5], f[i * 8 + 6],
                f[i * 8 + 7]);
            struct keyframe k;
            k.rot.x = f[i * 8];
            k.rot.y = f[i * 8 + 1];
            k.rot.z = f[i * 8 + 2];
            k.rot.w = f[i * 8 + 3];
            k.trans.x = f[i * 8 + 4];
            k.trans.y = f[i * 8 + 5];
            k.trans.z = f[i * 8 + 6];
            k.time = f[i * 8 + 7];
            animations[animations.size() - 1].tracks[animations[animations.size() - 1].tracks.size() - 1].keyframes.push_back(k);
        }
     } else if (!strcmp(tag, "KR00")) {
        assert((size % (4 * 5)) == 0);
        float *f = (float *)(data + 8);
        for (i = 0; i < size / 4 / 5; i++) {
            indent(ind + 1);
            printf("rot=(%f %f %f %f) time=%f\n", 
                f[i * 5], f[i * 5 + 1], f[i * 5 + 2], f[i * 5 + 3],
                f[i * 5 + 4]);
            size_t t = animations[animations.size() - 1].tracks.size() - 1;
            struct keyframe k;
            k.rot.x = f[i * 5];
            k.rot.y = f[i * 5 + 1];
            k.rot.z = f[i * 5 + 2];
            k.rot.w = f[i * 5 + 3];
            k.trans.x = 0;
            k.trans.y = 0;
            k.trans.z = 0;
            k.time = f[i * 5 + 4];
            animations[animations.size() - 1].tracks[t].keyframes.push_back(k);
        }
    }
    
    return size + 8;
}

int lookup_frame(const char *name)
{
    for (int i = 0; i < (int)meshnames.size(); i++)
        if (meshnames[i] == name)
            return i;
    return 0;
}

void output_bone(int id, int frameidx)
{
    frame_data &frame = frames[frameidx];
    fprintf(fskel, "\t\t<bone id=\"%i\" name=\"%s\">\n", id, meshnames[frameidx].c_str());
    if (meshnames[1] == "Swaist") {
        fprintf(fskel, "\t\t\t<position x=\"0\" y=\"0\" z=\"0\" />\n");
        fprintf(fskel, "\t\t\t<rotation angle=\"0\">\n");
        fprintf(fskel, "\t\t\t\t<axis x=\"1\" y=\"0\" z=\"0\" />\n");
        fprintf(fskel, "\t\t\t</rotation>\n");
    } else {
        fprintf(fskel, "\t\t\t<position x=\"%f\" y=\"%f\" z=\"%f\" />\n", 
                    frame.xyz[0], frame.xyz[1], frame.xyz[2]);
        Quaternion q;
        q.FromRotationMatrix(frame.rot);    
        Radian angle;
        Vector3 axis;
        q.ToAngleAxis(angle, axis);
        fprintf(fskel, "\t\t\t<rotation angle=\"%f\">\n", -angle);
        fprintf(fskel, "\t\t\t\t<axis x=\"%f\" y=\"%f\" z=\"%f\" />\n", 
                    axis.x, axis.y, axis.z);
        fprintf(fskel, "\t\t\t</rotation>\n");
    }
    fprintf(fskel, "\t\t</bone>\n");
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        printf("usage: dff2ogre <dff file> <ogre mesh xml file> [<ogre skeleton xml file>] [offset]\n");
        return 1;
    }

    FILE *f = fopen(argv[1], "rb");
    if (f == NULL) {
        fprintf(stderr, "can't open %s\n", argv[1]);
        return 1;
    }
    fseek(f, 0, SEEK_END);
    int size = ftell(f);
    fseek(f, 0, SEEK_SET);
    unsigned char *data = (unsigned char *)malloc(size);
    fread(data, 1, size, f);
    fclose(f);

    fout = fopen(argv[2], "w");
    if (fout == NULL) {
        fprintf(stderr, "can't open %s for writing\n", argv[2]);
        return 1;
    }
    fprintf(fout, "<mesh>\n\t<submeshes>\n");

    if (argc > 3) {
        fskel = fopen(argv[3], "w");
        if (fskel == NULL) {
            fprintf(stderr, "can't open %s for writing\n", argv[3]);
            return 1;
        }
    } else
        fskel = NULL;

    int off = 0;
    if (argc > 4) {
        sscanf(argv[4], "%i", &off);
    }

    section_header *h = (section_header *)(data + off);
    do {
        dump_section(h, 0, rwNONE);
        off += sizeof(*h) + h->size;
        if (off > size)
            break;
        h = (section_header *)(data + off);
    } while (h->kind == rwEXTENSION || h->kind == rwATOMIC);

    free(data);
    fprintf(fout, "\t</submeshes>\n");

    if (fskel) {
        *strrchr(argv[3], '.') = 0;
        fprintf(fout, "\t<skeletonlink name=\"%s\" />\n", argv[3]);
    } else {
#if 0
        // this doesn't take ATOMICs into account
        printf("%i meshnames\n", meshnames.size());
        fprintf(fout, "\t<submeshnames>\n");
        for (unsigned int i = 0; i < submeshnames.size(); i++) {
            fprintf(fout, "\t\t<submeshname name=\"%s\" index=\"%i\" />\n", submeshnames[i].c_str(), i);
        }
        fprintf(fout, "\t</submeshnames>\n");
#endif
    }
    fprintf(fout, "</mesh>");
    fclose(fout);

    if (fskel) {
        fprintf(fskel, "<skeleton>\n\t<bones>\n");
        assert(meshnames.size() == frames.size());
        std::set<int> bones_out;
        for (std::map<int, int>::iterator it = geometry_to_frame.begin();
                it != geometry_to_frame.end(); it++) {
            int i = (*it).first;
            bones_out.insert((*it).second);
            output_bone(i, (*it).second);
        }
        int idx = (int)bones_out.size();
        for (unsigned int i = 0; i < frames.size(); i++) {
            if (bones_out.find(i) != bones_out.end())
                continue;
            output_bone(idx++, i);
        }
        fprintf(fskel, "\t</bones>\n");
        fprintf(fskel, "\t<bonehierarchy>\n");
        for (std::map<int, int>::iterator it = geometry_to_frame.begin();
                it != geometry_to_frame.end(); it++) {
            frame_data &frame = frames[(*it).second];
            int parent = frame.parent;
            if (parent == -1)
                continue;
            fprintf(fskel, "\t\t<boneparent bone=\"%s\" parent=\"%s\" />\n", 
                meshnames[(*it).second].c_str(), meshnames[parent].c_str());
        }
        fprintf(fskel, "\t</bonehierarchy>\n");

#if 1
        FILE *fped = fopen("ped.ifp", "rb");
        if (fped != NULL) {
			fseek(fped, 0, SEEK_END);
			int ped_size = ftell(fped);
			fseek(fped, 0, SEEK_SET);
			unsigned char *ped_data = (unsigned char *)malloc(ped_size);
			fread(ped_data, 1, ped_size, fped);
			fclose(fped);
			if (meshnames[1] == "Swaist")
				dumpanims(ped_data, 0);
        }
#endif

        fprintf(fskel, "\t<animations>\n");
        fprintf(fskel, "\t\t<animation name=\"default\" length=\"0.0333\">\n");
        fprintf(fskel, "\t\t\t<tracks>\n");
        assert(meshnames.size() == frames.size());
        for (unsigned int i = 0; i < meshnames.size(); i++) { 
            fprintf(fskel, "\t\t\t\t<track bone=\"%s\">\n", meshnames[i].c_str());
            fprintf(fskel, "\t\t\t\t\t<keyframes>\n");
            fprintf(fskel, "\t\t\t\t\t\t<keyframe time=\"0\">\n");
            fprintf(fskel, "\t\t\t\t\t\t\t<translate x=\"%f\" y=\"%f\" z=\"%f\" />\n", frames[i].xyz[0], frames[i].xyz[1], frames[i].xyz[2]);
            fprintf(fskel, "\t\t\t\t\t\t\t<rotate angle=\"0\">\n");
            fprintf(fskel, "\t\t\t\t\t\t\t\t<axis x=\"1\" y=\"0\" z=\"0\" />\n");
            fprintf(fskel, "\t\t\t\t\t\t\t</rotate>\n");
            fprintf(fskel, "\t\t\t\t\t\t</keyframe>\n");
            fprintf(fskel, "\t\t\t\t\t</keyframes>\n");
            fprintf(fskel, "\t\t\t\t</track>\n");
        }
        fprintf(fskel, "\t\t\t</tracks>\n");
        fprintf(fskel, "\t\t</animation>\n");

        for (unsigned int a = 0; a < animations.size(); a++) {
            float max_time = 0;
            bool badanim = false;
            for (unsigned int t = 0; t < animations[a].tracks.size(); t++) {
                if (animations[a].tracks[t].keyframes[animations[a].tracks[t].keyframes.size() - 1].time > max_time)
                    max_time = animations[a].tracks[t].keyframes[animations[a].tracks[t].keyframes.size() - 1].time;

                bool found = false;
                for (unsigned int i = 0; i < meshnames.size(); i++)
                    if (animations[a].tracks[t].name == meshnames[i]) {
                        found = true;
                        break;
                    }
                if (!found)
                    badanim = true;
            }

            if (badanim)
                continue;
                
            fprintf(fskel, "\t\t<animation name=\"%s\" length=\"%f\">\n",
                animations[a].name.c_str(), 
                max_time);
            fprintf(fskel, "\t\t\t<tracks>\n");
            for (unsigned int t = 0; t < animations[a].tracks.size(); t++) {
                int frame = lookup_frame(animations[a].tracks[t].name.c_str());
                fprintf(fskel, "\t\t\t\t<track bone=\"%s\">\n", animations[a].tracks[t].name.c_str());
                fprintf(fskel, "\t\t\t\t\t<keyframes>\n");
                for (unsigned int k = 0; k < animations[a].tracks[t].keyframes.size(); k++) {
                    fprintf(fskel, "\t\t\t\t\t\t<keyframe time=\"%f\">\n", animations[a].tracks[t].keyframes[k].time);
                    fprintf(fskel, "\t\t\t\t\t\t\t<translate x=\"%f\" y=\"%f\" z=\"%f\" />\n", animations[a].tracks[t].keyframes[k].trans.x + frames[frame].xyz[0], 
             animations[a].tracks[t].keyframes[k].trans.y + frames[frame].xyz[1],
             animations[a].tracks[t].keyframes[k].trans.z + frames[frame].xyz[2]);
                    Quaternion q;
                    q.x = animations[a].tracks[t].keyframes[k].rot.x;
                    q.y = animations[a].tracks[t].keyframes[k].rot.y;
                    q.z = animations[a].tracks[t].keyframes[k].rot.z;
                    q.w = animations[a].tracks[t].keyframes[k].rot.w;
                    Quaternion q1;
                    q1.FromRotationMatrix(frames[frame].rot);
                    Radian angle;
                    Vector3 axis;
                    q.ToAngleAxis(angle, axis);
                    fprintf(fskel, "\t\t\t\t\t\t\t<rotate angle=\"%f\">\n", -angle);
                    fprintf(fskel, "\t\t\t\t\t\t\t\t<axis x=\"%f\" y=\"%f\" z=\"%f\" />\n", axis.x, axis.y, axis.z);
                    fprintf(fskel, "\t\t\t\t\t\t\t</rotate>\n");
                    fprintf(fskel, "\t\t\t\t\t\t</keyframe>\n");
                }
                fprintf(fskel, "\t\t\t\t\t</keyframes>\n");
                fprintf(fskel, "\t\t\t\t</track>\n");
            }
            fprintf(fskel, "\t\t\t</tracks>\n");
            fprintf(fskel, "\t\t</animation>\n");
        }
        fprintf(fskel, "\t</animations>\n");

        fprintf(fskel, "</skeleton>\n");
        fclose(fskel);
    }

    return 0;
}
