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