~etc-pgh-launchpad/wildpockets/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
"""
Wild Pockets

Copyright (c) 2010 Carnegie Mellon University

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.

"""

"""
Data structure constructor for models
"""


import solids,importer

modes={ "standard":0, "wireframe":1, "alphatest":2, }

class Model(importer.Importer):
    
    
    def __init__(self):
        self.description=None
        self.collisions=[]
        self.bones=[]
        self.meshes={}
        self.textures={}
        self.mass=None
        self.currentBone=None
        self.currentMesh=None
        self.currentMeshName=None
        self.currentVertex=None
        self.currentCollisionSphere=None
        self.currentCollisionBox=None
        self.physicsFlag=0
        self.centerOfMass=(0,0,0)
        self.inertiaRotation=(1,0,0,0)
        self.inertiaScale=(1,1,1)
        self.scriptFilename=None
        self.scriptClassname=None

    def _checkCurrentBone(self,cmdname):
        """
        Raises an error if a command is attempted that isn't valid without
        a bone
        """
        if self.currentBone==None:
            raise importer.ImporterError("Cannot do '"+cmdname+"' when there is no current bone.")

    def _checkCurrentMesh(self,cmdname):
        """
        Raises an error if a command is attempted that isn't valid without
        a mesh
        """
        if self.currentMesh==None:
            raise importer.ImporterError("Cannot do '"+cmdname+"' when there is no current mesh.")

    def _checkCurrentVertex(self,cmdname):
        """
        Raises an error if a command is attempted that isn't valid without a vertex
        """
        if self.currentVertex==None:
            raise importer.ImporterError("Cannot do '"+cmdname+"' when there is no current vertex.")

    def _checkCurrentCSphere(self,cmdname):
        if self.currentCollisionSphere==None:
            raise importer.ImporterError("Cannot do '"+cmdname+"' when there is no current collision sphere.")

    def _checkCurrentCBox(self,cmdname):
        if self.currentCollisionBox==None:
            raise importer.ImporterError("Cannot do '"+cmdname+"' when there is no current collision box.")

    def _checkCurrentWeight(self,cmdname):
        if self.currentWeight==None:
            raise importer.ImporterError("Cannot do '"+cmdname+"' when there is no current weight.")


    def _addCollisionSphere(self,name,position=(0,0,0),radius=1,bone=0):
        self.currentCollisionSphere={
            "name":name,
            "type":"sphere",
            "position":position,
            "radius":radius,
            "bone":bone
        }
        self.collisions.append(self.currentCollisionSphere)

    def _addCollisionBox(self,name,position=(0,0,0),size=(0,0,0),rotation=(1,0,0,0),bone=0):
        self.currentCollisionBox={
            "name":name,
            "type":"box",
            "position":position,
            "size":size,
            "rotation":rotation,
            "bone":bone
        }
        self.collisions.append(self.currentCollisionBox)

    def _addWeight(self,name,position=(0,0,0),magnitude=1,bone=0):
        self.currentWeight={
            "name":name,
            "position":position,
            "magnitude":magnitude,
            "bone":bone
        }
        self.m_weights.append(self.currentWeight)

    def setdescription(self,description):
        self.description=description

    def setmass(self,mass):
        self.mass=float(mass)

    def addbone(self,boneName,boneParent):
        """
        Adds a bone to the model
        """
        if boneName in self.bones:
            raise importer.ImporterError("Attempted to add a bone named '"+boneName+"', but a bone by the same name already exists.")
        self.currentBone={
            "parentName":boneParent,
            "position":(0,0,0),
            "rotation":(1,0,0,0),
            "scale":(1,1,1)
        }
        self.bones.append((boneName,self.currentBone))

    def bonepos(self,x,y,z):
        self._checkCurrentBone("bonepos")
        self.currentBone["position"]=(float(x),float(y),float(z))

    def bonequat(self,w,x,y,z):
        self._checkCurrentBone("bonequat")
        self.currentBone["rotation"]=tuple(map(float,(w,x,y,z)))

    def bonescale(self,sx,sy,sz):
        self._checkCurrentBone("bonescale")
        self.currentBone["scale"]=tuple(map(float,(sx,sy,sz)))

    
    def addmesh(self,meshname):
        if meshname in self.meshes:
            raise importer.ImporterError("Attempted to add a mesh with name '"+meshname+"', but that name was already used.")
        self.currentMesh={
            "vertices":[],
            "feedOrder":[],
            "texture":None,
            "bumpmap":None,
            "glossmap":None,
            "bumptype":None,
            "meshmode":(modes["standard"]),
            "color":None,
        }
        self.meshes[meshname]=self.currentMesh
        self.currentMeshName=meshname
        
    def meshmode(self, modename):
        self._checkCurrentMesh("meshmode")
        self.currentMesh["meshmode"] = modes[modename]

    def texture(self,texturePath):
        """
        Sets the texture image of the current mesh

        texturePath: Path to the texture
        """
        self._checkCurrentMesh("texture")
        self.textures[texturePath]="exists"
        self.currentMesh["texture"]=texturePath

    def bumpmap(self,texturePath):
        """
        Sets the bump map of the current path (mutually exclusive with normal map)

        texturePath: path to the texture
        """
        self._checkCurrentMesh("bumpmap")
        if(self.currentMesh["bumpmap"] != None):
            raise importer.ImporterError("Attempted to add a bumpmap to the current mesh, but a bump or normal map was already added.")
        self.textures[texturePath]="exists"
        self.currentMesh["bumpmap"]=texturePath
        self.currentMesh["bumptype"]="bump"
    
    def normalmap(self,texturePath):
        """
        Sets the bump map of the current path (mutually exclusive with normal map)

        texturePath: path to the texture
        """
        self._checkCurrentMesh("normalmap")
        if(self.currentMesh["bumpmap"] != None):
            raise importer.ImporterError("Attempted to add a normal map to the current mesh, but a bump or normal map was already added.")
        self.textures[texturePath]="exists"
        self.currentMesh["bumpmap"]=texturePath
        self.currentMesh["bumptype"]="normal"

    def glossmap(self,texturePath):
        """
        Sets the gloss map of the current path

        texturePath: path to the texture
        """
        self._checkCurrentMesh("glossmap")
        if(self.currentMesh["glossmap"] != None):
            raise importer.ImporterError("Attempted to add a gloss map to the current mesh, but a gloss map was already added.")
        self.textures[texturePath]="exists"
        self.currentMesh["glossmap"]=texturePath

    def addvertex(self,x,y,z):
        self._checkCurrentMesh("addvertex")
        try:
            x=float(x)
            y=float(y)
            z=float(z)
        except Exception,e:
            raise importer.ImportError("Vertex coordinates were not convertible to finite decimal values.")
        self.currentVertex={
            "coords":(x,y,z),
            "normal":(0,0,0),
            "texture":(0,0),
            "weights":None
        }
        self.currentMesh["vertices"].append(self.currentVertex)

    def normal(self,x,y,z):
        #note: we've decided to temporarily account for bad float values by simply smashing them to 0. Not the
        #      most robust solution, but we need the script to not crash until we can fix the loader
        try:
            x=float(x)
            y=float(y)
            z=float(z)
        except Exception,e:
            x=0
            y=0
            z=0
            
        self._checkCurrentVertex("normal")
        self.currentVertex["normal"]=(x,y,z)

    def texcoord(self,x,y,z):
        self._checkCurrentVertex("texcoord")
        self.currentVertex["texture"]=(x,y,z)

    def weights(self,i1,w1,i2,w2,i3,w3,i4,w4):
        self._checkCurrentVertex("weights")
        self.currentVertex["weights"]=((i1,w1),(i2,w2),(i3,w3),(i4,w4))

    def addtri(self,t1,t2,t3):
        self._checkCurrentMesh("addtri")
        self.currentMesh["feedOrder"].append(t1)
        self.currentMesh["feedOrder"].append(t2)
        self.currentMesh["feedOrder"].append(t3)

    def meshtoAABoundingBox(self):
        self._checkCurrentMesh("meshtoAABoundingBox")
        vertices=[]
        for v in self.currentMesh["vertices"]:
            vertices.append(v["coords"])
        center,extent=solids.pointsToAABB(vertices)
        self._addCollisionBox(
            self.currentMeshName,
            center,extent
        )

        del(self.meshes[self.currentMeshName])
        self.currentMeshName=None
        self.currentMesh=None

    def meshtoSphere(self):
        self._checkCurrentMesh("meshtoSphere")
        vertices=[]
        for v in self.currentMesh["vertices"]:
            vertices.append(v["coords"])
        center,radius=solids.pointsToSphere(vertices)
        self._addCollisionSphere(
            self.currentMeshName,
            center,radius
        )

        del(self.meshes[self.currentMeshName])
        self.currentMeshName=None
        self.currentMesh=None

    def meshtoBox(self):
        self._checkCurrentMesh("meshtoBox")
        vertices=[]
        for v in self.currentMesh["vertices"]:
            vertices.append(v["coords"])
        center,rotation,extents=solids.pointsToBox(vertices)
        self._addCollisionBox(
            self.currentMeshName,
            center,extents,rotation
        )

        del(self.meshes[self.currentMeshName])
        self.currentMeshName=None
        self.currentMesh=None

    def cbox(self,name):
        self._addCollisionBox(name)

    def cbcenter(self,cx,cy,cz):
        self._checkCurrentCBox("cbcenter")
        self.currentCollisionBox["position"]=tuple(map(float,(cx,cy,cz)))

    def cbsize(self,bx,by,bz):
        self._checkCurrentCBox("cbsize")
        self.currentCollisionBox["size"]=tuple(map(float,(bx,by,bz)))

    def cbquat(self,w,x,y,z):
        self._checkCurrentCBox("cbquat")
        self.currentCollisionBox["rotation"]=tuple(map(float,(w,x,y,z)))

    def cbbone(self,boneID):
        self._checkCurrentCBox("cbbone")
        self.currentCollisionBox["bone"]=int(boneID)

    def csphere(self,name):
        self._addCollisionSphere(name)

    def cscenter(self,cx,cy,cz):
        self._checkCurrentCSphere("cscenter")
        self.currentCollisionSphere["position"]=tuple(map(float,(cx,cy,cz)))

    def csradius(self,r):
        self._checkCurrentCSphere("csradius")
        self.currentCollisionSphere["radius"]=float(r)

    def csbone(self,boneID):
        self._checkCurrentCSphere("csbone")
        self.currentCollisionSphere["bone"]=int(boneID)

    def compos(self,x,y,z):
        if self.physicsFlag==2:
            raise importer.ImporterError("Cannot specify 'compos' command when any of the 'moi' commands have been specified.")
        self.physicsFlag=1
        self.centerOfMass=(float(x),float(y),float(z))

    def moipos(self,x,y,z):
        if self.physicsFlag==1:
            raise importer.ImporterError("Cannot specify 'moipos' command when 'compos' has already been specified.")
        self.physicsFlag=2
        self.centerOfMass=(float(x),float(y),float(z))

    def moiquat(self,w,x,y,z):
        if self.physicsFlag==1:
            raise importer.ImporterError("Cannot specify 'moiquat' command when 'compos' has already been specified.")
        self.physicsFlag=2
        self.inertiaRotation=(float(w),float(x),float(y),float(z))

    def moiscale(self,x,y,z):
        if self.physicsFlag==1:
            raise importer.ImporterError("Cannot specify 'moiscale' command when 'compos' has already been specified.")
        self.physicsFlag=2
        self.inertiaScale=(float(x),float(y),float(z))

    def luafilename(self,fname):
        self.scriptFilename=str(fname)

    def luaclassname(self,cname):
        self.scriptClassname=str(cname)
    
    def __str__(self):
        nl="\n"
        result=""
        result += "description: "+str(self.description)+nl
        result += "collisions: "+nl
        for c in self.collisions:
            result += "  "+str(c)+nl
        result += "bones:" +nl
        boneCount=0
        for (boneName,boneData) in self.bones:
            result += "  bone "+str(boneCount)+": "+boneName+" -> "+boneData["parentName"]+nl
            result += "    position: "+str(boneData["position"])+nl
            result += "    rotation: "+str(boneData["rotation"])+nl
            result += "    scale: "+str(boneData["scale"])+nl+nl
            boneCount += 1
        return result