[Tut]Opening and compiling .elu files

Gunz Online Hacks/Bots/Tutes Discussion Discuss, [Tut]Opening and compiling .elu files at Gunz Online General forum; DISCLAIMER : I WILL NOT BE HELD RESPONSIBLE FOR ANY LOSSES DURING THE PROCESSES OF THIS TUTORIAL. Other than that, ...


Go Back   Gamerz Needs - For All Your Gaming Needs! > Gunz Online > Gunz Online General > Gunz Online Hacks/Bots/Tutes Discussion
Forgot Password? | Sign Up!



Closed Thread
 
Bookmark this Thread Tools Display Modes
  #1  
Old 06-13-2010, 09:05 PM
isaachawks's Avatar
Metal Axe
This user has no status.
 
----
 
Last Online: 09-25-2012 07:38 PM
Join Date: Sep 2006
Posts: 73
Post Thanks / Like
Thanks (Given): 22
Thanks (Received): 24
Likes (Given): 0
Likes (Received): 0
Send a message via MSN to isaachawks
Smile [Tut]Opening and compiling .elu files

DISCLAIMER : I WILL NOT BE HELD RESPONSIBLE FOR ANY LOSSES DURING THE PROCESSES OF THIS TUTORIAL.

Other than that, enjoy!

Intro : .elu files are files found in GunZ .mrs files namely model.mrs. It basically is a model of the weapon/armor/etc..

Requirements : You will need two programs to be able to extract and compile .elu files.

1. You will need Blender from blender.org
Download it here : Blender 2.49b Installer for Windows 32 bits

2. You will need Python from python.org (Windows Users)
Download it here : Python 2.6.5 Windows Installer

Install both programs to your computer but don't run them yet.

Afterward steps:-
1. Copy this code,

Code:
#!BPY

# Copyright (c) 2008-2009 Peter S. Stevens
# 
# 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.


"""
Name: 'GUNZ (*.elu, *.ani)...'
Blender: 246
Group: 'Import'
Tooltip: 'Import GUNZ *.elu and/or *.ani game files'
"""

__author__ = 'Peter S. Stevens'
__email__ = 'pstevens:cryptomail*org'
__url__ = ('blender', 'elysiun', 'Project homepage, http://www.ragezone.com/')
__version__ = '09.12.00'
__bpydoc__ = """ \
This script imports GUNZ *.elu and/or *.ani game files.
"""


import Blender
import bpy
import struct


LEFT_TO_RIGHT = Blender.Mathutils.Matrix([-1.0, 0.0, 0.0, 0.0],
                                         [0.0, 0.0, 1.0, 0.0],
                                         [0.0, 1.0, 0.0, 0.0],
                                         [0.0, 0.0, 0.0, 1.0])

ELU_VERSIONS = (0x5004, 0x5005, 0x5006, 0x5007)

ANI_VERSIONS = (0x1001, 0x1003)

DOT_DDS = '.dds'

MAX_INFLUENCES = 4


class MagicError(ValueError):
    pass


class VersionError(ValueError):
    pass


def elu_to_blender_name(name):
    if name.startswith('Bip01 L ') == True:
        return "%s %s.L" % ('Bip01', name[8:])
    
    if name.startswith('Bip01 R ') == True:
        return "%s %s.R" % ('Bip01', name[8:])
    
    return name


def elu_read_material(file_object):
    data_chunk = file_object.read(64)
    
    high_index, \
    low_index = struct.unpack_from('<2I', data_chunk)
    diffuse_color = struct.unpack_from('<4f', data_chunk, 8)
    ambient_color = struct.unpack_from('<4f', data_chunk, 24)
    specular_color = struct.unpack_from('<4f', data_chunk, 40)
    specular_power, \
    emissive = struct.unpack_from('<2f', data_chunk, 56)
    
    material = Blender.Material.New()
    
    material.setRGBCol(diffuse_color[0:3])
    material.setAlpha(diffuse_color[3])
    material.setMirCol(ambient_color[0:3])
    material.setAmb(ambient_color[3])
    material.setSpecCol(specular_color[0:3])
    material.setSpec(specular_power)
    material.setEmit(emissive)
    
    return material


def elu_read_texture(file_object, version):
    texture_name_1 = ''
    texture_name_2 = ''
    
    if version == 0x5004 or version == 0x5005:
        texture_name_1 = file_object.read(40)
        texture_name_2 = file_object.read(40)
    elif version == 0x5006 or version == 0x5007:
        texture_name_1 = file_object.read(256)
        texture_name_2 = file_object.read(256)
    
    texture_name_1 = texture_name_1[0:texture_name_1.find('\0')]
    
    texture = None
    
    try:
        texture = Blender.Texture.Get(texture_name_1)
    except:
        texture = Blender.Texture.New(texture_name_1)
        
        texture.setType('Image')
        
        image = None
        
        try:
            image = Blender.Image.Get(texture_name_1 + DOT_DDS)
        except:
            search_paths = [Blender.sys.dirname(file_object.name), Blender.Get('texturesdir')]
            
            for search_path in search_paths:
                if search_path is not None and len(search_path) > 0:
                    image_file = Blender.sys.join(search_path, texture_name_1 + DOT_DDS)
                    
                    if Blender.sys.exists(image_file):
                        try:
                            image = Blender.Image.Load(image_file)
                        except:
                            Blender.Draw.PupMenu("Warning%%t|Could not load %s." % image_file)
                        
                        break
        finally:
            if image is not None:
                texture.setImage(image)
            else:
                Blender.Draw.PupMenu("Warning%%t|Could not locate %s." % texture_name_1 + DOT_DDS)
    
    double_sided, unknown_1 = struct.unpack('<2I', file_object.read(8))
    
    alpha_percentage = 0
    
    if version == 0x5007:
        alpha_percentage = struct.unpack('<I', file_object.read(4))
    
    if texture is not None and alpha_percentage > 0:
        texture.useAlpha = 1
    
    return texture


def elu_read_mesh(file_object, materials, version):
    def boolean_xor(a, b):
    	return (not a) != (not b)
    
    mesh_name = file_object.read(40)
    parent_mesh_name = file_object.read(40)
    
    mesh_name = mesh_name[0:mesh_name.find('\0')]
    parent_mesh_name = parent_mesh_name[0:parent_mesh_name.find('\0')]
    
    mesh_name = elu_to_blender_name(mesh_name)
    parent_mesh_name = elu_to_blender_name(parent_mesh_name)
    
    print "mesh %s start 0x%x" % (mesh_name, file_object.tell() - 80)
    
    mesh_object = Blender.Object.New('Mesh', mesh_name)
    
    mesh = mesh_object.getData(mesh = True)
    
    if mesh is None:
        if mesh_name.startswith('Bip') == True:
            mesh = Blender.Mesh.New(mesh_name + "~tmp")
        else:
            mesh = Blender.Mesh.New(mesh_name)
        
        mesh_object.link(mesh)
    else:
        if mesh_name.startswith('Bip') == True:
            mesh.name = mesh_name + "~tmp"
        else:
            mesh.name = mesh_name
    
    world_matrix = Blender.Mathutils.Matrix(struct.unpack('<4f', file_object.read(16)), \
                                            struct.unpack('<4f', file_object.read(16)), \
                                            struct.unpack('<4f', file_object.read(16)), \
                                            struct.unpack('<4f', file_object.read(16)))
    
    unknown_0 = struct.unpack('<11f', file_object.read(44))
    
    local_matrix = Blender.Mathutils.Matrix(struct.unpack('<4f', file_object.read(16)), \
                                            struct.unpack('<4f', file_object.read(16)), \
                                            struct.unpack('<4f', file_object.read(16)), \
                                            struct.unpack('<4f', file_object.read(16)))
    
    vertex_position_count = struct.unpack('<I', file_object.read(4))[0]
    
#    print "\tvertex position count %d" % vertex_position_count
    
    for x in xrange(vertex_position_count):
        position = Blender.Mathutils.Vector(struct.unpack('<3f', file_object.read(12)))
        
        mesh.verts.extend(position)
    
    face_count = struct.unpack('<I', file_object.read(4))[0]
    
#    print "\tface count %d" % face_count
    
    for x in xrange(face_count):
        mesh.faces.extend([mesh.verts[y] for y in struct.unpack('<3I', file_object.read(12))])
        
        face = mesh.faces[-1]
        
        face_uvs = []
        
        for y in xrange(len(face.verts)):
            uv = Blender.Mathutils.Vector(struct.unpack('<2f', file_object.read(8)))
            uv.y = float(1.0 - uv.y)
            
            face_uvs.append(uv)
            
            file_object.seek(4, 1)
        
        face.uv = tuple(face_uvs)
        
        file_object.seek(8, 1)
    
    material_index = 0
    
    if version >= 0x5005 and version <= 0x5007:
        # This is an assumption that these values are normals
        for face in mesh.faces:
            face_unknown_0 = Blender.Mathutils.Vector(struct.unpack('<3f', file_object.read(12)))
            
            for vertex in face.verts:
                vertex.no = Blender.Mathutils.Vector(struct.unpack('<3f', file_object.read(12)))
        
        temp_fix = face_count - len(mesh.faces)
        
        for x in xrange(temp_fix):
            file_object.seek(48, 1)
        
        vertex_color_count = struct.unpack('<I', file_object.read(4))[0]
        
#        print "\tvertex color count %d" % vertex_color_count
        
        vertex_colors = []
        
        for x in xrange(vertex_color_count):
            vertex_color = struct.unpack('<3f', file_object.read(12))
            
            vertex_colors.append([int(y * 255.0) for y in vertex_color])
        
        if vertex_color_count > 0:
            mesh.vertexColors = True
            
            for face in mesh.faces:
                for i, vertex in enumerate(face):
                    vertex_color = vertex_colors[vertex.index]
                    
                    face_color = face.col[i]
                    face_color.r = vertex_color[0]
                    face_color.g = vertex_color[1]
                    face_color.b = vertex_color[2]
        
        material_index = struct.unpack('<I', file_object.read(4))[0]
        
#        print "\tmaterial index %d" % material_index
        
        bone_influence_count = struct.unpack('<I', file_object.read(4))[0]
        
#        print "\tbone influence count %d" % bone_influence_count
        
        for x in xrange(bone_influence_count):
            bone_influence_names = []
            
            for y in xrange(MAX_INFLUENCES):
                bone_influence_name = file_object.read(40)
                bone_influence_name = bone_influence_name[0:bone_influence_name.find('\0')]
                
                if len(bone_influence_name) > 0:
                    bone_influence_name = elu_to_blender_name(bone_influence_name)
                    
                    bone_influence_names.append(bone_influence_name)
            
            bone_influence_weights = [y for y in struct.unpack('<8f', file_object.read(32)) if y > 0]
            
            # doesn't seem to be reliable... what might be needed is verifying if
            # the sum of the weights is 1.0 just to be safe
            count = struct.unpack('<I', file_object.read(4))[0]
            
            for y in xrange(len(bone_influence_weights)):
                mesh.addVertGroup(bone_influence_names[y])
                
                mesh.assignVertsToGroup(bone_influence_names[y], \
                                        [x],
                                        bone_influence_weights[y],
                                        Blender.Mesh.AssignModes.ADD)
            
            for y in xrange(MAX_INFLUENCES):
                a, b, c = struct.unpack('<3f', file_object.read(12))
#                print "\t\t%f, %f, %f" % (a, b, c)
    else:
        file_object.seek(4, 1)
        material_index = struct.unpack('<I', file_object.read(4))[0]
    
    if material_index < len(materials):
        material = materials[material_index]
        
        mesh.materials = [material]
        
        textures = material.getTextures()
        
        if len(textures) > 0:
            texture = textures[0].tex
            
            image = texture.getImage()
            
            for face in mesh.faces:
                face.mode = Blender.Mesh.FaceModes.TEX + Blender.Mesh.FaceModes.TWOSIDE
                face.image = image
        else:
            Blender.Draw.PupMenu("Warning%%t|Could not set material for %s mesh." % mesh_name)
    
    mesh_object.setMatrix(world_matrix * LEFT_TO_RIGHT)
    
    if len(parent_mesh_name) > 0:
        bip_check = boolean_xor(mesh_name.startswith('Bip'), parent_mesh_name.startswith('Bip'))
        
        if bip_check == False:
            parent_mesh_object = Blender.Object.Get(parent_mesh_name)
            parent_mesh_object.makeParent([mesh_object])
    
    print "mesh %s end 0x%x" % (mesh_name, file_object.tell())
    
    return mesh_object


def ani_read_mesh_transformations(file_object, armature_object):
    key_frames = {}
    
    armature_pose = armature_object.getPose()
    
    armature_pose_bones = armature_pose.bones
    
    unknown_0 = struct.unpack('<I', file_object.read(4))[0]
    
    mesh_name = file_object.read(40)
    
    mesh_name = mesh_name[0:mesh_name.find('\0')]
    
    mesh_name = elu_to_blender_name(mesh_name)
    
    print "transform %s start 0x%x" % (mesh_name, file_object.tell() - 80)
    
    pose_matrix = Blender.Mathutils.Matrix(struct.unpack('<4f', file_object.read(16)), \
                                           struct.unpack('<4f', file_object.read(16)), \
                                           struct.unpack('<4f', file_object.read(16)), \
                                           struct.unpack('<4f', file_object.read(16)))
    
    translation_count = struct.unpack('<I', file_object.read(4))[0]
    
#    print "translation count %d" % translation_count
    
    for y in xrange(translation_count):
        translation = Blender.Mathutils.Vector(struct.unpack('<3f', file_object.read(12)))
        
        key_frame_second = int(struct.unpack('<I', file_object.read(4))[0] / 60)
        
        key_frames[key_frame_second] = Blender.Mathutils.TranslationMatrix(translation)
    
    rotation_count = struct.unpack('<I', file_object.read(4))[0]
    
#    print "rotation count %d" % rotation_count
    
    for y in xrange(rotation_count):
        x, y, z, w = struct.unpack('<4f', file_object.read(16))
        
        rotation = Blender.Mathutils.Quaternion(w, x, y, z)
        
        key_frame_second = int(struct.unpack('<I', file_object.read(4))[0] / 60)
        
        if key_frame_second in key_frames:
            key_frames[key_frame_second] = rotation.toMatrix().resize4x4() * key_frames[key_frame_second]
        else:
            inverse_parent_pose_matrix = Blender.Mathutils.Matrix()
            inverse_parent_pose_matrix.identity()
            
            if mesh_name in armature_pose_bones.keys():
                if armature_pose_bones[mesh_name].parent is not None:
                    inverse_parent_pose_matrix = armature_pose_bones[mesh_name].parent.poseMatrix.copy() * LEFT_TO_RIGHT
            
            inverse_parent_pose_matrix.invert()
            
            key_frames[key_frame_second] = rotation.toMatrix().resize4x4() * Blender.Mathutils.TranslationMatrix((pose_matrix * inverse_parent_pose_matrix).translationPart())
    
    if mesh_name in armature_pose_bones.keys():
        if len(key_frames) > 0:
            for key_frame_second, key_frame_transformation in key_frames.iteritems():
                if armature_pose_bones[mesh_name].parent is not None:
                    key_frame_transformation *= (armature_pose_bones[mesh_name].parent.poseMatrix.copy() * LEFT_TO_RIGHT)
                
                armature_pose_bones[mesh_name].poseMatrix = key_frame_transformation * LEFT_TO_RIGHT
                armature_pose.update()
                armature_pose_bones[mesh_name].insertKey(armature_object, key_frame_second + 1)
            
            armature_pose_bones[mesh_name].poseMatrix = pose_matrix * LEFT_TO_RIGHT
            armature_pose.update()
        else:
            armature_pose_bones[mesh_name].poseMatrix = pose_matrix * LEFT_TO_RIGHT
            armature_pose.update()
            armature_pose_bones[mesh_name].insertKey(armature_object, 1)
    
    print "transform %s end 0x%x" % (mesh_name, file_object.tell())


def elu_import(file_path):
    file_object = None
    
    try:
        file_object = open(file_path, 'rb')
        
        data_chunk = file_object.read(16)
        
        magic, \
        version, \
        material_count, \
        mesh_count = struct.unpack('<4I', data_chunk)
        
        if magic != 0x0107F060:
            raise MagicError, "Bad magic number, %x" % magic
        
        print "version %d" % version
        
        if version not in ELU_VERSIONS and version not in ANI_VERSIONS:
            raise VersionError, "Bad version number %d" % version
        
        if version in ELU_VERSIONS:
            materials = []
            
            for x in xrange(material_count):
                material = elu_read_material(file_object)
                
                texture = elu_read_texture(file_object, version)
                
                if texture is not None:
                    material.setTexture(0, texture, Blender.Texture.TexCo.UV)
                    
                    if texture.useAlpha == 1:
                        material.setMode(Blender.Material.Modes.TEXFACE + Blender.Material.Modes.TEXFACE_ALPHA)
                    else:
                        material.setMode(Blender.Material.Modes.TEXFACE)
                
                materials.append(material)
            
            mesh_objects = []
            
            for x in xrange(mesh_count):
                mesh_objects.append(elu_read_mesh(file_object, materials, version))
        elif version in ANI_VERSIONS:
            try:
                armature_object = Blender.Object.Get('Armature')
            except ValueError:
                Blender.Draw.PupMenu("Error%%t|The scene does not contain an armature.")
            else:
                scene = Blender.Scene.GetCurrent()
                
                action_name = Blender.sys.basename(file_object.name)
                action_name = action_name[0:action_name.find('.')]
                
                action = Blender.Armature.NLA.NewAction(action_name)
                action.setActive(armature_object)
                
                for x in xrange(mesh_count):
                    ani_read_mesh_transformations(file_object, armature_object)
                
                scene.update(0)
    except IOError, (errno, strerror):
        Blender.Draw.PupMenu("Error%%t|I/O error(%d): %s." % (errno, strerror))
    #except Exception, err:
    #    Blender.Draw.PupMenu("Error%%t|.%s" % err)
    else:
        scene = Blender.Scene.GetCurrent()
        
        if version in ELU_VERSIONS:
            armature_object = Blender.Object.New('Armature')
            
            armature_object.drawMode = Blender.Object.DrawModes.XRAY
            
            armature = armature_object.getData()
            
            if armature is None:
                armature = Blender.Armature.New('Armature')
                armature_object.link(armature)
            
            armature.drawType = Blender.Armature.STICK
            armature.envelopes = False
            armature.vertexGroups = True
            
            armature.makeEditable()
            
            for mesh_object in mesh_objects:
                mesh = mesh_object.getData(mesh = True)
                
                if len(mesh.getVertGroupNames()) > 0:
                    armature_object.makeParent([mesh_object])
                    
                    armature_modifier = mesh_object.modifiers.append(Blender.Modifier.Types.ARMATURE)
                    armature_modifier[Blender.Modifier.Settings.OBJECT] = armature_object
                
                if mesh_object.name.startswith('Bip') == True:
                    edit_bone = Blender.Armature.Editbone()
                    
                    edit_bone.name = mesh_object.name
                    
                    parent_mesh_object = mesh_object.getParent()
                    
                    if parent_mesh_object is not None:
                        edit_bone.parent = armature.bones[parent_mesh_object.name]
                    
                    edit_bone.matrix = mesh_object.getMatrix()
                    
                    armature.bones[edit_bone.name] = edit_bone
                    
                    mesh.hide = True
                    
                    mesh_object.setDrawMode(Blender.Object.DrawModes['TRANSP'])
                    
                    if mesh.users == 0:
                        mesh.verts = None
                        mesh.faces = None
                    
                    scene.objects.unlink(mesh_object)
                else:
                    scene.objects.link(mesh_object)
            
            armature.update()
            
            if len(armature.bones) > 0:
                scene.objects.link(armature_object)
                
                armature_pose = armature_object.getPose()
                
                armature_pose_bones = armature_pose.bones
                
                for armature_pose_bone in armature_pose_bones.values():
                    try:
                        mesh_object = Blender.Object.Get(armature_pose_bone.name)
                    except:
                        pass
                    else:
                        armature_pose_bone.displayObject = mesh_object
            else:
                scene.objects.unlink(armature_object)
        
        scene.update(0)
    finally:
        if file_object is not None:
            file_object.close()


def main():
    def elu_file_selector(file_path):
        if file_path and not Blender.sys.exists(file_path):
            Blender.Draw.PupMenu("Error%%t|The file %s does not exist." % file_path)
        else:
            elu_import(file_path)
    
    Blender.Window.FileSelector(elu_file_selector, 'Ok', Blender.sys.makename(ext='.elu'))


if __name__ == "__main__":
    main()
and save it as gunz_import.py by using notepad
(when saving, choose "Save As..." followed by "Save as type : All Files" and change the file name as "gunz_import.py")
in your .blender/scripts FOLDER.
Some people have problems looking for this folder. If so, then you might have installed it to
"C:\Documents and Settings\user\Application Data\Blender Foundation\Blender\.blender\scripts"

2. Copy this code,

Code:
#!BPY

# Copyright (c) 2008-2009 Peter S. Stevens
# 
# 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.


"""
Name: 'GUNZ (*.elu)...'
Blender: 246
Group: 'Export'
Tooltip: 'Export GUNZ *.elu game files'
"""

__author__ = 'Peter S. Stevens'
__email__ = 'pstevens:cryptomail*org'
__url__ = ('blender', 'elysiun', 'Project homepage, http://www.ragezone.com/')
__version__ = '09.12.00'
__bpydoc__ = """ \
This script exports GUNZ *.elu game files.
"""

import Blender
import BPyMesh
import BPyObject
import struct


LEFT_TO_RIGHT = Blender.Mathutils.Matrix([-1.0, 0.0, 0.0, 0.0],
                                         [0.0, 0.0, 1.0, 0.0],
                                         [0.0, 1.0, 0.0, 0.0],
                                         [0.0, 0.0, 0.0, 1.0])


def blender_to_elu_name(name):
    if name.startswith('Bip01 ') == True:
        if name.endswith('.L'):
            return "%s %s" % ('Bip01 L', name[6:-2])
        
        if name.endswith('.R'):
            return "%s %s" % ('Bip01 R', name[6:-2])
    
    return name


def elu_sort_by_parent(a, b):
    if a.getParent() == b:
        return 1
    elif a == b.getParent():
        return -1
    
    return 0


def elu_recursive_bone_insert(bones, bone):
    index = len(bones)
    
    if bone not in bones:
        if bone.hasParent() == True:
            if bone.parent in bones:
                index = bones.index(bone.parent) + 1
            else:
                index = elu_recursive_bone_insert(bones, bone.parent)
        
        bones.insert(index, bone)
        
        index = index + 1
    
    return index


def elu_triangulate_mesh(mesh):
    if any(len(face.verts) == 4 for face in mesh.faces): 
        scene = Blender.Scene.GetCurrent()
        
        old_mesh_mode = Blender.Mesh.Mode()
        
        Blender.Mesh.Mode(Blender.Mesh.SelectModes['FACE'])
        
        mesh.sel = True
        
        temporary_mesh_object = scene.objects.new(mesh)
        
        mesh.quadToTriangle(0)
        
        old_mesh_mode = Blender.Mesh.Mode(old_mesh_mode)
        
        scene.objects.unlink(temporary_mesh_object)
        
        Blender.Mesh.Mode(old_mesh_mode)


def elu_write_material(file_object, material, index):
    file_object.write(struct.pack('<2I', index, 0xFFFFFFFF))
    
    file_object.write(struct.pack('<3f', *material.getRGBCol()))
    file_object.write(struct.pack('<f', material.getAlpha()))
    file_object.write(struct.pack('<3f', *material.getMirCol()))
    file_object.write(struct.pack('<f', material.getAlpha()))
    file_object.write(struct.pack('<3f', *material.getSpecCol()))
    file_object.write(struct.pack('<f', material.getAlpha()))
    file_object.write(struct.pack('<f', material.getSpec()))
    file_object.write(struct.pack('<f', material.getEmit()))


def elu_write_texture(file_object, texture, version):
    image = texture.getImage()
    
    if image is None:
        raise AttributeError, "Texture (%s) has no image." % texture.getName()
    
    image_file_name =  Blender.sys.basename(image.getFilename())
    
    image_file_name = image_file_name.replace('.dds', '')
    
    image_name = ''
    
    if version == 0x5004 or version == 0x5005:
        image_name = struct.pack('<40s', image_file_name)
    elif version == 0x5006 or version == 0x5007:
        image_name = struct.pack('<256s', image_file_name)
    
    file_object.write(image_name)
    
    file_object.write(image_name)
    
    file_object.write(struct.pack('<2I', 1, 0)) # double sided: should check face mode for Blender.Mesh.FaceModes.TWOSIDE
    
    if version == 0x5007:
        if texture.useAlpha != 0: #(texture.fields & Blender.Texture.USEALPHA) == Blender.Texture.USEALPHA:
            file_object.write(struct.pack('<I', 100))
        else:
            file_object.write(struct.pack('<I', 0))


def elu_write_mesh(file_object, mesh, parent_mesh, world_matrix, local_matrix, material_index, version):
    file_object.write(struct.pack('<40s', blender_to_elu_name(mesh.name)))
    
    if parent_mesh is not None:
        file_object.write(struct.pack('<40s', blender_to_elu_name(parent_mesh.name)))
    else:
        file_object.write(struct.pack('<40x'))
    
    file_object.write(struct.pack('<4f', *world_matrix[0]))
    file_object.write(struct.pack('<4f', *world_matrix[1]))
    file_object.write(struct.pack('<4f', *world_matrix[2]))
    file_object.write(struct.pack('<4f', *world_matrix[3]))
    
    file_object.write(struct.pack('<44x'))
    
    file_object.write(struct.pack('<4f', *local_matrix[0]))
    file_object.write(struct.pack('<4f', *local_matrix[1]))
    file_object.write(struct.pack('<4f', *local_matrix[2]))
    file_object.write(struct.pack('<4f', *local_matrix[3]))
    
    file_object.write(struct.pack('<I', len(mesh.verts)))
    
    for vertex in mesh.verts:
        file_object.write(struct.pack('<3f', *vertex.co))
    
    file_object.write(struct.pack('<I', len(mesh.faces)))
    
    for face in mesh.faces:
        file_object.write(struct.pack('<3I', *[vertex.index for vertex in face.verts]))
        
        if mesh.faceUV == 1:
            for uv in face.uv:
                file_object.write(struct.pack('<2f', uv.x, float(1 - uv.y)))
                
                file_object.write(struct.pack('<4x'))
        else:
            for x in xrange(3):
                file_object.write(struct.pack('<12x'))
        
        file_object.write(struct.pack('<2I', 1, 1))
#        file_object.write(struct.pack('<8x'))
    
    if version >= 0x5005 and version <= 0x5007:
        for face in mesh.faces:
            file_object.write(struct.pack('<3f', *face.no))
            
            for vertex in face.verts:
                file_object.write(struct.pack('<3f', *vertex.no))
        
        if mesh.vertexColors == 0:
            file_object.write(struct.pack('<I', 0))
        else:
            vertex_colors = []
            
            for vertex in mesh.verts:
                vertex_colors.append((1.0, 1.0, 1.0))
            
            for face in mesh.faces:
                for i, vertex in enumerate(face):
                    face_color = face.col[i]
                    
                    red = float(face_color.r) / 255.0
                    green = float(face_color.g) / 255.0
                    blue = float(face_color.b) / 255.0
                    
                    vertex_colors[vertex.index] = (red, green, blue)
            
            file_object.write(struct.pack('<I', len(vertex_colors)))
            
            for vertex_color in vertex_colors:
                file_object.write(struct.pack('<3f', *vertex_color))
        
        file_object.write(struct.pack('<I', material_index))
        
        if len(mesh.getVertGroupNames()) == 0:
            file_object.write(struct.pack('<I', 0))
        else:
            file_object.write(struct.pack('<I', len(mesh.verts)))
            
            for vertex in mesh.verts:
                vertex_influences = mesh.getVertexInfluences(vertex.index)
                
                vertex_weights = []
                
                for vertex_group, vertex_weight in vertex_influences:
                    file_object.write(struct.pack('<40s', blender_to_elu_name(vertex_group)))
                    
                    vertex_weights.append(vertex_weight)
                
                if len(vertex_weights) < 4:
                    file_object.write(struct.pack("<%dx" % ((4 - len(vertex_weights)) * 40)))
                
                file_object.write(struct.pack("<%df" % len(vertex_weights), *vertex_weights))
                
                if len(vertex_weights) < 8:
                    file_object.write(struct.pack("<%dx" % ((8 - len(vertex_weights)) * 4)))
                
                file_object.write(struct.pack('<I', len(vertex_weights)))
                
                file_object.write(struct.pack('<48x'))
    else:
        file_object.write(struct.pack('<4x'))
        file_object.write(struct.pack('<I', material_index))


def elu_bone_to_mesh(bone):
    mesh = Blender.Mesh.Primitives.UVsphere(8, 8, 2.0)
    
    mesh_object = Blender.Object.Get(bone.name)
    
    if mesh_object is None:
        mesh_object = Blender.Object.New('Mesh', bone.name)
    else:
        mesh_object.clrParent()
    
    mesh_object.link(mesh)
    
    mesh.name = bone.name
    
    mesh.update()
    
    world_matrix = bone.matrix['ARMATURESPACE'].copy()
    
    mesh_object.setMatrix(world_matrix)
    
    if bone.hasParent() == True:
        mesh_object_parent = Blender.Object.Get(bone.parent.name)
        
        if mesh_object_parent is not None:
            mesh_object_parent.makeParent([mesh_object])
    
    return mesh_object


def elu_export(file_path):
    mesh_objects = []
    armature_objects = []
    meshes = []
    materials = []
    material_textures = []
    mesh_parents = []
    mesh_world_matrices = []
    mesh_local_matrices = []
    mesh_material_indices = []
    temporary_mesh_objects = []
    
    version = Blender.Draw.Create(4)
    
    block = [('Version: ', version, 4, 7)]
    
    option = Blender.Draw.PupBlock('Export Options', block)
    
    version.val += 0x5000
    
    scene = Blender.Scene.GetCurrent()
    
    scene.update(0)
    
    selected_objects = Blender.Object.GetSelected()
    
    if len(selected_objects) == 0:
        raise IndexError, 'No objects selected.'
    
    for selected_object in selected_objects:
        if selected_object.getType() == 'Mesh':
            for derived_object, derived_object_world_matrix in BPyObject.getDerivedObjects(selected_object, False):
                if derived_object not in mesh_objects:
                    mesh_objects.append(derived_object)
        elif selected_object.getType() == 'Armature':
            armature_objects.append(selected_object)
    
    if len(mesh_objects) == 0:
        raise IndexError, 'No mesh objects selected.'
    else:
        mesh_objects.sort(elu_sort_by_parent)
    
    if len(armature_objects) == 1:
        armature = armature_objects[0].getData()
        
        bones = []
        
        for bone in armature.bones.values():
            elu_recursive_bone_insert(bones, bone)
        
        for bone in bones:
            mesh_object = elu_bone_to_mesh(bone)
            
            scene.objects.link(mesh_object)
            
            temporary_mesh_objects.append(mesh_object)
        
        if len(temporary_mesh_objects) > 0:
            mesh_objects.extend(temporary_mesh_objects)
    
    for mesh_object in mesh_objects:
        mesh = mesh_object.getData(mesh = True)
        
        elu_triangulate_mesh(mesh)
        
        world_matrix = mesh_object.getMatrix('worldspace').copy()
        world_matrix *= LEFT_TO_RIGHT
        
        local_matrix = mesh_object.getMatrix('localspace').copy()
        local_matrix *= LEFT_TO_RIGHT
        
#        BPyMesh.meshCalcNormals(mesh)
        mesh.calcNormals()
        
        meshes.append(mesh)
        
        mesh_world_matrices.append(world_matrix)
        
        mesh_local_matrices.append(local_matrix)
        
        mesh_object_parent = mesh_object.getParent()
        
        if mesh_object_parent is not None and mesh_object_parent in mesh_objects:
            mesh_object_index = mesh_objects.index(mesh_object_parent)
            
            mesh_parents.append(meshes[mesh_object_index])
            
            if mesh_object.name.startswith('Bip') == False:
                mesh_world_matrices[-1] = mesh_world_matrices[mesh_object_index] * mesh_world_matrices[-1]
        else:
            mesh_parents.append(None)
    
    for mesh in meshes:
        mesh_materials = mesh.materials
        
        if len(mesh_materials) > 0:
            material = None
            
            try:
                material = (mm for mm in mesh_materials if mm is not None).next()
            except StopIteration:
                pass
            else:
                material_index = 0
                
                if material not in materials:
                    textures = material.getTextures()
                    
                    if len(textures) == 0:
                        raise AttributeError, "Material (%s) does not contain any textures." % material.getName()
                    else:
                        texture = textures[0].tex
                        
                        material_textures.append(texture)
                    
                    materials.append(material)
                    
                    material_index = len(materials) - 1
                else:
                    material_index = materials.index(material)
                
                mesh_material_indices.append(material_index)
        else:
            if mesh_object.name.startswith('Bip') == True:
                mesh_material_indices.append(0)
            else:
                raise AttributeError, "Mesh (%s) has no assigned materials." % mesh.name
    
    file_object = None
    
    try:
        file_object = open(file_path, 'wb')
        
        file_object.write(struct.pack('<I', 0x0107F060))
        
        file_object.write(struct.pack('<I', version.val))
        
        file_object.write(struct.pack('<I', len(materials)))
        
        file_object.write(struct.pack('<I', len(mesh_objects)))
        
        for x, material in enumerate(materials):
            elu_write_material(file_object, material, x)
            elu_write_texture(file_object, material_textures[x], version.val)
        
        for x, mesh in enumerate(meshes):
            elu_write_mesh(file_object, mesh, mesh_parents[x], mesh_world_matrices[x], mesh_local_matrices[x], mesh_material_indices[x], version.val)
        
        for temporary_mesh_object in temporary_mesh_objects:
            temporary_mesh = temporary_mesh_object.getData(mesh = True)
#            temporary_mesh = BPyMesh.getMeshFromObject(temporary_mesh_object)
            
            scene.objects.unlink(temporary_mesh_object)
            
            if temporary_mesh.users == 0:
                temporary_mesh.faces = None
                temporary_mesh.verts = None
        
        scene.update(0)
    except IOError, (error_number, error_message):
        Blender.Draw.PupMenu("Error%%t|I/O error(%d): %s." % (error_number, error_message))
#    except Exception, error:
#        Blender.Draw.PupMenu("Error%%t|%s." % error)
    finally:
        if file_object is not None:
            file_object.close()


def main():
    def elu_file_selector(file_path):
        if file_path and Blender.sys.exists(file_path):
            option = Blender.Draw.PupMenu("Warning: The file %s exist. Replace it?%%t|Yes|No" % file_path)
            
            if option != 1:
                return
#        try:
        elu_export(file_path)
#        except Exception, error:
#            Blender.Draw.PupMenu("Error%%t|%s." % error)
    
    Blender.Window.FileSelector(elu_file_selector, 'Ok', Blender.sys.makename(ext='.elu'))


if __name__ == "__main__":
    main()
and save it as gunz_export.py by using notepad
(when saving, choose "Save As..." followed by "Save as type : All Files" and change the file name as "gunz_export.py")
in your .blender/scripts FOLDER.

3. Now you will need to startup Blender. (There will be a cmd.exe with the name Blender and the program itself also named Blender. The cmd.exe is the Blender console so if any error occurs, you may check this console.)

4. To open a .elu file, select "File > Import > GUNZ (*.elu, *.ani)..."
5. Go to the folder with your .elu file and select your .elu file.
6. Press "ok".
7. Your model will appear.
8. You may edit it in various ways (but i'm not going to teach you how to do that in this tutorial, you may find out for yourself on how to do so at blender.org - Tutorials).

9. And now, after completing with whatever you did to your model, you will want to compile it back to a .elu file again.
10. To compile a .elu file (from a .blend file), select "File > Export > GUNZ (*.elu)..."
11. Select your filename.
12. Press "ok".
13. Select your version (I honestly do not know the differences yet, but I always select Version 4).
14. Press "ok".
15. You're done~!

FAQ:-
1. If you get a texture has no image error, you will need to add a texture to your model. (Learn that from the blender tutorial site)

2. If you get a no objects selected error, you will just have to press "A" to select your whole model then export it normally.

3. HELP!?! I get Python script error: check console!!! What do I do?
Go to your Blender cmd.exe that is opened together with your Blender program (it's usually the first "Blender tab" on your taskbar). That is your console.

CREDITS:-
Firstly MOST of the credits goes to Phantom* in RageZone forums.
Secondly a little credit goes to me for putting everything together and posting it here.

Click HERE for your ultimate hacking resource!
I don't know why but I only trust GamerzNeeds.
Keep up the good work Trini_G!!! :D
Closed Thread


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -8. The time now is 09:01 PM.