now we're doing a bunch of them
[carveJwlIkooP6JGAAIwe30JlM.git] / blender_export.py
1 #
2 # =============================================================================
3 #
4 # Copyright . . . -----, ,----- ,---. .---.
5 # 2021-2023 |\ /| | / | | | | /|
6 # | \ / | +-- / +----- +---' | / |
7 # | \ / | | / | | \ | / |
8 # | \/ | | / | | \ | / |
9 # ' ' '--' [] '----- '----- ' ' '---' SOFTWARE
10 #
11 # =============================================================================
12 #
13 # Python exporter for Blender, compiles .mdl format for Skate Rift.
14 #
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
17 # otherwise
18 #
19
20 import bpy, math, gpu, os
21 import cProfile
22 from ctypes import *
23 from mathutils import *
24 from gpu_extras.batch import batch_for_shader
25
26 bl_info = {
27 "name":"Skate Rift model compiler",
28 "author": "Harry Godden (hgn)",
29 "version": (0,2),
30 "blender":(3,1,0),
31 "location":"Export",
32 "descriptin":"",
33 "warning":"",
34 "wiki_url":"",
35 "category":"Import/Export",
36 }
37
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),
42 ("norm",c_float*3),
43 ("uv",c_float*2),
44 ("colour",c_uint8*4),
45 ("weights",c_uint16*4),
46 ("groups",c_uint8*4)]
47 #}
48
49 class mdl_submesh(Structure):
50 #{
51 _pack_ = 1
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
58 #}
59
60 class mdl_texture(Structure):
61 #{
62 _pack_ = 1
63 _fields_ = [("pstr_name",c_uint32),
64 ("pack_offset",c_uint32),
65 ("pack_length",c_uint32)]
66 #}
67
68 class mdl_material(Structure):
69 #{
70 _pack_ = 1
71 _fields_ = [("pstr_name",c_uint32),
72 ("shader",c_uint32),
73 ("flags",c_uint32),
74 ("surface_prop",c_uint32),
75 ("colour",c_float*4),
76 ("colour1",c_float*4),
77 ("tex_diffuse",c_uint32),
78 ("tex_decal",c_uint32),
79 ("tex_normal",c_uint32)]
80 #}
81
82 class mdl_node(Structure):
83 #{
84 _pack_ = 1
85 _fields_ = [("co",c_float*3),
86 ( "q",c_float*4),
87 ( "s",c_float*3),
88 ("sub_uid",c_uint32), # dont use
89 ("submesh_start",c_uint32),
90 ("submesh_count",c_uint32),
91 ("classtype",c_uint32),
92 ("offset",c_uint32),
93 ("parent",c_uint32),
94 ("pstr_name",c_uint32)]
95 #}
96
97 class mdl_header(Structure):
98 #{
99 _pack_ = 1
100 _fields_ = [("identifier",c_uint32),
101 ("version",c_uint32),
102 ("file_length",c_uint32),
103 ("pad0",c_uint32),
104
105 ("node_count",c_uint32),
106 ("node_offset",c_uint32),
107
108 ("submesh_count",c_uint32),
109 ("submesh_offset",c_uint32),
110
111 ("material_count",c_uint32),
112 ("material_offset",c_uint32),
113
114 ("texture_count",c_uint32),
115 ("texture_offset",c_uint32),
116
117 ("anim_count",c_uint32),
118 ("anim_offset",c_uint32),
119
120 ("entdata_size",c_uint32),
121 ("entdata_offset",c_uint32),
122
123 ("strings_size",c_uint32),
124 ("strings_offset",c_uint32),
125
126 ("keyframe_count",c_uint32),
127 ("keyframe_offset",c_uint32),
128
129 ("vertex_count",c_uint32),
130 ("vertex_offset",c_uint32),
131
132 ("indice_count",c_uint32),
133 ("indice_offset",c_uint32),
134
135 ("pack_size",c_uint32),
136 ("pack_offset",c_uint32)]
137 #}
138
139 class mdl_animation(Structure):
140 #{
141 _pack_ = 1
142 _fields_ = [("pstr_name",c_uint32),
143 ("length",c_uint32),
144 ("rate",c_float),
145 ("offset",c_uint32)]
146 #}
147
148 class mdl_keyframe(Structure):
149 #{
150 _pack_ = 1
151 _fields_ = [("co",c_float*3),
152 ("q",c_float*4),
153 ("s",c_float*3)]
154 #}
155
156 # ---------------------------------------------------------------------------- #
157 # #
158 # Entity definitions #
159 # #
160 # ---------------------------------------------------------------------------- #
161 #
162 # ctypes _fields_ defines the data which is filled in by:
163 # def encode_obj( _, node, node_def ):
164 #
165 # gizmos get drawn into the viewport via:
166 # @staticmethod
167 # def draw_scene_helpers( obj ):
168 #
169 # editor enterface, simiraliy:
170 # @staticmethod
171 # def editor_interface( layout, obj ):
172 #
173
174 # Classtype 1
175 #
176 # Purpose: A rift. must target another gate, the target gate can not have more
177 # than one target nodes of its own.
178 #
179 class classtype_gate(Structure):
180 #{
181 _pack_ = 1
182 _fields_ = [("target",c_uint32),
183 ("dims",c_float*3)]
184
185 def encode_obj(_, node,node_def):
186 #{
187 node.classtype = 1
188
189 obj = node_def['obj']
190
191 if obj.cv_data.target != None:
192 _.target = obj.cv_data.target.cv_data.uid
193
194 if obj.type == 'MESH':
195 #{
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]
199 #}
200 else:
201 #{
202 _.dims[0] = obj.cv_data.v0[0]
203 _.dims[1] = obj.cv_data.v0[1]
204 _.dims[2] = obj.cv_data.v0[2]
205 #}
206 #}
207
208 @staticmethod
209 def draw_scene_helpers( obj ):
210 #{
211 global cv_view_verts, cv_view_colours
212
213 if obj.type == 'MESH':
214 dims = obj.data.cv_data.v0
215 else:
216 dims = obj.cv_data.v0
217
218 vs = [None]*9
219 c = Vector((0,0,dims[2]))
220
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)))
230
231 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
232
233 for l in indices:
234 #{
235 v0 = vs[l[0]]
236 v1 = vs[l[1]]
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)]
240 #}
241
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 )
245 #}
246
247 @staticmethod
248 def editor_interface( layout, obj ):
249 #{
250 layout.prop( obj.cv_data, "target" )
251
252 mesh = obj.data
253 layout.label( text=F"(i) Data is stored in {mesh.name}" )
254 layout.prop( mesh.cv_data, "v0", text="Gate dimensions" )
255 #}
256 #}
257
258 class classtype_nonlocal_gate(classtype_gate):
259 #{
260 def encode_obj(_,node,node_def):
261 #{
262 node.classtype = 300
263
264 obj = node_def['obj']
265 _.target = encoder_process_pstr( node_def['obj'].cv_data.strp )
266
267 if obj.type == 'MESH':
268 #{
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]
272 #}
273 else:
274 #{
275 _.dims[0] = obj.cv_data.v0[0]
276 _.dims[1] = obj.cv_data.v0[1]
277 _.dims[2] = obj.cv_data.v0[2]
278 #}
279 #}
280
281 @staticmethod
282 def editor_interface( layout, obj ):
283 #{
284 layout.prop( obj.cv_data, "strp", text="Nonlocal ID" )
285
286 mesh = obj.data
287 layout.label( text=F"(i) Data is stored in {mesh.name}" )
288 layout.prop( mesh.cv_data, "v0", text="Gate dimensions" )
289 #}
290 #}
291
292 # Classtype 3
293 #
294 # Purpose: player can reset here, its a safe place
295 # spawns can share the same name, the closest one will be picked
296 #
297 # when the world loads it will pick the one named 'start' first.
298 #
299 class classtype_spawn(Structure):
300 #{
301 _pack_ = 1
302 _fields_ = [("pstr_alias",c_uint32)]
303
304 def encode_obj(_, node,node_def):
305 #{
306 node.classtype = 3
307 _.pstr_alias = encoder_process_pstr( node_def['obj'].cv_data.strp )
308 #}
309
310 @staticmethod
311 def draw_scene_helpers( obj ):
312 #{
313 global cv_view_verts, cv_view_colours
314
315 vs = [None]*4
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)]
321
322 for l in indices:
323 #{
324 v0 = vs[l[0]]
325 v1 = vs[l[1]]
326
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)]
330 #}
331
332 cv_draw_sphere( obj.location, 20.0, [0.1,0,0.9,0.4] )
333 #}
334
335 @staticmethod
336 def editor_interface( layout, obj ):
337 #{
338 layout.prop( obj.cv_data, "strp", text="Alias" )
339 #}
340 #}
341
342 # Classtype 4
343 #
344 # Purpose: Tells the game to draw water HERE, at this entity.
345 #
346 class classtype_water(Structure):
347 #{
348 _pack_ = 1
349 _fields_ = [("temp",c_uint32)]
350
351 def encode_obj(_, node,node_def):
352 #{
353 node.classtype = 4
354 # no data, spooky
355 #}
356 #}
357
358 # Classtype 8
359 #
360 # Purpose: Defines a route node and links to up to two more nodes
361 #
362 class classtype_route_node(Structure):
363 #{
364 _pack_ = 1
365 _fields_ = [("target",c_uint32),
366 ("target1",c_uint32)]
367
368 def encode_obj(_, node,node_def):
369 #{
370 node.classtype = 8
371 obj = node_def['obj']
372
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
377 #}
378
379 @staticmethod
380 def draw_scene_helpers( obj ):
381 #{
382 global cv_view_verts, cv_view_colours
383
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 )
390
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) )
393
394 p1 = obj.location+ \
395 obj.matrix_world.to_quaternion() @ Vector((0,0,-6+1.5))
396 cv_draw_arrow( obj.location, p1, sw )
397 #}
398
399 @staticmethod
400 def editor_interface( layout, obj ):
401 #{
402 layout.prop( obj.cv_data, "target", text="Left" )
403 layout.prop( obj.cv_data, "target1", text="Right" )
404 #}
405 #}
406
407 # Classtype 9
408 #
409 # Purpose: Defines a route, its 'starting' point, and the colour to use for it
410 #
411 class classtype_route(Structure):
412 #{
413 _pack_ = 1
414 _fields_ = [("id_start",c_uint32),
415 ("pstr_name",c_uint32),
416 ("colour",c_float*3)]
417
418 def encode_obj(_, node,node_def):
419 #{
420 node.classtype = 9
421 obj = node_def['obj']
422
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 )
427
428 if obj.cv_data.target != None:
429 _.id_start = obj.cv_data.target.cv_data.uid
430 #}
431
432 @staticmethod
433 def draw_scene_helpers( obj ):
434 #{
435 global cv_view_verts, cv_view_colours, cv_view_course_i
436
437 if obj.cv_data.target:
438 cv_draw_arrow( obj.location, obj.cv_data.target.location, [1,1,1,1] )
439
440 # Tries to simulate how we do it in the game
441 #
442 stack = [None]*64
443 stack_i = [0]*64
444 stack[0] = obj.cv_data.target
445 si = 1
446 loop_complete = False
447
448 while si > 0:
449 #{
450 if stack_i[si-1] == 2:
451 #{
452 si -= 1
453 continue
454
455 if si == 0: # Loop failed to complete
456 break
457 #}
458
459 node = stack[si-1]
460
461 targets = [None,None]
462 targets[0] = node.cv_data.target
463
464 if node.cv_data.classtype == 'classtype_route_node':
465 #{
466 targets[1] = node.cv_data.target1
467 #}
468
469 nextnode = targets[stack_i[si-1]]
470 stack_i[si-1] += 1
471
472 if nextnode != None: # branch
473 #{
474 if nextnode == stack[0]: # Loop completed
475 #{
476 loop_complete = True
477 break
478 #}
479
480 valid=True
481 for sj in range(si):
482 #{
483 if stack[sj] == nextnode: # invalidated path
484 #{
485 valid=False
486 break
487 #}
488 #}
489
490 if valid:
491 #{
492 stack_i[si] = 0
493 stack[si] = nextnode
494 si += 1
495 continue
496 #}
497 #}
498 #}
499
500 if loop_complete:
501 #{
502 cc = Vector((obj.cv_data.colour[0],\
503 obj.cv_data.colour[1],\
504 obj.cv_data.colour[2],\
505 1.0))
506
507 for sj in range(si):
508 #{
509 sk = (sj+1)%si
510
511 if stack[sj].cv_data.classtype == 'classtype_gate' and \
512 stack[sk].cv_data.classtype == 'classtype_gate':
513 #{
514 dist = (stack[sj].location-stack[sk].location).magnitude
515 cv_draw_sbpath( stack[sj], stack[sk], cc*0.4, cc, dist, dist )
516 #}
517 else:
518 cv_draw_bpath( stack[sj], stack[sk], cc, cc )
519 #}
520
521 cv_view_course_i += 1
522 #}
523 #}
524
525 @staticmethod
526 def editor_interface( layout, obj ):
527 #{
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" )
531 #}
532 #}
533
534 # Classtype 12
535 #
536 # Purpose: links an mesh node to a type 11
537 #
538 class classtype_skin(Structure):
539 #{
540 _pack_ = 1
541 _fields_ = [("skeleton",c_uint32)]
542
543 def encode_obj(_, node,node_def):
544 #{
545 node.classtype = 12
546
547 armature_def = node_def['linked_armature']
548 _.skeleton = armature_def['obj'].cv_data.uid
549 #}
550 #}
551
552 # Classtype 11
553 #
554 # Purpose: defines the allocation requirements for a skeleton
555 #
556 class classtype_skeleton(Structure):
557 #{
558 _pack_ = 1
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)]
564
565 def encode_obj(_, node,node_def):
566 #{
567 node.classtype = 11
568
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']
574 #}
575 #}
576
577
578 # Classtype 10
579 #
580 # Purpose: intrinsic bone type, stores collision information and limits too
581 #
582 class classtype_bone(Structure):
583 #{
584 _pack_ = 1
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),
592 ("conet",c_float)]
593
594 def encode_obj(_, node,node_def):
595 #{
596 node.classtype = 10
597
598 armature_def = node_def['linked_armature']
599 obj = node_def['bone']
600
601 _.flags = node_def['deform']
602
603 if 'ik_target' in node_def:
604 #{
605 _.flags |= 0x2
606 _.ik_target = armature_def['bones'].index( node_def['ik_target'] )
607 _.ik_pole = armature_def['bones'].index( node_def['ik_pole'] )
608 #}
609
610 # For ragdolls
611 #
612 if obj.cv_data.collider != 'collider_none':
613 #{
614 if obj.cv_data.collider == 'collider_box':
615 _.flags |= 0x4
616 else:
617 _.flags |= 0x8
618
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]
625 #}
626
627 if obj.cv_data.con0:
628 #{
629 _.flags |= 0x100
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
640 #}
641 #}
642 #}
643
644 # Classtype 100
645 #
646 # Purpose: sends a signal to another entity
647 #
648 class classtype_trigger(Structure):
649 #{
650 _pack_ = 1
651 _fields_ = [("target",c_uint32)]
652
653 def encode_obj(_, node,node_def ):
654 #{
655 node.classtype = 100
656 if node_def['obj'].cv_data.target:
657 _.target = node_def['obj'].cv_data.target.cv_data.uid
658 #}
659
660 @staticmethod
661 def draw_scene_helpers( obj ):
662 #{
663 global cv_view_verts, cv_view_colours
664 cv_draw_ucube( obj.matrix_world, [0,1,0,1] )
665
666 if obj.cv_data.target:
667 cv_draw_arrow( obj.location, obj.cv_data.target.location, [1,1,1,1] )
668 #}
669
670 @staticmethod
671 def editor_interface( layout, obj ):
672 #{
673 layout.prop( obj.cv_data, "target", text="Triggers" )
674 #}
675 #}
676
677 # Classtype 101
678 #
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 ;)
682 #
683 class classtype_logic_achievement(Structure):
684 #{
685 _pack_ = 1
686 _fields_ = [("pstr_name",c_uint32)]
687
688 def encode_obj(_, node,node_def ):
689 #{
690 node.classtype = 101
691 _.pstr_name = encoder_process_pstr( node_def['obj'].cv_data.strp )
692 #}
693
694 @staticmethod
695 def editor_interface( layout, obj ):
696 #{
697 layout.prop( obj.cv_data, "strp", text="Achievement ID" )
698 #}
699 #}
700
701 # Classtype 102
702 #
703 # Purpose: sends a signal to another entity
704 #
705 class classtype_logic_relay(Structure):
706 #{
707 _pack_ = 1
708 _fields_ = [("targets",c_uint32*4)]
709
710 def encode_obj(_, node,node_def ):
711 #{
712 node.classtype = 102
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
722 #}
723
724 @staticmethod
725 def draw_scene_helpers( obj ):
726 #{
727 global cv_view_verts, cv_view_colours
728
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] )
737 #}
738
739 @staticmethod
740 def editor_interface( layout, obj ):
741 #{
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" )
746 #}
747 #}
748
749 # Classtype 14
750 #
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)
754 # per sample.
755 #
756 # volume: not used if has 3D flag
757 # flags:
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)
762 # ......
763 # the rest are just internal flags, only use the above 3.
764 #
765 class classtype_audio(Structure):
766 #{
767 _pack_ = 1
768 _fields_ = [("pstr_file",c_uint32),
769 ("flags",c_uint32),
770 ("volume",c_float)]
771
772 def encode_obj(_, node,node_def ):
773 #{
774 node.classtype = 14
775
776 obj = node_def['obj']
777
778 _.pstr_file = encoder_process_pstr( obj.cv_data.strp )
779
780 flags = 0x00
781 if obj.cv_data.bp0: flags |= 0x1
782 if obj.cv_data.bp1: flags |= 0x4
783 if obj.cv_data.bp2: flags |= 0x8
784
785 _.flags = flags
786 _.volume = obj.cv_data.fltp
787 #}
788
789 @staticmethod
790 def editor_interface( layout, obj ):
791 #{
792 layout.prop( obj.cv_data, "strp" )
793
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" )
797 #}
798
799 @staticmethod
800 def draw_scene_helpers( obj ):
801 #{
802 global cv_view_verts, cv_view_colours
803
804 cv_draw_sphere( obj.location, obj.scale[0], [1,1,0,1] )
805 #}
806 #}
807
808 # Classtype 200
809 #
810 # Purpose: point light
811 #
812 class classtype_point_light(Structure):
813 #{
814 _pack_ = 1
815 _fields_ = [("colour",c_float*4)]
816
817 def encode_obj(_, node, node_def):
818 #{
819 node.classtype = 200
820
821 data = node_def['obj'].data
822 _.colour[0] = data.color[0]
823 _.colour[1] = data.color[1]
824 _.colour[2] = data.color[2]
825 _.colour[3] = data.energy
826 #}
827
828 @staticmethod
829 def editor_interface( layout, obj ):
830 #{
831 pass
832 #}
833 #}
834
835 # Classtype 201
836 #
837 # Purpose: lighting settings for world
838 #
839 class classtype_lighting_info(Structure):
840 #{
841 _pack_ = 1
842 _fields_ = [("colours",(c_float*3)*3),
843 ("directions",(c_float*2)*3),
844 ("states",c_uint32*3),
845 ("shadow_spread",c_float),
846 ("shadow_length",c_float),
847 ("ambient",c_float*3)]
848
849 def encode_obj(_, node, node_def):
850 #{
851 node.classtype = 201
852
853 # TODO
854 #}
855
856 @staticmethod
857 def editor_interface( layout, obj ):
858 #{
859 pass
860 #}
861 #}
862
863 class classtype_spawn_link(Structure):
864 #{
865 _pack_ = 1
866 _fields_ = [("connections",c_uint32*4)]
867
868 def encode_obj(_, node,node_def ):
869 #{
870 node.classtype = 0
871 #}
872
873 @staticmethod
874 def editor_interface( layout, obj ):
875 #{
876 pass
877 #}
878
879 @staticmethod
880 def draw_scene_helpers( obj ):
881 #{
882 global cv_view_verts, cv_view_colours
883
884 count = 0
885
886 for obj1 in bpy.context.collection.objects:
887 #{
888 if (obj1.cv_data.classtype != 'classtype_spawn_link') and \
889 (obj1.cv_data.classtype != 'classtype_spawn') :
890 continue
891
892 if (obj1.location - obj.location).length < 40.0:
893 #{
894 cv_draw_line( obj.location, obj1.location, [1,1,1,1] )
895 count +=1
896 #}
897
898 if count == 4:
899 break
900 #}
901
902 cv_draw_sphere( obj.location, 20.0, [0.5,0,0.2,0.4] )
903 #}
904 #}
905
906 # ---------------------------------------------------------------------------- #
907 # #
908 # Compiler section #
909 # #
910 # ---------------------------------------------------------------------------- #
911
912 # Current encoder state
913 #
914 g_encoder = None
915
916 # Reset encoder
917 #
918 def encoder_init( collection ):
919 #{
920 global g_encoder
921
922 g_encoder = \
923 {
924 # The actual file header
925 #
926 'header': mdl_header(),
927
928 # Options
929 #
930 'pack_textures': collection.cv_data.pack_textures,
931
932 # Compiled data chunks (each can be read optionally by the client)
933 #
934 'data':
935 {
936 #1---------------------------------
937 'node': [], # Metadata 'chunk'
938 'submesh': [],
939 'material': [],
940 'texture': [],
941 'anim': [],
942 'entdata': bytearray(), # variable width
943 'strings': bytearray(), # .
944 #2---------------------------------
945 'keyframe': [], # Animations
946 #3---------------------------------
947 'vertex': [], # Mesh data
948 'indice': [],
949 #4---------------------------------
950 'pack': bytearray() # Other generic packed data
951 },
952
953 # All objects of the model in their final heirachy
954 #
955 "uid_count": 1,
956 "scene_graph":{},
957 "graph_lookup":{},
958
959 # Allows us to reuse definitions
960 #
961 'string_cache':{},
962 'mesh_cache': {},
963 'material_cache': {},
964 'texture_cache': {}
965 }
966
967 g_encoder['header'].identifier = 0xABCD0000
968 g_encoder['header'].version = 1
969
970 # Add fake NoneID material and texture
971 #
972 none_material = mdl_material()
973 none_material.pstr_name = encoder_process_pstr( "" )
974 none_material.texture_id = 0
975
976 none_texture = mdl_texture()
977 none_texture.pstr_name = encoder_process_pstr( "" )
978 none_texture.pack_offset = 0
979 none_texture.pack_length = 0
980
981 g_encoder['data']['material'] += [none_material]
982 g_encoder['data']['texture'] += [none_texture]
983
984 g_encoder['data']['pack'].extend( b'datapack\0\0\0\0\0\0\0\0' )
985
986 # Add root node
987 #
988 root = mdl_node()
989 root.co[0] = 0
990 root.co[1] = 0
991 root.co[2] = 0
992 root.q[0] = 0
993 root.q[1] = 0
994 root.q[2] = 0
995 root.q[3] = 1
996 root.s[0] = 1
997 root.s[1] = 1
998 root.s[2] = 1
999 root.pstr_name = encoder_process_pstr('')
1000 root.submesh_start = 0
1001 root.submesh_count = 0
1002 root.offset = 0
1003 root.classtype = 0
1004 root.parent = 0xffffffff
1005
1006 g_encoder['data']['node'] += [root]
1007 #}
1008
1009
1010 # fill with 0x00 until a multiple of align. Returns how many bytes it added
1011 #
1012 def bytearray_align_to( buffer, align, offset=0 ):
1013 #{
1014 count = 0
1015
1016 while ((len(buffer)+offset) % align) != 0:
1017 #{
1018 buffer.extend( b'\0' )
1019 count += 1
1020 #}
1021
1022 return count
1023 #}
1024
1025 # Add a string to the string buffer except if it already exists there then we
1026 # just return its ID.
1027 #
1028 def encoder_process_pstr( s ):
1029 #{
1030 global g_encoder
1031
1032 cache = g_encoder['string_cache']
1033
1034 if s in cache:
1035 return cache[s]
1036
1037 cache[s] = len( g_encoder['data']['strings'] )
1038
1039 buffer = g_encoder['data']['strings']
1040 buffer.extend( s.encode('utf-8') )
1041 buffer.extend( b'\0' )
1042
1043 bytearray_align_to( buffer, 4 )
1044 return cache[s]
1045 #}
1046
1047 def get_texture_resource_name( img ):
1048 #{
1049 return os.path.splitext( img.name )[0]
1050 #}
1051
1052 # Pack a texture
1053 #
1054 def encoder_process_texture( img ):
1055 #{
1056 global g_encoder
1057
1058 if img == None:
1059 return 0
1060
1061 cache = g_encoder['texture_cache']
1062 buffer = g_encoder['data']['texture']
1063 pack = g_encoder['data']['pack']
1064
1065 name = get_texture_resource_name( img )
1066
1067 if name in cache:
1068 return cache[name]
1069
1070 cache[name] = len( buffer )
1071
1072 tex = mdl_texture()
1073 tex.pstr_name = encoder_process_pstr( name )
1074
1075 if g_encoder['pack_textures']:
1076 #{
1077 tex.pack_offset = len( pack )
1078 pack.extend( qoi_encode( img ) )
1079 tex.pack_length = len( pack ) - tex.pack_offset
1080 #}
1081 else:
1082 tex.pack_offset = 0
1083
1084 buffer += [ tex ]
1085 return cache[name]
1086 #}
1087
1088 def material_tex_image(v):
1089 #{
1090 return {
1091 "Image Texture":
1092 {
1093 "image": F"{v}"
1094 }
1095 }
1096 #}
1097
1098 cxr_graph_mapping = \
1099 {
1100 # Default shader setup
1101 "Principled BSDF":
1102 {
1103 "Base Color":
1104 {
1105 "Image Texture":
1106 {
1107 "image": "tex_diffuse"
1108 },
1109 "Mix":
1110 {
1111 "A": material_tex_image("tex_diffuse"),
1112 "B": material_tex_image("tex_decal")
1113 },
1114 },
1115 "Normal":
1116 {
1117 "Normal Map":
1118 {
1119 "Color": material_tex_image("tex_normal")
1120 }
1121 }
1122 }
1123 }
1124
1125 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
1126 #
1127 def material_info(mat):
1128 #{
1129 info = {}
1130
1131 # Using the cv_graph_mapping as a reference, go through the shader
1132 # graph and gather all $props from it.
1133 #
1134 def _graph_read( node_def, node=None, depth=0 ):
1135 #{
1136 nonlocal mat
1137 nonlocal info
1138
1139 # Find rootnodes
1140 #
1141 if node == None:
1142 #{
1143 _graph_read.extracted = []
1144
1145 for node_idname in node_def:
1146 #{
1147 for n in mat.node_tree.nodes:
1148 #{
1149 if n.name == node_idname:
1150 #{
1151 node_def = node_def[node_idname]
1152 node = n
1153 break
1154 #}
1155 #}
1156 #}
1157 #}
1158
1159 for link in node_def:
1160 #{
1161 link_def = node_def[link]
1162
1163 if isinstance( link_def, dict ):
1164 #{
1165 node_link = None
1166 for x in node.inputs:
1167 #{
1168 if isinstance( x, bpy.types.NodeSocketColor ):
1169 #{
1170 if link == x.name:
1171 #{
1172 node_link = x
1173 break
1174 #}
1175 #}
1176 #}
1177
1178 if node_link and node_link.is_linked:
1179 #{
1180 # look for definitions for the connected node type
1181 #
1182 from_node = node_link.links[0].from_node
1183
1184 node_name = from_node.name.split('.')[0]
1185 if node_name in link_def:
1186 #{
1187 from_node_def = link_def[ node_name ]
1188
1189 _graph_read( from_node_def, from_node, depth+1 )
1190 #}
1191
1192 # No definition! :(
1193 # TODO: Make a warning for this?
1194 #}
1195 else:
1196 #{
1197 if "default" in link_def:
1198 #{
1199 prop = link_def['default']
1200 info[prop] = node_link.default_value
1201 #}
1202 #}
1203 #}
1204 else:
1205 #{
1206 prop = link_def
1207 info[prop] = getattr( node, link )
1208 #}
1209 #}
1210 #}
1211
1212 _graph_read( cxr_graph_mapping )
1213 return info
1214 #}
1215
1216 # Add a material to the material buffer. Returns 0 (None ID) if invalid
1217 #
1218 def encoder_process_material( mat ):
1219 #{
1220 global g_encoder
1221
1222 if mat == None:
1223 return 0
1224
1225 cache = g_encoder['material_cache']
1226 buffer = g_encoder['data']['material']
1227
1228 if mat.name in cache:
1229 return cache[mat.name]
1230
1231 cache[mat.name] = len( buffer )
1232
1233 dest = mdl_material()
1234 dest.pstr_name = encoder_process_pstr( mat.name )
1235
1236 flags = 0x00
1237 if mat.cv_data.collision:
1238 flags |= 0x2
1239 if mat.cv_data.skate_surface: flags |= 0x1
1240 if mat.cv_data.grind_surface: flags |= (0x8|0x1)
1241
1242 if mat.cv_data.grow_grass: flags |= 0x4
1243 dest.flags = flags
1244
1245 if mat.cv_data.surface_prop == 'concrete': dest.surface_prop = 0
1246 if mat.cv_data.surface_prop == 'wood': dest.surface_prop = 1
1247 if mat.cv_data.surface_prop == 'grass': dest.surface_prop = 2
1248
1249 if mat.cv_data.shader == 'standard': dest.shader = 0
1250 if mat.cv_data.shader == 'standard_cutout': dest.shader = 1
1251 if mat.cv_data.shader == 'terrain_blend':
1252 #{
1253 dest.shader = 2
1254
1255 dest.colour[0] = pow( mat.cv_data.sand_colour[0], 1.0/2.2 )
1256 dest.colour[1] = pow( mat.cv_data.sand_colour[1], 1.0/2.2 )
1257 dest.colour[2] = pow( mat.cv_data.sand_colour[2], 1.0/2.2 )
1258 dest.colour[3] = 1.0
1259
1260 dest.colour1[0] = mat.cv_data.blend_offset[0]
1261 dest.colour1[1] = mat.cv_data.blend_offset[1]
1262 #}
1263
1264 if mat.cv_data.shader == 'vertex_blend':
1265 #{
1266 dest.shader = 3
1267
1268 dest.colour1[0] = mat.cv_data.blend_offset[0]
1269 dest.colour1[1] = mat.cv_data.blend_offset[1]
1270 #}
1271
1272 if mat.cv_data.shader == 'water':
1273 #{
1274 dest.shader = 4
1275
1276 dest.colour[0] = pow( mat.cv_data.shore_colour[0], 1.0/2.2 )
1277 dest.colour[1] = pow( mat.cv_data.shore_colour[1], 1.0/2.2 )
1278 dest.colour[2] = pow( mat.cv_data.shore_colour[2], 1.0/2.2 )
1279 dest.colour[3] = 1.0
1280 dest.colour1[0] = pow( mat.cv_data.ocean_colour[0], 1.0/2.2 )
1281 dest.colour1[1] = pow( mat.cv_data.ocean_colour[1], 1.0/2.2 )
1282 dest.colour1[2] = pow( mat.cv_data.ocean_colour[2], 1.0/2.2 )
1283 dest.colour1[3] = 1.0
1284 #}
1285
1286 inf = material_info( mat )
1287
1288 if mat.cv_data.shader == 'standard' or \
1289 mat.cv_data.shader == 'standard_cutout' or \
1290 mat.cv_data.shader == 'terrain_blend' or \
1291 mat.cv_data.shader == 'vertex_blend':
1292 #{
1293 if 'tex_diffuse' in inf:
1294 dest.tex_diffuse = encoder_process_texture(inf['tex_diffuse'])
1295 #}
1296
1297 buffer += [dest]
1298 return cache[mat.name]
1299 #}
1300
1301 # Create a tree structure containing all the objects in the collection
1302 #
1303 def encoder_build_scene_graph( collection ):
1304 #{
1305 global g_encoder
1306
1307 print( " creating scene graph" )
1308
1309 # initialize root
1310 #
1311 graph = g_encoder['scene_graph']
1312 graph_lookup = g_encoder['graph_lookup']
1313 graph["obj"] = None
1314 graph["depth"] = 0
1315 graph["children"] = []
1316 graph["uid"] = 0
1317 graph["parent"] = None
1318
1319 def _new_uid():
1320 #{
1321 global g_encoder
1322 uid = g_encoder['uid_count']
1323 g_encoder['uid_count'] += 1
1324 return uid
1325 #}
1326
1327 for obj in collection.all_objects:
1328 #{
1329 if obj.parent: continue
1330
1331 def _extend( p, n, d ):
1332 #{
1333 nonlocal collection
1334
1335 uid = _new_uid()
1336 tree = {}
1337 tree["uid"] = uid
1338 tree["children"] = []
1339 tree["depth"] = d
1340 tree["obj"] = n
1341 tree["parent"] = p
1342 n.cv_data.uid = uid
1343
1344 # Descend into amature
1345 #
1346 if n.type == 'ARMATURE':
1347 #{
1348 tree["bones"] = [None] # None is the root transform
1349 tree["ik_count"] = 0
1350 tree["collider_count"] = 0
1351 tree["compile_animation"] = collection.cv_data.animations
1352
1353 # Here also collects some information about constraints, ik and
1354 # counts colliders for the armature.
1355 #
1356 def _extendb( p, n, d ):
1357 #{
1358 nonlocal tree
1359
1360 btree = {}
1361 btree["bone"] = n
1362 btree["linked_armature"] = tree
1363 btree["uid"] = _new_uid()
1364 btree["children"] = []
1365 btree["depth"] = d
1366 btree["parent"] = p
1367 tree["bones"] += [n.name]
1368
1369 for c in n.children:
1370 #{
1371 _extendb( btree, c, d+1 )
1372 #}
1373
1374 for c in tree['obj'].pose.bones[n.name].constraints:
1375 #{
1376 if c.type == 'IK':
1377 #{
1378 btree["ik_target"] = c.subtarget
1379 btree["ik_pole"] = c.pole_subtarget
1380 tree["ik_count"] += 1
1381 #}
1382 #}
1383
1384 if n.cv_data.collider != 'collider_none':
1385 tree['collider_count'] += 1
1386
1387 btree['deform'] = n.use_deform
1388 p['children'] += [btree]
1389 #}
1390
1391 for b in n.data.bones:
1392 if not b.parent:
1393 _extendb( tree, b, d+1 )
1394 #}
1395
1396 # Recurse into children of this object
1397 #
1398 for obj1 in n.children:
1399 #{
1400 for c1 in obj1.users_collection:
1401 #{
1402 if c1 == collection:
1403 #{
1404 _extend( tree, obj1, d+1 )
1405 break
1406 #}
1407 #}
1408 #}
1409
1410 p["children"] += [tree]
1411 graph_lookup[n] = tree
1412
1413 #}
1414
1415 _extend( graph, obj, 1 )
1416
1417 #}
1418 #}
1419
1420
1421 # Kind of a useless thing i made but it looks cool and adds complexity!!1
1422 #
1423 def encoder_graph_iterator( root ):
1424 #{
1425 for c in root['children']:
1426 #{
1427 yield c
1428 yield from encoder_graph_iterator(c)
1429 #}
1430 #}
1431
1432
1433 # Push a vertex into the model file, or return a cached index (c_uint32)
1434 #
1435 def encoder_vertex_push( vertex_reference, co,norm,uv,colour,groups,weights ):
1436 #{
1437 global g_encoder
1438 buffer = g_encoder['data']['vertex']
1439
1440 TOLERENCE = 4
1441 m = float(10**TOLERENCE)
1442
1443 # Would be nice to know if this can be done faster than it currently runs,
1444 # its quite slow.
1445 #
1446 key = (int(co[0]*m+0.5),
1447 int(co[1]*m+0.5),
1448 int(co[2]*m+0.5),
1449 int(norm[0]*m+0.5),
1450 int(norm[1]*m+0.5),
1451 int(norm[2]*m+0.5),
1452 int(uv[0]*m+0.5),
1453 int(uv[1]*m+0.5),
1454 colour[0], # these guys are already quantized
1455 colour[1], # .
1456 colour[2], # .
1457 colour[3], # .
1458 weights[0], # v
1459 weights[1],
1460 weights[2],
1461 weights[3],
1462 groups[0],
1463 groups[1],
1464 groups[2],
1465 groups[3])
1466
1467 if key in vertex_reference:
1468 return vertex_reference[key]
1469 else:
1470 #{
1471 index = c_uint32( len(vertex_reference) )
1472 vertex_reference[key] = index
1473
1474 v = mdl_vert()
1475 v.co[0] = co[0]
1476 v.co[1] = co[2]
1477 v.co[2] = -co[1]
1478 v.norm[0] = norm[0]
1479 v.norm[1] = norm[2]
1480 v.norm[2] = -norm[1]
1481 v.uv[0] = uv[0]
1482 v.uv[1] = uv[1]
1483 v.colour[0] = colour[0]
1484 v.colour[1] = colour[1]
1485 v.colour[2] = colour[2]
1486 v.colour[3] = colour[3]
1487 v.weights[0] = weights[0]
1488 v.weights[1] = weights[1]
1489 v.weights[2] = weights[2]
1490 v.weights[3] = weights[3]
1491 v.groups[0] = groups[0]
1492 v.groups[1] = groups[1]
1493 v.groups[2] = groups[2]
1494 v.groups[3] = groups[3]
1495
1496 buffer += [v]
1497 return index
1498 #}
1499 #}
1500
1501
1502 # Compile a mesh (or use one from the cache) onto node, based on node_def
1503 # No return value
1504 #
1505 def encoder_compile_mesh( node, node_def ):
1506 #{
1507 global g_encoder
1508
1509 graph = g_encoder['scene_graph']
1510 graph_lookup = g_encoder['graph_lookup']
1511 mesh_cache = g_encoder['mesh_cache']
1512 obj = node_def['obj']
1513 armature_def = None
1514 can_use_cache = True
1515
1516 # Check for modifiers that typically change the data per-instance
1517 # there is no well defined rule for the choices here, its just what i've
1518 # needed while producing the game.
1519 #
1520 # It may be possible to detect these cases automatically.
1521 #
1522 for mod in obj.modifiers:
1523 #{
1524 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
1525 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
1526 mod.type == 'ARRAY':
1527 #{
1528 can_use_cache = False
1529 #}
1530
1531 if mod.type == 'ARMATURE':
1532 armature_def = graph_lookup[mod.object]
1533
1534 # Check the cache first
1535 #
1536 if can_use_cache and (obj.data.name in mesh_cache):
1537 #{
1538 ref = mesh_cache[obj.data.name]
1539 node.submesh_start = ref.submesh_start
1540 node.submesh_count = ref.submesh_count
1541 return
1542 #}
1543
1544 # Compile a whole new mesh
1545 #
1546 node.submesh_start = len( g_encoder['data']['submesh'] )
1547 node.submesh_count = 0
1548
1549 dgraph = bpy.context.evaluated_depsgraph_get()
1550 data = obj.evaluated_get(dgraph).data
1551 data.calc_loop_triangles()
1552 data.calc_normals_split()
1553
1554 # Mesh is split into submeshes based on their material
1555 #
1556 mat_list = data.materials if len(data.materials) > 0 else [None]
1557 for material_id, mat in enumerate(mat_list):
1558 #{
1559 mref = {}
1560
1561 sm = mdl_submesh()
1562 sm.indice_start = len( g_encoder['data']['indice'] )
1563 sm.vertex_start = len( g_encoder['data']['vertex'] )
1564 sm.vertex_count = 0
1565 sm.indice_count = 0
1566 sm.material_id = encoder_process_material( mat )
1567
1568 for i in range(3):
1569 #{
1570 sm.bbx[0][i] = 999999
1571 sm.bbx[1][i] = -999999
1572 #}
1573
1574 # Keep a reference to very very very similar vertices
1575 #
1576 vertex_reference = {}
1577
1578 # Write the vertex / indice data
1579 #
1580 for tri_index, tri in enumerate(data.loop_triangles):
1581 #{
1582 if tri.material_index != material_id:
1583 continue
1584
1585 for j in range(3):
1586 #{
1587 vert = data.vertices[tri.vertices[j]]
1588 li = tri.loops[j]
1589 vi = data.loops[li].vertex_index
1590
1591 # Gather vertex information
1592 #
1593 co = vert.co
1594 norm = data.loops[li].normal
1595 uv = (0,0)
1596 colour = (255,255,255,255)
1597 groups = [0,0,0,0]
1598 weights = [0,0,0,0]
1599
1600 # Uvs
1601 #
1602 if data.uv_layers:
1603 uv = data.uv_layers.active.data[li].uv
1604
1605 # Vertex Colours
1606 #
1607 if data.vertex_colors:
1608 #{
1609 colour = data.vertex_colors.active.data[li].color
1610 colour = (int(colour[0]*255.0),\
1611 int(colour[1]*255.0),\
1612 int(colour[2]*255.0),\
1613 int(colour[3]*255.0))
1614 #}
1615
1616 # Weight groups: truncates to the 3 with the most influence. The
1617 # fourth bone ID is never used by the shader so it is
1618 # always 0
1619 #
1620 if armature_def:
1621 #{
1622 src_groups = [_ for _ in data.vertices[vi].groups \
1623 if obj.vertex_groups[_.group].name in \
1624 armature_def['bones']]
1625
1626 weight_groups = sorted( src_groups, key = \
1627 lambda a: a.weight, reverse=True )
1628 tot = 0.0
1629 for ml in range(3):
1630 #{
1631 if len(weight_groups) > ml:
1632 #{
1633 g = weight_groups[ml]
1634 name = obj.vertex_groups[g.group].name
1635 weight = g.weight
1636
1637 weights[ml] = weight
1638 groups[ml] = armature_def['bones'].index(name)
1639 tot += weight
1640 #}
1641 #}
1642
1643 if len(weight_groups) > 0:
1644 #{
1645 inv_norm = (1.0/tot) * 65535.0
1646 for ml in range(3):
1647 #{
1648 weights[ml] = int( weights[ml] * inv_norm )
1649 weights[ml] = min( weights[ml], 65535 )
1650 weights[ml] = max( weights[ml], 0 )
1651 #}
1652 #}
1653 #}
1654 else:
1655 #{
1656 li1 = tri.loops[(j+1)%3]
1657 vi1 = data.loops[li1].vertex_index
1658 e0 = data.edges[ data.loops[li].edge_index ]
1659
1660 if e0.use_freestyle_mark and \
1661 ((e0.vertices[0] == vi and e0.vertices[1] == vi1) or \
1662 (e0.vertices[0] == vi1 and e0.vertices[1] == vi)):
1663 #{
1664 weights[0] = 1
1665 #}
1666 #}
1667
1668 # Add vertex and expand bound box
1669 #
1670 index = encoder_vertex_push( vertex_reference, co, \
1671 norm, \
1672 uv, \
1673 colour, \
1674 groups, \
1675 weights )
1676 g_encoder['data']['indice'] += [index]
1677 #}
1678 #}
1679
1680 # How many unique verts did we add in total
1681 #
1682 sm.vertex_count = len(g_encoder['data']['vertex']) - sm.vertex_start
1683 sm.indice_count = len(g_encoder['data']['indice']) - sm.indice_start
1684
1685 # Make sure bounding box isn't -inf -> inf if no vertices
1686 #
1687 if sm.vertex_count == 0:
1688 for j in range(2):
1689 for i in range(3):
1690 sm.bbx[j][i] = 0
1691 else:
1692 #{
1693 for j in range(sm.vertex_count):
1694 #{
1695 vert = g_encoder['data']['vertex'][ sm.vertex_start + j ]
1696
1697 for i in range(3):
1698 #{
1699 sm.bbx[0][i] = min( sm.bbx[0][i], vert.co[i] )
1700 sm.bbx[1][i] = max( sm.bbx[1][i], vert.co[i] )
1701 #}
1702 #}
1703 #}
1704
1705 # Add submesh to encoder
1706 #
1707 g_encoder['data']['submesh'] += [sm]
1708 node.submesh_count += 1
1709
1710 #}
1711
1712 # Save a reference to this node since we want to reuse the submesh indices
1713 # later.
1714 g_encoder['mesh_cache'][obj.data.name] = node
1715 #}
1716
1717
1718 def encoder_compile_ent_as( name, node, node_def ):
1719 #{
1720 global g_encoder
1721
1722 if name == 'classtype_none':
1723 #{
1724 node.offset = 0
1725 node.classtype = 0
1726 return
1727 #}
1728 elif name not in globals():
1729 #{
1730 print( "Classtype '" +name + "' is unknown!" )
1731 return
1732 #}
1733
1734 buffer = g_encoder['data']['entdata']
1735 node.offset = len(buffer)
1736
1737 cl = globals()[ name ]
1738 inst = cl()
1739 inst.encode_obj( node, node_def )
1740
1741 buffer.extend( bytearray(inst) )
1742 bytearray_align_to( buffer, 4 )
1743 #}
1744
1745 # Compiles animation data into model and gives us some extra node_def entries
1746 #
1747 def encoder_compile_armature( node, node_def ):
1748 #{
1749 global g_encoder
1750
1751 entdata = g_encoder['data']['entdata']
1752 animdata = g_encoder['data']['anim']
1753 keyframedata = g_encoder['data']['keyframe']
1754 mesh_cache = g_encoder['mesh_cache']
1755 obj = node_def['obj']
1756 bones = node_def['bones']
1757
1758 # extra info
1759 node_def['anim_start'] = len(animdata)
1760 node_def['anim_count'] = 0
1761
1762 if not node_def['compile_animation']:
1763 #{
1764 return
1765 #}
1766
1767 # Compile anims
1768 #
1769 if obj.animation_data:
1770 #{
1771 # So we can restore later
1772 #
1773 previous_frame = bpy.context.scene.frame_current
1774 previous_action = obj.animation_data.action
1775 POSE_OR_REST_CACHE = obj.data.pose_position
1776 obj.data.pose_position = 'POSE'
1777
1778 for NLALayer in obj.animation_data.nla_tracks:
1779 #{
1780 for NLAStrip in NLALayer.strips:
1781 #{
1782 # set active
1783 #
1784 for a in bpy.data.actions:
1785 #{
1786 if a.name == NLAStrip.name:
1787 #{
1788 obj.animation_data.action = a
1789 break
1790 #}
1791 #}
1792
1793 # Clip to NLA settings
1794 #
1795 anim_start = int(NLAStrip.action_frame_start)
1796 anim_end = int(NLAStrip.action_frame_end)
1797
1798 # Export strips
1799 #
1800 anim = mdl_animation()
1801 anim.pstr_name = encoder_process_pstr( NLAStrip.action.name )
1802 anim.rate = 30.0
1803 anim.offset = len(keyframedata)
1804 anim.length = anim_end-anim_start
1805
1806 # Export the keyframes
1807 for frame in range(anim_start,anim_end):
1808 #{
1809 bpy.context.scene.frame_set(frame)
1810
1811 for bone_name in bones:
1812 #{
1813 for pb in obj.pose.bones:
1814 #{
1815 if pb.name != bone_name: continue
1816
1817 rb = obj.data.bones[ bone_name ]
1818
1819 # relative bone matrix
1820 if rb.parent is not None:
1821 #{
1822 offset_mtx = rb.parent.matrix_local
1823 offset_mtx = offset_mtx.inverted_safe() @ \
1824 rb.matrix_local
1825
1826 inv_parent = pb.parent.matrix @ offset_mtx
1827 inv_parent.invert_safe()
1828 fpm = inv_parent @ pb.matrix
1829 #}
1830 else:
1831 #{
1832 bone_mtx = rb.matrix.to_4x4()
1833 local_inv = rb.matrix_local.inverted_safe()
1834 fpm = bone_mtx @ local_inv @ pb.matrix
1835 #}
1836
1837 loc, rot, sca = fpm.decompose()
1838
1839 # local position
1840 final_pos = Vector(( loc[0], loc[2], -loc[1] ))
1841
1842 # rotation
1843 lc_m = pb.matrix_channel.to_3x3()
1844 if pb.parent is not None:
1845 #{
1846 smtx = pb.parent.matrix_channel.to_3x3()
1847 lc_m = smtx.inverted() @ lc_m
1848 #}
1849 rq = lc_m.to_quaternion()
1850
1851 kf = mdl_keyframe()
1852 kf.co[0] = final_pos[0]
1853 kf.co[1] = final_pos[1]
1854 kf.co[2] = final_pos[2]
1855
1856 kf.q[0] = rq[1]
1857 kf.q[1] = rq[3]
1858 kf.q[2] = -rq[2]
1859 kf.q[3] = rq[0]
1860
1861 # scale
1862 kf.s[0] = sca[0]
1863 kf.s[1] = sca[2]
1864 kf.s[2] = sca[1]
1865
1866 keyframedata += [kf]
1867 break
1868 #}
1869 #}
1870 #}
1871
1872 # Add to animation buffer
1873 #
1874 animdata += [anim]
1875 node_def['anim_count'] += 1
1876
1877 # Report progress
1878 #
1879 status_name = F" " + " |"*(node_def['depth']-1)
1880 print( F"{status_name} | *anim: {NLAStrip.action.name}" )
1881 #}
1882 #}
1883
1884 # Restore context to how it was before
1885 #
1886 bpy.context.scene.frame_set( previous_frame )
1887 obj.animation_data.action = previous_action
1888 obj.data.pose_position = POSE_OR_REST_CACHE
1889 #}
1890 #}
1891
1892 # We are trying to compile this node_def
1893 #
1894 def encoder_process_definition( node_def ):
1895 #{
1896 global g_encoder
1897
1898 # data sources for object/bone are taken differently
1899 #
1900 if 'obj' in node_def:
1901 #{
1902 obj = node_def['obj']
1903 obj_type = obj.type
1904 obj_co = obj.location
1905
1906 if obj_type == 'ARMATURE':
1907 obj_classtype = 'classtype_skeleton'
1908 elif obj_type == 'LIGHT':
1909 #{
1910 if obj.data.type == 'POINT':
1911 obj_classtype = 'classtype_point_light'
1912 #}
1913 else:
1914 #{
1915 obj_classtype = obj.cv_data.classtype
1916
1917 # Check for armature deform
1918 #
1919 for mod in obj.modifiers:
1920 #{
1921 if mod.type == 'ARMATURE':
1922 #{
1923 obj_classtype = 'classtype_skin'
1924
1925 # Make sure to freeze armature in rest while we collect
1926 # vertex information
1927 #
1928 armature_def = g_encoder['graph_lookup'][mod.object]
1929 POSE_OR_REST_CACHE = armature_def['obj'].data.pose_position
1930 armature_def['obj'].data.pose_position = 'REST'
1931 node_def['linked_armature'] = armature_def
1932 break
1933 #}
1934 #}
1935 #}
1936 #}
1937
1938 elif 'bone' in node_def:
1939 #{
1940 obj = node_def['bone']
1941 obj_type = 'BONE'
1942 obj_co = obj.head_local
1943 obj_classtype = 'classtype_bone'
1944 #}
1945
1946 # Create node
1947 #
1948 node = mdl_node()
1949 node.pstr_name = encoder_process_pstr( obj.name )
1950
1951 if node_def["parent"]:
1952 node.parent = node_def["parent"]["uid"]
1953
1954 # Setup transform
1955 #
1956 node.co[0] = obj_co[0]
1957 node.co[1] = obj_co[2]
1958 node.co[2] = -obj_co[1]
1959
1960 # Convert rotation quat to our space type
1961 #
1962 quat = obj.matrix_local.to_quaternion()
1963 node.q[0] = quat[1]
1964 node.q[1] = quat[3]
1965 node.q[2] = -quat[2]
1966 node.q[3] = quat[0]
1967
1968 # Bone scale is just a vector to the tail
1969 #
1970 if obj_type == 'BONE':
1971 #{
1972 node.s[0] = obj.tail_local[0] - node.co[0]
1973 node.s[1] = obj.tail_local[2] - node.co[1]
1974 node.s[2] = -obj.tail_local[1] - node.co[2]
1975 #}
1976 else:
1977 #{
1978 node.s[0] = obj.scale[0]
1979 node.s[1] = obj.scale[2]
1980 node.s[2] = obj.scale[1]
1981 #}
1982
1983 # Report status
1984 #
1985 tot_uid = g_encoder['uid_count']-1
1986 obj_uid = node_def['uid']
1987 obj_depth = node_def['depth']-1
1988
1989 status_id = F" [{obj_uid: 3}/{tot_uid}]" + " |"*obj_depth
1990 status_name = status_id + F" L {obj.name}"
1991
1992 if obj_classtype != 'classtype_none': status_type = obj_classtype
1993 else: status_type = obj_type
1994
1995 status_parent = F"{node.parent: 3}"
1996 status_armref = ""
1997
1998 if obj_classtype == 'classtype_skin':
1999 status_armref = F" [armature -> {armature_def['obj'].cv_data.uid}]"
2000
2001 print(F"{status_name:<32} {status_type:<22} {status_parent} {status_armref}")
2002
2003 # Process mesh if needed
2004 #
2005 if obj_type == 'MESH':
2006 #{
2007 encoder_compile_mesh( node, node_def )
2008 #}
2009 elif obj_type == 'ARMATURE':
2010 #{
2011 encoder_compile_armature( node, node_def )
2012 #}
2013
2014 encoder_compile_ent_as( obj_classtype, node, node_def )
2015
2016 # Make sure to reset the armature we just mucked about with
2017 #
2018 if obj_classtype == 'classtype_skin':
2019 armature_def['obj'].data.pose_position = POSE_OR_REST_CACHE
2020
2021 g_encoder['data']['node'] += [node]
2022 #}
2023
2024 # The post processing step or the pre processing to the writing step
2025 #
2026 def encoder_write_to_file( path ):
2027 #{
2028 global g_encoder
2029
2030 # Compile down to a byte array
2031 #
2032 header = g_encoder['header']
2033 file_pos = sizeof(header)
2034 file_data = bytearray()
2035 print( " Compositing data arrays" )
2036
2037 for array_name in g_encoder['data']:
2038 #{
2039 file_pos += bytearray_align_to( file_data, 16, sizeof(header) )
2040 arr = g_encoder['data'][array_name]
2041
2042 setattr( header, array_name + "_offset", file_pos )
2043
2044 print( F" {array_name:<16} @{file_pos:> 8X}[{len(arr)}]" )
2045
2046 if isinstance( arr, bytearray ):
2047 #{
2048 setattr( header, array_name + "_size", len(arr) )
2049
2050 file_data.extend( arr )
2051 file_pos += len(arr)
2052 #}
2053 else:
2054 #{
2055 setattr( header, array_name + "_count", len(arr) )
2056
2057 for item in arr:
2058 #{
2059 bbytes = bytearray(item)
2060 file_data.extend( bbytes )
2061 file_pos += sizeof(item)
2062 #}
2063 #}
2064 #}
2065
2066 # This imperitive for this field to be santized in the future!
2067 #
2068 header.file_length = file_pos
2069
2070 print( " Writing file" )
2071 # Write header and data chunk to file
2072 #
2073 fp = open( path, "wb" )
2074 fp.write( bytearray( header ) )
2075 fp.write( file_data )
2076 fp.close()
2077 #}
2078
2079 # Main compiler, uses string as the identifier for the collection
2080 #
2081 def write_model(collection_name):
2082 #{
2083 global g_encoder
2084 print( F"Model graph | Create mode '{collection_name}'" )
2085 folder = bpy.path.abspath(bpy.context.scene.cv_data.export_dir)
2086 path = F"{folder}{collection_name}.mdl"
2087 print( path )
2088
2089 collection = bpy.data.collections[collection_name]
2090
2091 encoder_init( collection )
2092 encoder_build_scene_graph( collection )
2093
2094 # Compile
2095 #
2096 print( " Comping objects" )
2097 it = encoder_graph_iterator( g_encoder['scene_graph'] )
2098 for node_def in it:
2099 encoder_process_definition( node_def )
2100
2101 # Write
2102 #
2103 encoder_write_to_file( path )
2104
2105 print( F"Completed {collection_name}.mdl" )
2106 #}
2107
2108 # ---------------------------------------------------------------------------- #
2109 # #
2110 # GUI section #
2111 # #
2112 # ---------------------------------------------------------------------------- #
2113
2114 cv_view_draw_handler = None
2115 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
2116 cv_view_verts = []
2117 cv_view_colours = []
2118 cv_view_course_i = 0
2119
2120 # Draw axis alligned sphere at position with radius
2121 #
2122 def cv_draw_sphere( pos, radius, colour ):
2123 #{
2124 global cv_view_verts, cv_view_colours
2125
2126 ly = pos + Vector((0,0,radius))
2127 lx = pos + Vector((0,radius,0))
2128 lz = pos + Vector((0,0,radius))
2129
2130 pi = 3.14159265358979323846264
2131
2132 for i in range(16):
2133 #{
2134 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
2135 s = math.sin(t)
2136 c = math.cos(t)
2137
2138 py = pos + Vector((s*radius,0.0,c*radius))
2139 px = pos + Vector((s*radius,c*radius,0.0))
2140 pz = pos + Vector((0.0,s*radius,c*radius))
2141
2142 cv_view_verts += [ px, lx ]
2143 cv_view_verts += [ py, ly ]
2144 cv_view_verts += [ pz, lz ]
2145
2146 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2147
2148 ly = py
2149 lx = px
2150 lz = pz
2151 #}
2152 cv_draw_lines()
2153 #}
2154
2155 # Draw axis alligned sphere at position with radius
2156 #
2157 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
2158 #{
2159 global cv_view_verts, cv_view_colours
2160
2161 ly = pos + tz*radius
2162 lx = pos + ty*radius
2163 lz = pos + tz*radius
2164
2165 pi = 3.14159265358979323846264
2166
2167 for i in range(16):
2168 #{
2169 t = ((i+1.0) * 1.0/16.0) * pi
2170 s = math.sin(t)
2171 c = math.cos(t)
2172
2173 s1 = math.sin(t*2.0)
2174 c1 = math.cos(t*2.0)
2175
2176 py = pos + s*tx*radius + c *tz*radius
2177 px = pos + s*tx*radius + c *ty*radius
2178 pz = pos + s1*ty*radius + c1*tz*radius
2179
2180 cv_view_verts += [ px, lx ]
2181 cv_view_verts += [ py, ly ]
2182 cv_view_verts += [ pz, lz ]
2183
2184 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2185
2186 ly = py
2187 lx = px
2188 lz = pz
2189 #}
2190 cv_draw_lines()
2191 #}
2192
2193 # Draw transformed -1 -> 1 cube
2194 #
2195 def cv_draw_ucube( transform, colour ):
2196 #{
2197 global cv_view_verts, cv_view_colours
2198
2199 a = Vector((-1,-1,-1))
2200 b = Vector((1,1,1))
2201
2202 vs = [None]*8
2203 vs[0] = transform @ Vector((a[0], a[1], a[2]))
2204 vs[1] = transform @ Vector((a[0], b[1], a[2]))
2205 vs[2] = transform @ Vector((b[0], b[1], a[2]))
2206 vs[3] = transform @ Vector((b[0], a[1], a[2]))
2207 vs[4] = transform @ Vector((a[0], a[1], b[2]))
2208 vs[5] = transform @ Vector((a[0], b[1], b[2]))
2209 vs[6] = transform @ Vector((b[0], b[1], b[2]))
2210 vs[7] = transform @ Vector((b[0], a[1], b[2]))
2211
2212 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2213 (0,4),(1,5),(2,6),(3,7)]
2214
2215 for l in indices:
2216 #{
2217 v0 = vs[l[0]]
2218 v1 = vs[l[1]]
2219 cv_view_verts += [(v0[0],v0[1],v0[2])]
2220 cv_view_verts += [(v1[0],v1[1],v1[2])]
2221 cv_view_colours += [(0,1,0,1),(0,1,0,1)]
2222 #}
2223 cv_draw_lines()
2224 #}
2225
2226 # Draw line with colour
2227 #
2228 def cv_draw_line( p0, p1, colour ):
2229 #{
2230 global cv_view_verts, cv_view_colours
2231
2232 cv_view_verts += [p0,p1]
2233 cv_view_colours += [colour, colour]
2234 cv_draw_lines()
2235 #}
2236
2237 # Draw line with colour(s)
2238 #
2239 def cv_draw_line2( p0, p1, c0, c1 ):
2240 #{
2241 global cv_view_verts, cv_view_colours
2242
2243 cv_view_verts += [p0,p1]
2244 cv_view_colours += [c0,c1]
2245 cv_draw_lines()
2246 #}
2247
2248 #
2249 #
2250 def cv_tangent_basis( n, tx, ty ):
2251 #{
2252 if abs( n[0] ) >= 0.57735027:
2253 #{
2254 tx[0] = n[1]
2255 tx[1] = -n[0]
2256 tx[2] = 0.0
2257 #}
2258 else:
2259 #{
2260 tx[0] = 0.0
2261 tx[1] = n[2]
2262 tx[2] = -n[1]
2263 #}
2264
2265 tx.normalize()
2266 _ty = n.cross( tx )
2267
2268 ty[0] = _ty[0]
2269 ty[1] = _ty[1]
2270 ty[2] = _ty[2]
2271 #}
2272
2273 # Draw coloured arrow
2274 #
2275 def cv_draw_arrow( p0, p1, c0 ):
2276 #{
2277 global cv_view_verts, cv_view_colours
2278
2279 n = p1-p0
2280 midpt = p0 + n*0.5
2281 n.normalize()
2282
2283 tx = Vector((1,0,0))
2284 ty = Vector((1,0,0))
2285 cv_tangent_basis( n, tx, ty )
2286
2287 cv_view_verts += [p0,p1, midpt+(tx-n)*0.15,midpt, midpt+(-tx-n)*0.15,midpt ]
2288 cv_view_colours += [c0,c0,c0,c0,c0,c0]
2289 cv_draw_lines()
2290 #}
2291
2292 # Drawhandles of a bezier control point
2293 #
2294 def cv_draw_bhandle( obj, direction, colour ):
2295 #{
2296 global cv_view_verts, cv_view_colours
2297
2298 p0 = obj.location
2299 h0 = obj.matrix_world @ Vector((0,direction,0))
2300
2301 cv_view_verts += [p0]
2302 cv_view_verts += [h0]
2303 cv_view_colours += [colour,colour]
2304 cv_draw_lines()
2305 #}
2306
2307 # Draw a bezier curve (at fixed resolution 10)
2308 #
2309 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2310 #{
2311 global cv_view_verts, cv_view_colours
2312
2313 last = p0
2314 for i in range(10):
2315 #{
2316 t = (i+1)/10
2317 a0 = 1-t
2318
2319 tt = t*t
2320 ttt = tt*t
2321 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2322
2323 cv_view_verts += [(last[0],last[1],last[2])]
2324 cv_view_verts += [(p[0],p[1],p[2])]
2325 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
2326
2327 last = p
2328 #}
2329 cv_draw_lines()
2330 #}
2331
2332 # I think this one extends the handles of the bezier otwards......
2333 #
2334 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2335 #{
2336 global cv_view_course_i
2337
2338 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2339
2340 p0 = o0.matrix_world @ Vector((offs, 0,0))
2341 h0 = o0.matrix_world @ Vector((offs, s0,0))
2342 p1 = o1.matrix_world @ Vector((offs, 0,0))
2343 h1 = o1.matrix_world @ Vector((offs,-s1,0))
2344
2345 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2346 cv_draw_lines()
2347 #}
2348
2349 # Flush the lines buffers. This is called often because god help you if you want
2350 # to do fixed, fast buffers in this catastrophic programming language.
2351 #
2352 def cv_draw_lines():
2353 #{
2354 global cv_view_shader, cv_view_verts, cv_view_colours
2355
2356 if len(cv_view_verts) < 2:
2357 return
2358
2359 lines = batch_for_shader(\
2360 cv_view_shader, 'LINES', \
2361 { "pos":cv_view_verts, "color":cv_view_colours })
2362
2363 lines.draw( cv_view_shader )
2364
2365 cv_view_verts = []
2366 cv_view_colours = []
2367 #}
2368
2369 # I dont remember what this does exactly
2370 #
2371 def cv_draw_bpath( o0,o1,c0,c1 ):
2372 #{
2373 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2374 #}
2375
2376 # Semi circle to show the limit. and some lines
2377 #
2378 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2379 #{
2380 global cv_view_verts, cv_view_colours
2381 f = 0.05
2382 ay = major*f
2383 ax = minor*f
2384
2385 for x in range(16):
2386 #{
2387 t0 = x/16
2388 t1 = (x+1)/16
2389 a0 = amin*(1.0-t0)+amax*t0
2390 a1 = amin*(1.0-t1)+amax*t1
2391
2392 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
2393 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
2394
2395 p0=obj.matrix_world @ p0
2396 p1=obj.matrix_world @ p1
2397 cv_view_verts += [p0,p1]
2398 cv_view_colours += [colour,colour]
2399
2400 if x == 0:
2401 #{
2402 cv_view_verts += [p0,center]
2403 cv_view_colours += [colour,colour]
2404 #}
2405 if x == 15:
2406 #{
2407 cv_view_verts += [p1,center]
2408 cv_view_colours += [colour,colour]
2409 #}
2410 #}
2411
2412 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2413 cv_view_colours += [colour,colour]
2414
2415 cv_draw_lines()
2416 #}
2417
2418 # Cone and twist limit
2419 #
2420 def draw_cone_twist( center, vx, vy, va ):
2421 #{
2422 global cv_view_verts, cv_view_colours
2423 axis = vy.cross( vx )
2424 axis.normalize()
2425
2426 size = 0.12
2427
2428 cv_view_verts += [center, center+va*size]
2429 cv_view_colours += [ (1,1,1,1), (1,1,1,1) ]
2430
2431 for x in range(32):
2432 #{
2433 t0 = (x/32) * math.tau
2434 t1 = ((x+1)/32) * math.tau
2435
2436 c0 = math.cos(t0)
2437 s0 = math.sin(t0)
2438 c1 = math.cos(t1)
2439 s1 = math.sin(t1)
2440
2441 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
2442 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
2443
2444 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
2445 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
2446
2447 cv_view_verts += [center, p0, p0, p1]
2448 cv_view_colours += [ (0,0,0,0), col0, col0, col1 ]
2449 #}
2450
2451 cv_draw_lines()
2452 #}
2453
2454 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2455 #
2456 def draw_skeleton_helpers( obj ):
2457 #{
2458 global cv_view_verts, cv_view_colours
2459
2460 if obj.data.pose_position != 'REST':
2461 #{
2462 return
2463 #}
2464
2465 for bone in obj.data.bones:
2466 #{
2467 c = bone.head_local
2468 a = Vector((bone.cv_data.v0[0], bone.cv_data.v0[1], bone.cv_data.v0[2]))
2469 b = Vector((bone.cv_data.v1[0], bone.cv_data.v1[1], bone.cv_data.v1[2]))
2470
2471 if bone.cv_data.collider == 'collider_box':
2472 #{
2473
2474 vs = [None]*8
2475 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
2476 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
2477 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
2478 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
2479 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
2480 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
2481 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
2482 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
2483
2484 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2485 (0,4),(1,5),(2,6),(3,7)]
2486
2487 for l in indices:
2488 #{
2489 v0 = vs[l[0]]
2490 v1 = vs[l[1]]
2491
2492 cv_view_verts += [(v0[0],v0[1],v0[2])]
2493 cv_view_verts += [(v1[0],v1[1],v1[2])]
2494 cv_view_colours += [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2495 #}
2496 #}
2497 elif bone.cv_data.collider == 'collider_capsule':
2498 #{
2499 v0 = b-a
2500 major_axis = 0
2501 largest = -1.0
2502
2503 for i in range(3):
2504 #{
2505 if abs(v0[i]) > largest:
2506 #{
2507 largest = abs(v0[i])
2508 major_axis = i
2509 #}
2510 #}
2511
2512 v1 = Vector((0,0,0))
2513 v1[major_axis] = 1.0
2514
2515 tx = Vector((0,0,0))
2516 ty = Vector((0,0,0))
2517
2518 cv_tangent_basis( v1, tx, ty )
2519 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
2520 l = v0[ major_axis ] - r*2
2521
2522 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
2523 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
2524
2525 colour = [0.2,0.2,0.2,1.0]
2526 colour[major_axis] = 0.5
2527
2528 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
2529 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
2530 cv_draw_line( p0+tx* r, p1+tx* r, colour )
2531 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
2532 cv_draw_line( p0+ty* r, p1+ty* r, colour )
2533 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
2534 #}
2535 else:
2536 #{
2537 continue
2538 #}
2539
2540 center = obj.matrix_world @ c
2541 if bone.cv_data.con0:
2542 #{
2543 vx = Vector([bone.cv_data.conevx[_] for _ in range(3)])
2544 vy = Vector([bone.cv_data.conevy[_] for _ in range(3)])
2545 va = Vector([bone.cv_data.coneva[_] for _ in range(3)])
2546 draw_cone_twist( center, vx, vy, va )
2547
2548 #draw_limit( obj, c, Vector((0,0,1)),Vector((0,-1,0)), \
2549 # bone.cv_data.mins[0], bone.cv_data.maxs[0], \
2550 # (1,0,0,1))
2551 #draw_limit( obj, c, Vector((0,-1,0)),Vector((1,0,0)), \
2552 # bone.cv_data.mins[1], bone.cv_data.maxs[1], \
2553 # (0,1,0,1))
2554 #draw_limit( obj, c, Vector((1,0,0)),Vector((0,0,1)), \
2555 # bone.cv_data.mins[2], bone.cv_data.maxs[2], \
2556 # (0,0,1,1))
2557 #}
2558 #}
2559 #}
2560
2561 def cv_draw():
2562 #{
2563 global cv_view_shader
2564 global cv_view_verts
2565 global cv_view_colours
2566 global cv_view_course_i
2567
2568 cv_view_course_i = 0
2569 cv_view_verts = []
2570 cv_view_colours = []
2571
2572 cv_view_shader.bind()
2573 gpu.state.depth_mask_set(False)
2574 gpu.state.line_width_set(2.0)
2575 gpu.state.face_culling_set('BACK')
2576 gpu.state.depth_test_set('LESS')
2577 gpu.state.blend_set('NONE')
2578
2579 for obj in bpy.context.collection.objects:
2580 #{
2581 if obj.type == 'ARMATURE':
2582 #{
2583 if obj.data.pose_position == 'REST':
2584 draw_skeleton_helpers( obj )
2585 #}
2586 else:
2587 #{
2588 classtype = obj.cv_data.classtype
2589 if (classtype != 'classtype_none') and (classtype in globals()):
2590 #{
2591 cl = globals()[ classtype ]
2592
2593 if getattr( cl, "draw_scene_helpers", None ):
2594 #{
2595 cl.draw_scene_helpers( obj )
2596 #}
2597 #}
2598 #}
2599 #}
2600
2601 cv_draw_lines()
2602 return
2603 #}
2604
2605
2606 # ---------------------------------------------------------------------------- #
2607 # #
2608 # Blender #
2609 # #
2610 # ---------------------------------------------------------------------------- #
2611
2612 # Checks whether this object has a classtype assigned. we can only target other
2613 # classes
2614 def cv_poll_target(scene, obj):
2615 #{
2616 if obj == bpy.context.active_object:
2617 return False
2618 if obj.cv_data.classtype == 'classtype_none':
2619 return False
2620
2621 return True
2622 #}
2623
2624 class CV_MESH_SETTINGS(bpy.types.PropertyGroup):
2625 #{
2626 v0: bpy.props.FloatVectorProperty(name="v0",size=3)
2627 v1: bpy.props.FloatVectorProperty(name="v1",size=3)
2628 v2: bpy.props.FloatVectorProperty(name="v2",size=3)
2629 v3: bpy.props.FloatVectorProperty(name="v3",size=3)
2630 #}
2631
2632 class CV_OBJ_SETTINGS(bpy.types.PropertyGroup):
2633 #{
2634 uid: bpy.props.IntProperty( name="" )
2635
2636 strp: bpy.props.StringProperty( name="strp" )
2637 intp: bpy.props.IntProperty( name="intp" )
2638 fltp: bpy.props.FloatProperty( name="fltp" )
2639 bp0: bpy.props.BoolProperty( name="bp0" )
2640 bp1: bpy.props.BoolProperty( name="bp1" )
2641 bp2: bpy.props.BoolProperty( name="bp2" )
2642 bp3: bpy.props.BoolProperty( name="bp3" )
2643
2644 target: bpy.props.PointerProperty( type=bpy.types.Object, name="target", \
2645 poll=cv_poll_target )
2646 target1: bpy.props.PointerProperty( type=bpy.types.Object, name="target1", \
2647 poll=cv_poll_target )
2648 target2: bpy.props.PointerProperty( type=bpy.types.Object, name="target2", \
2649 poll=cv_poll_target )
2650 target3: bpy.props.PointerProperty( type=bpy.types.Object, name="target3", \
2651 poll=cv_poll_target )
2652
2653 colour: bpy.props.FloatVectorProperty( name="colour",subtype='COLOR',\
2654 min=0.0,max=1.0)
2655
2656 classtype: bpy.props.EnumProperty(
2657 name="Format",
2658 items = [
2659 ('classtype_none', "classtype_none", "", 0),
2660 ('classtype_gate', "classtype_gate", "", 1),
2661 ('classtype_spawn', "classtype_spawn", "", 3),
2662 ('classtype_water', "classtype_water", "", 4),
2663 ('classtype_route_node', "classtype_route_node", "", 8 ),
2664 ('classtype_route', "classtype_route", "", 9 ),
2665 ('classtype_audio',"classtype_audio","",14),
2666 ('classtype_trigger',"classtype_trigger","",100),
2667 ('classtype_logic_achievement',"classtype_logic_achievement","",101),
2668 ('classtype_logic_relay',"classtype_logic_relay","",102),
2669 ('classtype_spawn_link',"classtype_spawn_link","",150),
2670 ('classtype_nonlocal_gate', "classtype_nonlocal_gate", "", 300)
2671 ])
2672 #}
2673
2674 class CV_BONE_SETTINGS(bpy.types.PropertyGroup):
2675 #{
2676 collider: bpy.props.EnumProperty(
2677 name="Collider Type",
2678 items = [
2679 ('collider_none', "collider_none", "", 0),
2680 ('collider_box', "collider_box", "", 1),
2681 ('collider_capsule', "collider_capsule", "", 2),
2682 ])
2683
2684 v0: bpy.props.FloatVectorProperty(name="v0",size=3)
2685 v1: bpy.props.FloatVectorProperty(name="v1",size=3)
2686
2687 con0: bpy.props.BoolProperty(name="Constriant 0",default=False)
2688 mins: bpy.props.FloatVectorProperty(name="mins",size=3)
2689 maxs: bpy.props.FloatVectorProperty(name="maxs",size=3)
2690
2691 conevx: bpy.props.FloatVectorProperty(name="conevx",size=3)
2692 conevy: bpy.props.FloatVectorProperty(name="conevy",size=3)
2693 coneva: bpy.props.FloatVectorProperty(name="coneva",size=3)
2694 conet: bpy.props.FloatProperty(name="conet")
2695 #}
2696
2697 class CV_BONE_PANEL(bpy.types.Panel):
2698 #{
2699 bl_label="Bone Config"
2700 bl_idname="SCENE_PT_cv_bone"
2701 bl_space_type='PROPERTIES'
2702 bl_region_type='WINDOW'
2703 bl_context='bone'
2704
2705 def draw(_,context):
2706 #{
2707 active_object = context.active_object
2708 if active_object == None: return
2709
2710 bone = active_object.data.bones.active
2711 if bone == None: return
2712
2713 _.layout.prop( bone.cv_data, "collider" )
2714 _.layout.prop( bone.cv_data, "v0" )
2715 _.layout.prop( bone.cv_data, "v1" )
2716
2717 _.layout.label( text="Angle Limits" )
2718 _.layout.prop( bone.cv_data, "con0" )
2719
2720 _.layout.prop( bone.cv_data, "conevx" )
2721 _.layout.prop( bone.cv_data, "conevy" )
2722 _.layout.prop( bone.cv_data, "coneva" )
2723 _.layout.prop( bone.cv_data, "conet" )
2724 #}
2725 #}
2726
2727 class CV_SCENE_SETTINGS(bpy.types.PropertyGroup):
2728 #{
2729 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
2730 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
2731 #}
2732
2733 class CV_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
2734 #{
2735 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
2736 animations: bpy.props.BoolProperty( name="Export animation", default=True)
2737 #}
2738
2739 class CV_MATERIAL_SETTINGS(bpy.types.PropertyGroup):
2740 #{
2741 shader: bpy.props.EnumProperty(
2742 name="Format",
2743 items = [
2744 ('standard',"standard","",0),
2745 ('standard_cutout', "standard_cutout", "", 1),
2746 ('terrain_blend', "terrain_blend", "", 2),
2747 ('vertex_blend', "vertex_blend", "", 3),
2748 ('water',"water","",4),
2749 ])
2750
2751 surface_prop: bpy.props.EnumProperty(
2752 name="Surface Property",
2753 items = [
2754 ('concrete','concrete','',0),
2755 ('wood','wood','',1),
2756 ('grass','grass','',2)
2757 ])
2758
2759 collision: bpy.props.BoolProperty( \
2760 name="Collisions Enabled",\
2761 default=True,\
2762 description = "Can the player collide with this material"\
2763 )
2764 skate_surface: bpy.props.BoolProperty( \
2765 name="Skate Surface", \
2766 default=True,\
2767 description = "Should the game try to target this surface?" \
2768 )
2769 grind_surface: bpy.props.BoolProperty( \
2770 name="Grind Surface", \
2771 default=False,\
2772 description = "Grind face?" \
2773 )
2774 grow_grass: bpy.props.BoolProperty( \
2775 name="Grow Grass", \
2776 default=False,\
2777 description = "Spawn grass sprites on this surface?" \
2778 )
2779 blend_offset: bpy.props.FloatVectorProperty( \
2780 name="Blend Offset", \
2781 size=2, \
2782 default=Vector((0.5,0.0)),\
2783 description="When surface is more than 45 degrees, add this vector " +\
2784 "to the UVs" \
2785 )
2786 sand_colour: bpy.props.FloatVectorProperty( \
2787 name="Sand Colour",\
2788 subtype='COLOR',\
2789 min=0.0,max=1.0,\
2790 default=Vector((0.79,0.63,0.48)),\
2791 description="Blend to this colour near the 0 coordinate on UP axis"\
2792 )
2793 shore_colour: bpy.props.FloatVectorProperty( \
2794 name="Shore Colour",\
2795 subtype='COLOR',\
2796 min=0.0,max=1.0,\
2797 default=Vector((0.03,0.32,0.61)),\
2798 description="Water colour at the shoreline"\
2799 )
2800 ocean_colour: bpy.props.FloatVectorProperty( \
2801 name="Ocean Colour",\
2802 subtype='COLOR',\
2803 min=0.0,max=1.0,\
2804 default=Vector((0.0,0.006,0.03)),\
2805 description="Water colour in the deep bits"\
2806 )
2807 #}
2808
2809 class CV_MATERIAL_PANEL(bpy.types.Panel):
2810 #{
2811 bl_label="Skate Rift material"
2812 bl_idname="MATERIAL_PT_cv_material"
2813 bl_space_type='PROPERTIES'
2814 bl_region_type='WINDOW'
2815 bl_context="material"
2816
2817 def draw(_,context):
2818 #{
2819 active_object = bpy.context.active_object
2820 if active_object == None: return
2821 active_mat = active_object.active_material
2822 if active_mat == None: return
2823
2824 info = material_info( active_mat )
2825
2826 if 'tex_diffuse' in info:
2827 #{
2828 _.layout.label( icon='INFO', \
2829 text=F"{info['tex_diffuse'].name} will be compiled" )
2830 #}
2831
2832 _.layout.prop( active_mat.cv_data, "shader" )
2833 _.layout.prop( active_mat.cv_data, "surface_prop" )
2834 _.layout.prop( active_mat.cv_data, "collision" )
2835
2836 if active_mat.cv_data.collision:
2837 _.layout.prop( active_mat.cv_data, "skate_surface" )
2838 _.layout.prop( active_mat.cv_data, "grind_surface" )
2839 _.layout.prop( active_mat.cv_data, "grow_grass" )
2840
2841 if active_mat.cv_data.shader == "terrain_blend":
2842 #{
2843 box = _.layout.box()
2844 box.prop( active_mat.cv_data, "blend_offset" )
2845 box.prop( active_mat.cv_data, "sand_colour" )
2846 #}
2847 elif active_mat.cv_data.shader == "vertex_blend":
2848 #{
2849 box = _.layout.box()
2850 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
2851 box.prop( active_mat.cv_data, "blend_offset" )
2852 #}
2853 elif active_mat.cv_data.shader == "water":
2854 #{
2855 box = _.layout.box()
2856 box.label( icon='INFO', text="Depth scale of 16 meters" )
2857 box.prop( active_mat.cv_data, "shore_colour" )
2858 box.prop( active_mat.cv_data, "ocean_colour" )
2859 #}
2860 #}
2861 #}
2862
2863 class CV_OBJ_PANEL(bpy.types.Panel):
2864 #{
2865 bl_label="Entity Config"
2866 bl_idname="SCENE_PT_cv_entity"
2867 bl_space_type='PROPERTIES'
2868 bl_region_type='WINDOW'
2869 bl_context="object"
2870
2871 def draw(_,context):
2872 #{
2873 active_object = bpy.context.active_object
2874 if active_object == None: return
2875 if active_object.type == 'ARMATURE':
2876 #{
2877 row = _.layout.row()
2878 row.enabled = False
2879 row.label( text="This object has the intrinsic classtype of skeleton" )
2880 return
2881 #}
2882
2883 _.layout.prop( active_object.cv_data, "classtype" )
2884
2885 classtype = active_object.cv_data.classtype
2886
2887 if (classtype != 'classtype_none') and (classtype in globals()):
2888 #{
2889 cl = globals()[ classtype ]
2890
2891 if getattr( cl, "editor_interface", None ):
2892 #{
2893 cl.editor_interface( _.layout, active_object )
2894 #}
2895 #}
2896 #}
2897 #}
2898
2899 class CV_COMPILE(bpy.types.Operator):
2900 #{
2901 bl_idname="carve.compile_all"
2902 bl_label="Compile All"
2903
2904 def execute(_,context):
2905 #{
2906 view_layer = bpy.context.view_layer
2907 for col in view_layer.layer_collection.children["export"].children:
2908 if not col.hide_viewport or bpy.context.scene.cv_data.use_hidden:
2909 write_model( col.name )
2910
2911 return {'FINISHED'}
2912 #}
2913 #}
2914
2915 class CV_COMPILE_THIS(bpy.types.Operator):
2916 #{
2917 bl_idname="carve.compile_this"
2918 bl_label="Compile This collection"
2919
2920 def execute(_,context):
2921 #{
2922 col = bpy.context.collection
2923 write_model( col.name )
2924
2925 return {'FINISHED'}
2926 #}
2927 #}
2928
2929 class CV_INTERFACE(bpy.types.Panel):
2930 #{
2931 bl_idname = "VIEW3D_PT_carve"
2932 bl_label = "Skate Rift"
2933 bl_space_type = 'VIEW_3D'
2934 bl_region_type = 'UI'
2935 bl_category = "Skate Rift"
2936
2937 def draw(_, context):
2938 #{
2939 layout = _.layout
2940 layout.prop( context.scene.cv_data, "export_dir" )
2941
2942 col = bpy.context.collection
2943
2944 found_in_export = False
2945 export_count = 0
2946 view_layer = bpy.context.view_layer
2947 for c1 in view_layer.layer_collection.children["export"].children:
2948 #{
2949 if not c1.hide_viewport or bpy.context.scene.cv_data.use_hidden:
2950 export_count += 1
2951
2952 if c1.name == col.name:
2953 #{
2954 found_in_export = True
2955 #}
2956 #}
2957
2958 box = layout.box()
2959 if found_in_export:
2960 #{
2961 box.label( text=col.name + ".mdl" )
2962 box.prop( col.cv_data, "pack_textures" )
2963 box.prop( col.cv_data, "animations" )
2964 box.operator( "carve.compile_this" )
2965 #}
2966 else:
2967 #{
2968 row = box.row()
2969 row.enabled=False
2970 row.label( text=col.name )
2971 box.label( text="This collection is not in the export group" )
2972 #}
2973
2974 box = layout.box()
2975 row = box.row()
2976
2977 split = row.split( factor = 0.3, align=True )
2978 split.prop( context.scene.cv_data, "use_hidden", text="hidden" )
2979
2980 row1 = split.row()
2981 if export_count == 0:
2982 row1.enabled=False
2983 row1.operator( "carve.compile_all", \
2984 text=F"Compile all ({export_count} collections)" )
2985 #}
2986 #}
2987
2988
2989 classes = [CV_OBJ_SETTINGS,CV_OBJ_PANEL,CV_COMPILE,CV_INTERFACE,\
2990 CV_MESH_SETTINGS, CV_SCENE_SETTINGS, CV_BONE_SETTINGS,\
2991 CV_BONE_PANEL, CV_COLLECTION_SETTINGS, CV_COMPILE_THIS,\
2992 CV_MATERIAL_SETTINGS, CV_MATERIAL_PANEL ]
2993
2994 def register():
2995 #{
2996 global cv_view_draw_handler
2997
2998 for c in classes:
2999 bpy.utils.register_class(c)
3000
3001 bpy.types.Object.cv_data = bpy.props.PointerProperty(type=CV_OBJ_SETTINGS)
3002 bpy.types.Mesh.cv_data = bpy.props.PointerProperty(type=CV_MESH_SETTINGS)
3003 bpy.types.Scene.cv_data = bpy.props.PointerProperty(type=CV_SCENE_SETTINGS)
3004 bpy.types.Bone.cv_data = bpy.props.PointerProperty(type=CV_BONE_SETTINGS)
3005 bpy.types.Collection.cv_data = \
3006 bpy.props.PointerProperty(type=CV_COLLECTION_SETTINGS)
3007 bpy.types.Material.cv_data = \
3008 bpy.props.PointerProperty(type=CV_MATERIAL_SETTINGS)
3009
3010 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
3011 cv_draw,(),'WINDOW','POST_VIEW')
3012 #}
3013
3014 def unregister():
3015 #{
3016 global cv_view_draw_handler
3017
3018 for c in classes:
3019 bpy.utils.unregister_class(c)
3020
3021 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
3022 #}
3023
3024 # ---------------------------------------------------------------------------- #
3025 # #
3026 # QOI encoder #
3027 # #
3028 # ---------------------------------------------------------------------------- #
3029 # #
3030 # Transliteration of: #
3031 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
3032 # #
3033 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
3034 # SPDX-License-Identifier: MIT #
3035 # QOI - The "Quite OK Image" format for fast, lossless image compression #
3036 # #
3037 # ---------------------------------------------------------------------------- #
3038
3039 class qoi_rgba_t(Structure):
3040 #{
3041 _pack_ = 1
3042 _fields_ = [("r",c_uint8),
3043 ("g",c_uint8),
3044 ("b",c_uint8),
3045 ("a",c_uint8)]
3046 #}
3047
3048 QOI_OP_INDEX = 0x00 # 00xxxxxx
3049 QOI_OP_DIFF = 0x40 # 01xxxxxx
3050 QOI_OP_LUMA = 0x80 # 10xxxxxx
3051 QOI_OP_RUN = 0xc0 # 11xxxxxx
3052 QOI_OP_RGB = 0xfe # 11111110
3053 QOI_OP_RGBA = 0xff # 11111111
3054
3055 QOI_MASK_2 = 0xc0 # 11000000
3056
3057 def qoi_colour_hash( c ):
3058 #{
3059 return c.r*3 + c.g*5 + c.b*7 + c.a*11
3060 #}
3061
3062 def qoi_eq( a, b ):
3063 #{
3064 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
3065 #}
3066
3067 def qoi_32bit( v ):
3068 #{
3069 return bytearray([ (0xff000000 & v) >> 24, \
3070 (0x00ff0000 & v) >> 16, \
3071 (0x0000ff00 & v) >> 8, \
3072 (0x000000ff & v) ])
3073 #}
3074
3075 def qoi_encode( img ):
3076 #{
3077 data = bytearray()
3078
3079 print(F" . Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]")
3080
3081 index = [ qoi_rgba_t() for _ in range(64) ]
3082
3083 # Header
3084 #
3085 data.extend( bytearray(c_uint32(0x66696f71)) )
3086 data.extend( qoi_32bit( img.size[0] ) )
3087 data.extend( qoi_32bit( img.size[1] ) )
3088 data.extend( bytearray(c_uint8(4)) )
3089 data.extend( bytearray(c_uint8(0)) )
3090
3091 run = 0
3092 px_prev = qoi_rgba_t()
3093 px_prev.r = c_uint8(0)
3094 px_prev.g = c_uint8(0)
3095 px_prev.b = c_uint8(0)
3096 px_prev.a = c_uint8(255)
3097
3098 px = qoi_rgba_t()
3099 px.r = c_uint8(0)
3100 px.g = c_uint8(0)
3101 px.b = c_uint8(0)
3102 px.a = c_uint8(255)
3103
3104 px_len = img.size[0] * img.size[1]
3105
3106 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
3107
3108 for px_pos in range( px_len ):
3109 #{
3110 idx = px_pos * img.channels
3111 nc = img.channels-1
3112
3113 px.r = paxels[idx+min(0,nc)]
3114 px.g = paxels[idx+min(1,nc)]
3115 px.b = paxels[idx+min(2,nc)]
3116 px.a = paxels[idx+min(3,nc)]
3117
3118 if qoi_eq( px, px_prev ):
3119 #{
3120 run += 1
3121
3122 if (run == 62) or (px_pos == px_len-1):
3123 #{
3124 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
3125 run = 0
3126 #}
3127 #}
3128 else:
3129 #{
3130 if run > 0:
3131 #{
3132 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
3133 run = 0
3134 #}
3135
3136 index_pos = qoi_colour_hash(px) % 64
3137
3138 if qoi_eq( index[index_pos], px ):
3139 #{
3140 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
3141 #}
3142 else:
3143 #{
3144 index[ index_pos ].r = px.r
3145 index[ index_pos ].g = px.g
3146 index[ index_pos ].b = px.b
3147 index[ index_pos ].a = px.a
3148
3149 if px.a == px_prev.a:
3150 #{
3151 vr = int(px.r) - int(px_prev.r)
3152 vg = int(px.g) - int(px_prev.g)
3153 vb = int(px.b) - int(px_prev.b)
3154
3155 vg_r = vr - vg
3156 vg_b = vb - vg
3157
3158 if (vr > -3) and (vr < 2) and\
3159 (vg > -3) and (vg < 2) and\
3160 (vb > -3) and (vb < 2):
3161 #{
3162 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
3163 data.extend( bytearray( c_uint8(op) ))
3164 #}
3165 elif (vg_r > -9) and (vg_r < 8) and\
3166 (vg > -33) and (vg < 32 ) and\
3167 (vg_b > -9) and (vg_b < 8):
3168 #{
3169 op = QOI_OP_LUMA | (vg+32)
3170 delta = (vg_r+8) << 4 | (vg_b + 8)
3171 data.extend( bytearray( c_uint8(op) ) )
3172 data.extend( bytearray( c_uint8(delta) ))
3173 #}
3174 else:
3175 #{
3176 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
3177 data.extend( bytearray( c_uint8(px.r) ))
3178 data.extend( bytearray( c_uint8(px.g) ))
3179 data.extend( bytearray( c_uint8(px.b) ))
3180 #}
3181 #}
3182 else:
3183 #{
3184 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
3185 data.extend( bytearray( c_uint8(px.r) ))
3186 data.extend( bytearray( c_uint8(px.g) ))
3187 data.extend( bytearray( c_uint8(px.b) ))
3188 data.extend( bytearray( c_uint8(px.a) ))
3189 #}
3190 #}
3191 #}
3192
3193 px_prev.r = px.r
3194 px_prev.g = px.g
3195 px_prev.b = px.b
3196 px_prev.a = px.a
3197 #}
3198
3199 # Padding
3200 for i in range(7):
3201 data.extend( bytearray( c_uint8(0) ))
3202 data.extend( bytearray( c_uint8(1) ))
3203 bytearray_align_to( data, 16, 0 )
3204
3205 return data
3206 #}