-
Notifications
You must be signed in to change notification settings - Fork 3
/
io_export_psx_tmesh.py
2202 lines (2173 loc) · 112 KB
/
io_export_psx_tmesh.py
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# bpy. app. debug = True
bl_info = {
"name": "PSX TMesh exporter",
"author": "Schnappy, TheDukeOfZill",
"blender": (2,7,9),
"version": (0,0,4),
"location": "File > Import-Export",
"description": "Export psx data format",
"category": "Import-Export"
}
import os
import bpy
import bmesh
import unicodedata
import subprocess
from math import radians, degrees, floor, cos, sin, sqrt, ceil
from mathutils import Vector
from collections import defaultdict
from bpy.props import (CollectionProperty,
StringProperty,
BoolProperty,
EnumProperty,
FloatProperty,
IntProperty
)
from bpy_extras.io_utils import (ExportHelper,
axis_conversion)
from bpy_extras.object_utils import world_to_camera_view
from re import sub
class ExportMyFormat(bpy.types.Operator, ExportHelper):
bl_idname = "export_psx.c";
bl_label = "PSX compatible scene exporter";
bl_options = {'PRESET'};
filename_ext = ".c";
exp_Triangulate = BoolProperty(
name="Triangulate meshes ( Destructive ! )",
description="Triangulate meshes (destructive ! Do not use your original file)",
default=False,
)
exp_Scale = FloatProperty(
name="Scale",
description="Scale of exported mesh.",
min=1, max=1000,
default=65.0,
)
exp_Precalc = BoolProperty(
name="Use precalculated BGs",
description="Render backgrounds and converts them to TIMs",
default=False,
)
# ~ exp_ShowPortals = BoolProperty(
# ~ name="Render Portals in precalculated BGs",
# ~ description="Useful for debugging",
# ~ default=False,
# ~ )
exp_useIMforTIM = BoolProperty(
name = "Use ImageMagick",
description = "Use installed Image Magick's convert tool to convert PNGs to 8/4bpp",
default = False
)
exp_convTexToPNG = BoolProperty(
name = "Convert images to PNG",
description = "Use installed Image Magick's convert tool to convert images to PNG.",
default = True
)
exp_TIMbpp = BoolProperty(
name = "Use 4bpp TIMs",
description = "Converts rendered backgrounds to 4bpp TIMs instead of the default 8bpp",
default = False
)
exp_LvlNbr = IntProperty(
name="Level number",
description="That number is used in the symbols name.",
min=1, max=10,
default=0,
)
exp_expMode = BoolProperty(
name="Use blend file directory for export",
description="Files will be exported in the same folder as the blend file.",
default=False,
)
exp_CustomTexFolder = StringProperty(
name = "Textures Dir",
description = "By default, the script looks for / saves textures in the ./TEX folder. You can tell it to use a different folder.",
default="TEX"
)
exp_XAmode = IntProperty(
name="XA mode",
description ="XA sector size : 0 = 2352, 1=2336",
min=0, max=1,
default=1
)
exp_isoCfg = StringProperty(
name="mkpsxiso config folder",
description = "Where should we look for mkpsxiso's config file ?",
default= "." + os.sep + "config" + os.sep + "3dcam.xml"
)
exp_CompressAnims = BoolProperty(
name="Compress animation data",
description="Use Delta/RLE compression on animations 's data.",
default=False,
)
exp_mixOverlapingStrips = BoolProperty(
name="Mix overlaping nla animation tracks",
description="If set, the resulting animation will be an interpolation between the overlapping nla tracks.",
default = False,
)
def execute(self, context):
### Globals declaration
global nextTpage, freeTpage
global nextClutSlot, freeClutSlot
global tpageY
global TIMbpp
global timFolder
global objAnims
XAmode = self.exp_XAmode
# Set Scale
scale = self.exp_Scale
### Functions
def psxLoc(location, scale=scale):
return round(location * scale)
def triangulate_object(obj):
# Triangulate an object's mesh
# Source : https://blender.stackexchange.com/questions/45698/triangulate-mesh-in-python/45722#45722
me = obj.data
# Get a BMesh representation
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method=0, ngon_method=0)
# Finish up, write the bmesh back to the mesh
bm.to_mesh(me)
bm.free()
def CleanName(strName):
# Removes specials characters, dots ans space from string
name = strName.replace(' ','_')
name = name.replace('.','_')
name = unicodedata.normalize('NFKD',name).encode('ASCII', 'ignore').decode()
return name
### Space utilities
def isInFrame(scene, cam, target):
# Checks if an object is in view frame
position = world_to_camera_view(scene, cam, target.location)
if (
(position.x < 0 or position.x > 1 ) or
(position.y < 0 or position.y > 1 ) or
(position.z < 0 )
) :
return False
else:
return True
def isInPlane(plane, obj):
# Checks if 'obj' has its coordinates contained between the plane's coordinate.
# Obj is a dict
# If 'obj' is contained, returns 1.
# If 'obj' is partly contained, returns which side (S == 2, W == 4, N == 8, E == 6) it's overlapping.
# If 'obj' is not contained in 'plane', returns 0.
if (
(plane.get('x1') <= obj.get('x1') and plane.get('x2') >= obj.get('x2') ) and
(plane.get('y1') <= obj.get('y1') and plane.get('y2') >= obj.get('y2') )
):
return 1
# Overlap on the West side of the plane
if (
( plane.get('x1') >= obj.get('x1') and plane.get('x1') <= obj.get('x2') ) and
( plane.get('y1') <= obj.get('y2') and plane.get('y2') >= obj.get('y1') )
):
return 4
# Overlap on the East side of the plane
if (
( plane.get('x2') <= obj.get('x2') and plane.get('x2') >= obj.get('x1') ) and
( plane.get('y1') <= obj.get('y2') and plane.get('y2') >= obj.get('y1') )
):
return 6
# Overlap on the North side of the plane
if (
( plane.get('y2') <= obj.get('y2') and plane.get('y2') >= obj.get('y1') ) and
( plane.get('x1') <= obj.get('x1') and plane.get('x2') >= obj.get('x2') )
):
return 8
# Overlap on the South side of the plane
if (
( plane.get('y1') >= obj.get('y1') and plane.get('y1') <= obj.get('y2') ) and
( plane.get('x1') <= obj.get('x1') and plane.get('x2') >= obj.get('x2') )
):
return 2
else:
return 0
def getSepLine(plane, side):
# Construct the line used for BSP generation from 'plane' 's coordinates, on specified side (S, W, N, E)
# Returns an array of 3 values
if side == 'N':
return [ LvlPlanes[plane]['x1'], LvlPlanes[plane]['y2'], LvlPlanes[plane]['x2'], LvlPlanes[plane]['y2'] ]
if side == 'S':
return [ LvlPlanes[plane]['x1'], LvlPlanes[plane]['y1'], LvlPlanes[plane]['x2'], LvlPlanes[plane]['y1'] ]
if side == 'W':
return [ LvlPlanes[plane]['x1'], LvlPlanes[plane]['y1'], LvlPlanes[plane]['x1'], LvlPlanes[plane]['y2'] ]
if side == 'E':
return [ LvlPlanes[plane]['x2'], LvlPlanes[plane]['y1'], LvlPlanes[plane]['x2'], LvlPlanes[plane]['y2'] ]
def checkLine(lineX1, lineY1 ,lineX2 ,lineY2, objX1, objY1, objX2, objY2):
# Returns wether object spanning from objXY1 to objXY2 is Back, Front, Same or Intersecting the line
# defined by points (lineXY1, lineXY2)
val1 = ( objX1 - lineX1 ) * ( lineY2-lineY1 ) - ( objY1 - lineY1 ) * ( lineX2 - lineX1 )
# Rounding to avoid false positives
val1 = round(val1, 4)
val2 = ( objX2 - lineX1 ) * ( lineY2-lineY1 ) - ( objY2 - lineY1 ) * ( lineX2 - lineX1 )
val2 = round(val2, 4)
if ( (val1 > 0) and (val2 > 0) ):
return "front"
elif ( (val1 < 0) and (val2 < 0) ):
return "back"
elif ( (val1 == 0) and (val2 == 0) ):
return "connected"
elif (
( (val1>0) and (val2==0) ) or
( (val1==0) and (val2>0) )
):
return "front"
elif (
( (val1<0) and (val2==0) ) or
( (val1==0) and (val2<0) )
):
return "back"
elif (
( (val1<0) and (val2>0) ) or
( (val1>0) and (val2<0) )
):
return "intersect"
def objVertLtoW(target):
# Converts an object's vertices coordinates from local to global
worldPos = []
mw = target.matrix_world
mesh = bpy.data.meshes[ target.name ]
for vertex in mesh.vertices:
worldPos.append( mw * vertex.co * scale )
return worldPos
def objVertWtoS(scene, cam, target, toScale = 1):
# Converts an object's vertices coordinates from local to screen coordinates
screenPos = []
# Get objects world matrix
mw = target.matrix_world
# Get object's mesh
mesh = bpy.data.meshes[ target.name ]
# For each vertex in mesh, get screen coordinates
for vertex in mesh.vertices:
# Get meshes world coordinates
screenPos.append( world_to_camera_view( scene, cam, ( mw * vertex.co ) ) )
if toScale:
# Get current scene rsolution
resX = scene.render.resolution_x
resY = scene.render.resolution_y
# Scale values
for vector in screenPos:
# ~ vector.x = int( resX * vector.x ) < 0 ? 0 : int( resX * vector.x ) > 320 ? 320 : int( resX * vector.x )
vector.x = max ( 0, min ( resX, int( resX * vector.x ) ) )
vector.y = resY - max ( 0, min ( resY, int( resY * vector.y ) ) )
vector.z = int( vector.z )
return screenPos
### Texture utilities
def convertBGtoTIM( filePathWithExt, colors = 256, bpp = 8, timX = 640, timY = 0, clutX = 0, clutY = 480, transparency = 'alpha'):
global timFolder
# By default, converts a RGB to 8bpp, 256 colors indexed PNG, then to a 8bpp TIM image
filePathWithoutExt = filePathWithExt[ : filePathWithExt.rfind('.') ]
ext = filePathWithExt[ filePathWithExt.rfind('.') + 1 : ]
fileBaseName = os.path.basename(filePathWithoutExt)
# For windows users, add '.exe' to the command
exe = ""
if os.name == 'nt':
exe = ".exe"
# 8bpp TIM needs < 256 colors
if bpp == 8:
# Clamp number of colors to 256
colors = min( 255, colors )
elif bpp == 4:
# 4bpp TIM needs < 16 colors
# Clamp number of colors to 16
colors = min( 16, colors )
if transparency == "alpha":
transpMethod = "-usealpha"
elif transparency == "black":
transpMethod = "-b"
elif transparency == "nonblack":
transpMethod = "-t"
# Image magick's convert can be used alternatively ( https://imagemagick.org/ )
if self.exp_useIMforTIM :
# ImageMagick alternative
subprocess.call( [ "convert" + exe, filePathWithExt, "-colors", str( colors ), filePathWithoutExt + ".png" ] )
filePathWithExt = filePathWithoutExt + ".png"
print("Using IM on " + filePathWithExt)
else:
if self.exp_convTexToPNG:
if ext != "png" or ext != "PNG":
# Convert images to PNG
subprocess.call( [ "convert" + exe, filePathWithExt, "-colors", str( colors ), filePathWithoutExt + ".png" ] )
filePathWithExt = filePathWithoutExt + ".png"
# Quantization of colors with pngquant ( https://pngquant.org/ )
subprocess.run( [ "pngquant" + exe, "-v", "--force", str( colors ), filePathWithExt, "--ext", ".pngq" ] )
# Convert to tim with img2tim ( https://github.com/Lameguy64/img2tim )
subprocess.call( [ "img2tim" + exe, transpMethod, "-bpp", str( bpp ), "-org", str( timX ), str( timY ), "-plt" , str( clutX ), str( clutY ),"-o", timFolder + os.sep + fileBaseName + ".tim", filePathWithExt + "q" ] )
### VRAM utilities
def VramIsFull( size ):
# Returns True if not enough space in Vram for image
# Transpose bpp to bitshift value
global nextTpage, freeTpage
global nextClutSlot, freeClutSlot
global tpageY
if TIMbpp == 8:
shift = 1
elif TIMbpp == 4:
shift = 2
else:
shift = 0
# Get image width in vram
if not size:
imageWidth = size[0] >> shift
else:
imageWidth = size >> shift
# Divide by cell width ( 64 pixels )
imageWidthInTPage = ceil( imageWidth / 64 )
if ( tpageY == 0 and
nextTpage + ( imageWidthInTPage * 64 ) < 1024 and
freeTpage - imageWidthInTPage > 0
) :
return False
elif ( tpageY == 256 and
nextTpage + ( imageWidthInTPage * 64 ) < 960 and
freeTpage - imageWidthInTPage > 1
) :
return False
else:
return True
def setNextTimPos( image ):
# Sets nextTpage, freeTpage, tpageY, nextClutSlot, freeClutSlot to next free space in Vram
# Transpose bpp to bitshift value
global nextTpage, freeTpage
global nextClutSlot, freeClutSlot
global tpageY
if TIMbpp == 8:
shift = 1
elif TIMbpp == 4:
shift = 2
else:
shift = 0
# Get image width in vram
imageWidth = image.size[0] >> shift
# Divide by cell width ( 64 pixels )
imageWidthInTPage = ceil( imageWidth / 64 )
if ( tpageY == 0 and
nextTpage + ( imageWidthInTPage * 64 ) < 1024 and
freeTpage - imageWidthInTPage > 0
) :
nextTpage += imageWidthInTPage * 64
freeTpage -= imageWidthInTPage
nextClutSlot += 1
freeClutSlot -= 1
elif ( tpageY == 256 and
nextTpage + ( imageWidthInTPage * 64 ) < 960 and
freeTpage - imageWidthInTPage > 1
) :
nextTpage += imageWidthInTPage * 64
freeTpage -= imageWidthInTPage
nextClutSlot += 1
freeClutSlot -= 1
else:
tpageY = 256
nextTpage = 320
nextClutSlot += 1
freeClutSlot -= 1
def linearToRGB(component):
# Convert linear Color in range 0.0-1.0 to range 0-255
# https://www.color.org/bgsrgb.pdf
a = 0.055
if component <= 0.0031308:
linear = component * 12.92
else:
linear = ( 1 + a ) * pow( component, 1 / 2.4 ) - a
return linear
### Animation utilities
def rmEmptyNLA( obj ):
# Remove lna_tracks with no strips
if obj.animation_data.nla_tracks:
for track in obj.animation_data.nla_tracks:
if not track.strips:
obj.animation_data.nla_tracks.remove(track)
def bakeActionToNLA( obj ):
# Bake action to nla_track
# Converting an action to nla_track makes it timeline independant.
hasAnim = 0
if obj.animation_data:
# Get action
objectAction = obj.animation_data.action
# If action exists
if objectAction:
# Create new nla_track
nlaTrack = obj.animation_data.nla_tracks.new()
# Create new strip from action
nlaTrack.strips.new( objectAction.name, objectAction.frame_range[0], objectAction )
# Remove action
obj.animation_data.action = None
hasAnim = 1
rmEmptyNLA(obj)
return hasAnim
def getTrackList(obj, parent):
# Build a dictionary of object's nla tracks and strips
# Dict data structure is like so:
# objDict[ <bpy_struct, Object("Object")> ][ <bpy_struct, NlaTrack("Track")> ][ <bpy_struct, NlaStrip("Action")> ]
# objAnims is a defaultdict(dict)
global objAnims
if obj.animation_data:
# Get nla tracks
objTracks = obj.animation_data.nla_tracks
for track in objTracks:
for strip in track.strips:
# If track struct exists in objAnims[parent], add strip to list
if track in objAnims[parent]:
if strip not in objAnims[parent][track]:
objAnims[parent][track].append(strip)
# If it doesn't, create dict item 'track' and initialize it to a list that contains the current strip
else:
objAnims[parent][track] = [strip]
def getStripsTotal(objList):
stripsTotal = []
for track in objList:
for strip in objList[track]:
stripsTotal.append(strip)
return stripsTotal
def findOverlappingTrack(obj):
# Find overlapping strips through all the tracks
# Get all strips
tmpStrips = []
overlappingStrips = defaultdict(dict)
for track in obj:
for strip in obj[track]:
tmpStrips.append(strip)
# Check each strip for overlapping
for tmpStrip in tmpStrips:
# Find other strips
otherStrips = [ otherStrip for otherStrip in tmpStrips if otherStrip is not tmpStrip ]
for otherStrip in otherStrips:
# If strips are overlapping
if otherStrip.frame_start < tmpStrip.frame_end :
if otherStrip.frame_end > tmpStrip.frame_start:
# Add to list, unless already there
if otherStrip in overlappingStrips:
if tmpStrip not in overlappingStrips:
overlappingStrips[otherStrip].append(tmpStrip)
else:
if tmpStrip not in overlappingStrips:
overlappingStrips[otherStrip] = [tmpStrip]
return overlappingStrips
def writeMESH_ANIMS(f, obj, stripList, fileName):
stripsTotal = len(stripList)
symbolName = fileName + "_model" + CleanName(obj.data.name) + "_anims"
f.write("MESH_ANIMS_TRACKS " + symbolName + " = {\n" +
"\t" + str( stripsTotal ) + ",\n" +
"\t{\n")
i = 0
for strip in stripList:
f.write("\t\t&" + fileName + "_model" + CleanName(obj.data.name) + "_anim_" + CleanName(strip.name))
if i < stripsTotal - 1:
f.write(",\n")
else:
f.write("\n")
i += 1
f.write("\t}\n};\n\n")
return str( "MESH_ANIMS_TRACKS " + symbolName )
def writeVANIM(f, obj, strip, fileName, strip_start, strip_end, compress=False):
# write the VANIM portion of a MESH_ANIMS struct declaration
# Get strip total length
# ~ print(strip.name)
strip_len = strip_end - strip_start
# Iteration counter
i = 0;
# Store temporary mesh in list for cleaning later
tmp_mesh = []
frameList = []
for frame in range(int(strip_start), int(strip_end)):
# Set current frame
bpy.context.scene.frame_set(frame)
# Update scene view
bpy.context.scene.update()
# Create a copy of the mesh with modifiers applied
objMod = obj.to_mesh(bpy.context.scene, True, 'PREVIEW')
# Get isLerp flag
lerp = 0
if 'isLerp' in obj.data:
lerp = obj.data['isLerp']
# Write VANIM struct
symbolName = fileName + "_model" + CleanName(obj.data.name) + "_anim_" + CleanName(strip.name)
if frame == strip_start :
f.write("VANIM " + symbolName + " = {\n" +
"\t" + str(int(strip_len)) + ", // number of frames e.g 20\n" +
"\t" + str(len(objMod.vertices)) + ", // number of vertices e.g 21\n" +
"\t-1, // anim cursor : -1 means not playing back\n" +
"\t0, // lerp cursor\n" +
"\t0, // loop : if -1 , infinite loop, if n > 0, loop n times\n" +
"\t1, // playback direction (1 or -1)\n" +
"\t0, // ping pong animation (A>B>A)\n" +
"\t" + str(lerp) + ", // use lerp to interpolate keyframes\n" +
"\t{ // vertex pos as BVECTORs e.g 20 * 21 BVECTORS\n"
)
# Add an empty list to the frame list
frameList.append([])
currentFrameNbr = int(frame - strip_start)
currentFrameItem = frameList[currentFrameNbr]
if currentFrameNbr > 0:
previousFrameItem = frameList[currentFrameNbr - 1]
else:
# If first iteration, use currentFrameItem
previousFrameItem = currentFrameItem
# Get vertices coordinates as a VECTORs
for vertIndex in range(len(objMod.vertices)):
# Store current vertex coords
currentVertex = Vector( ( round( objMod.vertices[ vertIndex ].co.x * scale), round( -objMod.vertices[ vertIndex ].co.z * scale), round( objMod.vertices[ vertIndex ].co.y * scale) ) )
# Add current vertex to current frame item
currentFrameItem.append(currentVertex)
# If compressing anim
if self.exp_CompressAnims:
# Find delta between current frame and previous frame
delta = currentFrameItem[vertIndex] - previousFrameItem[vertIndex]
currentVertex = delta
# Readability : if first vertex of the frame, write frame number as a comment
if vertIndex == 0:
f.write("\t\t//Frame " + str(currentFrameNbr) + "\n")
# Write vertex coordinates x,z,y
f.write( "\t\t{ " + str(int(currentVertex.x)) +
"," + str(int(currentVertex.y)) +
"," + str(int(currentVertex.z)) +
" }" )
# If vertex is not the last in the list, write a comma
if i != ( len(objMod.vertices) * (strip_len) * 3 ) - 3:
f.write(",\n")
# Readability : If vertex is the last in frame, insert a blank line
if vertIndex == len(objMod.vertices) - 1:
f.write("\n")
# Increment counter
i += 3;
# Add temporary mesh to the cleaning list
tmp_mesh.append( objMod )
# Close anim declaration
f.write("\t}\n};\n\n")
# ~ print(frameList)
# Remove temporary meshes
for o in tmp_mesh:
bpy.data.meshes.remove( o )
return str( "VANIM " + symbolName )
### Sound utilities
class Sound:
def __init__(self, objName, soundName, soundPath, convertedSoundPath, parent, location, volume, volume_min, volume_max, index, XAfile=-1, XAchannel=-1, XAsize=-1, XAend=-1):
self.objName = objName
self.soundName = soundName
self.soundPath = soundPath
self.convertedSoundPath = convertedSoundPath
self.parent = parent
self.location = location
self.volume = volume
self.volume_min = volume_min
self.volume_max = volume_max
self.index = index
self.XAfile = XAfile
self.XAchannel = XAchannel
self.XAsize = XAsize
self.XAend = XAend
def __eq__(self, other):
return self.convertedSoundPath == other.convertedSoundPath
def sound2XA( soundPath, soundName, soundFolder="XA", bpp=4, XAfile=0, XAchannel=0 ):
# Convert sound file to XA
# exports in ./XA by default
# ffmpeg -i input.mp3 -acodec pcm_s16le -ac 2 -ar 44100 output.wav
# psxavenc -f 37800 -t xa -b 4 -c 2 -F 1 -C 0 "../hello_cdda/audio/beach.wav" "xa/beach.xa"
exe = ""
if os.name == 'nt':
exe = ".exe"
# find export folder
filepath = self.filepath
# ~ filepath = bpy.data.filepath
expFolder = os.path.dirname(bpy.path.abspath(filepath)) + os.sep + soundFolder + os.sep
# create if non-existent
if not os.path.exists(expFolder):
os.mkdir(expFolder)
# find file base name
basename = soundName.split('.')[0]
exportPath = expFolder + basename + ".xa"
# Convert to 16-B WAV
subprocess.call( [ "ffmpeg" + exe, "-i", soundPath, "-acodec", "pcm_s16le", "-ac", "2", "-ar", "44100", "-y", "/tmp/tmp.wav"] )
# Convert WAV to XA
subprocess.call( [ "psxavenc" + exe, "-f", "37800", "-t", "xa", "-b", str(bpp), "-c", "2", "-F", str(XAfile), "-C", str(XAchannel), "/tmp/tmp.wav", exportPath ] )
return exportPath
def XAmanifest(XAlist, soundFolder="XA", XAchannels=8):
# generate manifest file
# find export folder
filepath = self.filepath
expFolder = os.path.dirname(bpy.path.abspath(filepath)) + os.sep + soundFolder + os.sep
XAfiles = []
for file_index in range(len(XAlist)):
manifestFile = open(os.path.normpath(expFolder + "inter_" + str(file_index) + ".txt" ), "w+")
# ~ print("\nFile_" + str(file_index) + " :")
lines = XAchannels
for xa in XAlist[file_index]:
manifestFile.write( str(XAmode) + " xa " + xa.convertedSoundPath + " " + str(xa.XAfile) + " " + str(xa.XAchannel) + "\n" )
lines -= 1
while lines:
manifestFile.write( str(XAmode) + " null\n")
lines -= 1
manifestFile.close()
def writeIsoCfg(configFile, insertString):
# Write insertString one line above searchString
print(configFile)
print(insertString)
searchString = "<dummy sectors"
if os.path.exists(configFile):
with open(configFile,"r+") as fd:
content = fd.readlines()
for index, line in enumerate(content):
if insertString in content[index]:
break
if searchString in line and insertString not in content[index] and insertString not in content[index-1]:
content.insert(index, insertString)
break
fd.seek(0)
fd.writelines(content)
else:
print("No mkpsxiso config file were found.")
def addXAtoISO(XAinterList, configFile, soundFolder="XA"):
# Add XA file to mkpsxiso config file if it existsd
filepath = self.filepath
expFolder = os.path.dirname(bpy.path.abspath(filepath)) + os.sep + soundFolder + os.sep
for xa in range(len(XAlist)):
XAfilePath = expFolder + "inter_" + str(xa) + ".xa"
insertString = '\t\t\t<file name="INTER_' + str(xa) + '.XA" type="xa" source="' + XAfilePath + '"/>\n'
writeIsoCfg(configFile, insertString)
def XAinterleave(XAlist, soundFolder="XA"):
# Generate interleaved XA files from existing XA files referenced in soundFiles
exe = ""
if os.name == 'nt':
exe = ".exe"
# find export folder
filepath = self.filepath
for xa in range(len(XAlist)):
manifestFile = expFolder + "inter_" + str(xa) + ".txt"
outputFile = expFolder + "inter_" + str(xa) + ".xa"
subprocess.call( [ "xainterleave" + exe, str(XAmode), manifestFile, outputFile ])
def sound2VAG( soundPath, soundName, soundFolder="VAG"):
# Convert sound file to VAG
# exports in ./VAG by default
# For windows users, add '.exe' to the command
exe = ""
if os.name == 'nt':
exe = ".exe"
# find export folder
filepath = self.filepath
# ~ filepath = bpy.data.filepath
expFolder = os.path.dirname(bpy.path.abspath(filepath)) + os.sep + soundFolder + os.sep
# create if non-existent
if not os.path.exists(expFolder):
os.mkdir(expFolder)
# find file base name
basename = soundName.split('.')[0]
exportPath = expFolder + basename + ".vag"
# Convert to RAW WAV data
subprocess.call( [ "ffmpeg" + exe, "-i", soundPath, "-f", "s16le", "-ac", "1", "-ar", "44100", "-y", "/tmp/tmp.dat"] )
# Convert WAV to VAG
subprocess.call( [ "wav2vag" + exe, "/tmp/tmp.dat", exportPath, "-sraw16", "-freq=44100" ] )
return exportPath
def writeExtList(f, soundName, level_symbols):
soundName = soundName.split('.')[0]
f.write("extern u_char _binary_VAG_" + soundName + "_vag_start;\n")
def writeVAGbank(f, soundList, level_symbols):
index = 0
SPU = 0
dups = []
for file_index in range(len(soundList)):
if soundList[file_index].XAsize == -1 :
if soundList[file_index] not in dups:
writeExtList(f, soundList[file_index].soundName, level_symbols)
dups.append(soundList[file_index])
index += 1
f.write("\nVAGbank " + fileName + "_VAGBank = {\n" +
"\t" + str(index) + ",\n" +
"\t{\n")
for sound in soundList:
if sound.XAsize == -1:
f.write("\t\t{ &_binary_VAG_" + sound.soundName.split('.')[0] + "_vag_start, SPU_0" + str(SPU) + "CH, 0 }")
if SPU < index - 1:
f.write(",\n")
sound.index = SPU
SPU += 1
f.write("\n\t}\n};\n\n" )
level_symbols.append("VAGbank " + fileName + "_VAGBank")
# If SPU, we're using VAGs
return SPU
def writeXAbank(f, XAfiles, level_symbols):
index = 0
XAinter = []
# ~ soundName = objName.split('.')[0]
for file_index in range(len(XAfiles)):
if XAfiles[file_index].XAsize != -1:
index += 1
if XAfiles[file_index].XAfile not in range( len( XAinter ) ) :
XAinter.append( list() )
XAinter[ XAfiles[file_index].XAfile ].append(XAfiles[file_index])
for XAlistIndex in range(len(XAinter)):
f.write("XAbank " + fileName + "_XABank_" + str(XAlistIndex) + " = {\n" +
"\t\"\\\\INTER_" + str(XAlistIndex) + ".XA;1\",\n" +
"\t" + str(len(XAinter[XAlistIndex])) + ",\n" +
"\t0,\n" +
"\t{\n")
index = 0
for sound in XAinter[XAlistIndex]:
if sound.XAsize != -1:
f.write( "\t\t{ " + str(index) + ", " + str(sound.XAsize) + ", " + str(sound.XAfile) + ", " + str(sound.XAchannel) + ", 0, " + str(sound.XAend) + " * XA_CHANNELS, -1 },\n" )
sound.index = index
index += 1
f.write( "\t}\n};\n" )
level_symbols.append("XAbank " + fileName + "_XABank_" + str(XAlistIndex))
return XAinter
def writeXAfiles(f, XAlist, fileName):
# Write XAFiles struct
f.write("XAfiles " + fileName + "_XAFiles = {\n" +
"\t" + str(len(XAlist)) + ",\n" +
"\t{\n")
if XAlist:
for xa in range(len(XAlist)):
f.write("\t\t&" + fileName + "_XABank_" + str(xa))
if xa < len(XAlist) - 1:
f.write(",")
else:
f.write("\t\t0")
f.write("\n\t}\n};\n")
level_symbols.append("XAfiles " + fileName + "_XAFiles")
def writeSoundObj(f, soundFiles, level_symbols):
index = 0
# Write SOUND_OBJECT structures
for obj in soundFiles:
f.write("SOUND_OBJECT " + fileName + "_" + obj.objName.replace(".", "_") + " = {\n" +
"\t{" + str(psxLoc(obj.location.x)) + "," + str(psxLoc(obj.location.y)) + "," + str(psxLoc(obj.location.z)) + "},\n" +
"\t" + str(obj.volume * 0x3fff) + ", " + str(obj.volume * 0x3fff) + ", " + str(obj.volume_min * 0x3fff) + ", " + str(obj.volume_max * 0x3fff) + ",\n" )
if obj.XAsize == -1 :
f.write("\t&" + fileName + "_VAGBank.samples[" + str(obj.index) + "],\n" +
"\t0,\n")
else:
f.write("\t0,\n" +
"\t&" + fileName + "_XABank_" + str(obj.XAfile) + ".samples[" + str(obj.index) + "],\n")
if obj.parent:
f.write( "\t&" + fileName + "_mesh" + CleanName(obj.parent.name) + "\n")
else:
f.write("\t0\n")
f.write("};\n\n")
index += 1
level_symbols.append("SOUND_OBJECT " + fileName + "_" + obj.objName.replace(".", "_"))
f.write("LEVEL_SOUNDS " + fileName + "_sounds = {\n" +
"\t" + str(index) + ",\n" +
"\t{\n")
for obj in range(len(soundFiles)):
f.write( "\t\t&" + fileName + "_" + soundFiles[obj].objName.replace(".", "_"))
if obj < len(soundFiles) - 1 :
f.write(",\n")
f.write("\n\t}\n};\n\n")
level_symbols.append("LEVEL_SOUNDS " + fileName + "_sounds")
return index
# Set rendering resolution to 320x240
bpy.context.scene.render.resolution_x = 320
bpy.context.scene.render.resolution_y = 240
### VRam Layout
nextTpage = 320
nextClutSlot = 480
freeTpage = 21
freeClutSlot = 32
tpageY = 0
# Set TIMs default bpp value
TIMbpp = 8
TIMshift = 1
if self.exp_TIMbpp:
TIMbpp = 4
TIMshift = 2
# Set context area to 3d view
previousAreaType = 0
if bpy.context.mode != 'OBJECT' :
previousAreaType = bpy.context.area.type
bpy.context.area.type="VIEW_3D"
if bpy.context.object is None:
# select first object in scene
bpy.context.scene.objects.active = bpy.context.scene.objects[0]
# Leave edit mode to avoid errors
bpy.ops.object.mode_set(mode='OBJECT')
# restore previous area type
bpy.context.area.type = previousAreaType
# If set, triangulate objects of type mesh
if self.exp_Triangulate:
for o in range(len(bpy.data.objects)):
if bpy.data.objects[o].type == 'MESH':
triangulate_object(bpy.data.objects[o])
# Get export directory path
filepath = self.filepath
if self.exp_expMode:
filepath = bpy.data.filepath
expFolder = os.path.dirname(bpy.path.abspath(filepath))
# If the file wasn't saved before, expFolder will be empty. Default to current directory in that case
if expFolder == "":
expFolder = os.getcwd()
# Get texture folder, default to ./TEX
textureFolder = os.path.join( expFolder, "TEX")
if self.exp_CustomTexFolder != "TEX":
textureFolder = os.path.join( expFolder, self.exp_CustomTexFolder)
timFolder = os.path.join( expFolder, "TIM")
# If the TIM folder doesn't exist, create it
if not os.path.exists(timFolder):
os.mkdir(timFolder)
### Export pre-calculated backgrounds and construct a list of visible objects for each camera angle
camAngles = []
defaultCam = 'NULL'
# List of Rigid/Static bodies to ray a cast upon
rayTargets = []
# If using precalculated BG, render and export them to ./TIM/
if self.exp_Precalc:
# Get BGs TIM size depending on mode
timSize = bpy.context.scene.render.resolution_x >> TIMshift
timSizeInCell = ceil( timSize / 64 )
# Create folder if it doesn't exist
# ~ os.makedirs(timFolder, exist_ok = 1)
# Set file format config
bpy.context.scene.render.image_settings.file_format = 'PNG'
# ~ bpy.context.scene.render.image_settings.quality = 100
# ~ bpy.context.scene.render.image_settings.compression = 0
bpy.context.scene.render.image_settings.color_depth = '8'
bpy.context.scene.render.image_settings.color_mode = 'RGB'
# Get active cam
scene = bpy.context.scene
cam = scene.camera
# Find default cam, and cameras in camPath
for o in bpy.data.objects:
# If orphan, ignore
if o.users == 0:
continue
if o.type == 'CAMERA' and o.data.get('isDefault'):
defaultCam = o.name
if o.type == 'CAMERA' and o.name.startswith("camPath"):
filepath = textureFolder + os.sep
filename = "bg_" + CleanName(o.name)
fileext = "." + str(bpy.context.scene.render.image_settings.file_format).lower()
# Set camera as active
bpy.context.scene.camera = o
# Render and save image
bpy.ops.render.render()
bpy.data.images["Render Result"].save_render( filepath + filename + fileext )
# Convert PNG to TIM
if not VramIsFull( bpy.context.scene.render.resolution_x ):
convertBGtoTIM( filepath + filename + fileext , bpp = TIMbpp, timX = nextTpage, timY = tpageY, clutY = nextClutSlot, transparency = "nonblack" )
else:
tpageY = 256
nextTpage = 320
if not VramIsFull( bpy.context.scene.render.resolution_x ):
convertBGtoTIM( filepath + filename + fileext , bpp = TIMbpp, timX = nextTpage, timY = tpageY, clutY = nextClutSlot, transparency = "nonblack" )
# Add camera object to camAngles
camAngles.append(o)
# Notify layout change to vars
nextTpage += timSizeInCell * 64
freeTpage -= timSizeInCell
nextClutSlot += 1
freeClutSlot -= 1
### Start writing output files
# Stolen from Lameguy64 : https://github.com/Lameguy64/Blender-RSD-Plugin/blob/b3b6fd4475aed4ca38587ca83d34000f60b68a47/io_export_rsd.py#L68
filepath = self.filepath
filepath = filepath.replace(self.filename_ext, "") # Quick fix to get around the aforementioned 'bugfix'
# TODO : add option to export scenes as levels
# ~ if self.exp_UseScenesAsLevels:
# ~ fileName = cleanName(bpy.data.scenes[0].name)
# ~ else:
#
# We're writing a few files:
# - custom_types.h contains the 'engine' 's specific struct definitions
# - level.h contains the forward declaration of the level's variables
# - level.c contains the initialization and data of those variables
# 'custom_types.h' goes in export folder
custom_types_h = expFolder + os.sep + 'custom_types.h'
# If export mode is set to Use blender file name
# ~ if self.exp_expMode:
# ~ fileName = bpy.path.basename(filepath)
# ~ filepath = self.filepath
# ~ folder = os.path.dirname(bpy.path.abspath(filepath))
# ~ levels_folder = folder + os.sep
# ~ else:
lvlNbr = self.exp_LvlNbr
fileName = 'level' + str( lvlNbr )
# Levels files go in ./levels/
# If ./levels does not exist, create it
if not os.path.exists( expFolder + os.sep + 'levels'):
os.mkdir( expFolder + os.sep + 'levels')
levels_folder = expFolder + os.sep + 'levels' + os.sep
# TODO : dynamic filenaming
level_h = levels_folder + fileName + '.h'
level_c = levels_folder + fileName + '.c'
### Custom types Header (custom_types.h)
# Open file
h = open(os.path.normpath(custom_types_h),"w+")
## Add C structures definitions
h.write(
"#pragma once\n" +
"#include <sys/types.h>\n" +
"#include <libgte.h>\n" +
"#include <stdint.h>\n" +
"#include <libgpu.h>\n\n"
)
# Partial declaration of structures to avoid inter-dependencies issues
h.write("struct BODY;\n" +
"struct BVECTOR;\n" +
"struct VANIM;\n" +
"struct MESH_ANIMS_TRACKS;\n" +
"struct PRIM;\n" +
"struct MESH;\n" +
"struct CAMPOS;\n" +
"struct CAMPATH;\n" +
"struct CAMANGLE;\n" +
"struct SIBLINGS;\n" +
"struct CHILDREN;\n" +
"struct NODE;\n" +
"struct QUAD;\n" +
"struct LEVEL;\n" +
"struct VAGsound;\n" +
"struct VAGbank;\n" +
"struct XAsound;\n" +
"struct XAbank;\n" +
"struct XAfiles;\n" +
"struct SOUND_OBJECT;\n" +
"struct LEVEL_SOUNDS;\n" +
"\n")
# BODY
h.write("typedef struct BODY {\n" +
"\tVECTOR gForce;\n" +
"\tVECTOR position;\n" +
"\tSVECTOR velocity;\n" +
"\tint mass;\n" +
"\tint invMass;\n" +
"\tVECTOR min; \n" +
"\tVECTOR max; \n" +
"\tint restitution; \n" +
# ~ "\tstruct NODE * curNode; \n" +
"\t} BODY;\n\n")
# VANIM
h.write("typedef struct BVECTOR {\n" +
"\tint8_t vx, vy;\n" +
"\tint8_t vz;\n" +
"\t// int8_t factor; // could be useful for anims where delta is > 256 \n" +
"} BVECTOR;\n\n")
h.write("typedef struct VANIM { \n" +
"\tint nframes; // number of frames e.g 20\n" +
"\tint nvert; // number of vertices e.g 21\n" +
"\tint cursor; // anim cursor : -1 == not playing, n>=0 == current frame number\n" +
"\tint lerpCursor; // anim cursor\n" +
"\tint loop; // loop anim : -1 == infinite, n>0 == play n times\n" +
"\tint dir; // playback direction (1 or -1)\n" +
"\tint pingpong; // ping pong animation (A>B>A)\n" +
"\tint interpolate; // use lerp to interpolate keyframes\n" +
"\tBVECTOR data[]; // vertex pos as SVECTORs e.g 20 * 21 SVECTORS\n" +
"\t} VANIM;\n\n")
h.write("typedef struct MESH_ANIMS_TRACKS {\n" +
"\tu_short index;\n" +
"\tVANIM * strips[];\n" +
"} MESH_ANIMS_TRACKS;\n\n" )
# PRIM
h.write("typedef struct PRIM {\n" +
"\tVECTOR order;\n" +
"\tint code; // Same as POL3/POL4 codes : Code (F3 = 1, FT3 = 2, G3 = 3,\n// GT3 = 4) Code (F4 = 5, FT4 = 6, G4 = 7, GT4 = 8)\n" +
"\t} PRIM;\n\n")
# MESH
h.write("typedef struct MESH { \n"+
"\tint totalVerts;\n" +
"\tTMESH * tmesh;\n" +
"\tPRIM * index;\n" +
"\tTIM_IMAGE * tim; \n" +
"\tunsigned long * tim_data;\n"+
"\tMATRIX mat;\n" +
"\tVECTOR pos;\n" +
"\tSVECTOR rot;\n" +
"\tshort isProp;\n" +
"\tshort isRigidBody;\n" +
"\tshort isStaticBody;\n" +
"\tshort isRound;\n" +
"\tshort isPrism;\n" +
"\tshort isAnim;\n" +
"\tshort isActor;\n" +
"\tshort isLevel;\n" +