2 # =============================================================================
4 # Copyright . . . -----, ,----- ,---. .---.
5 # 2021-2023 |\ /| | / | | | | /|
6 # | \ / | +-- / +----- +---' | / |
7 # | \ / | | / | | \ | / |
8 # | \/ | | / | | \ | / |
9 # ' ' '--' [] '----- '----- ' ' '---' SOFTWARE
11 # =============================================================================
13 # Python exporter for Blender, compiles .mdl format for Skate Rift.
15 # Its really slow, sorry, I don't know how to speed it up.
16 # Also not sure why you need to put # before {} in code blocks, there is errors
20 import bpy
, math
, gpu
, os
23 from mathutils
import *
24 from gpu_extras
.batch
import batch_for_shader
27 "name":"Skate Rift model compiler",
28 "author": "Harry Godden (hgn)",
35 "category":"Import/Export",
38 class mdl_vert(Structure
): # 48 bytes. Quite large. Could compress
39 #{ # the normals and uvs to i16s. Not an
40 _pack_
= 1 # real issue, yet.
41 _fields_
= [("co",c_float
*3),
45 ("weights",c_uint16
*4),
49 class mdl_submesh(Structure
):
52 _fields_
= [("indice_start",c_uint32
),
53 ("indice_count",c_uint32
),
54 ("vertex_start",c_uint32
),
55 ("vertex_count",c_uint32
),
56 ("bbx",(c_float
*3)*2),
57 ("material_id",c_uint32
)] # index into the material array
60 class mdl_texture(Structure
):
63 _fields_
= [("pstr_name",c_uint32
),
64 ("pack_offset",c_uint32
),
65 ("pack_length",c_uint32
)]
68 class mdl_material(Structure
):
71 _fields_
= [("pstr_name",c_uint32
),
74 ("surface_prop",c_uint32
),
76 ("colour1",c_float
*4),
77 ("tex_diffuse",c_uint32
),
78 ("tex_decal",c_uint32
),
79 ("tex_normal",c_uint32
)]
82 class mdl_node(Structure
):
85 _fields_
= [("co",c_float
*3),
88 ("sub_uid",c_uint32
), # dont use
89 ("submesh_start",c_uint32
),
90 ("submesh_count",c_uint32
),
91 ("classtype",c_uint32
),
94 ("pstr_name",c_uint32
)]
97 class mdl_header(Structure
):
100 _fields_
= [("identifier",c_uint32
),
101 ("version",c_uint32
),
102 ("file_length",c_uint32
),
105 ("node_count",c_uint32
),
106 ("node_offset",c_uint32
),
108 ("submesh_count",c_uint32
),
109 ("submesh_offset",c_uint32
),
111 ("material_count",c_uint32
),
112 ("material_offset",c_uint32
),
114 ("texture_count",c_uint32
),
115 ("texture_offset",c_uint32
),
117 ("anim_count",c_uint32
),
118 ("anim_offset",c_uint32
),
120 ("entdata_size",c_uint32
),
121 ("entdata_offset",c_uint32
),
123 ("strings_size",c_uint32
),
124 ("strings_offset",c_uint32
),
126 ("keyframe_count",c_uint32
),
127 ("keyframe_offset",c_uint32
),
129 ("vertex_count",c_uint32
),
130 ("vertex_offset",c_uint32
),
132 ("indice_count",c_uint32
),
133 ("indice_offset",c_uint32
),
135 ("pack_size",c_uint32
),
136 ("pack_offset",c_uint32
)]
139 class mdl_animation(Structure
):
142 _fields_
= [("pstr_name",c_uint32
),
148 class mdl_keyframe(Structure
):
151 _fields_
= [("co",c_float
*3),
156 # ---------------------------------------------------------------------------- #
158 # Entity definitions #
160 # ---------------------------------------------------------------------------- #
162 # ctypes _fields_ defines the data which is filled in by:
163 # def encode_obj( _, node, node_def ):
165 # gizmos get drawn into the viewport via:
167 # def draw_scene_helpers( obj ):
169 # editor enterface, simiraliy:
171 # def editor_interface( layout, obj ):
176 # Purpose: A rift. must target another gate, the target gate can not have more
177 # than one target nodes of its own.
179 class classtype_gate(Structure
):
182 _fields_
= [("target",c_uint32
),
185 def encode_obj(_
, node
,node_def
):
189 obj
= node_def
['obj']
191 if obj
.cv_data
.target
!= None:
192 _
.target
= obj
.cv_data
.target
.cv_data
.uid
194 if obj
.type == 'MESH':
196 _
.dims
[0] = obj
.data
.cv_data
.v0
[0]
197 _
.dims
[1] = obj
.data
.cv_data
.v0
[1]
198 _
.dims
[2] = obj
.data
.cv_data
.v0
[2]
202 _
.dims
[0] = obj
.cv_data
.v0
[0]
203 _
.dims
[1] = obj
.cv_data
.v0
[1]
204 _
.dims
[2] = obj
.cv_data
.v0
[2]
209 def draw_scene_helpers( obj
):
211 global cv_view_verts
, cv_view_colours
213 if obj
.type == 'MESH':
214 dims
= obj
.data
.cv_data
.v0
216 dims
= obj
.cv_data
.v0
219 c
= Vector((0,0,dims
[2]))
221 vs
[0] = obj
.matrix_world
@ Vector((-dims
[0],0.0,-dims
[1]+dims
[2]))
222 vs
[1] = obj
.matrix_world
@ Vector((-dims
[0],0.0, dims
[1]+dims
[2]))
223 vs
[2] = obj
.matrix_world
@ Vector(( dims
[0],0.0, dims
[1]+dims
[2]))
224 vs
[3] = obj
.matrix_world
@ Vector(( dims
[0],0.0,-dims
[1]+dims
[2]))
225 vs
[4] = obj
.matrix_world
@ (c
+Vector((-1,0,-2)))
226 vs
[5] = obj
.matrix_world
@ (c
+Vector((-1,0, 2)))
227 vs
[6] = obj
.matrix_world
@ (c
+Vector(( 1,0, 2)))
228 vs
[7] = obj
.matrix_world
@ (c
+Vector((-1,0, 0)))
229 vs
[8] = obj
.matrix_world
@ (c
+Vector(( 1,0, 0)))
231 indices
= [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
237 cv_view_verts
+= [(v0
[0],v0
[1],v0
[2])]
238 cv_view_verts
+= [(v1
[0],v1
[1],v1
[2])]
239 cv_view_colours
+= [(1,1,0,1),(1,1,0,1)]
242 sw
= (0.4,0.4,0.4,0.2)
243 if obj
.cv_data
.target
!= None:
244 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, sw
)
248 def editor_interface( layout
, obj
):
250 layout
.prop( obj
.cv_data
, "target" )
253 layout
.label( text
=F
"(i) Data is stored in {mesh.name}" )
254 layout
.prop( mesh
.cv_data
, "v0", text
="Gate dimensions" )
258 class classtype_nonlocal_gate(classtype_gate
):
260 def encode_obj(_
,node
,node_def
):
264 obj
= node_def
['obj']
265 _
.target
= encoder_process_pstr( node_def
['obj'].cv_data
.strp
)
267 if obj
.type == 'MESH':
269 _
.dims
[0] = obj
.data
.cv_data
.v0
[0]
270 _
.dims
[1] = obj
.data
.cv_data
.v0
[1]
271 _
.dims
[2] = obj
.data
.cv_data
.v0
[2]
275 _
.dims
[0] = obj
.cv_data
.v0
[0]
276 _
.dims
[1] = obj
.cv_data
.v0
[1]
277 _
.dims
[2] = obj
.cv_data
.v0
[2]
282 def editor_interface( layout
, obj
):
284 layout
.prop( obj
.cv_data
, "strp", text
="Nonlocal ID" )
287 layout
.label( text
=F
"(i) Data is stored in {mesh.name}" )
288 layout
.prop( mesh
.cv_data
, "v0", text
="Gate dimensions" )
294 # Purpose: player can reset here, its a safe place
295 # spawns can share the same name, the closest one will be picked
297 # when the world loads it will pick the one named 'start' first.
299 class classtype_spawn(Structure
):
302 _fields_
= [("pstr_alias",c_uint32
)]
304 def encode_obj(_
, node
,node_def
):
307 _
.pstr_alias
= encoder_process_pstr( node_def
['obj'].cv_data
.strp
)
311 def draw_scene_helpers( obj
):
313 global cv_view_verts
, cv_view_colours
316 vs
[0] = obj
.matrix_world
@ Vector((0,0,0))
317 vs
[1] = obj
.matrix_world
@ Vector((0,2,0))
318 vs
[2] = obj
.matrix_world
@ Vector((0.5,1,0))
319 vs
[3] = obj
.matrix_world
@ Vector((-0.5,1,0))
320 indices
= [(0,1),(1,2),(1,3)]
327 cv_view_verts
+= [(v0
[0],v0
[1],v0
[2])]
328 cv_view_verts
+= [(v1
[0],v1
[1],v1
[2])]
329 cv_view_colours
+= [(0,1,1,1),(0,1,1,1)]
332 cv_draw_sphere( obj
.location
, 20.0, [0.1,0,0.9,0.4] )
336 def editor_interface( layout
, obj
):
338 layout
.prop( obj
.cv_data
, "strp", text
="Alias" )
344 # Purpose: Tells the game to draw water HERE, at this entity.
346 class classtype_water(Structure
):
349 _fields_
= [("temp",c_uint32
)]
351 def encode_obj(_
, node
,node_def
):
360 # Purpose: Defines a route node and links to up to two more nodes
362 class classtype_route_node(Structure
):
365 _fields_
= [("target",c_uint32
),
366 ("target1",c_uint32
)]
368 def encode_obj(_
, node
,node_def
):
371 obj
= node_def
['obj']
373 if obj
.cv_data
.target
!= None:
374 _
.target
= obj
.cv_data
.target
.cv_data
.uid
375 if obj
.cv_data
.target1
!= None:
376 _
.target1
= obj
.cv_data
.target1
.cv_data
.uid
380 def draw_scene_helpers( obj
):
382 global cv_view_verts
, cv_view_colours
384 sw
= Vector((0.4,0.4,0.4,0.2))
385 sw2
= Vector((1.5,0.2,0.2,0.0))
386 if obj
.cv_data
.target
!= None:
387 cv_draw_bpath( obj
, obj
.cv_data
.target
, sw
, sw
)
388 if obj
.cv_data
.target1
!= None:
389 cv_draw_bpath( obj
, obj
.cv_data
.target1
, sw
, sw
)
391 cv_draw_bhandle( obj
, 1.0, (0.8,0.8,0.8,1.0) )
392 cv_draw_bhandle( obj
, -1.0, (0.4,0.4,0.4,1.0) )
395 obj
.matrix_world
.to_quaternion() @ Vector((0,0,-6+1.5))
396 cv_draw_arrow( obj
.location
, p1
, sw
)
400 def editor_interface( layout
, obj
):
402 layout
.prop( obj
.cv_data
, "target", text
="Left" )
403 layout
.prop( obj
.cv_data
, "target1", text
="Right" )
409 # Purpose: Defines a route, its 'starting' point, and the colour to use for it
411 class classtype_route(Structure
):
414 _fields_
= [("id_start",c_uint32
),
415 ("pstr_name",c_uint32
),
416 ("colour",c_float
*3)]
418 def encode_obj(_
, node
,node_def
):
421 obj
= node_def
['obj']
423 _
.colour
[0] = obj
.cv_data
.colour
[0]
424 _
.colour
[1] = obj
.cv_data
.colour
[1]
425 _
.colour
[2] = obj
.cv_data
.colour
[2]
426 _
.pstr_name
= encoder_process_pstr( obj
.cv_data
.strp
)
428 if obj
.cv_data
.target
!= None:
429 _
.id_start
= obj
.cv_data
.target
.cv_data
.uid
433 def draw_scene_helpers( obj
):
435 global cv_view_verts
, cv_view_colours
, cv_view_course_i
437 if obj
.cv_data
.target
:
438 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, [1,1,1,1] )
440 # Tries to simulate how we do it in the game
444 stack
[0] = obj
.cv_data
.target
446 loop_complete
= False
450 if stack_i
[si
-1] == 2:
455 if si
== 0: # Loop failed to complete
461 targets
= [None,None]
462 targets
[0] = node
.cv_data
.target
464 if node
.cv_data
.classtype
== 'classtype_route_node':
466 targets
[1] = node
.cv_data
.target1
469 nextnode
= targets
[stack_i
[si
-1]]
472 if nextnode
!= None: # branch
474 if nextnode
== stack
[0]: # Loop completed
483 if stack
[sj
] == nextnode
: # invalidated path
502 cc
= Vector((obj
.cv_data
.colour
[0],\
503 obj
.cv_data
.colour
[1],\
504 obj
.cv_data
.colour
[2],\
511 if stack
[sj
].cv_data
.classtype
== 'classtype_gate' and \
512 stack
[sk
].cv_data
.classtype
== 'classtype_gate':
514 dist
= (stack
[sj
].location
-stack
[sk
].location
).magnitude
515 cv_draw_sbpath( stack
[sj
], stack
[sk
], cc
*0.4, cc
, dist
, dist
)
518 cv_draw_bpath( stack
[sj
], stack
[sk
], cc
, cc
)
521 cv_view_course_i
+= 1
526 def editor_interface( layout
, obj
):
528 layout
.prop( obj
.cv_data
, "target", text
="'Start' from" )
529 layout
.prop( obj
.cv_data
, "colour" )
530 layout
.prop( obj
.cv_data
, "strp", text
="Name" )
536 # Purpose: links an mesh node to a type 11
538 class classtype_skin(Structure
):
541 _fields_
= [("skeleton",c_uint32
)]
543 def encode_obj(_
, node
,node_def
):
547 armature_def
= node_def
['linked_armature']
548 _
.skeleton
= armature_def
['obj'].cv_data
.uid
554 # Purpose: defines the allocation requirements for a skeleton
556 class classtype_skeleton(Structure
):
559 _fields_
= [("channels",c_uint32
),
560 ("ik_count",c_uint32
),
561 ("collider_count",c_uint32
),
562 ("anim_start",c_uint32
),
563 ("anim_count",c_uint32
)]
565 def encode_obj(_
, node
,node_def
):
569 _
.channels
= len( node_def
['bones'] )
570 _
.ik_count
= node_def
['ik_count']
571 _
.collider_count
= node_def
['collider_count']
572 _
.anim_start
= node_def
['anim_start']
573 _
.anim_count
= node_def
['anim_count']
580 # Purpose: intrinsic bone type, stores collision information and limits too
582 class classtype_bone(Structure
):
585 _fields_
= [("flags",c_uint32
),
586 ("ik_target",c_uint32
),
587 ("ik_pole",c_uint32
),
588 ("hitbox",(c_float
*3)*2),
589 ("conevx",c_float
*3),
590 ("conevy",c_float
*3),
591 ("coneva",c_float
*3),
594 def encode_obj(_
, node
,node_def
):
598 armature_def
= node_def
['linked_armature']
599 obj
= node_def
['bone']
601 _
.flags
= node_def
['deform']
603 if 'ik_target' in node_def
:
606 _
.ik_target
= armature_def
['bones'].index( node_def
['ik_target'] )
607 _
.ik_pole
= armature_def
['bones'].index( node_def
['ik_pole'] )
612 if obj
.cv_data
.collider
!= 'collider_none':
614 if obj
.cv_data
.collider
== 'collider_box':
619 _
.hitbox
[0][0] = obj
.cv_data
.v0
[0]
620 _
.hitbox
[0][1] = obj
.cv_data
.v0
[2]
621 _
.hitbox
[0][2] = -obj
.cv_data
.v1
[1]
622 _
.hitbox
[1][0] = obj
.cv_data
.v1
[0]
623 _
.hitbox
[1][1] = obj
.cv_data
.v1
[2]
624 _
.hitbox
[1][2] = -obj
.cv_data
.v0
[1]
630 _
.conevx
[0] = obj
.cv_data
.conevx
[0]
631 _
.conevx
[1] = obj
.cv_data
.conevx
[2]
632 _
.conevx
[2] = -obj
.cv_data
.conevx
[1]
633 _
.conevy
[0] = obj
.cv_data
.conevy
[0]
634 _
.conevy
[1] = obj
.cv_data
.conevy
[2]
635 _
.conevy
[2] = -obj
.cv_data
.conevy
[1]
636 _
.coneva
[0] = obj
.cv_data
.coneva
[0]
637 _
.coneva
[1] = obj
.cv_data
.coneva
[2]
638 _
.coneva
[2] = -obj
.cv_data
.coneva
[1]
639 _
.conet
= obj
.cv_data
.conet
646 # Purpose: sends a signal to another entity
648 class classtype_trigger(Structure
):
651 _fields_
= [("target",c_uint32
)]
653 def encode_obj(_
, node
,node_def
):
656 if node_def
['obj'].cv_data
.target
:
657 _
.target
= node_def
['obj'].cv_data
.target
.cv_data
.uid
661 def draw_scene_helpers( obj
):
663 global cv_view_verts
, cv_view_colours
664 cv_draw_ucube( obj
.matrix_world
, [0,1,0,1] )
666 if obj
.cv_data
.target
:
667 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, [1,1,1,1] )
671 def editor_interface( layout
, obj
):
673 layout
.prop( obj
.cv_data
, "target", text
="Triggers" )
679 # Purpose: Gives the player an achievement.
680 # No cheating! You shouldn't use this entity anyway, since only ME can
681 # add achievements to the steam ;)
683 class classtype_logic_achievement(Structure
):
686 _fields_
= [("pstr_name",c_uint32
)]
688 def encode_obj(_
, node
,node_def
):
691 _
.pstr_name
= encoder_process_pstr( node_def
['obj'].cv_data
.strp
)
695 def editor_interface( layout
, obj
):
697 layout
.prop( obj
.cv_data
, "strp", text
="Achievement ID" )
703 # Purpose: sends a signal to another entity
705 class classtype_logic_relay(Structure
):
708 _fields_
= [("targets",c_uint32
*4)]
710 def encode_obj(_
, node
,node_def
):
713 obj
= node_def
['obj']
714 if obj
.cv_data
.target
:
715 _
.targets
[0] = obj
.cv_data
.target
.cv_data
.uid
716 if obj
.cv_data
.target1
:
717 _
.targets
[1] = obj
.cv_data
.target1
.cv_data
.uid
718 if obj
.cv_data
.target2
:
719 _
.targets
[2] = obj
.cv_data
.target2
.cv_data
.uid
720 if obj
.cv_data
.target3
:
721 _
.targets
[3] = obj
.cv_data
.target3
.cv_data
.uid
725 def draw_scene_helpers( obj
):
727 global cv_view_verts
, cv_view_colours
729 if obj
.cv_data
.target
:
730 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, [1,1,1,1] )
731 if obj
.cv_data
.target1
:
732 cv_draw_arrow( obj
.location
, obj
.cv_data
.target1
.location
, [1,1,1,1] )
733 if obj
.cv_data
.target2
:
734 cv_draw_arrow( obj
.location
, obj
.cv_data
.target2
.location
, [1,1,1,1] )
735 if obj
.cv_data
.target3
:
736 cv_draw_arrow( obj
.location
, obj
.cv_data
.target3
.location
, [1,1,1,1] )
740 def editor_interface( layout
, obj
):
742 layout
.prop( obj
.cv_data
, "target", text
="Triggers" )
743 layout
.prop( obj
.cv_data
, "target1", text
="Triggers" )
744 layout
.prop( obj
.cv_data
, "target2", text
="Triggers" )
745 layout
.prop( obj
.cv_data
, "target3", text
="Triggers" )
751 # Purpose: Plays some audio (44100hz .ogg vorbis only)
752 # NOTE: There is a 32mb limit on the audio buffer, world audio is
753 # decompressed and stored in signed 16 bit integers (2 bytes)
756 # volume: not used if has 3D flag
758 # AUDIO_FLAG_LOOP 0x1
759 # AUDIO_FLAG_ONESHOT 0x2 (DONT USE THIS, it breaks semaphores)
760 # AUDIO_FLAG_SPACIAL_3D 0x4 (Probably what you want)
761 # AUDIO_FLAG_AUTO_START 0x8 (Play when the world starts)
763 # the rest are just internal flags, only use the above 3.
765 class classtype_audio(Structure
):
768 _fields_
= [("pstr_file",c_uint32
),
772 def encode_obj(_
, node
,node_def
):
776 obj
= node_def
['obj']
778 _
.pstr_file
= encoder_process_pstr( obj
.cv_data
.strp
)
781 if obj
.cv_data
.bp0
: flags |
= 0x1
782 if obj
.cv_data
.bp1
: flags |
= 0x4
783 if obj
.cv_data
.bp2
: flags |
= 0x8
786 _
.volume
= obj
.cv_data
.fltp
790 def editor_interface( layout
, obj
):
792 layout
.prop( obj
.cv_data
, "strp" )
794 layout
.prop( obj
.cv_data
, "bp0", text
= "Looping" )
795 layout
.prop( obj
.cv_data
, "bp1", text
= "3D Audio" )
796 layout
.prop( obj
.cv_data
, "bp2", text
= "Auto Start" )
800 def draw_scene_helpers( obj
):
802 global cv_view_verts
, cv_view_colours
804 cv_draw_sphere( obj
.location
, obj
.scale
[0], [1,1,0,1] )
810 # Purpose: world light
812 class classtype_world_light( Structure
):
815 _fields_
= [("type",c_uint32
),
816 ("colour",c_float
*4),
819 def encode_obj(_
, node
, node_def
):
823 obj
= node_def
['obj']
825 _
.colour
[0] = data
.color
[0]
826 _
.colour
[1] = data
.color
[1]
827 _
.colour
[2] = data
.color
[2]
828 _
.colour
[3] = data
.energy
830 if obj
.data
.type == 'POINT':
835 elif obj
.data
.type == 'SPOT':
838 _
.angle
= math
.cos(data
.spot_size
*0.5)
843 def editor_interface( layout
, obj
):
851 # Purpose: lighting settings for world
853 class classtype_lighting_info(Structure
):
856 _fields_
= [("colours",(c_float
*3)*3),
857 ("directions",(c_float
*2)*3),
858 ("states",c_uint32
*3),
859 ("shadow_spread",c_float
),
860 ("shadow_length",c_float
),
861 ("ambient",c_float
*3)]
863 def encode_obj(_
, node
, node_def
):
871 def editor_interface( layout
, obj
):
877 class classtype_spawn_link(Structure
):
880 _fields_
= [("connections",c_uint32
*4)]
882 def encode_obj(_
, node
,node_def
):
888 def editor_interface( layout
, obj
):
894 def draw_scene_helpers( obj
):
896 global cv_view_verts
, cv_view_colours
900 for obj1
in bpy
.context
.collection
.objects
:
902 if (obj1
.cv_data
.classtype
!= 'classtype_spawn_link') and \
903 (obj1
.cv_data
.classtype
!= 'classtype_spawn') :
906 if (obj1
.location
- obj
.location
).length
< 40.0:
908 cv_draw_line( obj
.location
, obj1
.location
, [1,1,1,1] )
916 cv_draw_sphere( obj
.location
, 20.0, [0.5,0,0.2,0.4] )
920 # ---------------------------------------------------------------------------- #
924 # ---------------------------------------------------------------------------- #
926 # Current encoder state
932 def encoder_init( collection
):
938 # The actual file header
940 'header': mdl_header(),
944 'pack_textures': collection
.cv_data
.pack_textures
,
946 # Compiled data chunks (each can be read optionally by the client)
950 #1---------------------------------
951 'node': [], # Metadata 'chunk'
956 'entdata': bytearray(), # variable width
957 'strings': bytearray(), # .
958 #2---------------------------------
959 'keyframe': [], # Animations
960 #3---------------------------------
961 'vertex': [], # Mesh data
963 #4---------------------------------
964 'pack': bytearray() # Other generic packed data
967 # All objects of the model in their final heirachy
973 # Allows us to reuse definitions
977 'material_cache': {},
981 g_encoder
['header'].identifier
= 0xABCD0000
982 g_encoder
['header'].version
= 1
984 # Add fake NoneID material and texture
986 none_material
= mdl_material()
987 none_material
.pstr_name
= encoder_process_pstr( "" )
988 none_material
.texture_id
= 0
990 none_texture
= mdl_texture()
991 none_texture
.pstr_name
= encoder_process_pstr( "" )
992 none_texture
.pack_offset
= 0
993 none_texture
.pack_length
= 0
995 g_encoder
['data']['material'] += [none_material
]
996 g_encoder
['data']['texture'] += [none_texture
]
998 g_encoder
['data']['pack'].extend( b
'datapack\0\0\0\0\0\0\0\0' )
1013 root
.pstr_name
= encoder_process_pstr('')
1014 root
.submesh_start
= 0
1015 root
.submesh_count
= 0
1018 root
.parent
= 0xffffffff
1020 g_encoder
['data']['node'] += [root
]
1024 # fill with 0x00 until a multiple of align. Returns how many bytes it added
1026 def bytearray_align_to( buffer, align
, offset
=0 ):
1030 while ((len(buffer)+offset
) % align
) != 0:
1032 buffer.extend( b
'\0' )
1039 # Add a string to the string buffer except if it already exists there then we
1040 # just return its ID.
1042 def encoder_process_pstr( s
):
1046 cache
= g_encoder
['string_cache']
1051 cache
[s
] = len( g_encoder
['data']['strings'] )
1053 buffer = g_encoder
['data']['strings']
1054 buffer.extend( s
.encode('utf-8') )
1055 buffer.extend( b
'\0' )
1057 bytearray_align_to( buffer, 4 )
1061 def get_texture_resource_name( img
):
1063 return os
.path
.splitext( img
.name
)[0]
1068 def encoder_process_texture( img
):
1075 cache
= g_encoder
['texture_cache']
1076 buffer = g_encoder
['data']['texture']
1077 pack
= g_encoder
['data']['pack']
1079 name
= get_texture_resource_name( img
)
1084 cache
[name
] = len( buffer )
1087 tex
.pstr_name
= encoder_process_pstr( name
)
1089 if g_encoder
['pack_textures']:
1091 tex
.pack_offset
= len( pack
)
1092 pack
.extend( qoi_encode( img
) )
1093 tex
.pack_length
= len( pack
) - tex
.pack_offset
1102 def material_tex_image(v
):
1112 cxr_graph_mapping
= \
1114 # Default shader setup
1121 "image": "tex_diffuse"
1125 "A": material_tex_image("tex_diffuse"),
1126 "B": material_tex_image("tex_decal")
1133 "Color": material_tex_image("tex_normal")
1139 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
1141 def material_info(mat
):
1145 # Using the cv_graph_mapping as a reference, go through the shader
1146 # graph and gather all $props from it.
1148 def _graph_read( node_def
, node
=None, depth
=0 ):
1157 _graph_read
.extracted
= []
1159 for node_idname
in node_def
:
1161 for n
in mat
.node_tree
.nodes
:
1163 if n
.name
== node_idname
:
1165 node_def
= node_def
[node_idname
]
1173 for link
in node_def
:
1175 link_def
= node_def
[link
]
1177 if isinstance( link_def
, dict ):
1180 for x
in node
.inputs
:
1182 if isinstance( x
, bpy
.types
.NodeSocketColor
):
1192 if node_link
and node_link
.is_linked
:
1194 # look for definitions for the connected node type
1196 from_node
= node_link
.links
[0].from_node
1198 node_name
= from_node
.name
.split('.')[0]
1199 if node_name
in link_def
:
1201 from_node_def
= link_def
[ node_name
]
1203 _graph_read( from_node_def
, from_node
, depth
+1 )
1207 # TODO: Make a warning for this?
1211 if "default" in link_def
:
1213 prop
= link_def
['default']
1214 info
[prop
] = node_link
.default_value
1221 info
[prop
] = getattr( node
, link
)
1226 _graph_read( cxr_graph_mapping
)
1230 # Add a material to the material buffer. Returns 0 (None ID) if invalid
1232 def encoder_process_material( mat
):
1239 cache
= g_encoder
['material_cache']
1240 buffer = g_encoder
['data']['material']
1242 if mat
.name
in cache
:
1243 return cache
[mat
.name
]
1245 cache
[mat
.name
] = len( buffer )
1247 dest
= mdl_material()
1248 dest
.pstr_name
= encoder_process_pstr( mat
.name
)
1251 if mat
.cv_data
.collision
:
1253 if mat
.cv_data
.skate_surface
: flags |
= 0x1
1254 if mat
.cv_data
.grind_surface
: flags |
= (0x8|
0x1)
1256 if mat
.cv_data
.grow_grass
: flags |
= 0x4
1259 if mat
.cv_data
.surface_prop
== 'concrete': dest
.surface_prop
= 0
1260 if mat
.cv_data
.surface_prop
== 'wood': dest
.surface_prop
= 1
1261 if mat
.cv_data
.surface_prop
== 'grass': dest
.surface_prop
= 2
1263 if mat
.cv_data
.shader
== 'standard': dest
.shader
= 0
1264 if mat
.cv_data
.shader
== 'standard_cutout': dest
.shader
= 1
1265 if mat
.cv_data
.shader
== 'terrain_blend':
1269 dest
.colour
[0] = pow( mat
.cv_data
.sand_colour
[0], 1.0/2.2 )
1270 dest
.colour
[1] = pow( mat
.cv_data
.sand_colour
[1], 1.0/2.2 )
1271 dest
.colour
[2] = pow( mat
.cv_data
.sand_colour
[2], 1.0/2.2 )
1272 dest
.colour
[3] = 1.0
1274 dest
.colour1
[0] = mat
.cv_data
.blend_offset
[0]
1275 dest
.colour1
[1] = mat
.cv_data
.blend_offset
[1]
1278 if mat
.cv_data
.shader
== 'vertex_blend':
1282 dest
.colour1
[0] = mat
.cv_data
.blend_offset
[0]
1283 dest
.colour1
[1] = mat
.cv_data
.blend_offset
[1]
1286 if mat
.cv_data
.shader
== 'water':
1290 dest
.colour
[0] = pow( mat
.cv_data
.shore_colour
[0], 1.0/2.2 )
1291 dest
.colour
[1] = pow( mat
.cv_data
.shore_colour
[1], 1.0/2.2 )
1292 dest
.colour
[2] = pow( mat
.cv_data
.shore_colour
[2], 1.0/2.2 )
1293 dest
.colour
[3] = 1.0
1294 dest
.colour1
[0] = pow( mat
.cv_data
.ocean_colour
[0], 1.0/2.2 )
1295 dest
.colour1
[1] = pow( mat
.cv_data
.ocean_colour
[1], 1.0/2.2 )
1296 dest
.colour1
[2] = pow( mat
.cv_data
.ocean_colour
[2], 1.0/2.2 )
1297 dest
.colour1
[3] = 1.0
1300 inf
= material_info( mat
)
1302 if mat
.cv_data
.shader
== 'standard' or \
1303 mat
.cv_data
.shader
== 'standard_cutout' or \
1304 mat
.cv_data
.shader
== 'terrain_blend' or \
1305 mat
.cv_data
.shader
== 'vertex_blend':
1307 if 'tex_diffuse' in inf
:
1308 dest
.tex_diffuse
= encoder_process_texture(inf
['tex_diffuse'])
1312 return cache
[mat
.name
]
1315 # Create a tree structure containing all the objects in the collection
1317 def encoder_build_scene_graph( collection
):
1321 print( " creating scene graph" )
1325 graph
= g_encoder
['scene_graph']
1326 graph_lookup
= g_encoder
['graph_lookup']
1329 graph
["children"] = []
1331 graph
["parent"] = None
1336 uid
= g_encoder
['uid_count']
1337 g_encoder
['uid_count'] += 1
1341 for obj
in collection
.all_objects
:
1343 if obj
.parent
: continue
1345 def _extend( p
, n
, d
):
1352 tree
["children"] = []
1358 # Descend into amature
1360 if n
.type == 'ARMATURE':
1362 tree
["bones"] = [None] # None is the root transform
1363 tree
["ik_count"] = 0
1364 tree
["collider_count"] = 0
1365 tree
["compile_animation"] = collection
.cv_data
.animations
1367 # Here also collects some information about constraints, ik and
1368 # counts colliders for the armature.
1370 def _extendb( p
, n
, d
):
1376 btree
["linked_armature"] = tree
1377 btree
["uid"] = _new_uid()
1378 btree
["children"] = []
1381 tree
["bones"] += [n
.name
]
1383 for c
in n
.children
:
1385 _extendb( btree
, c
, d
+1 )
1388 for c
in tree
['obj'].pose
.bones
[n
.name
].constraints
:
1392 btree
["ik_target"] = c
.subtarget
1393 btree
["ik_pole"] = c
.pole_subtarget
1394 tree
["ik_count"] += 1
1398 if n
.cv_data
.collider
!= 'collider_none':
1399 tree
['collider_count'] += 1
1401 btree
['deform'] = n
.use_deform
1402 p
['children'] += [btree
]
1405 for b
in n
.data
.bones
:
1407 _extendb( tree
, b
, d
+1 )
1410 # Recurse into children of this object
1412 for obj1
in n
.children
:
1414 for c1
in obj1
.users_collection
:
1416 if c1
== collection
:
1418 _extend( tree
, obj1
, d
+1 )
1424 p
["children"] += [tree
]
1425 graph_lookup
[n
] = tree
1429 _extend( graph
, obj
, 1 )
1435 # Kind of a useless thing i made but it looks cool and adds complexity!!1
1437 def encoder_graph_iterator( root
):
1439 for c
in root
['children']:
1442 yield from encoder_graph_iterator(c
)
1447 # Push a vertex into the model file, or return a cached index (c_uint32)
1449 def encoder_vertex_push( vertex_reference
, co
,norm
,uv
,colour
,groups
,weights
):
1452 buffer = g_encoder
['data']['vertex']
1455 m
= float(10**TOLERENCE
)
1457 # Would be nice to know if this can be done faster than it currently runs,
1460 key
= (int(co
[0]*m
+0.5),
1468 colour
[0], # these guys are already quantized
1481 if key
in vertex_reference
:
1482 return vertex_reference
[key
]
1485 index
= c_uint32( len(vertex_reference
) )
1486 vertex_reference
[key
] = index
1494 v
.norm
[2] = -norm
[1]
1497 v
.colour
[0] = colour
[0]
1498 v
.colour
[1] = colour
[1]
1499 v
.colour
[2] = colour
[2]
1500 v
.colour
[3] = colour
[3]
1501 v
.weights
[0] = weights
[0]
1502 v
.weights
[1] = weights
[1]
1503 v
.weights
[2] = weights
[2]
1504 v
.weights
[3] = weights
[3]
1505 v
.groups
[0] = groups
[0]
1506 v
.groups
[1] = groups
[1]
1507 v
.groups
[2] = groups
[2]
1508 v
.groups
[3] = groups
[3]
1516 # Compile a mesh (or use one from the cache) onto node, based on node_def
1519 def encoder_compile_mesh( node
, node_def
):
1523 graph
= g_encoder
['scene_graph']
1524 graph_lookup
= g_encoder
['graph_lookup']
1525 mesh_cache
= g_encoder
['mesh_cache']
1526 obj
= node_def
['obj']
1528 can_use_cache
= True
1530 # Check for modifiers that typically change the data per-instance
1531 # there is no well defined rule for the choices here, its just what i've
1532 # needed while producing the game.
1534 # It may be possible to detect these cases automatically.
1536 for mod
in obj
.modifiers
:
1538 if mod
.type == 'DATA_TRANSFER' or mod
.type == 'SHRINKWRAP' or \
1539 mod
.type == 'BOOLEAN' or mod
.type == 'CURVE' or \
1540 mod
.type == 'ARRAY':
1542 can_use_cache
= False
1545 if mod
.type == 'ARMATURE':
1546 armature_def
= graph_lookup
[mod
.object]
1548 # Check the cache first
1550 if can_use_cache
and (obj
.data
.name
in mesh_cache
):
1552 ref
= mesh_cache
[obj
.data
.name
]
1553 node
.submesh_start
= ref
.submesh_start
1554 node
.submesh_count
= ref
.submesh_count
1558 # Compile a whole new mesh
1560 node
.submesh_start
= len( g_encoder
['data']['submesh'] )
1561 node
.submesh_count
= 0
1563 dgraph
= bpy
.context
.evaluated_depsgraph_get()
1564 data
= obj
.evaluated_get(dgraph
).data
1565 data
.calc_loop_triangles()
1566 data
.calc_normals_split()
1568 # Mesh is split into submeshes based on their material
1570 mat_list
= data
.materials
if len(data
.materials
) > 0 else [None]
1571 for material_id
, mat
in enumerate(mat_list
):
1576 sm
.indice_start
= len( g_encoder
['data']['indice'] )
1577 sm
.vertex_start
= len( g_encoder
['data']['vertex'] )
1580 sm
.material_id
= encoder_process_material( mat
)
1584 sm
.bbx
[0][i
] = 999999
1585 sm
.bbx
[1][i
] = -999999
1588 # Keep a reference to very very very similar vertices
1590 vertex_reference
= {}
1592 # Write the vertex / indice data
1594 for tri_index
, tri
in enumerate(data
.loop_triangles
):
1596 if tri
.material_index
!= material_id
:
1601 vert
= data
.vertices
[tri
.vertices
[j
]]
1603 vi
= data
.loops
[li
].vertex_index
1605 # Gather vertex information
1608 norm
= data
.loops
[li
].normal
1610 colour
= (255,255,255,255)
1617 uv
= data
.uv_layers
.active
.data
[li
].uv
1621 if data
.vertex_colors
:
1623 colour
= data
.vertex_colors
.active
.data
[li
].color
1624 colour
= (int(colour
[0]*255.0),\
1625 int(colour
[1]*255.0),\
1626 int(colour
[2]*255.0),\
1627 int(colour
[3]*255.0))
1630 # Weight groups: truncates to the 3 with the most influence. The
1631 # fourth bone ID is never used by the shader so it is
1636 src_groups
= [_
for _
in data
.vertices
[vi
].groups \
1637 if obj
.vertex_groups
[_
.group
].name
in \
1638 armature_def
['bones']]
1640 weight_groups
= sorted( src_groups
, key
= \
1641 lambda a
: a
.weight
, reverse
=True )
1645 if len(weight_groups
) > ml
:
1647 g
= weight_groups
[ml
]
1648 name
= obj
.vertex_groups
[g
.group
].name
1651 weights
[ml
] = weight
1652 groups
[ml
] = armature_def
['bones'].index(name
)
1657 if len(weight_groups
) > 0:
1659 inv_norm
= (1.0/tot
) * 65535.0
1662 weights
[ml
] = int( weights
[ml
] * inv_norm
)
1663 weights
[ml
] = min( weights
[ml
], 65535 )
1664 weights
[ml
] = max( weights
[ml
], 0 )
1670 li1
= tri
.loops
[(j
+1)%3]
1671 vi1
= data
.loops
[li1
].vertex_index
1672 e0
= data
.edges
[ data
.loops
[li
].edge_index
]
1674 if e0
.use_freestyle_mark
and \
1675 ((e0
.vertices
[0] == vi
and e0
.vertices
[1] == vi1
) or \
1676 (e0
.vertices
[0] == vi1
and e0
.vertices
[1] == vi
)):
1682 # Add vertex and expand bound box
1684 index
= encoder_vertex_push( vertex_reference
, co
, \
1690 g_encoder
['data']['indice'] += [index
]
1694 # How many unique verts did we add in total
1696 sm
.vertex_count
= len(g_encoder
['data']['vertex']) - sm
.vertex_start
1697 sm
.indice_count
= len(g_encoder
['data']['indice']) - sm
.indice_start
1699 # Make sure bounding box isn't -inf -> inf if no vertices
1701 if sm
.vertex_count
== 0:
1707 for j
in range(sm
.vertex_count
):
1709 vert
= g_encoder
['data']['vertex'][ sm
.vertex_start
+ j
]
1713 sm
.bbx
[0][i
] = min( sm
.bbx
[0][i
], vert
.co
[i
] )
1714 sm
.bbx
[1][i
] = max( sm
.bbx
[1][i
], vert
.co
[i
] )
1719 # Add submesh to encoder
1721 g_encoder
['data']['submesh'] += [sm
]
1722 node
.submesh_count
+= 1
1726 # Save a reference to this node since we want to reuse the submesh indices
1728 g_encoder
['mesh_cache'][obj
.data
.name
] = node
1732 def encoder_compile_ent_as( name
, node
, node_def
):
1736 if name
== 'classtype_none':
1742 elif name
not in globals():
1744 print( "Classtype '" +name
+ "' is unknown!" )
1748 buffer = g_encoder
['data']['entdata']
1749 node
.offset
= len(buffer)
1751 cl
= globals()[ name
]
1753 inst
.encode_obj( node
, node_def
)
1755 buffer.extend( bytearray(inst
) )
1756 bytearray_align_to( buffer, 4 )
1759 # Compiles animation data into model and gives us some extra node_def entries
1761 def encoder_compile_armature( node
, node_def
):
1765 entdata
= g_encoder
['data']['entdata']
1766 animdata
= g_encoder
['data']['anim']
1767 keyframedata
= g_encoder
['data']['keyframe']
1768 mesh_cache
= g_encoder
['mesh_cache']
1769 obj
= node_def
['obj']
1770 bones
= node_def
['bones']
1773 node_def
['anim_start'] = len(animdata
)
1774 node_def
['anim_count'] = 0
1776 if not node_def
['compile_animation']:
1783 if obj
.animation_data
:
1785 # So we can restore later
1787 previous_frame
= bpy
.context
.scene
.frame_current
1788 previous_action
= obj
.animation_data
.action
1789 POSE_OR_REST_CACHE
= obj
.data
.pose_position
1790 obj
.data
.pose_position
= 'POSE'
1792 for NLALayer
in obj
.animation_data
.nla_tracks
:
1794 for NLAStrip
in NLALayer
.strips
:
1798 for a
in bpy
.data
.actions
:
1800 if a
.name
== NLAStrip
.name
:
1802 obj
.animation_data
.action
= a
1807 # Clip to NLA settings
1809 anim_start
= int(NLAStrip
.action_frame_start
)
1810 anim_end
= int(NLAStrip
.action_frame_end
)
1814 anim
= mdl_animation()
1815 anim
.pstr_name
= encoder_process_pstr( NLAStrip
.action
.name
)
1817 anim
.offset
= len(keyframedata
)
1818 anim
.length
= anim_end
-anim_start
1820 # Export the keyframes
1821 for frame
in range(anim_start
,anim_end
):
1823 bpy
.context
.scene
.frame_set(frame
)
1825 for bone_name
in bones
:
1827 for pb
in obj
.pose
.bones
:
1829 if pb
.name
!= bone_name
: continue
1831 rb
= obj
.data
.bones
[ bone_name
]
1833 # relative bone matrix
1834 if rb
.parent
is not None:
1836 offset_mtx
= rb
.parent
.matrix_local
1837 offset_mtx
= offset_mtx
.inverted_safe() @ \
1840 inv_parent
= pb
.parent
.matrix
@ offset_mtx
1841 inv_parent
.invert_safe()
1842 fpm
= inv_parent
@ pb
.matrix
1846 bone_mtx
= rb
.matrix
.to_4x4()
1847 local_inv
= rb
.matrix_local
.inverted_safe()
1848 fpm
= bone_mtx
@ local_inv
@ pb
.matrix
1851 loc
, rot
, sca
= fpm
.decompose()
1854 final_pos
= Vector(( loc
[0], loc
[2], -loc
[1] ))
1857 lc_m
= pb
.matrix_channel
.to_3x3()
1858 if pb
.parent
is not None:
1860 smtx
= pb
.parent
.matrix_channel
.to_3x3()
1861 lc_m
= smtx
.inverted() @ lc_m
1863 rq
= lc_m
.to_quaternion()
1866 kf
.co
[0] = final_pos
[0]
1867 kf
.co
[1] = final_pos
[1]
1868 kf
.co
[2] = final_pos
[2]
1880 keyframedata
+= [kf
]
1886 # Add to animation buffer
1889 node_def
['anim_count'] += 1
1893 status_name
= F
" " + " |"*(node_def
['depth']-1)
1894 print( F
"{status_name} | *anim: {NLAStrip.action.name}" )
1898 # Restore context to how it was before
1900 bpy
.context
.scene
.frame_set( previous_frame
)
1901 obj
.animation_data
.action
= previous_action
1902 obj
.data
.pose_position
= POSE_OR_REST_CACHE
1906 # We are trying to compile this node_def
1908 def encoder_process_definition( node_def
):
1912 # data sources for object/bone are taken differently
1914 if 'obj' in node_def
:
1916 obj
= node_def
['obj']
1918 obj_co
= obj
.location
1920 if obj_type
== 'ARMATURE':
1921 obj_classtype
= 'classtype_skeleton'
1922 elif obj_type
== 'LIGHT':
1924 obj_classtype
= 'classtype_world_light'
1928 obj_classtype
= obj
.cv_data
.classtype
1930 # Check for armature deform
1932 for mod
in obj
.modifiers
:
1934 if mod
.type == 'ARMATURE':
1936 obj_classtype
= 'classtype_skin'
1938 # Make sure to freeze armature in rest while we collect
1939 # vertex information
1941 armature_def
= g_encoder
['graph_lookup'][mod
.object]
1942 POSE_OR_REST_CACHE
= armature_def
['obj'].data
.pose_position
1943 armature_def
['obj'].data
.pose_position
= 'REST'
1944 node_def
['linked_armature'] = armature_def
1951 elif 'bone' in node_def
:
1953 obj
= node_def
['bone']
1955 obj_co
= obj
.head_local
1956 obj_classtype
= 'classtype_bone'
1962 node
.pstr_name
= encoder_process_pstr( obj
.name
)
1964 if node_def
["parent"]:
1965 node
.parent
= node_def
["parent"]["uid"]
1969 node
.co
[0] = obj_co
[0]
1970 node
.co
[1] = obj_co
[2]
1971 node
.co
[2] = -obj_co
[1]
1973 # Convert rotation quat to our space type
1975 quat
= obj
.matrix_local
.to_quaternion()
1978 node
.q
[2] = -quat
[2]
1981 # Bone scale is just a vector to the tail
1983 if obj_type
== 'BONE':
1985 node
.s
[0] = obj
.tail_local
[0] - node
.co
[0]
1986 node
.s
[1] = obj
.tail_local
[2] - node
.co
[1]
1987 node
.s
[2] = -obj
.tail_local
[1] - node
.co
[2]
1991 node
.s
[0] = obj
.scale
[0]
1992 node
.s
[1] = obj
.scale
[2]
1993 node
.s
[2] = obj
.scale
[1]
1998 tot_uid
= g_encoder
['uid_count']-1
1999 obj_uid
= node_def
['uid']
2000 obj_depth
= node_def
['depth']-1
2002 status_id
= F
" [{obj_uid: 3}/{tot_uid}]" + " |"*obj_depth
2003 status_name
= status_id
+ F
" L {obj.name}"
2005 if obj_classtype
!= 'classtype_none': status_type
= obj_classtype
2006 else: status_type
= obj_type
2008 status_parent
= F
"{node.parent: 3}"
2011 if obj_classtype
== 'classtype_skin':
2012 status_armref
= F
" [armature -> {armature_def['obj'].cv_data.uid}]"
2014 print(F
"{status_name:<32} {status_type:<22} {status_parent} {status_armref}")
2016 # Process mesh if needed
2018 if obj_type
== 'MESH':
2020 encoder_compile_mesh( node
, node_def
)
2022 elif obj_type
== 'ARMATURE':
2024 encoder_compile_armature( node
, node_def
)
2027 encoder_compile_ent_as( obj_classtype
, node
, node_def
)
2029 # Make sure to reset the armature we just mucked about with
2031 if obj_classtype
== 'classtype_skin':
2032 armature_def
['obj'].data
.pose_position
= POSE_OR_REST_CACHE
2034 g_encoder
['data']['node'] += [node
]
2037 # The post processing step or the pre processing to the writing step
2039 def encoder_write_to_file( path
):
2043 # Compile down to a byte array
2045 header
= g_encoder
['header']
2046 file_pos
= sizeof(header
)
2047 file_data
= bytearray()
2048 print( " Compositing data arrays" )
2050 for array_name
in g_encoder
['data']:
2052 file_pos
+= bytearray_align_to( file_data
, 16, sizeof(header
) )
2053 arr
= g_encoder
['data'][array_name
]
2055 setattr( header
, array_name
+ "_offset", file_pos
)
2057 print( F
" {array_name:<16} @{file_pos:> 8X}[{len(arr)}]" )
2059 if isinstance( arr
, bytearray
):
2061 setattr( header
, array_name
+ "_size", len(arr
) )
2063 file_data
.extend( arr
)
2064 file_pos
+= len(arr
)
2068 setattr( header
, array_name
+ "_count", len(arr
) )
2072 bbytes
= bytearray(item
)
2073 file_data
.extend( bbytes
)
2074 file_pos
+= sizeof(item
)
2079 # This imperitive for this field to be santized in the future!
2081 header
.file_length
= file_pos
2083 print( " Writing file" )
2084 # Write header and data chunk to file
2086 fp
= open( path
, "wb" )
2087 fp
.write( bytearray( header
) )
2088 fp
.write( file_data
)
2092 # Main compiler, uses string as the identifier for the collection
2094 def write_model(collection_name
):
2097 print( F
"Model graph | Create mode '{collection_name}'" )
2098 folder
= bpy
.path
.abspath(bpy
.context
.scene
.cv_data
.export_dir
)
2099 path
= F
"{folder}{collection_name}.mdl"
2102 collection
= bpy
.data
.collections
[collection_name
]
2104 encoder_init( collection
)
2105 encoder_build_scene_graph( collection
)
2109 print( " Comping objects" )
2110 it
= encoder_graph_iterator( g_encoder
['scene_graph'] )
2112 encoder_process_definition( node_def
)
2116 encoder_write_to_file( path
)
2118 print( F
"Completed {collection_name}.mdl" )
2121 # ---------------------------------------------------------------------------- #
2125 # ---------------------------------------------------------------------------- #
2127 cv_view_draw_handler
= None
2128 cv_view_shader
= gpu
.shader
.from_builtin('3D_SMOOTH_COLOR')
2130 cv_view_colours
= []
2131 cv_view_course_i
= 0
2133 # Draw axis alligned sphere at position with radius
2135 def cv_draw_sphere( pos
, radius
, colour
):
2137 global cv_view_verts
, cv_view_colours
2139 ly
= pos
+ Vector((0,0,radius
))
2140 lx
= pos
+ Vector((0,radius
,0))
2141 lz
= pos
+ Vector((0,0,radius
))
2143 pi
= 3.14159265358979323846264
2147 t
= ((i
+1.0) * 1.0/16.0) * pi
* 2.0
2151 py
= pos
+ Vector((s
*radius
,0.0,c
*radius
))
2152 px
= pos
+ Vector((s
*radius
,c
*radius
,0.0))
2153 pz
= pos
+ Vector((0.0,s
*radius
,c
*radius
))
2155 cv_view_verts
+= [ px
, lx
]
2156 cv_view_verts
+= [ py
, ly
]
2157 cv_view_verts
+= [ pz
, lz
]
2159 cv_view_colours
+= [ colour
, colour
, colour
, colour
, colour
, colour
]
2168 # Draw axis alligned sphere at position with radius
2170 def cv_draw_halfsphere( pos
, tx
, ty
, tz
, radius
, colour
):
2172 global cv_view_verts
, cv_view_colours
2174 ly
= pos
+ tz
*radius
2175 lx
= pos
+ ty
*radius
2176 lz
= pos
+ tz
*radius
2178 pi
= 3.14159265358979323846264
2182 t
= ((i
+1.0) * 1.0/16.0) * pi
2186 s1
= math
.sin(t
*2.0)
2187 c1
= math
.cos(t
*2.0)
2189 py
= pos
+ s
*tx
*radius
+ c
*tz
*radius
2190 px
= pos
+ s
*tx
*radius
+ c
*ty
*radius
2191 pz
= pos
+ s1
*ty
*radius
+ c1
*tz
*radius
2193 cv_view_verts
+= [ px
, lx
]
2194 cv_view_verts
+= [ py
, ly
]
2195 cv_view_verts
+= [ pz
, lz
]
2197 cv_view_colours
+= [ colour
, colour
, colour
, colour
, colour
, colour
]
2206 # Draw transformed -1 -> 1 cube
2208 def cv_draw_ucube( transform
, colour
):
2210 global cv_view_verts
, cv_view_colours
2212 a
= Vector((-1,-1,-1))
2216 vs
[0] = transform
@ Vector((a
[0], a
[1], a
[2]))
2217 vs
[1] = transform
@ Vector((a
[0], b
[1], a
[2]))
2218 vs
[2] = transform
@ Vector((b
[0], b
[1], a
[2]))
2219 vs
[3] = transform
@ Vector((b
[0], a
[1], a
[2]))
2220 vs
[4] = transform
@ Vector((a
[0], a
[1], b
[2]))
2221 vs
[5] = transform
@ Vector((a
[0], b
[1], b
[2]))
2222 vs
[6] = transform
@ Vector((b
[0], b
[1], b
[2]))
2223 vs
[7] = transform
@ Vector((b
[0], a
[1], b
[2]))
2225 indices
= [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2226 (0,4),(1,5),(2,6),(3,7)]
2232 cv_view_verts
+= [(v0
[0],v0
[1],v0
[2])]
2233 cv_view_verts
+= [(v1
[0],v1
[1],v1
[2])]
2234 cv_view_colours
+= [(0,1,0,1),(0,1,0,1)]
2239 # Draw line with colour
2241 def cv_draw_line( p0
, p1
, colour
):
2243 global cv_view_verts
, cv_view_colours
2245 cv_view_verts
+= [p0
,p1
]
2246 cv_view_colours
+= [colour
, colour
]
2250 # Draw line with colour(s)
2252 def cv_draw_line2( p0
, p1
, c0
, c1
):
2254 global cv_view_verts
, cv_view_colours
2256 cv_view_verts
+= [p0
,p1
]
2257 cv_view_colours
+= [c0
,c1
]
2263 def cv_tangent_basis( n
, tx
, ty
):
2265 if abs( n
[0] ) >= 0.57735027:
2286 # Draw coloured arrow
2288 def cv_draw_arrow( p0
, p1
, c0
):
2290 global cv_view_verts
, cv_view_colours
2296 tx
= Vector((1,0,0))
2297 ty
= Vector((1,0,0))
2298 cv_tangent_basis( n
, tx
, ty
)
2300 cv_view_verts
+= [p0
,p1
, midpt
+(tx
-n
)*0.15,midpt
, midpt
+(-tx
-n
)*0.15,midpt
]
2301 cv_view_colours
+= [c0
,c0
,c0
,c0
,c0
,c0
]
2305 # Drawhandles of a bezier control point
2307 def cv_draw_bhandle( obj
, direction
, colour
):
2309 global cv_view_verts
, cv_view_colours
2312 h0
= obj
.matrix_world
@ Vector((0,direction
,0))
2314 cv_view_verts
+= [p0
]
2315 cv_view_verts
+= [h0
]
2316 cv_view_colours
+= [colour
,colour
]
2320 # Draw a bezier curve (at fixed resolution 10)
2322 def cv_draw_bezier( p0
,h0
,p1
,h1
,c0
,c1
):
2324 global cv_view_verts
, cv_view_colours
2334 p
=ttt
*p1
+(3*tt
-3*ttt
)*h1
+(3*ttt
-6*tt
+3*t
)*h0
+(3*tt
-ttt
-3*t
+1)*p0
2336 cv_view_verts
+= [(last
[0],last
[1],last
[2])]
2337 cv_view_verts
+= [(p
[0],p
[1],p
[2])]
2338 cv_view_colours
+= [c0
*a0
+c1
*(1-a0
),c0
*a0
+c1
*(1-a0
)]
2345 # I think this one extends the handles of the bezier otwards......
2347 def cv_draw_sbpath( o0
,o1
,c0
,c1
,s0
,s1
):
2349 global cv_view_course_i
2351 offs
= ((cv_view_course_i
% 2)*2-1) * cv_view_course_i
* 0.02
2353 p0
= o0
.matrix_world
@ Vector((offs
, 0,0))
2354 h0
= o0
.matrix_world
@ Vector((offs
, s0
,0))
2355 p1
= o1
.matrix_world
@ Vector((offs
, 0,0))
2356 h1
= o1
.matrix_world
@ Vector((offs
,-s1
,0))
2358 cv_draw_bezier( p0
,h0
,p1
,h1
,c0
,c1
)
2362 # Flush the lines buffers. This is called often because god help you if you want
2363 # to do fixed, fast buffers in this catastrophic programming language.
2365 def cv_draw_lines():
2367 global cv_view_shader
, cv_view_verts
, cv_view_colours
2369 if len(cv_view_verts
) < 2:
2372 lines
= batch_for_shader(\
2373 cv_view_shader
, 'LINES', \
2374 { "pos":cv_view_verts
, "color":cv_view_colours
})
2376 lines
.draw( cv_view_shader
)
2379 cv_view_colours
= []
2382 # I dont remember what this does exactly
2384 def cv_draw_bpath( o0
,o1
,c0
,c1
):
2386 cv_draw_sbpath( o0
,o1
,c0
,c1
,1.0,1.0 )
2389 # Semi circle to show the limit. and some lines
2391 def draw_limit( obj
, center
, major
, minor
, amin
, amax
, colour
):
2393 global cv_view_verts
, cv_view_colours
2402 a0
= amin
*(1.0-t0
)+amax
*t0
2403 a1
= amin
*(1.0-t1
)+amax
*t1
2405 p0
= center
+ major
*f
*math
.cos(a0
) + minor
*f
*math
.sin(a0
)
2406 p1
= center
+ major
*f
*math
.cos(a1
) + minor
*f
*math
.sin(a1
)
2408 p0
=obj
.matrix_world
@ p0
2409 p1
=obj
.matrix_world
@ p1
2410 cv_view_verts
+= [p0
,p1
]
2411 cv_view_colours
+= [colour
,colour
]
2415 cv_view_verts
+= [p0
,center
]
2416 cv_view_colours
+= [colour
,colour
]
2420 cv_view_verts
+= [p1
,center
]
2421 cv_view_colours
+= [colour
,colour
]
2425 cv_view_verts
+= [center
+major
*1.2*f
,center
+major
*f
*0.8]
2426 cv_view_colours
+= [colour
,colour
]
2431 # Cone and twist limit
2433 def draw_cone_twist( center
, vx
, vy
, va
):
2435 global cv_view_verts
, cv_view_colours
2436 axis
= vy
.cross( vx
)
2441 cv_view_verts
+= [center
, center
+va
*size
]
2442 cv_view_colours
+= [ (1,1,1,1), (1,1,1,1) ]
2446 t0
= (x
/32) * math
.tau
2447 t1
= ((x
+1)/32) * math
.tau
2454 p0
= center
+ (axis
+ vx
*c0
+ vy
*s0
).normalized() * size
2455 p1
= center
+ (axis
+ vx
*c1
+ vy
*s1
).normalized() * size
2457 col0
= ( abs(c0
), abs(s0
), 0.0, 1.0 )
2458 col1
= ( abs(c1
), abs(s1
), 0.0, 1.0 )
2460 cv_view_verts
+= [center
, p0
, p0
, p1
]
2461 cv_view_colours
+= [ (0,0,0,0), col0
, col0
, col1
]
2467 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2469 def draw_skeleton_helpers( obj
):
2471 global cv_view_verts
, cv_view_colours
2473 if obj
.data
.pose_position
!= 'REST':
2478 for bone
in obj
.data
.bones
:
2481 a
= Vector((bone
.cv_data
.v0
[0], bone
.cv_data
.v0
[1], bone
.cv_data
.v0
[2]))
2482 b
= Vector((bone
.cv_data
.v1
[0], bone
.cv_data
.v1
[1], bone
.cv_data
.v1
[2]))
2484 if bone
.cv_data
.collider
== 'collider_box':
2488 vs
[0]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+a
[1],c
[2]+a
[2]))
2489 vs
[1]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+b
[1],c
[2]+a
[2]))
2490 vs
[2]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+b
[1],c
[2]+a
[2]))
2491 vs
[3]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+a
[1],c
[2]+a
[2]))
2492 vs
[4]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+a
[1],c
[2]+b
[2]))
2493 vs
[5]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+b
[1],c
[2]+b
[2]))
2494 vs
[6]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+b
[1],c
[2]+b
[2]))
2495 vs
[7]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+a
[1],c
[2]+b
[2]))
2497 indices
= [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2498 (0,4),(1,5),(2,6),(3,7)]
2505 cv_view_verts
+= [(v0
[0],v0
[1],v0
[2])]
2506 cv_view_verts
+= [(v1
[0],v1
[1],v1
[2])]
2507 cv_view_colours
+= [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2510 elif bone
.cv_data
.collider
== 'collider_capsule':
2518 if abs(v0
[i
]) > largest
:
2520 largest
= abs(v0
[i
])
2525 v1
= Vector((0,0,0))
2526 v1
[major_axis
] = 1.0
2528 tx
= Vector((0,0,0))
2529 ty
= Vector((0,0,0))
2531 cv_tangent_basis( v1
, tx
, ty
)
2532 r
= (abs(tx
.dot( v0
)) + abs(ty
.dot( v0
))) * 0.25
2533 l
= v0
[ major_axis
] - r
*2
2535 p0
= obj
.matrix_world
@Vector( c
+ (a
+b
)*0.5 + v1
*l
*-0.5 )
2536 p1
= obj
.matrix_world
@Vector( c
+ (a
+b
)*0.5 + v1
*l
* 0.5 )
2538 colour
= [0.2,0.2,0.2,1.0]
2539 colour
[major_axis
] = 0.5
2541 cv_draw_halfsphere( p0
, -v1
, ty
, tx
, r
, colour
)
2542 cv_draw_halfsphere( p1
, v1
, ty
, tx
, r
, colour
)
2543 cv_draw_line( p0
+tx
* r
, p1
+tx
* r
, colour
)
2544 cv_draw_line( p0
+tx
*-r
, p1
+tx
*-r
, colour
)
2545 cv_draw_line( p0
+ty
* r
, p1
+ty
* r
, colour
)
2546 cv_draw_line( p0
+ty
*-r
, p1
+ty
*-r
, colour
)
2553 center
= obj
.matrix_world
@ c
2554 if bone
.cv_data
.con0
:
2556 vx
= Vector([bone
.cv_data
.conevx
[_
] for _
in range(3)])
2557 vy
= Vector([bone
.cv_data
.conevy
[_
] for _
in range(3)])
2558 va
= Vector([bone
.cv_data
.coneva
[_
] for _
in range(3)])
2559 draw_cone_twist( center
, vx
, vy
, va
)
2561 #draw_limit( obj, c, Vector((0,0,1)),Vector((0,-1,0)), \
2562 # bone.cv_data.mins[0], bone.cv_data.maxs[0], \
2564 #draw_limit( obj, c, Vector((0,-1,0)),Vector((1,0,0)), \
2565 # bone.cv_data.mins[1], bone.cv_data.maxs[1], \
2567 #draw_limit( obj, c, Vector((1,0,0)),Vector((0,0,1)), \
2568 # bone.cv_data.mins[2], bone.cv_data.maxs[2], \
2576 global cv_view_shader
2577 global cv_view_verts
2578 global cv_view_colours
2579 global cv_view_course_i
2581 cv_view_course_i
= 0
2583 cv_view_colours
= []
2585 cv_view_shader
.bind()
2586 gpu
.state
.depth_mask_set(False)
2587 gpu
.state
.line_width_set(2.0)
2588 gpu
.state
.face_culling_set('BACK')
2589 gpu
.state
.depth_test_set('LESS')
2590 gpu
.state
.blend_set('NONE')
2592 for obj
in bpy
.context
.collection
.objects
:
2594 if obj
.type == 'ARMATURE':
2596 if obj
.data
.pose_position
== 'REST':
2597 draw_skeleton_helpers( obj
)
2601 classtype
= obj
.cv_data
.classtype
2602 if (classtype
!= 'classtype_none') and (classtype
in globals()):
2604 cl
= globals()[ classtype
]
2606 if getattr( cl
, "draw_scene_helpers", None ):
2608 cl
.draw_scene_helpers( obj
)
2619 # ---------------------------------------------------------------------------- #
2623 # ---------------------------------------------------------------------------- #
2625 # Checks whether this object has a classtype assigned. we can only target other
2627 def cv_poll_target(scene
, obj
):
2629 if obj
== bpy
.context
.active_object
:
2631 if obj
.cv_data
.classtype
== 'classtype_none':
2637 class CV_MESH_SETTINGS(bpy
.types
.PropertyGroup
):
2639 v0
: bpy
.props
.FloatVectorProperty(name
="v0",size
=3)
2640 v1
: bpy
.props
.FloatVectorProperty(name
="v1",size
=3)
2641 v2
: bpy
.props
.FloatVectorProperty(name
="v2",size
=3)
2642 v3
: bpy
.props
.FloatVectorProperty(name
="v3",size
=3)
2645 class CV_OBJ_SETTINGS(bpy
.types
.PropertyGroup
):
2647 uid
: bpy
.props
.IntProperty( name
="" )
2649 strp
: bpy
.props
.StringProperty( name
="strp" )
2650 intp
: bpy
.props
.IntProperty( name
="intp" )
2651 fltp
: bpy
.props
.FloatProperty( name
="fltp" )
2652 bp0
: bpy
.props
.BoolProperty( name
="bp0" )
2653 bp1
: bpy
.props
.BoolProperty( name
="bp1" )
2654 bp2
: bpy
.props
.BoolProperty( name
="bp2" )
2655 bp3
: bpy
.props
.BoolProperty( name
="bp3" )
2657 target
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target", \
2658 poll
=cv_poll_target
)
2659 target1
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target1", \
2660 poll
=cv_poll_target
)
2661 target2
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target2", \
2662 poll
=cv_poll_target
)
2663 target3
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target3", \
2664 poll
=cv_poll_target
)
2666 colour
: bpy
.props
.FloatVectorProperty( name
="colour",subtype
='COLOR',\
2669 classtype
: bpy
.props
.EnumProperty(
2672 ('classtype_none', "classtype_none", "", 0),
2673 ('classtype_gate', "classtype_gate", "", 1),
2674 ('classtype_spawn', "classtype_spawn", "", 3),
2675 ('classtype_water', "classtype_water", "", 4),
2676 ('classtype_route_node', "classtype_route_node", "", 8 ),
2677 ('classtype_route', "classtype_route", "", 9 ),
2678 ('classtype_audio',"classtype_audio","",14),
2679 ('classtype_trigger',"classtype_trigger","",100),
2680 ('classtype_logic_achievement',"classtype_logic_achievement","",101),
2681 ('classtype_logic_relay',"classtype_logic_relay","",102),
2682 ('classtype_spawn_link',"classtype_spawn_link","",150),
2683 ('classtype_nonlocal_gate', "classtype_nonlocal_gate", "", 300)
2687 class CV_BONE_SETTINGS(bpy
.types
.PropertyGroup
):
2689 collider
: bpy
.props
.EnumProperty(
2690 name
="Collider Type",
2692 ('collider_none', "collider_none", "", 0),
2693 ('collider_box', "collider_box", "", 1),
2694 ('collider_capsule', "collider_capsule", "", 2),
2697 v0
: bpy
.props
.FloatVectorProperty(name
="v0",size
=3)
2698 v1
: bpy
.props
.FloatVectorProperty(name
="v1",size
=3)
2700 con0
: bpy
.props
.BoolProperty(name
="Constriant 0",default
=False)
2701 mins
: bpy
.props
.FloatVectorProperty(name
="mins",size
=3)
2702 maxs
: bpy
.props
.FloatVectorProperty(name
="maxs",size
=3)
2704 conevx
: bpy
.props
.FloatVectorProperty(name
="conevx",size
=3)
2705 conevy
: bpy
.props
.FloatVectorProperty(name
="conevy",size
=3)
2706 coneva
: bpy
.props
.FloatVectorProperty(name
="coneva",size
=3)
2707 conet
: bpy
.props
.FloatProperty(name
="conet")
2710 class CV_BONE_PANEL(bpy
.types
.Panel
):
2712 bl_label
="Bone Config"
2713 bl_idname
="SCENE_PT_cv_bone"
2714 bl_space_type
='PROPERTIES'
2715 bl_region_type
='WINDOW'
2718 def draw(_
,context
):
2720 active_object
= context
.active_object
2721 if active_object
== None: return
2723 bone
= active_object
.data
.bones
.active
2724 if bone
== None: return
2726 _
.layout
.prop( bone
.cv_data
, "collider" )
2727 _
.layout
.prop( bone
.cv_data
, "v0" )
2728 _
.layout
.prop( bone
.cv_data
, "v1" )
2730 _
.layout
.label( text
="Angle Limits" )
2731 _
.layout
.prop( bone
.cv_data
, "con0" )
2733 _
.layout
.prop( bone
.cv_data
, "conevx" )
2734 _
.layout
.prop( bone
.cv_data
, "conevy" )
2735 _
.layout
.prop( bone
.cv_data
, "coneva" )
2736 _
.layout
.prop( bone
.cv_data
, "conet" )
2740 class CV_SCENE_SETTINGS(bpy
.types
.PropertyGroup
):
2742 use_hidden
: bpy
.props
.BoolProperty( name
="use hidden", default
=False )
2743 export_dir
: bpy
.props
.StringProperty( name
="Export Dir", subtype
='DIR_PATH' )
2746 class CV_COLLECTION_SETTINGS(bpy
.types
.PropertyGroup
):
2748 pack_textures
: bpy
.props
.BoolProperty( name
="Pack Textures", default
=False )
2749 animations
: bpy
.props
.BoolProperty( name
="Export animation", default
=True)
2752 class CV_MATERIAL_SETTINGS(bpy
.types
.PropertyGroup
):
2754 shader
: bpy
.props
.EnumProperty(
2757 ('standard',"standard","",0),
2758 ('standard_cutout', "standard_cutout", "", 1),
2759 ('terrain_blend', "terrain_blend", "", 2),
2760 ('vertex_blend', "vertex_blend", "", 3),
2761 ('water',"water","",4),
2764 surface_prop
: bpy
.props
.EnumProperty(
2765 name
="Surface Property",
2767 ('concrete','concrete','',0),
2768 ('wood','wood','',1),
2769 ('grass','grass','',2)
2772 collision
: bpy
.props
.BoolProperty( \
2773 name
="Collisions Enabled",\
2775 description
= "Can the player collide with this material"\
2777 skate_surface
: bpy
.props
.BoolProperty( \
2778 name
="Skate Surface", \
2780 description
= "Should the game try to target this surface?" \
2782 grind_surface
: bpy
.props
.BoolProperty( \
2783 name
="Grind Surface", \
2785 description
= "Grind face?" \
2787 grow_grass
: bpy
.props
.BoolProperty( \
2788 name
="Grow Grass", \
2790 description
= "Spawn grass sprites on this surface?" \
2792 blend_offset
: bpy
.props
.FloatVectorProperty( \
2793 name
="Blend Offset", \
2795 default
=Vector((0.5,0.0)),\
2796 description
="When surface is more than 45 degrees, add this vector " +\
2799 sand_colour
: bpy
.props
.FloatVectorProperty( \
2800 name
="Sand Colour",\
2803 default
=Vector((0.79,0.63,0.48)),\
2804 description
="Blend to this colour near the 0 coordinate on UP axis"\
2806 shore_colour
: bpy
.props
.FloatVectorProperty( \
2807 name
="Shore Colour",\
2810 default
=Vector((0.03,0.32,0.61)),\
2811 description
="Water colour at the shoreline"\
2813 ocean_colour
: bpy
.props
.FloatVectorProperty( \
2814 name
="Ocean Colour",\
2817 default
=Vector((0.0,0.006,0.03)),\
2818 description
="Water colour in the deep bits"\
2822 class CV_MATERIAL_PANEL(bpy
.types
.Panel
):
2824 bl_label
="Skate Rift material"
2825 bl_idname
="MATERIAL_PT_cv_material"
2826 bl_space_type
='PROPERTIES'
2827 bl_region_type
='WINDOW'
2828 bl_context
="material"
2830 def draw(_
,context
):
2832 active_object
= bpy
.context
.active_object
2833 if active_object
== None: return
2834 active_mat
= active_object
.active_material
2835 if active_mat
== None: return
2837 info
= material_info( active_mat
)
2839 if 'tex_diffuse' in info
:
2841 _
.layout
.label( icon
='INFO', \
2842 text
=F
"{info['tex_diffuse'].name} will be compiled" )
2845 _
.layout
.prop( active_mat
.cv_data
, "shader" )
2846 _
.layout
.prop( active_mat
.cv_data
, "surface_prop" )
2847 _
.layout
.prop( active_mat
.cv_data
, "collision" )
2849 if active_mat
.cv_data
.collision
:
2850 _
.layout
.prop( active_mat
.cv_data
, "skate_surface" )
2851 _
.layout
.prop( active_mat
.cv_data
, "grind_surface" )
2852 _
.layout
.prop( active_mat
.cv_data
, "grow_grass" )
2854 if active_mat
.cv_data
.shader
== "terrain_blend":
2856 box
= _
.layout
.box()
2857 box
.prop( active_mat
.cv_data
, "blend_offset" )
2858 box
.prop( active_mat
.cv_data
, "sand_colour" )
2860 elif active_mat
.cv_data
.shader
== "vertex_blend":
2862 box
= _
.layout
.box()
2863 box
.label( icon
='INFO', text
="Uses vertex colours, the R channel" )
2864 box
.prop( active_mat
.cv_data
, "blend_offset" )
2866 elif active_mat
.cv_data
.shader
== "water":
2868 box
= _
.layout
.box()
2869 box
.label( icon
='INFO', text
="Depth scale of 16 meters" )
2870 box
.prop( active_mat
.cv_data
, "shore_colour" )
2871 box
.prop( active_mat
.cv_data
, "ocean_colour" )
2876 class CV_OBJ_PANEL(bpy
.types
.Panel
):
2878 bl_label
="Entity Config"
2879 bl_idname
="SCENE_PT_cv_entity"
2880 bl_space_type
='PROPERTIES'
2881 bl_region_type
='WINDOW'
2884 def draw(_
,context
):
2886 active_object
= bpy
.context
.active_object
2887 if active_object
== None: return
2888 if active_object
.type == 'ARMATURE':
2890 row
= _
.layout
.row()
2892 row
.label( text
="This object has the intrinsic classtype of skeleton" )
2896 _
.layout
.prop( active_object
.cv_data
, "classtype" )
2898 classtype
= active_object
.cv_data
.classtype
2900 if (classtype
!= 'classtype_none') and (classtype
in globals()):
2902 cl
= globals()[ classtype
]
2904 if getattr( cl
, "editor_interface", None ):
2906 cl
.editor_interface( _
.layout
, active_object
)
2912 class CV_COMPILE(bpy
.types
.Operator
):
2914 bl_idname
="carve.compile_all"
2915 bl_label
="Compile All"
2917 def execute(_
,context
):
2919 view_layer
= bpy
.context
.view_layer
2920 for col
in view_layer
.layer_collection
.children
["export"].children
:
2921 if not col
.hide_viewport
or bpy
.context
.scene
.cv_data
.use_hidden
:
2922 write_model( col
.name
)
2928 class CV_COMPILE_THIS(bpy
.types
.Operator
):
2930 bl_idname
="carve.compile_this"
2931 bl_label
="Compile This collection"
2933 def execute(_
,context
):
2935 col
= bpy
.context
.collection
2936 write_model( col
.name
)
2942 class CV_INTERFACE(bpy
.types
.Panel
):
2944 bl_idname
= "VIEW3D_PT_carve"
2945 bl_label
= "Skate Rift"
2946 bl_space_type
= 'VIEW_3D'
2947 bl_region_type
= 'UI'
2948 bl_category
= "Skate Rift"
2950 def draw(_
, context
):
2953 layout
.prop( context
.scene
.cv_data
, "export_dir" )
2955 col
= bpy
.context
.collection
2957 found_in_export
= False
2959 view_layer
= bpy
.context
.view_layer
2960 for c1
in view_layer
.layer_collection
.children
["export"].children
:
2962 if not c1
.hide_viewport
or bpy
.context
.scene
.cv_data
.use_hidden
:
2965 if c1
.name
== col
.name
:
2967 found_in_export
= True
2974 box
.label( text
=col
.name
+ ".mdl" )
2975 box
.prop( col
.cv_data
, "pack_textures" )
2976 box
.prop( col
.cv_data
, "animations" )
2977 box
.operator( "carve.compile_this" )
2983 row
.label( text
=col
.name
)
2984 box
.label( text
="This collection is not in the export group" )
2990 split
= row
.split( factor
= 0.3, align
=True )
2991 split
.prop( context
.scene
.cv_data
, "use_hidden", text
="hidden" )
2994 if export_count
== 0:
2996 row1
.operator( "carve.compile_all", \
2997 text
=F
"Compile all ({export_count} collections)" )
3002 classes
= [CV_OBJ_SETTINGS
,CV_OBJ_PANEL
,CV_COMPILE
,CV_INTERFACE
,\
3003 CV_MESH_SETTINGS
, CV_SCENE_SETTINGS
, CV_BONE_SETTINGS
,\
3004 CV_BONE_PANEL
, CV_COLLECTION_SETTINGS
, CV_COMPILE_THIS
,\
3005 CV_MATERIAL_SETTINGS
, CV_MATERIAL_PANEL
]
3009 global cv_view_draw_handler
3012 bpy
.utils
.register_class(c
)
3014 bpy
.types
.Object
.cv_data
= bpy
.props
.PointerProperty(type=CV_OBJ_SETTINGS
)
3015 bpy
.types
.Mesh
.cv_data
= bpy
.props
.PointerProperty(type=CV_MESH_SETTINGS
)
3016 bpy
.types
.Scene
.cv_data
= bpy
.props
.PointerProperty(type=CV_SCENE_SETTINGS
)
3017 bpy
.types
.Bone
.cv_data
= bpy
.props
.PointerProperty(type=CV_BONE_SETTINGS
)
3018 bpy
.types
.Collection
.cv_data
= \
3019 bpy
.props
.PointerProperty(type=CV_COLLECTION_SETTINGS
)
3020 bpy
.types
.Material
.cv_data
= \
3021 bpy
.props
.PointerProperty(type=CV_MATERIAL_SETTINGS
)
3023 cv_view_draw_handler
= bpy
.types
.SpaceView3D
.draw_handler_add(\
3024 cv_draw
,(),'WINDOW','POST_VIEW')
3029 global cv_view_draw_handler
3032 bpy
.utils
.unregister_class(c
)
3034 bpy
.types
.SpaceView3D
.draw_handler_remove(cv_view_draw_handler
,'WINDOW')
3037 # ---------------------------------------------------------------------------- #
3041 # ---------------------------------------------------------------------------- #
3043 # Transliteration of: #
3044 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
3046 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
3047 # SPDX-License-Identifier: MIT #
3048 # QOI - The "Quite OK Image" format for fast, lossless image compression #
3050 # ---------------------------------------------------------------------------- #
3052 class qoi_rgba_t(Structure
):
3055 _fields_
= [("r",c_uint8
),
3061 QOI_OP_INDEX
= 0x00 # 00xxxxxx
3062 QOI_OP_DIFF
= 0x40 # 01xxxxxx
3063 QOI_OP_LUMA
= 0x80 # 10xxxxxx
3064 QOI_OP_RUN
= 0xc0 # 11xxxxxx
3065 QOI_OP_RGB
= 0xfe # 11111110
3066 QOI_OP_RGBA
= 0xff # 11111111
3068 QOI_MASK_2
= 0xc0 # 11000000
3070 def qoi_colour_hash( c
):
3072 return c
.r
*3 + c
.g
*5 + c
.b
*7 + c
.a
*11
3077 return (a
.r
==b
.r
) and (a
.g
==b
.g
) and (a
.b
==b
.b
) and (a
.a
==b
.a
)
3082 return bytearray([ (0xff000000 & v
) >> 24, \
3083 (0x00ff0000 & v
) >> 16, \
3084 (0x0000ff00 & v
) >> 8, \
3088 def qoi_encode( img
):
3092 print(F
" . Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]")
3094 index
= [ qoi_rgba_t() for _
in range(64) ]
3098 data
.extend( bytearray(c_uint32(0x66696f71)) )
3099 data
.extend( qoi_32bit( img
.size
[0] ) )
3100 data
.extend( qoi_32bit( img
.size
[1] ) )
3101 data
.extend( bytearray(c_uint8(4)) )
3102 data
.extend( bytearray(c_uint8(0)) )
3105 px_prev
= qoi_rgba_t()
3106 px_prev
.r
= c_uint8(0)
3107 px_prev
.g
= c_uint8(0)
3108 px_prev
.b
= c_uint8(0)
3109 px_prev
.a
= c_uint8(255)
3117 px_len
= img
.size
[0] * img
.size
[1]
3119 paxels
= [ int(min(max(_
,0),1)*255) for _
in img
.pixels
]
3121 for px_pos
in range( px_len
):
3123 idx
= px_pos
* img
.channels
3126 px
.r
= paxels
[idx
+min(0,nc
)]
3127 px
.g
= paxels
[idx
+min(1,nc
)]
3128 px
.b
= paxels
[idx
+min(2,nc
)]
3129 px
.a
= paxels
[idx
+min(3,nc
)]
3131 if qoi_eq( px
, px_prev
):
3135 if (run
== 62) or (px_pos
== px_len
-1):
3137 data
.extend( bytearray( c_uint8(QOI_OP_RUN |
(run
-1))) )
3145 data
.extend( bytearray( c_uint8(QOI_OP_RUN |
(run
-1))) )
3149 index_pos
= qoi_colour_hash(px
) % 64
3151 if qoi_eq( index
[index_pos
], px
):
3153 data
.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos
)) )
3157 index
[ index_pos
].r
= px
.r
3158 index
[ index_pos
].g
= px
.g
3159 index
[ index_pos
].b
= px
.b
3160 index
[ index_pos
].a
= px
.a
3162 if px
.a
== px_prev
.a
:
3164 vr
= int(px
.r
) - int(px_prev
.r
)
3165 vg
= int(px
.g
) - int(px_prev
.g
)
3166 vb
= int(px
.b
) - int(px_prev
.b
)
3171 if (vr
> -3) and (vr
< 2) and\
3172 (vg
> -3) and (vg
< 2) and\
3173 (vb
> -3) and (vb
< 2):
3175 op
= QOI_OP_DIFF |
(vr
+2) << 4 |
(vg
+2) << 2 |
(vb
+2)
3176 data
.extend( bytearray( c_uint8(op
) ))
3178 elif (vg_r
> -9) and (vg_r
< 8) and\
3179 (vg
> -33) and (vg
< 32 ) and\
3180 (vg_b
> -9) and (vg_b
< 8):
3182 op
= QOI_OP_LUMA |
(vg
+32)
3183 delta
= (vg_r
+8) << 4 |
(vg_b
+ 8)
3184 data
.extend( bytearray( c_uint8(op
) ) )
3185 data
.extend( bytearray( c_uint8(delta
) ))
3189 data
.extend( bytearray( c_uint8(QOI_OP_RGB
) ) )
3190 data
.extend( bytearray( c_uint8(px
.r
) ))
3191 data
.extend( bytearray( c_uint8(px
.g
) ))
3192 data
.extend( bytearray( c_uint8(px
.b
) ))
3197 data
.extend( bytearray( c_uint8(QOI_OP_RGBA
) ) )
3198 data
.extend( bytearray( c_uint8(px
.r
) ))
3199 data
.extend( bytearray( c_uint8(px
.g
) ))
3200 data
.extend( bytearray( c_uint8(px
.b
) ))
3201 data
.extend( bytearray( c_uint8(px
.a
) ))
3214 data
.extend( bytearray( c_uint8(0) ))
3215 data
.extend( bytearray( c_uint8(1) ))
3216 bytearray_align_to( data
, 16, 0 )