b60b2e02fc8cf14550c3f2ace276c11545c48bec
[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: world light
811 #
812 class classtype_world_light( Structure ):
813 #{
814 _pack_ = 1
815 _fields_ = [("type",c_uint32),
816 ("colour",c_float*4),
817 ("angle",c_float)]
818
819 def encode_obj(_, node, node_def):
820 #{
821 node.classtype = 200
822
823 obj = node_def['obj']
824 data = obj.data
825 _.colour[0] = data.color[0]
826 _.colour[1] = data.color[1]
827 _.colour[2] = data.color[2]
828 _.colour[3] = data.energy
829
830 if obj.data.type == 'POINT':
831 #{
832 _.type = 0
833 _.angle = 0.0
834 #}
835 elif obj.data.type == 'SPOT':
836 #{
837 _.type = 1
838 _.angle = math.cos(data.spot_size*0.5)
839 #}
840 #}
841
842 @staticmethod
843 def editor_interface( layout, obj ):
844 #{
845 pass
846 #}
847 #}
848
849 # Classtype 201
850 #
851 # Purpose: lighting settings for world
852 #
853 class classtype_lighting_info(Structure):
854 #{
855 _pack_ = 1
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)]
862
863 def encode_obj(_, node, node_def):
864 #{
865 node.classtype = 201
866
867 # TODO
868 #}
869
870 @staticmethod
871 def editor_interface( layout, obj ):
872 #{
873 pass
874 #}
875 #}
876
877 class classtype_spawn_link(Structure):
878 #{
879 _pack_ = 1
880 _fields_ = [("connections",c_uint32*4)]
881
882 def encode_obj(_, node,node_def ):
883 #{
884 node.classtype = 0
885 #}
886
887 @staticmethod
888 def editor_interface( layout, obj ):
889 #{
890 pass
891 #}
892
893 @staticmethod
894 def draw_scene_helpers( obj ):
895 #{
896 global cv_view_verts, cv_view_colours
897
898 count = 0
899
900 for obj1 in bpy.context.collection.objects:
901 #{
902 if (obj1.cv_data.classtype != 'classtype_spawn_link') and \
903 (obj1.cv_data.classtype != 'classtype_spawn') :
904 continue
905
906 if (obj1.location - obj.location).length < 40.0:
907 #{
908 cv_draw_line( obj.location, obj1.location, [1,1,1,1] )
909 count +=1
910 #}
911
912 if count == 4:
913 break
914 #}
915
916 cv_draw_sphere( obj.location, 20.0, [0.5,0,0.2,0.4] )
917 #}
918 #}
919
920 # ---------------------------------------------------------------------------- #
921 # #
922 # Compiler section #
923 # #
924 # ---------------------------------------------------------------------------- #
925
926 # Current encoder state
927 #
928 g_encoder = None
929
930 # Reset encoder
931 #
932 def encoder_init( collection ):
933 #{
934 global g_encoder
935
936 g_encoder = \
937 {
938 # The actual file header
939 #
940 'header': mdl_header(),
941
942 # Options
943 #
944 'pack_textures': collection.cv_data.pack_textures,
945
946 # Compiled data chunks (each can be read optionally by the client)
947 #
948 'data':
949 {
950 #1---------------------------------
951 'node': [], # Metadata 'chunk'
952 'submesh': [],
953 'material': [],
954 'texture': [],
955 'anim': [],
956 'entdata': bytearray(), # variable width
957 'strings': bytearray(), # .
958 #2---------------------------------
959 'keyframe': [], # Animations
960 #3---------------------------------
961 'vertex': [], # Mesh data
962 'indice': [],
963 #4---------------------------------
964 'pack': bytearray() # Other generic packed data
965 },
966
967 # All objects of the model in their final heirachy
968 #
969 "uid_count": 1,
970 "scene_graph":{},
971 "graph_lookup":{},
972
973 # Allows us to reuse definitions
974 #
975 'string_cache':{},
976 'mesh_cache': {},
977 'material_cache': {},
978 'texture_cache': {}
979 }
980
981 g_encoder['header'].identifier = 0xABCD0000
982 g_encoder['header'].version = 1
983
984 # Add fake NoneID material and texture
985 #
986 none_material = mdl_material()
987 none_material.pstr_name = encoder_process_pstr( "" )
988 none_material.texture_id = 0
989
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
994
995 g_encoder['data']['material'] += [none_material]
996 g_encoder['data']['texture'] += [none_texture]
997
998 g_encoder['data']['pack'].extend( b'datapack\0\0\0\0\0\0\0\0' )
999
1000 # Add root node
1001 #
1002 root = mdl_node()
1003 root.co[0] = 0
1004 root.co[1] = 0
1005 root.co[2] = 0
1006 root.q[0] = 0
1007 root.q[1] = 0
1008 root.q[2] = 0
1009 root.q[3] = 1
1010 root.s[0] = 1
1011 root.s[1] = 1
1012 root.s[2] = 1
1013 root.pstr_name = encoder_process_pstr('')
1014 root.submesh_start = 0
1015 root.submesh_count = 0
1016 root.offset = 0
1017 root.classtype = 0
1018 root.parent = 0xffffffff
1019
1020 g_encoder['data']['node'] += [root]
1021 #}
1022
1023
1024 # fill with 0x00 until a multiple of align. Returns how many bytes it added
1025 #
1026 def bytearray_align_to( buffer, align, offset=0 ):
1027 #{
1028 count = 0
1029
1030 while ((len(buffer)+offset) % align) != 0:
1031 #{
1032 buffer.extend( b'\0' )
1033 count += 1
1034 #}
1035
1036 return count
1037 #}
1038
1039 # Add a string to the string buffer except if it already exists there then we
1040 # just return its ID.
1041 #
1042 def encoder_process_pstr( s ):
1043 #{
1044 global g_encoder
1045
1046 cache = g_encoder['string_cache']
1047
1048 if s in cache:
1049 return cache[s]
1050
1051 cache[s] = len( g_encoder['data']['strings'] )
1052
1053 buffer = g_encoder['data']['strings']
1054 buffer.extend( s.encode('utf-8') )
1055 buffer.extend( b'\0' )
1056
1057 bytearray_align_to( buffer, 4 )
1058 return cache[s]
1059 #}
1060
1061 def get_texture_resource_name( img ):
1062 #{
1063 return os.path.splitext( img.name )[0]
1064 #}
1065
1066 # Pack a texture
1067 #
1068 def encoder_process_texture( img ):
1069 #{
1070 global g_encoder
1071
1072 if img == None:
1073 return 0
1074
1075 cache = g_encoder['texture_cache']
1076 buffer = g_encoder['data']['texture']
1077 pack = g_encoder['data']['pack']
1078
1079 name = get_texture_resource_name( img )
1080
1081 if name in cache:
1082 return cache[name]
1083
1084 cache[name] = len( buffer )
1085
1086 tex = mdl_texture()
1087 tex.pstr_name = encoder_process_pstr( name )
1088
1089 if g_encoder['pack_textures']:
1090 #{
1091 tex.pack_offset = len( pack )
1092 pack.extend( qoi_encode( img ) )
1093 tex.pack_length = len( pack ) - tex.pack_offset
1094 #}
1095 else:
1096 tex.pack_offset = 0
1097
1098 buffer += [ tex ]
1099 return cache[name]
1100 #}
1101
1102 def material_tex_image(v):
1103 #{
1104 return {
1105 "Image Texture":
1106 {
1107 "image": F"{v}"
1108 }
1109 }
1110 #}
1111
1112 cxr_graph_mapping = \
1113 {
1114 # Default shader setup
1115 "Principled BSDF":
1116 {
1117 "Base Color":
1118 {
1119 "Image Texture":
1120 {
1121 "image": "tex_diffuse"
1122 },
1123 "Mix":
1124 {
1125 "A": material_tex_image("tex_diffuse"),
1126 "B": material_tex_image("tex_decal")
1127 },
1128 },
1129 "Normal":
1130 {
1131 "Normal Map":
1132 {
1133 "Color": material_tex_image("tex_normal")
1134 }
1135 }
1136 }
1137 }
1138
1139 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
1140 #
1141 def material_info(mat):
1142 #{
1143 info = {}
1144
1145 # Using the cv_graph_mapping as a reference, go through the shader
1146 # graph and gather all $props from it.
1147 #
1148 def _graph_read( node_def, node=None, depth=0 ):
1149 #{
1150 nonlocal mat
1151 nonlocal info
1152
1153 # Find rootnodes
1154 #
1155 if node == None:
1156 #{
1157 _graph_read.extracted = []
1158
1159 for node_idname in node_def:
1160 #{
1161 for n in mat.node_tree.nodes:
1162 #{
1163 if n.name == node_idname:
1164 #{
1165 node_def = node_def[node_idname]
1166 node = n
1167 break
1168 #}
1169 #}
1170 #}
1171 #}
1172
1173 for link in node_def:
1174 #{
1175 link_def = node_def[link]
1176
1177 if isinstance( link_def, dict ):
1178 #{
1179 node_link = None
1180 for x in node.inputs:
1181 #{
1182 if isinstance( x, bpy.types.NodeSocketColor ):
1183 #{
1184 if link == x.name:
1185 #{
1186 node_link = x
1187 break
1188 #}
1189 #}
1190 #}
1191
1192 if node_link and node_link.is_linked:
1193 #{
1194 # look for definitions for the connected node type
1195 #
1196 from_node = node_link.links[0].from_node
1197
1198 node_name = from_node.name.split('.')[0]
1199 if node_name in link_def:
1200 #{
1201 from_node_def = link_def[ node_name ]
1202
1203 _graph_read( from_node_def, from_node, depth+1 )
1204 #}
1205
1206 # No definition! :(
1207 # TODO: Make a warning for this?
1208 #}
1209 else:
1210 #{
1211 if "default" in link_def:
1212 #{
1213 prop = link_def['default']
1214 info[prop] = node_link.default_value
1215 #}
1216 #}
1217 #}
1218 else:
1219 #{
1220 prop = link_def
1221 info[prop] = getattr( node, link )
1222 #}
1223 #}
1224 #}
1225
1226 _graph_read( cxr_graph_mapping )
1227 return info
1228 #}
1229
1230 # Add a material to the material buffer. Returns 0 (None ID) if invalid
1231 #
1232 def encoder_process_material( mat ):
1233 #{
1234 global g_encoder
1235
1236 if mat == None:
1237 return 0
1238
1239 cache = g_encoder['material_cache']
1240 buffer = g_encoder['data']['material']
1241
1242 if mat.name in cache:
1243 return cache[mat.name]
1244
1245 cache[mat.name] = len( buffer )
1246
1247 dest = mdl_material()
1248 dest.pstr_name = encoder_process_pstr( mat.name )
1249
1250 flags = 0x00
1251 if mat.cv_data.collision:
1252 flags |= 0x2
1253 if mat.cv_data.skate_surface: flags |= 0x1
1254 if mat.cv_data.grind_surface: flags |= (0x8|0x1)
1255
1256 if mat.cv_data.grow_grass: flags |= 0x4
1257 dest.flags = flags
1258
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
1262
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':
1266 #{
1267 dest.shader = 2
1268
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
1273
1274 dest.colour1[0] = mat.cv_data.blend_offset[0]
1275 dest.colour1[1] = mat.cv_data.blend_offset[1]
1276 #}
1277
1278 if mat.cv_data.shader == 'vertex_blend':
1279 #{
1280 dest.shader = 3
1281
1282 dest.colour1[0] = mat.cv_data.blend_offset[0]
1283 dest.colour1[1] = mat.cv_data.blend_offset[1]
1284 #}
1285
1286 if mat.cv_data.shader == 'water':
1287 #{
1288 dest.shader = 4
1289
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
1298 #}
1299
1300 inf = material_info( mat )
1301
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':
1306 #{
1307 if 'tex_diffuse' in inf:
1308 dest.tex_diffuse = encoder_process_texture(inf['tex_diffuse'])
1309 #}
1310
1311 buffer += [dest]
1312 return cache[mat.name]
1313 #}
1314
1315 # Create a tree structure containing all the objects in the collection
1316 #
1317 def encoder_build_scene_graph( collection ):
1318 #{
1319 global g_encoder
1320
1321 print( " creating scene graph" )
1322
1323 # initialize root
1324 #
1325 graph = g_encoder['scene_graph']
1326 graph_lookup = g_encoder['graph_lookup']
1327 graph["obj"] = None
1328 graph["depth"] = 0
1329 graph["children"] = []
1330 graph["uid"] = 0
1331 graph["parent"] = None
1332
1333 def _new_uid():
1334 #{
1335 global g_encoder
1336 uid = g_encoder['uid_count']
1337 g_encoder['uid_count'] += 1
1338 return uid
1339 #}
1340
1341 for obj in collection.all_objects:
1342 #{
1343 if obj.parent: continue
1344
1345 def _extend( p, n, d ):
1346 #{
1347 nonlocal collection
1348
1349 uid = _new_uid()
1350 tree = {}
1351 tree["uid"] = uid
1352 tree["children"] = []
1353 tree["depth"] = d
1354 tree["obj"] = n
1355 tree["parent"] = p
1356 n.cv_data.uid = uid
1357
1358 # Descend into amature
1359 #
1360 if n.type == 'ARMATURE':
1361 #{
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
1366
1367 # Here also collects some information about constraints, ik and
1368 # counts colliders for the armature.
1369 #
1370 def _extendb( p, n, d ):
1371 #{
1372 nonlocal tree
1373
1374 btree = {}
1375 btree["bone"] = n
1376 btree["linked_armature"] = tree
1377 btree["uid"] = _new_uid()
1378 btree["children"] = []
1379 btree["depth"] = d
1380 btree["parent"] = p
1381 tree["bones"] += [n.name]
1382
1383 for c in n.children:
1384 #{
1385 _extendb( btree, c, d+1 )
1386 #}
1387
1388 for c in tree['obj'].pose.bones[n.name].constraints:
1389 #{
1390 if c.type == 'IK':
1391 #{
1392 btree["ik_target"] = c.subtarget
1393 btree["ik_pole"] = c.pole_subtarget
1394 tree["ik_count"] += 1
1395 #}
1396 #}
1397
1398 if n.cv_data.collider != 'collider_none':
1399 tree['collider_count'] += 1
1400
1401 btree['deform'] = n.use_deform
1402 p['children'] += [btree]
1403 #}
1404
1405 for b in n.data.bones:
1406 if not b.parent:
1407 _extendb( tree, b, d+1 )
1408 #}
1409
1410 # Recurse into children of this object
1411 #
1412 for obj1 in n.children:
1413 #{
1414 for c1 in obj1.users_collection:
1415 #{
1416 if c1 == collection:
1417 #{
1418 _extend( tree, obj1, d+1 )
1419 break
1420 #}
1421 #}
1422 #}
1423
1424 p["children"] += [tree]
1425 graph_lookup[n] = tree
1426
1427 #}
1428
1429 _extend( graph, obj, 1 )
1430
1431 #}
1432 #}
1433
1434
1435 # Kind of a useless thing i made but it looks cool and adds complexity!!1
1436 #
1437 def encoder_graph_iterator( root ):
1438 #{
1439 for c in root['children']:
1440 #{
1441 yield c
1442 yield from encoder_graph_iterator(c)
1443 #}
1444 #}
1445
1446
1447 # Push a vertex into the model file, or return a cached index (c_uint32)
1448 #
1449 def encoder_vertex_push( vertex_reference, co,norm,uv,colour,groups,weights ):
1450 #{
1451 global g_encoder
1452 buffer = g_encoder['data']['vertex']
1453
1454 TOLERENCE = 4
1455 m = float(10**TOLERENCE)
1456
1457 # Would be nice to know if this can be done faster than it currently runs,
1458 # its quite slow.
1459 #
1460 key = (int(co[0]*m+0.5),
1461 int(co[1]*m+0.5),
1462 int(co[2]*m+0.5),
1463 int(norm[0]*m+0.5),
1464 int(norm[1]*m+0.5),
1465 int(norm[2]*m+0.5),
1466 int(uv[0]*m+0.5),
1467 int(uv[1]*m+0.5),
1468 colour[0], # these guys are already quantized
1469 colour[1], # .
1470 colour[2], # .
1471 colour[3], # .
1472 weights[0], # v
1473 weights[1],
1474 weights[2],
1475 weights[3],
1476 groups[0],
1477 groups[1],
1478 groups[2],
1479 groups[3])
1480
1481 if key in vertex_reference:
1482 return vertex_reference[key]
1483 else:
1484 #{
1485 index = c_uint32( len(vertex_reference) )
1486 vertex_reference[key] = index
1487
1488 v = mdl_vert()
1489 v.co[0] = co[0]
1490 v.co[1] = co[2]
1491 v.co[2] = -co[1]
1492 v.norm[0] = norm[0]
1493 v.norm[1] = norm[2]
1494 v.norm[2] = -norm[1]
1495 v.uv[0] = uv[0]
1496 v.uv[1] = uv[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]
1509
1510 buffer += [v]
1511 return index
1512 #}
1513 #}
1514
1515
1516 # Compile a mesh (or use one from the cache) onto node, based on node_def
1517 # No return value
1518 #
1519 def encoder_compile_mesh( node, node_def ):
1520 #{
1521 global g_encoder
1522
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']
1527 armature_def = None
1528 can_use_cache = True
1529
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.
1533 #
1534 # It may be possible to detect these cases automatically.
1535 #
1536 for mod in obj.modifiers:
1537 #{
1538 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
1539 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
1540 mod.type == 'ARRAY':
1541 #{
1542 can_use_cache = False
1543 #}
1544
1545 if mod.type == 'ARMATURE':
1546 armature_def = graph_lookup[mod.object]
1547
1548 # Check the cache first
1549 #
1550 if can_use_cache and (obj.data.name in mesh_cache):
1551 #{
1552 ref = mesh_cache[obj.data.name]
1553 node.submesh_start = ref.submesh_start
1554 node.submesh_count = ref.submesh_count
1555 return
1556 #}
1557
1558 # Compile a whole new mesh
1559 #
1560 node.submesh_start = len( g_encoder['data']['submesh'] )
1561 node.submesh_count = 0
1562
1563 dgraph = bpy.context.evaluated_depsgraph_get()
1564 data = obj.evaluated_get(dgraph).data
1565 data.calc_loop_triangles()
1566 data.calc_normals_split()
1567
1568 # Mesh is split into submeshes based on their material
1569 #
1570 mat_list = data.materials if len(data.materials) > 0 else [None]
1571 for material_id, mat in enumerate(mat_list):
1572 #{
1573 mref = {}
1574
1575 sm = mdl_submesh()
1576 sm.indice_start = len( g_encoder['data']['indice'] )
1577 sm.vertex_start = len( g_encoder['data']['vertex'] )
1578 sm.vertex_count = 0
1579 sm.indice_count = 0
1580 sm.material_id = encoder_process_material( mat )
1581
1582 for i in range(3):
1583 #{
1584 sm.bbx[0][i] = 999999
1585 sm.bbx[1][i] = -999999
1586 #}
1587
1588 # Keep a reference to very very very similar vertices
1589 #
1590 vertex_reference = {}
1591
1592 # Write the vertex / indice data
1593 #
1594 for tri_index, tri in enumerate(data.loop_triangles):
1595 #{
1596 if tri.material_index != material_id:
1597 continue
1598
1599 for j in range(3):
1600 #{
1601 vert = data.vertices[tri.vertices[j]]
1602 li = tri.loops[j]
1603 vi = data.loops[li].vertex_index
1604
1605 # Gather vertex information
1606 #
1607 co = vert.co
1608 norm = data.loops[li].normal
1609 uv = (0,0)
1610 colour = (255,255,255,255)
1611 groups = [0,0,0,0]
1612 weights = [0,0,0,0]
1613
1614 # Uvs
1615 #
1616 if data.uv_layers:
1617 uv = data.uv_layers.active.data[li].uv
1618
1619 # Vertex Colours
1620 #
1621 if data.vertex_colors:
1622 #{
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))
1628 #}
1629
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
1632 # always 0
1633 #
1634 if armature_def:
1635 #{
1636 src_groups = [_ for _ in data.vertices[vi].groups \
1637 if obj.vertex_groups[_.group].name in \
1638 armature_def['bones']]
1639
1640 weight_groups = sorted( src_groups, key = \
1641 lambda a: a.weight, reverse=True )
1642 tot = 0.0
1643 for ml in range(3):
1644 #{
1645 if len(weight_groups) > ml:
1646 #{
1647 g = weight_groups[ml]
1648 name = obj.vertex_groups[g.group].name
1649 weight = g.weight
1650
1651 weights[ml] = weight
1652 groups[ml] = armature_def['bones'].index(name)
1653 tot += weight
1654 #}
1655 #}
1656
1657 if len(weight_groups) > 0:
1658 #{
1659 inv_norm = (1.0/tot) * 65535.0
1660 for ml in range(3):
1661 #{
1662 weights[ml] = int( weights[ml] * inv_norm )
1663 weights[ml] = min( weights[ml], 65535 )
1664 weights[ml] = max( weights[ml], 0 )
1665 #}
1666 #}
1667 #}
1668 else:
1669 #{
1670 li1 = tri.loops[(j+1)%3]
1671 vi1 = data.loops[li1].vertex_index
1672 e0 = data.edges[ data.loops[li].edge_index ]
1673
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)):
1677 #{
1678 weights[0] = 1
1679 #}
1680 #}
1681
1682 # Add vertex and expand bound box
1683 #
1684 index = encoder_vertex_push( vertex_reference, co, \
1685 norm, \
1686 uv, \
1687 colour, \
1688 groups, \
1689 weights )
1690 g_encoder['data']['indice'] += [index]
1691 #}
1692 #}
1693
1694 # How many unique verts did we add in total
1695 #
1696 sm.vertex_count = len(g_encoder['data']['vertex']) - sm.vertex_start
1697 sm.indice_count = len(g_encoder['data']['indice']) - sm.indice_start
1698
1699 # Make sure bounding box isn't -inf -> inf if no vertices
1700 #
1701 if sm.vertex_count == 0:
1702 for j in range(2):
1703 for i in range(3):
1704 sm.bbx[j][i] = 0
1705 else:
1706 #{
1707 for j in range(sm.vertex_count):
1708 #{
1709 vert = g_encoder['data']['vertex'][ sm.vertex_start + j ]
1710
1711 for i in range(3):
1712 #{
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] )
1715 #}
1716 #}
1717 #}
1718
1719 # Add submesh to encoder
1720 #
1721 g_encoder['data']['submesh'] += [sm]
1722 node.submesh_count += 1
1723
1724 #}
1725
1726 # Save a reference to this node since we want to reuse the submesh indices
1727 # later.
1728 g_encoder['mesh_cache'][obj.data.name] = node
1729 #}
1730
1731
1732 def encoder_compile_ent_as( name, node, node_def ):
1733 #{
1734 global g_encoder
1735
1736 if name == 'classtype_none':
1737 #{
1738 node.offset = 0
1739 node.classtype = 0
1740 return
1741 #}
1742 elif name not in globals():
1743 #{
1744 print( "Classtype '" +name + "' is unknown!" )
1745 return
1746 #}
1747
1748 buffer = g_encoder['data']['entdata']
1749 node.offset = len(buffer)
1750
1751 cl = globals()[ name ]
1752 inst = cl()
1753 inst.encode_obj( node, node_def )
1754
1755 buffer.extend( bytearray(inst) )
1756 bytearray_align_to( buffer, 4 )
1757 #}
1758
1759 # Compiles animation data into model and gives us some extra node_def entries
1760 #
1761 def encoder_compile_armature( node, node_def ):
1762 #{
1763 global g_encoder
1764
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']
1771
1772 # extra info
1773 node_def['anim_start'] = len(animdata)
1774 node_def['anim_count'] = 0
1775
1776 if not node_def['compile_animation']:
1777 #{
1778 return
1779 #}
1780
1781 # Compile anims
1782 #
1783 if obj.animation_data:
1784 #{
1785 # So we can restore later
1786 #
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'
1791
1792 for NLALayer in obj.animation_data.nla_tracks:
1793 #{
1794 for NLAStrip in NLALayer.strips:
1795 #{
1796 # set active
1797 #
1798 for a in bpy.data.actions:
1799 #{
1800 if a.name == NLAStrip.name:
1801 #{
1802 obj.animation_data.action = a
1803 break
1804 #}
1805 #}
1806
1807 # Clip to NLA settings
1808 #
1809 anim_start = int(NLAStrip.action_frame_start)
1810 anim_end = int(NLAStrip.action_frame_end)
1811
1812 # Export strips
1813 #
1814 anim = mdl_animation()
1815 anim.pstr_name = encoder_process_pstr( NLAStrip.action.name )
1816 anim.rate = 30.0
1817 anim.offset = len(keyframedata)
1818 anim.length = anim_end-anim_start
1819
1820 # Export the keyframes
1821 for frame in range(anim_start,anim_end):
1822 #{
1823 bpy.context.scene.frame_set(frame)
1824
1825 for bone_name in bones:
1826 #{
1827 for pb in obj.pose.bones:
1828 #{
1829 if pb.name != bone_name: continue
1830
1831 rb = obj.data.bones[ bone_name ]
1832
1833 # relative bone matrix
1834 if rb.parent is not None:
1835 #{
1836 offset_mtx = rb.parent.matrix_local
1837 offset_mtx = offset_mtx.inverted_safe() @ \
1838 rb.matrix_local
1839
1840 inv_parent = pb.parent.matrix @ offset_mtx
1841 inv_parent.invert_safe()
1842 fpm = inv_parent @ pb.matrix
1843 #}
1844 else:
1845 #{
1846 bone_mtx = rb.matrix.to_4x4()
1847 local_inv = rb.matrix_local.inverted_safe()
1848 fpm = bone_mtx @ local_inv @ pb.matrix
1849 #}
1850
1851 loc, rot, sca = fpm.decompose()
1852
1853 # local position
1854 final_pos = Vector(( loc[0], loc[2], -loc[1] ))
1855
1856 # rotation
1857 lc_m = pb.matrix_channel.to_3x3()
1858 if pb.parent is not None:
1859 #{
1860 smtx = pb.parent.matrix_channel.to_3x3()
1861 lc_m = smtx.inverted() @ lc_m
1862 #}
1863 rq = lc_m.to_quaternion()
1864
1865 kf = mdl_keyframe()
1866 kf.co[0] = final_pos[0]
1867 kf.co[1] = final_pos[1]
1868 kf.co[2] = final_pos[2]
1869
1870 kf.q[0] = rq[1]
1871 kf.q[1] = rq[3]
1872 kf.q[2] = -rq[2]
1873 kf.q[3] = rq[0]
1874
1875 # scale
1876 kf.s[0] = sca[0]
1877 kf.s[1] = sca[2]
1878 kf.s[2] = sca[1]
1879
1880 keyframedata += [kf]
1881 break
1882 #}
1883 #}
1884 #}
1885
1886 # Add to animation buffer
1887 #
1888 animdata += [anim]
1889 node_def['anim_count'] += 1
1890
1891 # Report progress
1892 #
1893 status_name = F" " + " |"*(node_def['depth']-1)
1894 print( F"{status_name} | *anim: {NLAStrip.action.name}" )
1895 #}
1896 #}
1897
1898 # Restore context to how it was before
1899 #
1900 bpy.context.scene.frame_set( previous_frame )
1901 obj.animation_data.action = previous_action
1902 obj.data.pose_position = POSE_OR_REST_CACHE
1903 #}
1904 #}
1905
1906 # We are trying to compile this node_def
1907 #
1908 def encoder_process_definition( node_def ):
1909 #{
1910 global g_encoder
1911
1912 # data sources for object/bone are taken differently
1913 #
1914 if 'obj' in node_def:
1915 #{
1916 obj = node_def['obj']
1917 obj_type = obj.type
1918 obj_co = obj.location
1919
1920 if obj_type == 'ARMATURE':
1921 obj_classtype = 'classtype_skeleton'
1922 elif obj_type == 'LIGHT':
1923 #{
1924 obj_classtype = 'classtype_world_light'
1925 #}
1926 else:
1927 #{
1928 obj_classtype = obj.cv_data.classtype
1929
1930 # Check for armature deform
1931 #
1932 for mod in obj.modifiers:
1933 #{
1934 if mod.type == 'ARMATURE':
1935 #{
1936 obj_classtype = 'classtype_skin'
1937
1938 # Make sure to freeze armature in rest while we collect
1939 # vertex information
1940 #
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
1945 break
1946 #}
1947 #}
1948 #}
1949 #}
1950
1951 elif 'bone' in node_def:
1952 #{
1953 obj = node_def['bone']
1954 obj_type = 'BONE'
1955 obj_co = obj.head_local
1956 obj_classtype = 'classtype_bone'
1957 #}
1958
1959 # Create node
1960 #
1961 node = mdl_node()
1962 node.pstr_name = encoder_process_pstr( obj.name )
1963
1964 if node_def["parent"]:
1965 node.parent = node_def["parent"]["uid"]
1966
1967 # Setup transform
1968 #
1969 node.co[0] = obj_co[0]
1970 node.co[1] = obj_co[2]
1971 node.co[2] = -obj_co[1]
1972
1973 # Convert rotation quat to our space type
1974 #
1975 quat = obj.matrix_local.to_quaternion()
1976 node.q[0] = quat[1]
1977 node.q[1] = quat[3]
1978 node.q[2] = -quat[2]
1979 node.q[3] = quat[0]
1980
1981 # Bone scale is just a vector to the tail
1982 #
1983 if obj_type == 'BONE':
1984 #{
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]
1988 #}
1989 else:
1990 #{
1991 node.s[0] = obj.scale[0]
1992 node.s[1] = obj.scale[2]
1993 node.s[2] = obj.scale[1]
1994 #}
1995
1996 # Report status
1997 #
1998 tot_uid = g_encoder['uid_count']-1
1999 obj_uid = node_def['uid']
2000 obj_depth = node_def['depth']-1
2001
2002 status_id = F" [{obj_uid: 3}/{tot_uid}]" + " |"*obj_depth
2003 status_name = status_id + F" L {obj.name}"
2004
2005 if obj_classtype != 'classtype_none': status_type = obj_classtype
2006 else: status_type = obj_type
2007
2008 status_parent = F"{node.parent: 3}"
2009 status_armref = ""
2010
2011 if obj_classtype == 'classtype_skin':
2012 status_armref = F" [armature -> {armature_def['obj'].cv_data.uid}]"
2013
2014 print(F"{status_name:<32} {status_type:<22} {status_parent} {status_armref}")
2015
2016 # Process mesh if needed
2017 #
2018 if obj_type == 'MESH':
2019 #{
2020 encoder_compile_mesh( node, node_def )
2021 #}
2022 elif obj_type == 'ARMATURE':
2023 #{
2024 encoder_compile_armature( node, node_def )
2025 #}
2026
2027 encoder_compile_ent_as( obj_classtype, node, node_def )
2028
2029 # Make sure to reset the armature we just mucked about with
2030 #
2031 if obj_classtype == 'classtype_skin':
2032 armature_def['obj'].data.pose_position = POSE_OR_REST_CACHE
2033
2034 g_encoder['data']['node'] += [node]
2035 #}
2036
2037 # The post processing step or the pre processing to the writing step
2038 #
2039 def encoder_write_to_file( path ):
2040 #{
2041 global g_encoder
2042
2043 # Compile down to a byte array
2044 #
2045 header = g_encoder['header']
2046 file_pos = sizeof(header)
2047 file_data = bytearray()
2048 print( " Compositing data arrays" )
2049
2050 for array_name in g_encoder['data']:
2051 #{
2052 file_pos += bytearray_align_to( file_data, 16, sizeof(header) )
2053 arr = g_encoder['data'][array_name]
2054
2055 setattr( header, array_name + "_offset", file_pos )
2056
2057 print( F" {array_name:<16} @{file_pos:> 8X}[{len(arr)}]" )
2058
2059 if isinstance( arr, bytearray ):
2060 #{
2061 setattr( header, array_name + "_size", len(arr) )
2062
2063 file_data.extend( arr )
2064 file_pos += len(arr)
2065 #}
2066 else:
2067 #{
2068 setattr( header, array_name + "_count", len(arr) )
2069
2070 for item in arr:
2071 #{
2072 bbytes = bytearray(item)
2073 file_data.extend( bbytes )
2074 file_pos += sizeof(item)
2075 #}
2076 #}
2077 #}
2078
2079 # This imperitive for this field to be santized in the future!
2080 #
2081 header.file_length = file_pos
2082
2083 print( " Writing file" )
2084 # Write header and data chunk to file
2085 #
2086 fp = open( path, "wb" )
2087 fp.write( bytearray( header ) )
2088 fp.write( file_data )
2089 fp.close()
2090 #}
2091
2092 # Main compiler, uses string as the identifier for the collection
2093 #
2094 def write_model(collection_name):
2095 #{
2096 global g_encoder
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"
2100 print( path )
2101
2102 collection = bpy.data.collections[collection_name]
2103
2104 encoder_init( collection )
2105 encoder_build_scene_graph( collection )
2106
2107 # Compile
2108 #
2109 print( " Comping objects" )
2110 it = encoder_graph_iterator( g_encoder['scene_graph'] )
2111 for node_def in it:
2112 encoder_process_definition( node_def )
2113
2114 # Write
2115 #
2116 encoder_write_to_file( path )
2117
2118 print( F"Completed {collection_name}.mdl" )
2119 #}
2120
2121 # ---------------------------------------------------------------------------- #
2122 # #
2123 # GUI section #
2124 # #
2125 # ---------------------------------------------------------------------------- #
2126
2127 cv_view_draw_handler = None
2128 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
2129 cv_view_verts = []
2130 cv_view_colours = []
2131 cv_view_course_i = 0
2132
2133 # Draw axis alligned sphere at position with radius
2134 #
2135 def cv_draw_sphere( pos, radius, colour ):
2136 #{
2137 global cv_view_verts, cv_view_colours
2138
2139 ly = pos + Vector((0,0,radius))
2140 lx = pos + Vector((0,radius,0))
2141 lz = pos + Vector((0,0,radius))
2142
2143 pi = 3.14159265358979323846264
2144
2145 for i in range(16):
2146 #{
2147 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
2148 s = math.sin(t)
2149 c = math.cos(t)
2150
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))
2154
2155 cv_view_verts += [ px, lx ]
2156 cv_view_verts += [ py, ly ]
2157 cv_view_verts += [ pz, lz ]
2158
2159 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2160
2161 ly = py
2162 lx = px
2163 lz = pz
2164 #}
2165 cv_draw_lines()
2166 #}
2167
2168 # Draw axis alligned sphere at position with radius
2169 #
2170 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
2171 #{
2172 global cv_view_verts, cv_view_colours
2173
2174 ly = pos + tz*radius
2175 lx = pos + ty*radius
2176 lz = pos + tz*radius
2177
2178 pi = 3.14159265358979323846264
2179
2180 for i in range(16):
2181 #{
2182 t = ((i+1.0) * 1.0/16.0) * pi
2183 s = math.sin(t)
2184 c = math.cos(t)
2185
2186 s1 = math.sin(t*2.0)
2187 c1 = math.cos(t*2.0)
2188
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
2192
2193 cv_view_verts += [ px, lx ]
2194 cv_view_verts += [ py, ly ]
2195 cv_view_verts += [ pz, lz ]
2196
2197 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2198
2199 ly = py
2200 lx = px
2201 lz = pz
2202 #}
2203 cv_draw_lines()
2204 #}
2205
2206 # Draw transformed -1 -> 1 cube
2207 #
2208 def cv_draw_ucube( transform, colour ):
2209 #{
2210 global cv_view_verts, cv_view_colours
2211
2212 a = Vector((-1,-1,-1))
2213 b = Vector((1,1,1))
2214
2215 vs = [None]*8
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]))
2224
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)]
2227
2228 for l in indices:
2229 #{
2230 v0 = vs[l[0]]
2231 v1 = vs[l[1]]
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)]
2235 #}
2236 cv_draw_lines()
2237 #}
2238
2239 # Draw line with colour
2240 #
2241 def cv_draw_line( p0, p1, colour ):
2242 #{
2243 global cv_view_verts, cv_view_colours
2244
2245 cv_view_verts += [p0,p1]
2246 cv_view_colours += [colour, colour]
2247 cv_draw_lines()
2248 #}
2249
2250 # Draw line with colour(s)
2251 #
2252 def cv_draw_line2( p0, p1, c0, c1 ):
2253 #{
2254 global cv_view_verts, cv_view_colours
2255
2256 cv_view_verts += [p0,p1]
2257 cv_view_colours += [c0,c1]
2258 cv_draw_lines()
2259 #}
2260
2261 #
2262 #
2263 def cv_tangent_basis( n, tx, ty ):
2264 #{
2265 if abs( n[0] ) >= 0.57735027:
2266 #{
2267 tx[0] = n[1]
2268 tx[1] = -n[0]
2269 tx[2] = 0.0
2270 #}
2271 else:
2272 #{
2273 tx[0] = 0.0
2274 tx[1] = n[2]
2275 tx[2] = -n[1]
2276 #}
2277
2278 tx.normalize()
2279 _ty = n.cross( tx )
2280
2281 ty[0] = _ty[0]
2282 ty[1] = _ty[1]
2283 ty[2] = _ty[2]
2284 #}
2285
2286 # Draw coloured arrow
2287 #
2288 def cv_draw_arrow( p0, p1, c0 ):
2289 #{
2290 global cv_view_verts, cv_view_colours
2291
2292 n = p1-p0
2293 midpt = p0 + n*0.5
2294 n.normalize()
2295
2296 tx = Vector((1,0,0))
2297 ty = Vector((1,0,0))
2298 cv_tangent_basis( n, tx, ty )
2299
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]
2302 cv_draw_lines()
2303 #}
2304
2305 # Drawhandles of a bezier control point
2306 #
2307 def cv_draw_bhandle( obj, direction, colour ):
2308 #{
2309 global cv_view_verts, cv_view_colours
2310
2311 p0 = obj.location
2312 h0 = obj.matrix_world @ Vector((0,direction,0))
2313
2314 cv_view_verts += [p0]
2315 cv_view_verts += [h0]
2316 cv_view_colours += [colour,colour]
2317 cv_draw_lines()
2318 #}
2319
2320 # Draw a bezier curve (at fixed resolution 10)
2321 #
2322 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2323 #{
2324 global cv_view_verts, cv_view_colours
2325
2326 last = p0
2327 for i in range(10):
2328 #{
2329 t = (i+1)/10
2330 a0 = 1-t
2331
2332 tt = t*t
2333 ttt = tt*t
2334 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2335
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)]
2339
2340 last = p
2341 #}
2342 cv_draw_lines()
2343 #}
2344
2345 # I think this one extends the handles of the bezier otwards......
2346 #
2347 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2348 #{
2349 global cv_view_course_i
2350
2351 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2352
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))
2357
2358 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2359 cv_draw_lines()
2360 #}
2361
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.
2364 #
2365 def cv_draw_lines():
2366 #{
2367 global cv_view_shader, cv_view_verts, cv_view_colours
2368
2369 if len(cv_view_verts) < 2:
2370 return
2371
2372 lines = batch_for_shader(\
2373 cv_view_shader, 'LINES', \
2374 { "pos":cv_view_verts, "color":cv_view_colours })
2375
2376 lines.draw( cv_view_shader )
2377
2378 cv_view_verts = []
2379 cv_view_colours = []
2380 #}
2381
2382 # I dont remember what this does exactly
2383 #
2384 def cv_draw_bpath( o0,o1,c0,c1 ):
2385 #{
2386 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2387 #}
2388
2389 # Semi circle to show the limit. and some lines
2390 #
2391 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2392 #{
2393 global cv_view_verts, cv_view_colours
2394 f = 0.05
2395 ay = major*f
2396 ax = minor*f
2397
2398 for x in range(16):
2399 #{
2400 t0 = x/16
2401 t1 = (x+1)/16
2402 a0 = amin*(1.0-t0)+amax*t0
2403 a1 = amin*(1.0-t1)+amax*t1
2404
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)
2407
2408 p0=obj.matrix_world @ p0
2409 p1=obj.matrix_world @ p1
2410 cv_view_verts += [p0,p1]
2411 cv_view_colours += [colour,colour]
2412
2413 if x == 0:
2414 #{
2415 cv_view_verts += [p0,center]
2416 cv_view_colours += [colour,colour]
2417 #}
2418 if x == 15:
2419 #{
2420 cv_view_verts += [p1,center]
2421 cv_view_colours += [colour,colour]
2422 #}
2423 #}
2424
2425 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2426 cv_view_colours += [colour,colour]
2427
2428 cv_draw_lines()
2429 #}
2430
2431 # Cone and twist limit
2432 #
2433 def draw_cone_twist( center, vx, vy, va ):
2434 #{
2435 global cv_view_verts, cv_view_colours
2436 axis = vy.cross( vx )
2437 axis.normalize()
2438
2439 size = 0.12
2440
2441 cv_view_verts += [center, center+va*size]
2442 cv_view_colours += [ (1,1,1,1), (1,1,1,1) ]
2443
2444 for x in range(32):
2445 #{
2446 t0 = (x/32) * math.tau
2447 t1 = ((x+1)/32) * math.tau
2448
2449 c0 = math.cos(t0)
2450 s0 = math.sin(t0)
2451 c1 = math.cos(t1)
2452 s1 = math.sin(t1)
2453
2454 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
2455 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
2456
2457 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
2458 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
2459
2460 cv_view_verts += [center, p0, p0, p1]
2461 cv_view_colours += [ (0,0,0,0), col0, col0, col1 ]
2462 #}
2463
2464 cv_draw_lines()
2465 #}
2466
2467 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2468 #
2469 def draw_skeleton_helpers( obj ):
2470 #{
2471 global cv_view_verts, cv_view_colours
2472
2473 if obj.data.pose_position != 'REST':
2474 #{
2475 return
2476 #}
2477
2478 for bone in obj.data.bones:
2479 #{
2480 c = bone.head_local
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]))
2483
2484 if bone.cv_data.collider == 'collider_box':
2485 #{
2486
2487 vs = [None]*8
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]))
2496
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)]
2499
2500 for l in indices:
2501 #{
2502 v0 = vs[l[0]]
2503 v1 = vs[l[1]]
2504
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)]
2508 #}
2509 #}
2510 elif bone.cv_data.collider == 'collider_capsule':
2511 #{
2512 v0 = b-a
2513 major_axis = 0
2514 largest = -1.0
2515
2516 for i in range(3):
2517 #{
2518 if abs(v0[i]) > largest:
2519 #{
2520 largest = abs(v0[i])
2521 major_axis = i
2522 #}
2523 #}
2524
2525 v1 = Vector((0,0,0))
2526 v1[major_axis] = 1.0
2527
2528 tx = Vector((0,0,0))
2529 ty = Vector((0,0,0))
2530
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
2534
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 )
2537
2538 colour = [0.2,0.2,0.2,1.0]
2539 colour[major_axis] = 0.5
2540
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 )
2547 #}
2548 else:
2549 #{
2550 continue
2551 #}
2552
2553 center = obj.matrix_world @ c
2554 if bone.cv_data.con0:
2555 #{
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 )
2560
2561 #draw_limit( obj, c, Vector((0,0,1)),Vector((0,-1,0)), \
2562 # bone.cv_data.mins[0], bone.cv_data.maxs[0], \
2563 # (1,0,0,1))
2564 #draw_limit( obj, c, Vector((0,-1,0)),Vector((1,0,0)), \
2565 # bone.cv_data.mins[1], bone.cv_data.maxs[1], \
2566 # (0,1,0,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], \
2569 # (0,0,1,1))
2570 #}
2571 #}
2572 #}
2573
2574 def cv_draw():
2575 #{
2576 global cv_view_shader
2577 global cv_view_verts
2578 global cv_view_colours
2579 global cv_view_course_i
2580
2581 cv_view_course_i = 0
2582 cv_view_verts = []
2583 cv_view_colours = []
2584
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')
2591
2592 for obj in bpy.context.collection.objects:
2593 #{
2594 if obj.type == 'ARMATURE':
2595 #{
2596 if obj.data.pose_position == 'REST':
2597 draw_skeleton_helpers( obj )
2598 #}
2599 else:
2600 #{
2601 classtype = obj.cv_data.classtype
2602 if (classtype != 'classtype_none') and (classtype in globals()):
2603 #{
2604 cl = globals()[ classtype ]
2605
2606 if getattr( cl, "draw_scene_helpers", None ):
2607 #{
2608 cl.draw_scene_helpers( obj )
2609 #}
2610 #}
2611 #}
2612 #}
2613
2614 cv_draw_lines()
2615 return
2616 #}
2617
2618
2619 # ---------------------------------------------------------------------------- #
2620 # #
2621 # Blender #
2622 # #
2623 # ---------------------------------------------------------------------------- #
2624
2625 # Checks whether this object has a classtype assigned. we can only target other
2626 # classes
2627 def cv_poll_target(scene, obj):
2628 #{
2629 if obj == bpy.context.active_object:
2630 return False
2631 if obj.cv_data.classtype == 'classtype_none':
2632 return False
2633
2634 return True
2635 #}
2636
2637 class CV_MESH_SETTINGS(bpy.types.PropertyGroup):
2638 #{
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)
2643 #}
2644
2645 class CV_OBJ_SETTINGS(bpy.types.PropertyGroup):
2646 #{
2647 uid: bpy.props.IntProperty( name="" )
2648
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" )
2656
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 )
2665
2666 colour: bpy.props.FloatVectorProperty( name="colour",subtype='COLOR',\
2667 min=0.0,max=1.0)
2668
2669 classtype: bpy.props.EnumProperty(
2670 name="Format",
2671 items = [
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)
2684 ])
2685 #}
2686
2687 class CV_BONE_SETTINGS(bpy.types.PropertyGroup):
2688 #{
2689 collider: bpy.props.EnumProperty(
2690 name="Collider Type",
2691 items = [
2692 ('collider_none', "collider_none", "", 0),
2693 ('collider_box', "collider_box", "", 1),
2694 ('collider_capsule', "collider_capsule", "", 2),
2695 ])
2696
2697 v0: bpy.props.FloatVectorProperty(name="v0",size=3)
2698 v1: bpy.props.FloatVectorProperty(name="v1",size=3)
2699
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)
2703
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")
2708 #}
2709
2710 class CV_BONE_PANEL(bpy.types.Panel):
2711 #{
2712 bl_label="Bone Config"
2713 bl_idname="SCENE_PT_cv_bone"
2714 bl_space_type='PROPERTIES'
2715 bl_region_type='WINDOW'
2716 bl_context='bone'
2717
2718 def draw(_,context):
2719 #{
2720 active_object = context.active_object
2721 if active_object == None: return
2722
2723 bone = active_object.data.bones.active
2724 if bone == None: return
2725
2726 _.layout.prop( bone.cv_data, "collider" )
2727 _.layout.prop( bone.cv_data, "v0" )
2728 _.layout.prop( bone.cv_data, "v1" )
2729
2730 _.layout.label( text="Angle Limits" )
2731 _.layout.prop( bone.cv_data, "con0" )
2732
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" )
2737 #}
2738 #}
2739
2740 class CV_SCENE_SETTINGS(bpy.types.PropertyGroup):
2741 #{
2742 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
2743 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
2744 #}
2745
2746 class CV_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
2747 #{
2748 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
2749 animations: bpy.props.BoolProperty( name="Export animation", default=True)
2750 #}
2751
2752 class CV_MATERIAL_SETTINGS(bpy.types.PropertyGroup):
2753 #{
2754 shader: bpy.props.EnumProperty(
2755 name="Format",
2756 items = [
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),
2762 ])
2763
2764 surface_prop: bpy.props.EnumProperty(
2765 name="Surface Property",
2766 items = [
2767 ('concrete','concrete','',0),
2768 ('wood','wood','',1),
2769 ('grass','grass','',2)
2770 ])
2771
2772 collision: bpy.props.BoolProperty( \
2773 name="Collisions Enabled",\
2774 default=True,\
2775 description = "Can the player collide with this material"\
2776 )
2777 skate_surface: bpy.props.BoolProperty( \
2778 name="Skate Surface", \
2779 default=True,\
2780 description = "Should the game try to target this surface?" \
2781 )
2782 grind_surface: bpy.props.BoolProperty( \
2783 name="Grind Surface", \
2784 default=False,\
2785 description = "Grind face?" \
2786 )
2787 grow_grass: bpy.props.BoolProperty( \
2788 name="Grow Grass", \
2789 default=False,\
2790 description = "Spawn grass sprites on this surface?" \
2791 )
2792 blend_offset: bpy.props.FloatVectorProperty( \
2793 name="Blend Offset", \
2794 size=2, \
2795 default=Vector((0.5,0.0)),\
2796 description="When surface is more than 45 degrees, add this vector " +\
2797 "to the UVs" \
2798 )
2799 sand_colour: bpy.props.FloatVectorProperty( \
2800 name="Sand Colour",\
2801 subtype='COLOR',\
2802 min=0.0,max=1.0,\
2803 default=Vector((0.79,0.63,0.48)),\
2804 description="Blend to this colour near the 0 coordinate on UP axis"\
2805 )
2806 shore_colour: bpy.props.FloatVectorProperty( \
2807 name="Shore Colour",\
2808 subtype='COLOR',\
2809 min=0.0,max=1.0,\
2810 default=Vector((0.03,0.32,0.61)),\
2811 description="Water colour at the shoreline"\
2812 )
2813 ocean_colour: bpy.props.FloatVectorProperty( \
2814 name="Ocean Colour",\
2815 subtype='COLOR',\
2816 min=0.0,max=1.0,\
2817 default=Vector((0.0,0.006,0.03)),\
2818 description="Water colour in the deep bits"\
2819 )
2820 #}
2821
2822 class CV_MATERIAL_PANEL(bpy.types.Panel):
2823 #{
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"
2829
2830 def draw(_,context):
2831 #{
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
2836
2837 info = material_info( active_mat )
2838
2839 if 'tex_diffuse' in info:
2840 #{
2841 _.layout.label( icon='INFO', \
2842 text=F"{info['tex_diffuse'].name} will be compiled" )
2843 #}
2844
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" )
2848
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" )
2853
2854 if active_mat.cv_data.shader == "terrain_blend":
2855 #{
2856 box = _.layout.box()
2857 box.prop( active_mat.cv_data, "blend_offset" )
2858 box.prop( active_mat.cv_data, "sand_colour" )
2859 #}
2860 elif active_mat.cv_data.shader == "vertex_blend":
2861 #{
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" )
2865 #}
2866 elif active_mat.cv_data.shader == "water":
2867 #{
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" )
2872 #}
2873 #}
2874 #}
2875
2876 class CV_OBJ_PANEL(bpy.types.Panel):
2877 #{
2878 bl_label="Entity Config"
2879 bl_idname="SCENE_PT_cv_entity"
2880 bl_space_type='PROPERTIES'
2881 bl_region_type='WINDOW'
2882 bl_context="object"
2883
2884 def draw(_,context):
2885 #{
2886 active_object = bpy.context.active_object
2887 if active_object == None: return
2888 if active_object.type == 'ARMATURE':
2889 #{
2890 row = _.layout.row()
2891 row.enabled = False
2892 row.label( text="This object has the intrinsic classtype of skeleton" )
2893 return
2894 #}
2895
2896 _.layout.prop( active_object.cv_data, "classtype" )
2897
2898 classtype = active_object.cv_data.classtype
2899
2900 if (classtype != 'classtype_none') and (classtype in globals()):
2901 #{
2902 cl = globals()[ classtype ]
2903
2904 if getattr( cl, "editor_interface", None ):
2905 #{
2906 cl.editor_interface( _.layout, active_object )
2907 #}
2908 #}
2909 #}
2910 #}
2911
2912 class CV_COMPILE(bpy.types.Operator):
2913 #{
2914 bl_idname="carve.compile_all"
2915 bl_label="Compile All"
2916
2917 def execute(_,context):
2918 #{
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 )
2923
2924 return {'FINISHED'}
2925 #}
2926 #}
2927
2928 class CV_COMPILE_THIS(bpy.types.Operator):
2929 #{
2930 bl_idname="carve.compile_this"
2931 bl_label="Compile This collection"
2932
2933 def execute(_,context):
2934 #{
2935 col = bpy.context.collection
2936 write_model( col.name )
2937
2938 return {'FINISHED'}
2939 #}
2940 #}
2941
2942 class CV_INTERFACE(bpy.types.Panel):
2943 #{
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"
2949
2950 def draw(_, context):
2951 #{
2952 layout = _.layout
2953 layout.prop( context.scene.cv_data, "export_dir" )
2954
2955 col = bpy.context.collection
2956
2957 found_in_export = False
2958 export_count = 0
2959 view_layer = bpy.context.view_layer
2960 for c1 in view_layer.layer_collection.children["export"].children:
2961 #{
2962 if not c1.hide_viewport or bpy.context.scene.cv_data.use_hidden:
2963 export_count += 1
2964
2965 if c1.name == col.name:
2966 #{
2967 found_in_export = True
2968 #}
2969 #}
2970
2971 box = layout.box()
2972 if found_in_export:
2973 #{
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" )
2978 #}
2979 else:
2980 #{
2981 row = box.row()
2982 row.enabled=False
2983 row.label( text=col.name )
2984 box.label( text="This collection is not in the export group" )
2985 #}
2986
2987 box = layout.box()
2988 row = box.row()
2989
2990 split = row.split( factor = 0.3, align=True )
2991 split.prop( context.scene.cv_data, "use_hidden", text="hidden" )
2992
2993 row1 = split.row()
2994 if export_count == 0:
2995 row1.enabled=False
2996 row1.operator( "carve.compile_all", \
2997 text=F"Compile all ({export_count} collections)" )
2998 #}
2999 #}
3000
3001
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 ]
3006
3007 def register():
3008 #{
3009 global cv_view_draw_handler
3010
3011 for c in classes:
3012 bpy.utils.register_class(c)
3013
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)
3022
3023 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
3024 cv_draw,(),'WINDOW','POST_VIEW')
3025 #}
3026
3027 def unregister():
3028 #{
3029 global cv_view_draw_handler
3030
3031 for c in classes:
3032 bpy.utils.unregister_class(c)
3033
3034 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
3035 #}
3036
3037 # ---------------------------------------------------------------------------- #
3038 # #
3039 # QOI encoder #
3040 # #
3041 # ---------------------------------------------------------------------------- #
3042 # #
3043 # Transliteration of: #
3044 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
3045 # #
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 #
3049 # #
3050 # ---------------------------------------------------------------------------- #
3051
3052 class qoi_rgba_t(Structure):
3053 #{
3054 _pack_ = 1
3055 _fields_ = [("r",c_uint8),
3056 ("g",c_uint8),
3057 ("b",c_uint8),
3058 ("a",c_uint8)]
3059 #}
3060
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
3067
3068 QOI_MASK_2 = 0xc0 # 11000000
3069
3070 def qoi_colour_hash( c ):
3071 #{
3072 return c.r*3 + c.g*5 + c.b*7 + c.a*11
3073 #}
3074
3075 def qoi_eq( a, b ):
3076 #{
3077 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
3078 #}
3079
3080 def qoi_32bit( v ):
3081 #{
3082 return bytearray([ (0xff000000 & v) >> 24, \
3083 (0x00ff0000 & v) >> 16, \
3084 (0x0000ff00 & v) >> 8, \
3085 (0x000000ff & v) ])
3086 #}
3087
3088 def qoi_encode( img ):
3089 #{
3090 data = bytearray()
3091
3092 print(F" . Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]")
3093
3094 index = [ qoi_rgba_t() for _ in range(64) ]
3095
3096 # Header
3097 #
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)) )
3103
3104 run = 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)
3110
3111 px = qoi_rgba_t()
3112 px.r = c_uint8(0)
3113 px.g = c_uint8(0)
3114 px.b = c_uint8(0)
3115 px.a = c_uint8(255)
3116
3117 px_len = img.size[0] * img.size[1]
3118
3119 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
3120
3121 for px_pos in range( px_len ):
3122 #{
3123 idx = px_pos * img.channels
3124 nc = img.channels-1
3125
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)]
3130
3131 if qoi_eq( px, px_prev ):
3132 #{
3133 run += 1
3134
3135 if (run == 62) or (px_pos == px_len-1):
3136 #{
3137 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
3138 run = 0
3139 #}
3140 #}
3141 else:
3142 #{
3143 if run > 0:
3144 #{
3145 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
3146 run = 0
3147 #}
3148
3149 index_pos = qoi_colour_hash(px) % 64
3150
3151 if qoi_eq( index[index_pos], px ):
3152 #{
3153 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
3154 #}
3155 else:
3156 #{
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
3161
3162 if px.a == px_prev.a:
3163 #{
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)
3167
3168 vg_r = vr - vg
3169 vg_b = vb - vg
3170
3171 if (vr > -3) and (vr < 2) and\
3172 (vg > -3) and (vg < 2) and\
3173 (vb > -3) and (vb < 2):
3174 #{
3175 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
3176 data.extend( bytearray( c_uint8(op) ))
3177 #}
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):
3181 #{
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) ))
3186 #}
3187 else:
3188 #{
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) ))
3193 #}
3194 #}
3195 else:
3196 #{
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) ))
3202 #}
3203 #}
3204 #}
3205
3206 px_prev.r = px.r
3207 px_prev.g = px.g
3208 px_prev.b = px.b
3209 px_prev.a = px.a
3210 #}
3211
3212 # Padding
3213 for i in range(7):
3214 data.extend( bytearray( c_uint8(0) ))
3215 data.extend( bytearray( c_uint8(1) ))
3216 bytearray_align_to( data, 16, 0 )
3217
3218 return data
3219 #}