var i = 0;
var _null = 'set null anyway';
function def(a, d) {
    if (a != undefined && a != null) return (d != undefined && d != null ? a : true);
    else
        if (d != _null)
            return (d != undefined && d != null ? d : false);
    return null;
}

function down(op) {
    op = def(op, {});
    op.type = def(op.type, 'Get');
    op.url = def(op.url, '/');
    op.success = def(op.success, function (data) { alert(data); });
    op.error = def(op.error, function (data) { alert(data.responseText); });
    op.end = def(op.end, function () { });
    op.begin = def(op.begin, function () { });

    function processData(data) {
        op.success(data);
    }

    function handler() {
        op.subProgress = def(op.subProgress, function (p) { });
        op.subProgress(this);
        if (this.readyState == this.DONE) {
            if (this.status == 200) {
                // success!
                processData(this.responseText);
            }
            else {
                op.error(this);
            }
            op.end();
        }
    }

    try {
        op.begin();
        var client = new XMLHttpRequest();
        client.onreadystatechange = handler;
        client.open(op.type, op.url);
        client.send();
        client.onprogress = function (pe) {
            if (pe.lengthComputable) {
                op.progress = def(op.progress, function (p) { });
                op.progress(pe.loaded * 100. / pe.total);
            }
        }
    } catch (e) { op.error(e); op.end(); }

} 
var BX  ;
down({
    url: '/loader/scene.js', success: function (d) {
        eval(d);

        console.log(BABYLONX);
        BX = BABYLONX; 
    }
});
var BABYLONX;
 
onmessage = function (e) {
   
    decodeObj(e.data.data);
    
}
var _ObjGrps;
function decodeObj(data) {
    var li = (data.toLocaleLowerCase().split('\n'));
    
    var gpInd = 0;
    var wgState = 0;
    var ObjGrps = [{ v: [], vt: [], f: [], vn: [], o: '', g: '' }];

     
    for (var i = 0; i < li.length; i++) {
        if (li[i].trim()[0] == 'v') {

            if (wgState == 2) {

                wgState = 0;
                gpInd++;
                ObjGrps[gpInd] = { v: [], vt: [], f: [], vn: [], o: '', g: '' };

            }
            if (li[i].trim()[1] == ' ') ObjGrps[gpInd].v.push(li[i].split(' '));
            if (li[i].trim()[1] == 't') ObjGrps[gpInd].vt.push(li[i].split(' '));
            if (li[i].trim()[1] == 'n') ObjGrps[gpInd].vn.push(li[i].split(' '));
        }
        if (li[i].trim()[0] == 'f') {
            ObjGrps[gpInd].f.push(li[i].split(' '));
            wgState = 2;
        }
        if (li[i].trim()[0] == 'o') ObjGrps[gpInd].o = li[i];
        if (li[i].trim()[0] == 'g') { 

            ObjGrps[gpInd].g = li[i]; wgState = 1;
        }
        postMessage('prg'+0.5*(i / li.length) );    

        _ObjGrps = ObjGrps;
        makeGeo( );
    }
}

var Import_Obj;
function makeGeo( ) {
    var i = 0;
    if (!BX) {
       
        setTimeout(makeGeo,300); return;
    }
    BABYLONX = BX; 
    GB = BABYLONX.GeometryBuilder;
    Import_Obj =   function (op) {
        var builder = function (setting /*{seg:number}*/, geo) {
            for (var i = 0; i < setting.v.length; i++) {
                try {
                    var x = 0;
                    var y = 0;
                    var z = 0;

                    if (setting.v[i][4]) {
                        x = setting.v[i][2].replace('\r', '').valueOf() * 1.0;
                        y = setting.v[i][3].replace('\r', '').valueOf() * 1.0;
                        z = setting.v[i][4].replace('\r', '').valueOf() * 1.0;
                    }
                    else {
                        x = setting.v[i][1].replace('\r', '').valueOf() * 1.0;
                        y = setting.v[i][2].replace('\r', '').valueOf() * 1.0;
                        z = setting.v[i][3].replace('\r', '').valueOf() * 1.0;
                    }


                    GB.PushVertex(geo, { x: x, y: y, z: z });
                    geo.uvs.push(-999.999, -999.999);
                } catch (e) { console.log(setting.v[i]); }

            }

            var uvs = [];

            function lastUV(a, va) {
                var x = 0;
                var y = 0;
                var z = 0;

                if (setting.v[a][4]) {
                    x = setting.v[a][2].replace('\r', '').valueOf() * 1.0;
                    y = setting.v[a][3].replace('\r', '').valueOf() * 1.0;
                    z = setting.v[a][4].replace('\r', '').valueOf() * 1.0;
                }
                else {
                    x = setting.v[a][1].replace('\r', '').valueOf() * 1.0;
                    y = setting.v[a][2].replace('\r', '').valueOf() * 1.0;
                    z = setting.v[a][3].replace('\r', '').valueOf() * 1.0;
                }
                GB.PushVertex(geo, { x: x, y: y, z: z });
                geo.uvs.push(-999.999, -999.999);
                uvs.push({ u: uvs[va].u, v: uvs[va].v });
                va = uvs.length - 1;
                a = geo.vertices.length - 1;
                return { a: a, va: va };
            }

            for (var i = 0; i < setting.vt.length; i++) {
                var x = 0; var y = 0;

                try {
                    x = setting.vt[i][1].replace('\r', '').valueOf() * 1.0;
                    y = setting.vt[i][2].replace('\r', '').valueOf() * 1.0;
                    var z = 0;
                    try {
                        z = setting.vt[i][3].replace('\r', '').valueOf() * 1.0;


                    } catch (e) { }


                    uvs.push({ u: x, v: y });

                } catch (e) { console.log(e.message); }
            }
            for (var i = 0; i < setting.f.length; i++) {
                try {

                    function addFace(a1, a2, a3) {
                        var a = setting.f[i][a1].replace('\r', '').split('/')[0].valueOf() * 1;
                        var b = setting.f[i][a2].replace('\r', '').split('/')[0].valueOf() * 1;
                        var c = setting.f[i][a3].replace('\r', '').split('/')[0].valueOf() * 1;

                        if (a < 0) a = setting.v.length + a;
                        else a = a - 1;
                        if (b < 0) b = setting.v.length + b;
                        else b = b - 1;
                        if (c < 0) c = setting.v.length + c;
                        else c = c - 1;

                        var va = setting.f[i][a1].replace('\r', '').split('/')[1].valueOf() * 1;
                        var vb = setting.f[i][a2].replace('\r', '').split('/')[1].valueOf() * 1;
                        var vc = setting.f[i][a3].replace('\r', '').split('/')[1].valueOf() * 1;
                        if (va < 0) va = setting.vt.length + va;
                        else va = va - 1;
                        if (vb < 0) vb = setting.vt.length + vb;
                        else vb = vb - 1;
                        if (vc < 0) vc = setting.vt.length + vc;
                        else vc = vc - 1;

                        if (geo.uvs[a * 2] != -999.999 && (geo.uvs[a * 2] != uvs[va].u || geo.uvs[a * 2 + 1] != uvs[va].v)) {
                            var vv = lastUV(a, va);
                            a = vv.a;
                            va = vv.va;
                        }

                        if (geo.uvs[b * 2] != -999.999 && (geo.uvs[b * 2] != uvs[vb].u || geo.uvs[b * 2 + 1] != uvs[vb].v)) {
                            var vv = lastUV(b, vb);
                            b = vv.a;
                            vb = vv.va;
                        }
                        if (geo.uvs[c * 2] != -999.999 && (geo.uvs[c * 2] != uvs[vc].u || geo.uvs[c * 2 + 1] != uvs[vc].v)) {
                            var vv = lastUV(c, vc);
                            c = vv.a;
                            vc = vv.va;
                        }


                        geo.uvs[a * 2] = uvs[va].u; geo.uvs[a * 2 + 1] = uvs[va].v;
                        geo.uvs[b * 2] = uvs[vb].u; geo.uvs[b * 2 + 1] = uvs[vb].v;
                        geo.uvs[c * 2] = uvs[vc].u; geo.uvs[c * 2 + 1] = uvs[vc].v;
                         

                        if (setting.dblface) {
                            GB.MakeFace(geo, [a, b, c], {
                                flip: !setting.flip,
                                Face3Point: true,
                                faceUVMap: "012",
                                uvStart: { u: 0.01, v: 0.5 },
                                uvEnd: { u: 0.01, v: 0.5 },
                            });
                        }

                        GB.MakeFace(geo, [a, b, c], {
                            flip: setting.flip,
                            Face3Point: true,
                            faceUVMap: "012",
                            uvStart: { u: 0.01, v: 0.5 },
                            uvEnd: { u: 0.01, v: 0.5 },
                        });

                    }
                    addFace(1, 2, 3);

                    if (setting.f[i][4]) {
                        try { addFace(3,4, 1); } catch (e) { }
                    }




                } catch (e) {
                    console.log(e);
                }
            }
        };

        return new BABYLONX.Geometry(GB.GeometryBase(op, builder, op.custom));
    };

    for (var ar in _ObjGrps) {
        i++;
        try {
            var geo = Import_Obj(_ObjGrps[ar]);
            postMessage({ geo: geo, obj: _ObjGrps[ar] });
        } catch (e) { }
        
      
        postMessage('prg' + (0.5 + 0.5 * (i / _ObjGrps.length)) );    

        
    }

}