Advertisement
Guest User

sueastside

a guest
Dec 21st, 2009
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.69 KB | None | 0 0
  1. #-*- coding: UTF-8 -*-
  2.  
  3. import os
  4. from string import Template
  5. import re
  6.                              
  7.                      
  8. texture = Template("""                    
  9.        <texture name=\"$NAME\">
  10.            <file>$FILE</file>
  11.        </texture>  
  12. """)
  13.  
  14. material = Template("""
  15.        <material name=\"$NAME\">
  16.            <texture>$TEXTURE</texture>
  17.            $OPTIONS
  18.        </material>
  19. """)
  20.  
  21. library = Template("""
  22.        <library>
  23.            $FACTORIES
  24.        </library>
  25. """)
  26.  
  27. world = Template("""
  28. <world>
  29.    <textures>
  30.    $TEXTURES
  31.    </textures>
  32.    
  33.    <materials>
  34.    $MATERIALS
  35.    </materials>
  36.    
  37.    $LIBARIES
  38.    
  39.    
  40.    $FACTORIES
  41.    
  42.    
  43.    <settings>
  44.            <clearzbuf>yes</clearzbuf>
  45.            <clearscreen>yes</clearscreen>
  46.    </settings>
  47.    
  48.    <start name=\"Camera\">
  49.            <sector>Scene</sector>
  50.            <position x=\"0\" y=\"0\" z=\"-5\" />
  51.    </start>
  52.    
  53.    <sector name=\"Scene\">
  54.    $OBJECTS
  55.    
  56.    <light name=\"Lamp\">
  57.        <center x=\"0\" y=\"5\" z=\"0\" />
  58.        <color red=\"0.9\" green=\"0.9\" blue=\"1.0\" />
  59.        <radius>50</radius>
  60.        <attenuation c=\"0\" l=\"0\" q=\"0.1\" />
  61.    </light>
  62.        
  63.    </sector>
  64. </world>
  65. """)
  66.  
  67. factory = Template("""
  68. <meshfact name=\"$NAME\">
  69.    <plugin>$PLUGIN</plugin>
  70.    <params>
  71.    $PARAMS
  72.    </params>
  73. </meshfact>
  74. """)
  75.  
  76. object = Template("""
  77. <meshobj name=\"$NAME\">
  78.    <plugin>$PLUGIN</plugin>
  79.    <params>
  80.    <factory>$FACTORY</factory>
  81.    </params>
  82. </meshobj>
  83. """)
  84.  
  85. renderbuffer = Template("""                    
  86.        <$TAG name=\"$NAME\" $EXTRA components=\"$NR\" type=\"$TYPE\">
  87.            $CONTENTS
  88.        </$TAG>  
  89. """)
  90.  
  91. def RenderBuffer(name, nr, type, contents, extra="checkelementcount=\"no\"", tag="renderbuffer"):
  92.     text = ""
  93.     for c in contents:
  94.       text += c + "\n"
  95.     return renderbuffer.substitute(NAME=name, NR=nr, TYPE=type, CONTENTS=text, EXTRA=extra, TAG=tag)
  96.    
  97. def IndexBuffer(contents, tag="indexbuffer"):
  98.     text = ""
  99.     for c in contents:
  100.       text += c + "\n"
  101.     return renderbuffer.substitute(NAME="index", NR=1, TYPE="uint", CONTENTS=text, EXTRA="indices=\"yes\"", TAG=tag)
  102.    
  103. def Element(v):
  104.     text = "<e "
  105.     for i,e in enumerate(v):
  106.         text += "c"+str(i)+"=\"" + str(e) + "\" "
  107.     return text + "/>"
  108.  
  109. def Factory(name, plugin, params):
  110.     text = factory.substitute(NAME=str(name), PLUGIN=plugin, PARAMS=params)
  111.     return text
  112.    
  113. def Object(name, plugin, factory):
  114.     plugin = plugin.replace(".factory", "")
  115.     text = object.substitute(NAME=str(name), PLUGIN=plugin, FACTORY=factory)
  116.     return text
  117.  
  118. def Change(bool, name):
  119.     def blah(*args):
  120.         if bool:
  121.             args = args + ("", name, )
  122.         return RenderBuffer(*args)
  123.     return blah
  124.  
  125. def group(lst, n):
  126.     import itertools
  127.     """group([0,3,4,10,2,3], 2) => iterator
  128.  
  129.    Group an iterable into an n-tuples iterable. Incomplete tuples
  130.    are discarded e.g.
  131.  
  132.    >>> list(group(range(10), 3))
  133.    [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
  134.    """
  135.     return itertools.izip(*[itertools.islice(lst, i, None, n) for i in range(n)])
  136.  
  137.  
  138. def main():
  139.     model = open("data/3dobjs/base.obj", 'r')
  140.  
  141.     plugin = "crystalspace.mesh.loader.factory.animesh"
  142.    
  143.     textures = ""
  144.     materials = ""
  145.     factories = ""
  146.     objects = ""
  147.    
  148.     size = [0.25, 0.25, 0.25]
  149.    
  150.     vertices=[]
  151.     tc=[]
  152.     tcnew=[]
  153.    
  154.     currentsub = "main"
  155.     indicess={}
  156.    
  157.     for line in model.readlines():
  158.       if line.startswith('v '):
  159.         m = re.findall("[+-]?\d+\.\d+", line)
  160.         m = [s*float(v) for v,s in zip(m, size)]
  161.         vertices.append(Element(m))
  162.       elif line.startswith('vt '):
  163.         m = re.findall("[+-]?\d+\.\d+", line)
  164.         tc.append(Element(m))
  165.       elif line.startswith('g '):
  166.         #currentsub = line.split(" ")[1] # disabled submeshes, put everything in 'main' submesh
  167.         if currentsub not in indicess.keys():
  168.           indicess[currentsub] = []
  169.       elif line.startswith('f '):
  170.         m = re.findall("\d+", line)
  171.         m = group(m, 2)
  172.         m = [(int(x)-1, int(y)-1) for x, y in m] # obj is 1 based, cs is 0 based, so -1
  173.         if len(tcnew) < len(tc):
  174.           tcnew = len(tc)*['<e c0="0.0" c1="0.0" />']
  175.         for v, t in m:
  176.           tcnew[v] = tc[t]
  177.         #triangulate
  178.         tt = [0,1,2] if len(m)==3 else [0, 1, 2, 3, 0, 2]
  179.         for i in tt:
  180.           e = m[i][0]
  181.           indicess[currentsub].append(Element([e]))
  182.    
  183.     data = ""
  184.     RenderBufferP = Change(True, "vertex")
  185.     data += RenderBufferP("position", 3, "float", vertices)
  186.     RenderBufferP = Change(True, "texcoord")
  187.     data += RenderBufferP("texture coordinate 0", 2, "float", tcnew)
  188.    
  189.     data += "<boneinfluences>\n"
  190.     for i in range(len(vertices)*4):
  191.       data += '        <bi bone="%d" weight="%.4f"/>\n' % (0, 0.0)
  192.     data += "</boneinfluences>\n"
  193.    
  194.     for name in indicess:
  195.       data += "<submesh name=\""+name.strip()+"\">" + "<material>skin</material>" + IndexBuffer(indicess[name],"index") +"</submesh>\n"
  196.    
  197.     data += "<skeleton>rig</skeleton>"
  198.    
  199.     morphtargets={}
  200.     import os, glob
  201.     for target in glob.glob( os.path.join('data/targets/macrodetails/', 'universal-*.target') ):
  202.       name = os.path.splitext(os.path.basename(target))[0]
  203.       targetf = open(target, 'r')
  204.       print "Converting target:", target
  205.       morphtargets[name] = len(vertices)*['<e c0="0.0" c1="0.0" c2="0.0" />']
  206.       for line in targetf.readlines():
  207.         i = int(re.findall("\d+", line)[0])
  208.         m = re.findall("[+-]?\d+\.\d+", line)
  209.         m = [s*float(v) for v,s in zip(m, size)]
  210.         morphtargets[name][i] = Element(m)
  211.       targetf.close()
  212.     RenderBufferP = Change(True, "offsets")
  213.     for name in morphtargets:
  214.       data += "<morphtarget name=\""+name.strip()+"\">" + RenderBufferP("", 3, "float", morphtargets[name]) +"</morphtarget>\n"
  215.    
  216.     factories += "<textures><texture name=\"skin\"><file>skin.png</file></texture></textures>"
  217.     factories += "<materials><material name=\"skin\"><texture>skin</texture></material></materials>"  
  218.     factories += "<library>rig</library>\n"
  219.     factories += Factory("testf", plugin, data) + "\n"
  220.     objects += Object("test", plugin, "testf") + "\n"
  221.    
  222.     text = library.substitute(FACTORIES=factories)
  223.     f = open('factory', 'w')
  224.     f.write(text)
  225.     f.close()
  226.     libaries = "<library>factory</library>"
  227.    
  228.     text = world.substitute(TEXTURES=textures, MATERIALS=materials, LIBARIES=libaries, OBJECTS=objects, FACTORIES="")
  229.    
  230.     f = open('world', 'w')
  231.     f.write(text)
  232.     f.close()
  233.    
  234.    
  235.  
  236. if __name__ == "__main__":
  237.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement