cb3b9907ea337adc4e3ff9ee6c1c5901d3e2ae90
[carveJwlIkooP6JGAAIwe30JlM.git] / blender_export.py
1 import bpy, math, gpu, os
2 import cProfile
3 from ctypes import *
4 from mathutils import *
5 from gpu_extras.batch import batch_for_shader
6 from bpy_extras import mesh_utils
7
8 bl_info = {
9 "name":"Skaterift .mdl exporter",
10 "author": "Harry Godden (hgn)",
11 "version": (0,2),
12 "blender":(3,1,0),
13 "location":"Export",
14 "description":"",
15 "warning":"",
16 "wiki_url":"",
17 "category":"Import/Export",
18 }
19
20 sr_entity_list = [
21 ('none', 'None', '', 0 ),
22 ('ent_gate', 'Gate', '', 1 ),
23 ('ent_spawn', 'Spawn Point', '', 2 ),
24 ('ent_route_node', 'Routing Path', '', 3 ),
25 ('ent_route', 'Skate Course', '', 4 ),
26 ('ent_water', 'Water Surface', '', 5 ),
27 ('ent_volume', 'Volume/Trigger', '', 6 ),
28 ('ent_audio', 'Audio', '', 7 ),
29 ('ent_marker', 'Marker', '', 8 ),
30 ('ent_font', 'Font', '', 9 ),
31 ('ent_font_variant', 'Font:Variant', '', 10 ),
32 ('ent_traffic', 'Traffic Model', '', 11 ),
33 ('ent_skateshop', 'Skate Shop', '', 12 ),
34 ('ent_camera', 'Camera', '', 13 ),
35 ('ent_swspreview', 'Workshop Preview', '', 14 ),
36 ('ent_menuitem', 'Menu Item', '', 15 )
37 ]
38
39 def get_entity_enum_id( alias ):
40 #{
41 for et in sr_entity_list:#{
42 if et[0] == alias:#{
43 return et[3]
44 #}
45 #}
46
47 return 0
48 #}
49
50 class mdl_vert(Structure): # 48 bytes. Quite large. Could compress
51 #{ # the normals and uvs to i16s. Not an
52 _pack_ = 1 # real issue, yet.
53 _fields_ = [("co",c_float*3),
54 ("norm",c_float*3),
55 ("uv",c_float*2),
56 ("colour",c_uint8*4),
57 ("weights",c_uint16*4),
58 ("groups",c_uint8*4)]
59 #}
60
61 class mdl_transform(Structure):
62 #{
63 _fields_ = [("co",c_float*3),
64 ( "s",c_float*3),
65 ( "q",c_float*4)]
66 #}
67
68 class mdl_submesh(Structure):
69 #{
70 _fields_ = [("indice_start",c_uint32),
71 ("indice_count",c_uint32),
72 ("vertex_start",c_uint32),
73 ("vertex_count",c_uint32),
74 ("bbx",(c_float*3)*2),
75 ("material_id",c_uint16), # index into the material array
76 ("flags",c_uint16)]
77 #}
78
79 class mdl_material(Structure):
80 #{
81 _fields_ = [("pstr_name",c_uint32),
82 ("shader",c_uint32),
83 ("flags",c_uint32),
84 ("surface_prop",c_uint32),
85 ("colour",c_float*4),
86 ("colour1",c_float*4),
87 ("tex_diffuse",c_uint32),
88 ("tex_none0",c_uint32),
89 ("tex_none1",c_uint32)]
90 #}
91
92 class mdl_bone(Structure):
93 #{
94 _fields_ = [("co",c_float*3),("end",c_float*3),
95 ("parent",c_uint32),
96 ("collider",c_uint32),
97 ("ik_target",c_uint32),
98 ("ik_pole",c_uint32),
99 ("flags",c_uint32),
100 ("pstr_name",c_uint32),
101 ("hitbox",(c_float*3)*2),
102 ("conevx",c_float*3),("conevy",c_float*3),("coneva",c_float*3),
103 ("conet",c_float)]
104 #}
105
106 class mdl_armature(Structure):
107 #{
108 _fields_ = [("transform",mdl_transform),
109 ("bone_start",c_uint32),
110 ("bone_count",c_uint32),
111 ("anim_start",c_uint32),
112 ("anim_count",c_uint32)]
113 #}
114
115 class mdl_animation(Structure):
116 #{
117 _fields_ = [("pstr_name",c_uint32),
118 ("length",c_uint32),
119 ("rate",c_float),
120 ("keyframe_start",c_uint32)]
121 #}
122
123 class mdl_mesh(Structure):
124 #{
125 _fields_ = [("transform",mdl_transform),
126 ("submesh_start",c_uint32),
127 ("submesh_count",c_uint32),
128 ("pstr_name",c_uint32),
129 ("entity_id",c_uint32),
130 ("armature_id",c_uint32)]
131 #}
132
133 class mdl_file(Structure):
134 #{
135 _fields_ = [("path",c_uint32),
136 ("pack_offset",c_uint32),
137 ("pack_size",c_uint32)]
138 #}
139
140 class mdl_texture(Structure):
141 #{
142 _fields_ = [("file",mdl_file),
143 ("glname",c_uint32)]
144 #}
145
146 class mdl_array(Structure):
147 #{
148 _fields_ = [("file_offset",c_uint32),
149 ("item_count",c_uint32),
150 ("item_size",c_uint32),
151 ("name",c_byte*16)]
152 #}
153
154 class mdl_header(Structure):
155 #{
156 _fields_ = [("version",c_uint32),
157 ("arrays",mdl_array)]
158 #}
159
160 class ent_spawn(Structure):
161 #{
162 _fields_ = [("transform",mdl_transform),
163 ("pstr_name",c_uint32)]
164 #}
165
166 class ent_light(Structure):
167 #{
168 _fields_ = [("transform",mdl_transform),
169 ("daytime",c_uint32),
170 ("type",c_uint32),
171 ("colour",c_float*4),
172 ("angle",c_float),
173 ("range",c_float),
174 ("inverse_world",(c_float*3)*4), # Runtime
175 ("angle_sin_cos",(c_float*2))] # Runtime
176 #}
177
178 class version_refcount_union(Union):
179 #{
180 _fields_ = [("timing_version",c_uint32),
181 ("ref_count",c_uint8)]
182 #}
183
184 class ent_gate(Structure):
185 #{
186 _fields_ = [("type",c_uint32),
187 ("target", c_uint32),
188 ("dimensions", c_float*3),
189 ("co", (c_float*3)*2),
190 ("q", (c_float*4)*2),
191 ("to_world",(c_float*3)*4),
192 ("transport",(c_float*3)*4),
193 ("_anonymous_union",version_refcount_union),
194 ("timing_time",c_double),
195 ("routes",c_uint16*4),
196 ("route_count",c_uint8)]
197 #}
198
199 class ent_route_node(Structure):
200 #{
201 _fields_ = [("co",c_float*3),
202 ("ref_count",c_uint8),
203 ("ref_total",c_uint8)]
204 #}
205
206 class ent_path_index(Structure):
207 #{
208 _fields_ = [("index",c_uint16)]
209 #}
210
211 class vg_audio_clip(Structure):
212 #{
213 _fields_ = [("path",c_uint64),
214 ("flags",c_uint32),
215 ("size",c_uint32),
216 ("data",c_uint64)]
217 #}
218
219 class union_file_audio_clip(Union):
220 #{
221 _fields_ = [("file",mdl_file),
222 ("reserved",vg_audio_clip)]
223 #}
224
225 class ent_audio_clip(Structure):
226 #{
227 _fields_ = [("_anon",union_file_audio_clip),
228 ("probability",c_float)]
229 #}
230
231 class ent_checkpoint(Structure):
232 #{
233 _fields_ = [("gate_index",c_uint16),
234 ("path_start",c_uint16),
235 ("path_count",c_uint16)]
236 #}
237
238 class ent_route(Structure):
239 #{
240 _fields_ = [("transform",mdl_transform),
241 ("pstr_name",c_uint32),
242 ("checkpoints_start",c_uint16),
243 ("checkpoints_count",c_uint16),
244 ("colour",c_float*4),
245 ("active",c_uint32), #runtime
246 ("factive",c_float),
247 ("board_transform",(c_float*3)*4),
248 ("sm",mdl_submesh),
249 ("latest_pass",c_double)]
250 #}
251
252 class ent_water(Structure):
253 #{
254 _fields_ = [("transform",mdl_transform),
255 ("max_dist",c_float),
256 ("reserved0",c_uint32),
257 ("reserved1",c_uint32)]
258 #}
259
260 class volume_trigger(Structure):
261 #{
262 _fields_ = [("event",c_uint32),
263 ("blank",c_uint32)]
264 #}
265
266 class volume_particles(Structure):
267 #{
268 _fields_ = [("blank",c_uint32),
269 ("blank2",c_uint32)]
270 #}
271
272 class volume_union(Union):
273 #{
274 _fields_ = [("trigger",volume_trigger),
275 ("particles",volume_particles)]
276 #}
277
278 class ent_volume(Structure):
279 #{
280 _fields_ = [("transform",mdl_transform),
281 ("to_world",(c_float*3)*4),
282 ("to_local",(c_float*3)*4),
283 ("type",c_uint32),
284 ("target",c_uint32),
285 ("_anon",volume_union)]
286 #}
287
288 class ent_audio(Structure):
289 #{
290 _fields_ = [("transform",mdl_transform),
291 ("flags",c_uint32),
292 ("clip_start",c_uint32),
293 ("clip_count",c_uint32),
294 ("volume",c_float),
295 ("crossfade",c_float),
296 ("channel_behaviour",c_uint32),
297 ("group",c_uint32),
298 ("probability_curve",c_uint32),
299 ("max_channels",c_uint32)]
300 #}
301
302 class ent_marker(Structure):
303 #{
304 _fields_ = [("transform",mdl_transform),
305 ("name",c_uint32)]
306 #}
307
308 class ent_glyph(Structure):
309 #{
310 _fields_ = [("size",c_float*2),
311 ("indice_start",c_uint32),
312 ("indice_count",c_uint32)]
313 #}
314
315 class ent_font_variant(Structure):
316 #{
317 _fields_ = [("name",c_uint32),
318 ("material_id",c_uint32)]
319 #}
320
321 class ent_font(Structure):
322 #{
323 _fields_ = [("alias",c_uint32),
324 ("variant_start",c_uint32),
325 ("variant_count",c_uint32),
326 ("glyph_start",c_uint32),
327 ("glyph_count",c_uint32),
328 ("glyph_utf32_base",c_uint32)]
329 #}
330
331 class ent_traffic(Structure):
332 #{
333 _fields_ = [("transform",mdl_transform),
334 ("submesh_start",c_uint32),
335 ("submesh_count",c_uint32),
336 ("start_node",c_uint32),
337 ("node_count",c_uint32),
338 ("speed",c_float),
339 ("t",c_float),
340 ("index",c_uint32)]
341 #}
342
343 class ent_skateshop(Structure):
344 #{
345 _fields_ = [("transform",mdl_transform),
346 ("id_display",c_uint32),
347 ("id_info",c_uint32),
348 ("id_rack",c_uint32),
349 ("id_camera",c_uint32)]
350 #}
351
352 class ent_swspreview(Structure):
353 #{
354 _fields_ = [("id_camera",c_uint32),
355 ("id_display",c_uint32),
356 ("id_display1",c_uint32)]
357 #}
358
359 class ent_menuitem_slider(Structure):
360 #{
361 _fields_ = [("id_min",c_uint32),
362 ("id_max",c_uint32),
363 ("id_handle",c_uint32),
364 ("pstr_data",c_uint32)]
365 #}
366
367 class ent_menuitem_button(Structure):
368 #{
369 _fields_ = [("pstr",c_uint32)]
370 #}
371
372 class ent_menuitem_checkmark(Structure):
373 #{
374 _fields_ = [("id_check",c_uint32),
375 ("pstr_data",c_uint32)]
376 #}
377
378 class ent_menuitem_page(Structure):
379 #{
380 _fields_ = [("pstr_name",c_uint32),
381 ("id_entrypoint",c_uint32),
382 ("id_viewpoint",c_uint32)]
383 #}
384
385 class ent_menuitem_anon_union(Union):
386 #{
387 _fields_ = [("slider",ent_menuitem_slider),
388 ("button",ent_menuitem_button),
389 ("checkmark",ent_menuitem_checkmark),
390 ("page",ent_menuitem_page)]
391 #}
392
393 class ent_menuitem(Structure):
394 #{
395 _fields_ = [("type",c_uint32), ("groups",c_uint32),
396 ("id_links",c_uint32*4),
397 #-- TODO: Refactor this into a simple mesh structure
398 ("transform",mdl_transform),
399 ("submesh_start",c_uint32),("submesh_count",c_uint32),
400 #-- end
401 ("_anonymous_union", ent_menuitem_anon_union)]
402 #}
403
404 class ent_camera(Structure):
405 #{
406 _fields_ = [("transform",mdl_transform),
407 ("fov",c_float)]
408 #}
409
410 def obj_ent_type( obj ):
411 #{
412 if obj.type == 'ARMATURE': return 'mdl_armature'
413 elif obj.type == 'LIGHT': return 'ent_light'
414 elif obj.type == 'CAMERA': return 'ent_camera'
415 else: return obj.SR_data.ent_type
416 #}
417
418 def sr_filter_ent_type( obj, ent_types ):
419 #{
420 if obj == bpy.context.active_object: return False
421
422 for c0 in obj.users_collection:#{
423 for c1 in bpy.context.active_object.users_collection:#{
424 if c0 == c1:#{
425 return obj_ent_type( obj ) in ent_types
426 #}
427 #}
428 #}
429
430 return False
431 #}
432
433 def compile_obj_transform( obj, transform ):
434 #{
435 co = obj.matrix_world @ Vector((0,0,0))
436
437 # This was changed from matrix_local on 09.05.23
438 q = obj.matrix_world.to_quaternion()
439 s = obj.scale
440
441 # Setup transform
442 #
443 transform.co[0] = co[0]
444 transform.co[1] = co[2]
445 transform.co[2] = -co[1]
446 transform.q[0] = q[1]
447 transform.q[1] = q[3]
448 transform.q[2] = -q[2]
449 transform.q[3] = q[0]
450 transform.s[0] = s[0]
451 transform.s[1] = s[2]
452 transform.s[2] = s[1]
453 #}
454
455 def int_align_to( v, align ):
456 #{
457 while(v%align)!=0: v += 1
458 return v
459 #}
460
461 def bytearray_align_to( buffer, align, w=b'\xaa' ):
462 #{
463 while (len(buffer) % align) != 0: buffer.extend(w)
464 return buffer
465 #}
466
467 def bytearray_print_hex( s, w=16 ):
468 #{
469 for r in range((len(s)+(w-1))//w):#{
470 i0=(r+0)*w
471 i1=min((r+1)*w,len(s))
472 print( F'{r*w:06x}| \x1B[31m', end='')
473 print( F"{' '.join('{:02x}'.format(x) for x in s[i0:i1]):<48}",end='' )
474 print( "\x1B[0m", end='')
475 print( ''.join(chr(x) if (x>=33 and x<=126) else '.' for x in s[i0:i1] ) )
476 #}
477 #}
478
479 def sr_compile_string( s ):
480 #{
481 if s in sr_compile.string_cache: return sr_compile.string_cache[s]
482
483 index = len( sr_compile.string_data )
484 sr_compile.string_cache[s] = index
485 sr_compile.string_data.extend( c_uint32(hash_djb2(s)) )
486 sr_compile.string_data.extend( s.encode('utf-8') )
487 sr_compile.string_data.extend( b'\0' )
488
489 bytearray_align_to( sr_compile.string_data, 4 )
490 return index
491 #}
492
493 def material_tex_image(v):
494 #{
495 return {
496 "Image Texture":
497 {
498 "image": F"{v}"
499 }
500 }
501 #}
502
503 cxr_graph_mapping = \
504 {
505 # Default shader setup
506 "Principled BSDF":
507 {
508 "Base Color":
509 {
510 "Image Texture":
511 {
512 "image": "tex_diffuse"
513 },
514 "Mix":
515 {
516 "A": material_tex_image("tex_diffuse"),
517 "B": material_tex_image("tex_decal")
518 },
519 },
520 "Normal":
521 {
522 "Normal Map":
523 {
524 "Color": material_tex_image("tex_normal")
525 }
526 }
527 },
528 "Emission":
529 {
530 "Color": material_tex_image("tex_diffuse")
531 }
532 }
533
534 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
535 #
536 def material_info(mat):
537 #{
538 info = {}
539
540 # Using the cxr_graph_mapping as a reference, go through the shader
541 # graph and gather all $props from it.
542 #
543 def _graph_read( node_def, node=None, depth=0 ):#{
544 nonlocal mat
545 nonlocal info
546
547 # Find rootnodes
548 #
549 if node == None:#{
550 _graph_read.extracted = []
551
552 for node_idname in node_def:#{
553 for n in mat.node_tree.nodes:#{
554 if n.name == node_idname:#{
555 node_def = node_def[node_idname]
556 node = n
557 break
558 #}
559 #}
560 #}
561 #}
562
563 for link in node_def:#{
564 link_def = node_def[link]
565
566 if isinstance( link_def, dict ):#{
567 node_link = None
568 for x in node.inputs:#{
569 if isinstance( x, bpy.types.NodeSocketColor ):#{
570 if link == x.name:#{
571 node_link = x
572 break
573 #}
574 #}
575 #}
576
577 if node_link and node_link.is_linked:#{
578 # look for definitions for the connected node type
579 #
580 from_node = node_link.links[0].from_node
581
582 node_name = from_node.name.split('.')[0]
583 if node_name in link_def:#{
584 from_node_def = link_def[ node_name ]
585
586 _graph_read( from_node_def, from_node, depth+1 )
587 #}
588 #}
589 else:#{
590 if "default" in link_def:#{
591 prop = link_def['default']
592 info[prop] = node_link.default_value
593 #}
594 #}
595 #}
596 else:#{
597 prop = link_def
598 info[prop] = getattr( node, link )
599 #}
600 #}
601 #}
602
603 _graph_read( cxr_graph_mapping )
604 return info
605 #}
606
607 def vg_str_bin( s ):
608 #{
609 decoded = bytearray()
610 for i in range(len(s)//2):#{
611 c = (ord(s[i*2+0])-0x41)
612 c |= (ord(s[i*2+1])-0x41)<<4
613 decoded.extend(bytearray(c_uint8(c))) #??
614 #}
615 return decoded
616 #}
617
618 def sr_pack_file( file, path, data ):
619 #{
620 file.path = sr_compile_string( path )
621 file.pack_offset = len( sr_compile.pack_data )
622 file.pack_size = len( data )
623
624 sr_compile.pack_data.extend( data )
625 bytearray_align_to( sr_compile.pack_data, 16 )
626 #}
627
628 def sr_compile_texture( img ):
629 #{
630 if img == None:
631 return 0
632
633 name = os.path.splitext( img.name )[0]
634
635 if name in sr_compile.texture_cache:
636 return sr_compile.texture_cache[name]
637
638 texture_index = (len(sr_compile.texture_data)//sizeof(mdl_texture)) +1
639
640 tex = mdl_texture()
641 tex.glname = 0
642
643 if sr_compile.pack_textures:#{
644 filedata = qoi_encode( img )
645 sr_pack_file( tex.file, name, filedata )
646 #}
647
648 sr_compile.texture_cache[name] = texture_index
649 sr_compile.texture_data.extend( bytearray(tex) )
650 return texture_index
651 #}
652
653 def sr_compile_material( mat ):
654 #{
655 if mat == None:
656 return 0
657 if mat.name in sr_compile.material_cache:
658 return sr_compile.material_cache[mat.name]
659
660 index = (len(sr_compile.material_data)//sizeof(mdl_material))+1
661 sr_compile.material_cache[mat.name] = index
662
663 m = mdl_material()
664 m.pstr_name = sr_compile_string( mat.name )
665
666 flags = 0x00
667 if mat.SR_data.collision:#{
668 flags |= 0x2 # collision flag
669 if (mat.SR_data.shader != 'invisible') and \
670 (mat.SR_data.shader != 'boundary'):#{
671 if mat.SR_data.skate_surface: flags |= 0x1
672 if mat.SR_data.grow_grass: flags |= 0x4
673 if mat.SR_data.grind_surface: flags |= 0x8
674 #}
675 if mat.SR_data.shader == 'invisible': flags |= 0x10
676 if mat.SR_data.shader == 'boundary': flags |= (0x10|0x20)
677 #}
678
679 m.flags = flags
680
681 m.surface_prop = int(mat.SR_data.surface_prop)
682
683 if mat.SR_data.shader == 'standard': m.shader = 0
684 if mat.SR_data.shader == 'standard_cutout': m.shader = 1
685 if mat.SR_data.shader == 'terrain_blend':#{
686 m.shader = 2
687
688 m.colour[0] = pow( mat.SR_data.sand_colour[0], 1.0/2.2 )
689 m.colour[1] = pow( mat.SR_data.sand_colour[1], 1.0/2.2 )
690 m.colour[2] = pow( mat.SR_data.sand_colour[2], 1.0/2.2 )
691 m.colour[3] = 1.0
692
693 m.colour1[0] = mat.SR_data.blend_offset[0]
694 m.colour1[1] = mat.SR_data.blend_offset[1]
695 #}
696
697 if mat.SR_data.shader == 'vertex_blend':#{
698 m.shader = 3
699
700 m.colour1[0] = mat.SR_data.blend_offset[0]
701 m.colour1[1] = mat.SR_data.blend_offset[1]
702 #}
703
704 if mat.SR_data.shader == 'water':#{
705 m.shader = 4
706
707 m.colour[0] = pow( mat.SR_data.shore_colour[0], 1.0/2.2 )
708 m.colour[1] = pow( mat.SR_data.shore_colour[1], 1.0/2.2 )
709 m.colour[2] = pow( mat.SR_data.shore_colour[2], 1.0/2.2 )
710 m.colour[3] = 1.0
711 m.colour1[0] = pow( mat.SR_data.ocean_colour[0], 1.0/2.2 )
712 m.colour1[1] = pow( mat.SR_data.ocean_colour[1], 1.0/2.2 )
713 m.colour1[2] = pow( mat.SR_data.ocean_colour[2], 1.0/2.2 )
714 m.colour1[3] = 1.0
715 #}
716
717 if mat.SR_data.shader == 'invisible':#{
718 m.shader = 5
719 #}
720
721 if mat.SR_data.shader == 'boundary':#{
722 m.shader = 6
723 #}
724
725 inf = material_info( mat )
726
727 if mat.SR_data.shader == 'standard' or \
728 mat.SR_data.shader == 'standard_cutout' or \
729 mat.SR_data.shader == 'terrain_blend' or \
730 mat.SR_data.shader == 'vertex_blend':
731 #{
732 if 'tex_diffuse' in inf:
733 m.tex_diffuse = sr_compile_texture(inf['tex_diffuse'])
734 #}
735
736 sr_compile.material_data.extend( bytearray(m) )
737 return index
738 #}
739
740 def sr_armature_bones( armature ):
741 #{
742 def _recurse_bone( b ):
743 #{
744 yield b
745 for c in b.children: yield from _recurse_bone( c )
746 #}
747
748 for b in armature.data.bones:
749 if not b.parent:
750 yield from _recurse_bone( b )
751 #}
752
753 def sr_entity_id( obj ):
754 #{
755 tipo = get_entity_enum_id( obj_ent_type(obj) )
756 index = sr_compile.entity_ids[ obj.name ]
757
758 return (tipo&0xffff)<<16 | (index&0xffff)
759 #}
760
761 # Returns submesh_start,count and armature_id
762 def sr_compile_mesh_internal( obj ):
763 #{
764 can_use_cache = True
765 armature = None
766
767 submesh_start = 0
768 submesh_count = 0
769 armature_id = 0
770
771 for mod in obj.modifiers:#{
772 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
773 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
774 mod.type == 'ARRAY':
775 #{
776 can_use_cache = False
777 #}
778
779 if mod.type == 'ARMATURE': #{
780 armature = mod.object
781 rig_weight_groups = \
782 ['0 [ROOT]']+[_.name for _ in sr_armature_bones(mod.object)]
783 armature_id = sr_compile.entity_ids[armature.name]
784
785 POSE_OR_REST_CACHE = armature.data.pose_position
786 armature.data.pose_position = 'REST'
787 #}
788 #}
789
790 # Check the cache first
791 #
792 if can_use_cache and (obj.data.name in sr_compile.mesh_cache):#{
793 ref = sr_compile.mesh_cache[obj.data.name]
794 submesh_start = ref[0]
795 submesh_count = ref[1]
796 return (submesh_start,submesh_count,armature_id)
797 #}
798
799 # Compile a whole new mesh
800 #
801 submesh_start = len(sr_compile.submesh_data)//sizeof(mdl_submesh)
802 submesh_count = 0
803
804 dgraph = bpy.context.evaluated_depsgraph_get()
805 data = obj.evaluated_get(dgraph).data
806 data.calc_loop_triangles()
807 data.calc_normals_split()
808
809 # Mesh is split into submeshes based on their material
810 #
811 mat_list = data.materials if len(data.materials) > 0 else [None]
812 for material_id, mat in enumerate(mat_list): #{
813 mref = {}
814
815 sm = mdl_submesh()
816 sm.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
817 sm.vertex_start = len(sr_compile.vertex_data)//sizeof(mdl_vert)
818 sm.vertex_count = 0
819 sm.indice_count = 0
820 sm.material_id = sr_compile_material( mat )
821
822 INF=99999999.99999999
823 for i in range(3):#{
824 sm.bbx[0][i] = INF
825 sm.bbx[1][i] = -INF
826 #}
827
828 # Keep a reference to very very very similar vertices
829 # i have no idea how to speed it up.
830 #
831 vertex_reference = {}
832
833 # Write the vertex / indice data
834 #
835 for tri_index, tri in enumerate(data.loop_triangles):#{
836 if tri.material_index != material_id: continue
837
838 for j in range(3):#{
839 vert = data.vertices[tri.vertices[j]]
840 li = tri.loops[j]
841 vi = data.loops[li].vertex_index
842
843 # Gather vertex information
844 #
845 co = vert.co
846 norm = data.loops[li].normal
847 uv = (0,0)
848 colour = (255,255,255,255)
849 groups = [0,0,0,0]
850 weights = [0,0,0,0]
851
852 # Uvs
853 #
854 if data.uv_layers:
855 uv = data.uv_layers.active.data[li].uv
856
857 # Vertex Colours
858 #
859 if data.vertex_colors:#{
860 colour = data.vertex_colors.active.data[li].color
861 colour = (int(colour[0]*255.0),\
862 int(colour[1]*255.0),\
863 int(colour[2]*255.0),\
864 int(colour[3]*255.0))
865 #}
866
867 # Weight groups: truncates to the 3 with the most influence. The
868 # fourth bone ID is never used by the shader so it
869 # is always 0
870 #
871 if armature:#{
872 src_groups = [_ for _ in data.vertices[vi].groups \
873 if obj.vertex_groups[_.group].name in \
874 rig_weight_groups ]
875
876 weight_groups = sorted( src_groups, key = \
877 lambda a: a.weight, reverse=True )
878 tot = 0.0
879 for ml in range(3):#{
880 if len(weight_groups) > ml:#{
881 g = weight_groups[ml]
882 name = obj.vertex_groups[g.group].name
883 weight = g.weight
884 weights[ml] = weight
885 groups[ml] = rig_weight_groups.index(name)
886 tot += weight
887 #}
888 #}
889
890 if len(weight_groups) > 0:#{
891 inv_norm = (1.0/tot) * 65535.0
892 for ml in range(3):#{
893 weights[ml] = int( weights[ml] * inv_norm )
894 weights[ml] = min( weights[ml], 65535 )
895 weights[ml] = max( weights[ml], 0 )
896 #}
897 #}
898 #}
899 else:#{
900 li1 = tri.loops[(j+1)%3]
901 vi1 = data.loops[li1].vertex_index
902 e0 = data.edges[ data.loops[li].edge_index ]
903
904 if e0.use_freestyle_mark and \
905 ((e0.vertices[0] == vi and e0.vertices[1] == vi1) or \
906 (e0.vertices[0] == vi1 and e0.vertices[1] == vi)):
907 #{
908 weights[0] = 1
909 #}
910 #}
911
912 TOLERENCE = float(10**4)
913 key = (int(co[0]*TOLERENCE+0.5),
914 int(co[1]*TOLERENCE+0.5),
915 int(co[2]*TOLERENCE+0.5),
916 int(norm[0]*TOLERENCE+0.5),
917 int(norm[1]*TOLERENCE+0.5),
918 int(norm[2]*TOLERENCE+0.5),
919 int(uv[0]*TOLERENCE+0.5),
920 int(uv[1]*TOLERENCE+0.5),
921 colour[0], # these guys are already quantized
922 colour[1], # .
923 colour[2], # .
924 colour[3], # .
925 weights[0], # v
926 weights[1],
927 weights[2],
928 weights[3],
929 groups[0],
930 groups[1],
931 groups[2],
932 groups[3])
933
934 if key in vertex_reference:
935 index = vertex_reference[key]
936 else:#{
937 index = bytearray(c_uint32(sm.vertex_count))
938 sm.vertex_count+=1
939
940 vertex_reference[key] = index
941 v = mdl_vert()
942 v.co[0] = co[0]
943 v.co[1] = co[2]
944 v.co[2] = -co[1]
945 v.norm[0] = norm[0]
946 v.norm[1] = norm[2]
947 v.norm[2] = -norm[1]
948 v.uv[0] = uv[0]
949 v.uv[1] = uv[1]
950 v.colour[0] = colour[0]
951 v.colour[1] = colour[1]
952 v.colour[2] = colour[2]
953 v.colour[3] = colour[3]
954 v.weights[0] = weights[0]
955 v.weights[1] = weights[1]
956 v.weights[2] = weights[2]
957 v.weights[3] = weights[3]
958 v.groups[0] = groups[0]
959 v.groups[1] = groups[1]
960 v.groups[2] = groups[2]
961 v.groups[3] = groups[3]
962
963 for i in range(3):#{
964 sm.bbx[0][i] = min( sm.bbx[0][i], v.co[i] )
965 sm.bbx[1][i] = max( sm.bbx[1][i], v.co[i] )
966 #}
967
968 sr_compile.vertex_data.extend(bytearray(v))
969 #}
970
971 sm.indice_count += 1
972 sr_compile.indice_data.extend( index )
973 #}
974 #}
975
976 # Make sure bounding box isn't -inf -> inf if no vertices
977 #
978 if sm.vertex_count == 0:
979 for j in range(2):
980 for i in range(3):
981 sm.bbx[j][i] = 0
982
983 # Add submesh to encoder
984 #
985 sr_compile.submesh_data.extend( bytearray(sm) )
986 submesh_count += 1
987 #}
988
989 if armature:#{
990 armature.data.pose_position = POSE_OR_REST_CACHE
991 #}
992
993 # Save a reference to this mesh since we want to reuse the submesh indices
994 # later.
995 sr_compile.mesh_cache[obj.data.name]=(submesh_start,submesh_count)
996 return (submesh_start,submesh_count,armature_id)
997 #}
998
999 def sr_compile_mesh( obj ):
1000 #{
1001 node=mdl_mesh()
1002 compile_obj_transform(obj, node.transform)
1003 node.pstr_name = sr_compile_string(obj.name)
1004 ent_type = obj_ent_type( obj )
1005
1006 node.entity_id = 0
1007
1008 if ent_type != 'none':#{
1009 ent_id_lwr = sr_compile.entity_ids[obj.name]
1010 ent_id_upr = get_entity_enum_id( obj_ent_type(obj) )
1011 node.entity_id = (ent_id_upr << 16) | ent_id_lwr
1012 #}
1013
1014 node.submesh_start, node.submesh_count, node.armature_id = \
1015 sr_compile_mesh_internal( obj )
1016
1017 sr_compile.mesh_data.extend(bytearray(node))
1018 #}
1019
1020 def sr_compile_fonts( collection ):
1021 #{
1022 print( F"[SR] Compiling fonts" )
1023
1024 glyph_count = 0
1025 variant_count = 0
1026
1027 for obj in collection.all_objects:#{
1028 if obj_ent_type(obj) != 'ent_font': continue
1029
1030 data = obj.SR_data.ent_font[0]
1031
1032 font=ent_font()
1033 font.alias = sr_compile_string( data.alias )
1034 font.variant_start = variant_count
1035 font.variant_count = 0
1036 font.glyph_start = glyph_count
1037
1038 glyph_base = data.glyphs[0].utf32
1039 glyph_range = data.glyphs[-1].utf32+1 - glyph_base
1040
1041 font.glyph_utf32_base = glyph_base
1042 font.glyph_count = glyph_range
1043
1044 for i in range(len(data.variants)):#{
1045 data_var = data.variants[i]
1046 if not data_var.mesh: continue
1047
1048 mesh = data_var.mesh.data
1049
1050 variant = ent_font_variant()
1051 variant.name = sr_compile_string( data_var.tipo )
1052
1053 # fonts (variants) only support one material each
1054 mat = None
1055 if len(mesh.materials) != 0:
1056 mat = mesh.materials[0]
1057 variant.material_id = sr_compile_material( mat )
1058
1059 font.variant_count += 1
1060
1061 islands = mesh_utils.mesh_linked_triangles(mesh)
1062 centroids = [Vector((0,0)) for _ in range(len(islands))]
1063
1064 for j in range(len(islands)):#{
1065 for tri in islands[j]:#{
1066 centroids[j].x += tri.center[0]
1067 centroids[j].y += tri.center[2]
1068 #}
1069
1070 centroids[j] /= len(islands[j])
1071 #}
1072
1073 for j in range(glyph_range):#{
1074 data_glyph = data.glyphs[j]
1075 glyph = ent_glyph()
1076 glyph.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
1077 glyph.indice_count = 0
1078 glyph.size[0] = data_glyph.bounds[2]
1079 glyph.size[1] = data_glyph.bounds[3]
1080
1081 vertex_reference = {}
1082
1083 for k in range(len(islands)):#{
1084 if centroids[k].x < data_glyph.bounds[0] or \
1085 centroids[k].x > data_glyph.bounds[0]+data_glyph.bounds[2] or\
1086 centroids[k].y < data_glyph.bounds[1] or \
1087 centroids[k].y > data_glyph.bounds[1]+data_glyph.bounds[3]:
1088 #{
1089 continue
1090 #}
1091
1092 for l in range(len(islands[k])):#{
1093 tri = islands[k][l]
1094 for m in range(3):#{
1095 vert = mesh.vertices[tri.vertices[m]]
1096 li = tri.loops[m]
1097 vi = mesh.loops[li].vertex_index
1098
1099 # Gather vertex information
1100 #
1101 co = [vert.co[_] for _ in range(3)]
1102 co[0] -= data_glyph.bounds[0]
1103 co[2] -= data_glyph.bounds[1]
1104 norm = mesh.loops[li].normal
1105 uv = (0,0)
1106 if mesh.uv_layers: uv = mesh.uv_layers.active.data[li].uv
1107
1108 TOLERENCE = float(10**4)
1109 key = (int(co[0]*TOLERENCE+0.5),
1110 int(co[1]*TOLERENCE+0.5),
1111 int(co[2]*TOLERENCE+0.5),
1112 int(norm[0]*TOLERENCE+0.5),
1113 int(norm[1]*TOLERENCE+0.5),
1114 int(norm[2]*TOLERENCE+0.5),
1115 int(uv[0]*TOLERENCE+0.5),
1116 int(uv[1]*TOLERENCE+0.5))
1117
1118 if key in vertex_reference:
1119 index = vertex_reference[key]
1120 else:#{
1121 vindex = len(sr_compile.vertex_data)//sizeof(mdl_vert)
1122 index = bytearray(c_uint32(vindex))
1123 vertex_reference[key] = index
1124 v = mdl_vert()
1125 v.co[0] = co[0]
1126 v.co[1] = co[2]
1127 v.co[2] = -co[1]
1128 v.norm[0] = norm[0]
1129 v.norm[1] = norm[2]
1130 v.norm[2] = -norm[1]
1131 v.uv[0] = uv[0]
1132 v.uv[1] = uv[1]
1133
1134 sr_compile.vertex_data.extend(bytearray(v))
1135 #}
1136
1137 glyph.indice_count += 1
1138 sr_compile.indice_data.extend( index )
1139 #}
1140 #}
1141 #}
1142 sr_ent_push( glyph )
1143 #}
1144 sr_ent_push( variant )
1145 #}
1146 sr_ent_push( font )
1147 #}
1148 #}
1149
1150 def sr_compile_menus( collection ):
1151 #{
1152 print( "[SR] Compiling menus" )
1153 groups = []
1154
1155 for obj in collection.all_objects:#{
1156 if obj_ent_type(obj) != 'ent_menuitem': continue
1157 obj_data = obj.SR_data.ent_menuitem[0]
1158
1159 bitmask = 0x00000000
1160
1161 for col in obj.users_collection:#{
1162 name = col.name
1163 if name not in groups: groups.append( name )
1164 bitmask |= (0x1 << groups.index(name))
1165 #}
1166
1167 item = ent_menuitem()
1168 item.type = int( obj_data.tipo )
1169 item.groups = bitmask
1170
1171 compile_obj_transform( obj, item.transform )
1172 if obj.type == 'MESH':#{
1173 item.submesh_start, item.submesh_count, _ = \
1174 sr_compile_mesh_internal( obj )
1175 #}
1176
1177 if item.type == 1 or item.type == 2:#{
1178 item_button = item._anonymous_union.button
1179 item_button.pstr = sr_compile_string( obj_data.string )
1180 #}
1181 elif item.type == 3:#{
1182 item_checkmark = item._anonymous_union.checkmark
1183 item_checkmark.pstr_data = sr_compile_string( obj_data.string )
1184 item_checkmark.id_check = sr_entity_id( obj_data.checkmark )
1185 #}
1186 elif item.type == 4:#{
1187 item_slider = item._anonymous_union.slider
1188 item_slider.id_min = sr_entity_id( obj_data.slider_minloc )
1189 item_slider.id_max = sr_entity_id( obj_data.slider_maxloc )
1190 item_slider.id_handle = sr_entity_id( obj_data.slider_handle )
1191 #}
1192 elif item.type == 5:#{
1193 item_page = item._anonymous_union.page
1194 item_page.pstr_name = sr_compile_string( obj_data.string )
1195 item_page.id_entrypoint = sr_entity_id( obj_data.newloc )
1196 item_page.id_viewpoint = sr_entity_id( obj_data.camera )
1197 #}
1198
1199 if obj_data.link0:
1200 item.id_links[0] = sr_entity_id( obj_data.link0 )
1201 if obj_data.link1:
1202 item.id_links[1] = sr_entity_id( obj_data.link1 )
1203 if item.type != 4:#{
1204 if obj_data.link2:
1205 item.id_links[2] = sr_entity_id( obj_data.link2 )
1206 if obj_data.link3:
1207 item.id_links[3] = sr_entity_id( obj_data.link3 )
1208 #}
1209
1210 sr_ent_push( item )
1211 #}
1212 #}
1213
1214 def sr_compile_armature( obj ):
1215 #{
1216 node = mdl_armature()
1217 node.bone_start = len(sr_compile.bone_data)//sizeof(mdl_bone)
1218 node.bone_count = 0
1219 node.anim_start = len(sr_compile.anim_data)//sizeof(mdl_animation)
1220 node.anim_count = 0
1221
1222 bones = [_ for _ in sr_armature_bones(obj)]
1223 bones_names = [None]+[_.name for _ in bones]
1224
1225 for b in bones:#{
1226 bone = mdl_bone()
1227 if b.use_deform: bone.flags = 0x1
1228 if b.parent: bone.parent = bones_names.index(b.parent.name)
1229
1230 bone.collider = int(b.SR_data.collider)
1231
1232 if bone.collider>0:#{
1233 bone.hitbox[0][0] = b.SR_data.collider_min[0]
1234 bone.hitbox[0][1] = b.SR_data.collider_min[2]
1235 bone.hitbox[0][2] = -b.SR_data.collider_max[1]
1236 bone.hitbox[1][0] = b.SR_data.collider_max[0]
1237 bone.hitbox[1][1] = b.SR_data.collider_max[2]
1238 bone.hitbox[1][2] = -b.SR_data.collider_min[1]
1239 #}
1240
1241 if b.SR_data.cone_constraint:#{
1242 bone.flags |= 0x4
1243 bone.conevx[0] = b.SR_data.conevx[0]
1244 bone.conevx[1] = b.SR_data.conevx[2]
1245 bone.conevx[2] = -b.SR_data.conevx[1]
1246 bone.conevy[0] = b.SR_data.conevy[0]
1247 bone.conevy[1] = b.SR_data.conevy[2]
1248 bone.conevy[2] = -b.SR_data.conevy[1]
1249 bone.coneva[0] = b.SR_data.coneva[0]
1250 bone.coneva[1] = b.SR_data.coneva[2]
1251 bone.coneva[2] = -b.SR_data.coneva[1]
1252 bone.conet = b.SR_data.conet
1253 #}
1254
1255 bone.co[0] = b.head_local[0]
1256 bone.co[1] = b.head_local[2]
1257 bone.co[2] = -b.head_local[1]
1258 bone.end[0] = b.tail_local[0] - bone.co[0]
1259 bone.end[1] = b.tail_local[2] - bone.co[1]
1260 bone.end[2] = -b.tail_local[1] - bone.co[2]
1261 bone.pstr_name = sr_compile_string( b.name )
1262
1263 for c in obj.pose.bones[b.name].constraints:#{
1264 if c.type == 'IK':#{
1265 bone.flags |= 0x2
1266 bone.ik_target = bones_names.index(c.subtarget)
1267 bone.ik_pole = bones_names.index(c.pole_subtarget)
1268 #}
1269 #}
1270
1271 node.bone_count += 1
1272 sr_compile.bone_data.extend(bytearray(bone))
1273 #}
1274
1275 # Compile anims
1276 #
1277 if obj.animation_data and sr_compile.pack_animations: #{
1278 # So we can restore later
1279 #
1280 previous_frame = bpy.context.scene.frame_current
1281 previous_action = obj.animation_data.action
1282 POSE_OR_REST_CACHE = obj.data.pose_position
1283 obj.data.pose_position = 'POSE'
1284
1285 for NLALayer in obj.animation_data.nla_tracks:#{
1286 for NLAStrip in NLALayer.strips:#{
1287 # set active
1288 #
1289 for a in bpy.data.actions:#{
1290 if a.name == NLAStrip.name:#{
1291 obj.animation_data.action = a
1292 break
1293 #}
1294 #}
1295
1296 # Clip to NLA settings
1297 #
1298 anim_start = int(NLAStrip.action_frame_start)
1299 anim_end = int(NLAStrip.action_frame_end)
1300
1301 # Export strips
1302 #
1303 anim = mdl_animation()
1304 anim.pstr_name = sr_compile_string( NLAStrip.action.name )
1305 anim.rate = 30.0
1306 anim.keyframe_start = len(sr_compile.keyframe_data)//\
1307 sizeof(mdl_transform)
1308 anim.length = anim_end-anim_start
1309
1310 i = 0
1311 # Export the keyframes
1312 for frame in range(anim_start,anim_end):#{
1313 bpy.context.scene.frame_set(frame)
1314
1315 for rb in bones:#{
1316 pb = obj.pose.bones[rb.name]
1317
1318 # relative bone matrix
1319 if rb.parent is not None:#{
1320 offset_mtx = rb.parent.matrix_local
1321 offset_mtx = offset_mtx.inverted_safe() @ \
1322 rb.matrix_local
1323
1324 inv_parent = pb.parent.matrix @ offset_mtx
1325 inv_parent.invert_safe()
1326 fpm = inv_parent @ pb.matrix
1327 #}
1328 else:#{
1329 bone_mtx = rb.matrix.to_4x4()
1330 local_inv = rb.matrix_local.inverted_safe()
1331 fpm = bone_mtx @ local_inv @ pb.matrix
1332 #}
1333
1334 loc, rot, sca = fpm.decompose()
1335
1336 # rotation
1337 lc_m = pb.matrix_channel.to_3x3()
1338 if pb.parent is not None:#{
1339 smtx = pb.parent.matrix_channel.to_3x3()
1340 lc_m = smtx.inverted() @ lc_m
1341 #}
1342 rq = lc_m.to_quaternion()
1343
1344 kf = mdl_transform()
1345 kf.co[0] = loc[0]
1346 kf.co[1] = loc[2]
1347 kf.co[2] = -loc[1]
1348 kf.q[0] = rq[1]
1349 kf.q[1] = rq[3]
1350 kf.q[2] = -rq[2]
1351 kf.q[3] = rq[0]
1352 kf.s[0] = sca[0]
1353 kf.s[1] = sca[1]
1354 kf.s[2] = sca[2]
1355 sr_compile.keyframe_data.extend(bytearray(kf))
1356
1357 i+=1
1358 #}
1359 #}
1360
1361 # Add to animation buffer
1362 #
1363 sr_compile.anim_data.extend(bytearray(anim))
1364 node.anim_count += 1
1365
1366 # Report progress
1367 #
1368 print( F"[SR] | anim( {NLAStrip.action.name} )" )
1369 #}
1370 #}
1371
1372 # Restore context to how it was before
1373 #
1374 bpy.context.scene.frame_set( previous_frame )
1375 obj.animation_data.action = previous_action
1376 obj.data.pose_position = POSE_OR_REST_CACHE
1377 #}
1378
1379 sr_compile.armature_data.extend(bytearray(node))
1380 #}
1381
1382 def sr_ent_push( struct ):
1383 #{
1384 clase = type(struct).__name__
1385
1386 if clase not in sr_compile.entity_data:#{
1387 sr_compile.entity_data[ clase ] = bytearray()
1388 sr_compile.entity_info[ clase ] = { 'size': sizeof(struct) }
1389 #}
1390
1391 index = len(sr_compile.entity_data[ clase ])//sizeof(struct)
1392 sr_compile.entity_data[ clase ].extend( bytearray(struct) )
1393 return index
1394 #}
1395
1396 def sr_array_title( arr, name, count, size, offset ):
1397 #{
1398 for i in range(len(name)):#{
1399 arr.name[i] = ord(name[i])
1400 #}
1401 arr.file_offset = offset
1402 arr.item_count = count
1403 arr.item_size = size
1404 #}
1405
1406 def hash_djb2(s):
1407 #{
1408 picadillo = 5381
1409 for x in s:#{
1410 picadillo = (((picadillo << 5) + picadillo) + ord(x)) & 0xFFFFFFFF
1411 #}
1412 return picadillo
1413 #}
1414
1415 def sr_compile( collection ):
1416 #{
1417 print( F"[SR] compiler begin ({collection.name}.mdl)" )
1418
1419 #settings
1420 sr_compile.pack_textures = collection.SR_data.pack_textures
1421 sr_compile.pack_animations = collection.SR_data.animations
1422
1423 # caches
1424 sr_compile.string_cache = {}
1425 sr_compile.mesh_cache = {}
1426 sr_compile.material_cache = {}
1427 sr_compile.texture_cache = {}
1428
1429 # compiled data
1430 sr_compile.mesh_data = bytearray()
1431 sr_compile.submesh_data = bytearray()
1432 sr_compile.vertex_data = bytearray()
1433 sr_compile.indice_data = bytearray()
1434 sr_compile.bone_data = bytearray()
1435 sr_compile.material_data = bytearray()
1436 sr_compile.armature_data = bytearray()
1437 sr_compile.anim_data = bytearray()
1438 sr_compile.keyframe_data = bytearray()
1439 sr_compile.texture_data = bytearray()
1440
1441 # just bytes not structures
1442 sr_compile.string_data = bytearray()
1443 sr_compile.pack_data = bytearray()
1444
1445 # variable
1446 sr_compile.entity_data = {}
1447 sr_compile.entity_info = {}
1448
1449 print( F"[SR] assign entity ID's" )
1450 sr_compile.entities = {}
1451 sr_compile.entity_ids = {}
1452
1453 # begin
1454 # -------------------------------------------------------
1455
1456 sr_compile_string( "null" )
1457
1458 mesh_count = 0
1459 for obj in collection.all_objects: #{
1460 if obj.type == 'MESH':#{
1461 mesh_count += 1
1462 #}
1463
1464 ent_type = obj_ent_type( obj )
1465 if ent_type == 'none': continue
1466
1467 if ent_type not in sr_compile.entities: sr_compile.entities[ent_type] = []
1468 sr_compile.entity_ids[obj.name] = len( sr_compile.entities[ent_type] )
1469 sr_compile.entities[ent_type] += [obj]
1470 #}
1471
1472 print( F"[SR] Compiling geometry" )
1473 i=0
1474 for obj in collection.all_objects:#{
1475 if obj.type == 'MESH':#{
1476 i+=1
1477
1478 ent_type = obj_ent_type( obj )
1479
1480 # entity ignore mesh list
1481 #
1482 if ent_type == 'ent_traffic': continue
1483 if ent_type == 'ent_font': continue
1484 if ent_type == 'ent_font_variant': continue
1485 if ent_type == 'ent_menuitem': continue
1486 #--------------------------
1487
1488 print( F'[SR] {i: 3}/{mesh_count} {obj.name:<40}', end='\r' )
1489 sr_compile_mesh( obj )
1490 #}
1491 #}
1492
1493 audio_clip_count = 0
1494
1495 for ent_type, arr in sr_compile.entities.items():#{
1496 print(F"[SR] Compiling {len(arr)} {ent_type}{'s' if len(arr)>1 else ''}")
1497
1498 for i in range(len(arr)):#{
1499 obj = arr[i]
1500
1501 print( F"[SR] {i+1: 3}/{len(arr)} {obj.name:<40} ",end='\r' )
1502
1503 if ent_type == 'mdl_armature': sr_compile_armature(obj)
1504 elif ent_type == 'ent_light': #{
1505 light = ent_light()
1506 compile_obj_transform( obj, light.transform )
1507 light.daytime = obj.data.SR_data.daytime
1508 if obj.data.type == 'POINT':#{
1509 light.type = 0
1510 #}
1511 elif obj.data.type == 'SPOT':#{
1512 light.type = 1
1513 light.angle = obj.data.spot_size*0.5
1514 #}
1515 light.range = obj.data.cutoff_distance
1516 light.colour[0] = obj.data.color[0]
1517 light.colour[1] = obj.data.color[1]
1518 light.colour[2] = obj.data.color[2]
1519 light.colour[3] = obj.data.energy
1520 sr_ent_push( light )
1521 #}
1522 elif ent_type == 'ent_camera': #{
1523 cam = ent_camera()
1524 compile_obj_transform( obj, cam.transform )
1525 cam.fov = obj.data.angle * 45.0
1526 sr_ent_push(cam)
1527 #}
1528 elif ent_type == 'ent_gate': #{
1529 gate = ent_gate()
1530 obj_data = obj.SR_data.ent_gate[0]
1531 mesh_data = obj.data.SR_data.ent_gate[0]
1532
1533 if obj_data.tipo == 'default':#{
1534 if obj_data.target:#{
1535 gate.target = sr_compile.entity_ids[obj_data.target.name]
1536 gate.type = 1
1537 #}
1538 #}
1539 elif obj_data.tipo == 'nonlocal':#{
1540 gate.target = sr_compile_string(obj_data.key)
1541 gate.type = 2
1542 #}
1543 else: gate.type = 0
1544
1545 gate.dimensions[0] = mesh_data.dimensions[0]
1546 gate.dimensions[1] = mesh_data.dimensions[1]
1547 gate.dimensions[2] = mesh_data.dimensions[2]
1548
1549 q = [obj.matrix_local.to_quaternion(), (0,0,0,1)]
1550 co = [obj.matrix_world @ Vector((0,0,0)), (0,0,0)]
1551
1552 if obj_data.target:#{
1553 q[1] = obj_data.target.matrix_local.to_quaternion()
1554 co[1]= obj_data.target.matrix_world @ Vector((0,0,0))
1555 #}
1556
1557 # Setup transform
1558 #
1559 for x in range(2):#{
1560 gate.co[x][0] = co[x][0]
1561 gate.co[x][1] = co[x][2]
1562 gate.co[x][2] = -co[x][1]
1563 gate.q[x][0] = q[x][1]
1564 gate.q[x][1] = q[x][3]
1565 gate.q[x][2] = -q[x][2]
1566 gate.q[x][3] = q[x][0]
1567 #}
1568
1569 sr_ent_push( gate )
1570 #}
1571 elif ent_type == 'ent_spawn': #{
1572 spawn = ent_spawn()
1573 compile_obj_transform( obj, spawn.transform )
1574 obj_data = obj.SR_data.ent_spawn[0]
1575 spawn.pstr_name = sr_compile_string( obj_data.alias )
1576 sr_ent_push( spawn )
1577 #}
1578 elif ent_type == 'ent_water':#{
1579 water = ent_water()
1580 compile_obj_transform( obj, water.transform )
1581 water.max_dist = 0.0
1582 sr_ent_push( water )
1583 #}
1584 elif ent_type == 'ent_audio':#{
1585 obj_data = obj.SR_data.ent_audio[0]
1586 audio = ent_audio()
1587 compile_obj_transform( obj, audio.transform )
1588 audio.clip_start = audio_clip_count
1589 audio.clip_count = len(obj_data.files)
1590 audio_clip_count += audio.clip_count
1591 audio.max_channels = obj_data.max_channels
1592 audio.volume = obj_data.volume
1593
1594 # TODO flags:
1595 # - allow/disable doppler
1596 # - channel group tags with random colours
1597 # - transition properties
1598
1599 if obj_data.flag_loop: audio.flags |= 0x1
1600 if obj_data.flag_nodoppler: audio.flags |= 0x2
1601 if obj_data.flag_3d: audio.flags |= 0x4
1602 if obj_data.flag_auto: audio.flags |= 0x8
1603 if obj_data.formato == '0': audio.flags |= 0x000
1604 elif obj_data.formato == '1': audio.flags |= 0x400
1605 elif obj_data.formato == '2': audio.flags |= 0x1000
1606
1607 audio.channel_behaviour = int(obj_data.channel_behaviour)
1608 if audio.channel_behaviour >= 1:#{
1609 audio.group = obj_data.group
1610 #}
1611 if audio.channel_behaviour == 2:#{
1612 audio.crossfade = obj_data.transition_duration
1613 #}
1614 audio.probability_curve = int(obj_data.probability_curve)
1615
1616 for ci in range(audio.clip_count):#{
1617 entry = obj_data.files[ci]
1618 clip = ent_audio_clip()
1619 clip.probability = entry.probability
1620 if obj_data.formato == '2':#{
1621 sr_pack_file( clip._anon.file, '', vg_str_bin(entry.path) )
1622 #}
1623 else:#{
1624 clip._anon.file.path = sr_compile_string( entry.path )
1625 clip._anon.file.pack_offset = 0
1626 clip._anon.file.pack_size = 0
1627 #}
1628 sr_ent_push( clip )
1629 #}
1630 sr_ent_push( audio )
1631 #}
1632 elif ent_type == 'ent_volume':#{
1633 obj_data = obj.SR_data.ent_volume[0]
1634 volume = ent_volume()
1635 volume.type = int(obj_data.subtype)
1636 compile_obj_transform( obj, volume.transform )
1637
1638 if obj_data.target:#{
1639 volume.target = sr_entity_id( obj_data.target )
1640 #}
1641
1642 sr_ent_push(volume)
1643 #}
1644 elif ent_type == 'ent_marker':#{
1645 marker = ent_marker()
1646 marker.name = sr_compile_string( obj.SR_data.ent_marker[0].alias )
1647 compile_obj_transform( obj, marker.transform )
1648 sr_ent_push(marker)
1649 #}
1650 elif ent_type == 'ent_skateshop':#{
1651 skateshop = ent_skateshop()
1652 obj_data = obj.SR_data.ent_skateshop[0]
1653 skateshop.id_display = sr_entity_id( obj_data.mark_display )
1654 skateshop.id_info = sr_entity_id( obj_data.mark_info )
1655 skateshop.id_rack = sr_entity_id( obj_data.mark_rack )
1656 skateshop.id_camera = sr_entity_id( obj_data.cam )
1657 compile_obj_transform( obj, skateshop.transform )
1658 sr_ent_push(skateshop)
1659 #}
1660 elif ent_type == 'ent_swspreview':#{
1661 workshop_preview = ent_swspreview()
1662 obj_data = obj.SR_data.ent_swspreview[0]
1663 workshop_preview.id_display = sr_entity_id( obj_data.mark_display )
1664 workshop_preview.id_display1 = sr_entity_id( obj_data.mark_display1)
1665 workshop_preview.id_camera = sr_entity_id( obj_data.cam )
1666 sr_ent_push( workshop_preview )
1667 #}
1668 #}
1669 #}
1670
1671 sr_compile_menus( collection )
1672 sr_compile_fonts( collection )
1673
1674 def _children( col ):#{
1675 yield col
1676 for c in col.children:#{
1677 yield from _children(c)
1678 #}
1679 #}
1680
1681 checkpoint_count = 0
1682 pathindice_count = 0
1683 routenode_count = 0
1684
1685 for col in _children(collection):#{
1686 print( F"Adding routes for subcollection: {col.name}" )
1687 route_gates = []
1688 route_curves = []
1689 routes = []
1690 traffics = []
1691
1692 for obj in col.objects:#{
1693 if obj.type == 'ARMATURE': pass
1694 else:#{
1695 ent_type = obj_ent_type( obj )
1696
1697 if ent_type == 'ent_gate':
1698 route_gates += [obj]
1699 elif ent_type == 'ent_route_node':#{
1700 if obj.type == 'CURVE':#{
1701 route_curves += [obj]
1702 #}
1703 #}
1704 elif ent_type == 'ent_route':
1705 routes += [obj]
1706 elif ent_type == 'ent_traffic':
1707 traffics += [obj]
1708 #}
1709 #}
1710
1711 dij = create_node_graph( route_curves, route_gates )
1712
1713 for obj in routes:#{
1714 obj_data = obj.SR_data.ent_route[0]
1715 route = ent_route()
1716 route.pstr_name = sr_compile_string( obj_data.alias )
1717 route.checkpoints_start = checkpoint_count
1718 route.checkpoints_count = 0
1719
1720 for ci in range(3):
1721 route.colour[ci] = obj_data.colour[ci]
1722 route.colour[3] = 1.0
1723
1724 compile_obj_transform( obj, route.transform )
1725 checkpoints = obj_data.gates
1726
1727 for i in range(len(checkpoints)):#{
1728 gi = checkpoints[i].target
1729 gj = checkpoints[(i+1)%len(checkpoints)].target
1730 gate = gi
1731
1732 if gi:#{
1733 dest = gi.SR_data.ent_gate[0].target
1734 gi = dest
1735 #}
1736
1737 if gi==gj: continue # error?
1738 if not gi or not gj: continue
1739
1740 checkpoint = ent_checkpoint()
1741 checkpoint.gate_index = sr_compile.entity_ids[gate.name]
1742 checkpoint.path_start = pathindice_count
1743 checkpoint.path_count = 0
1744
1745 path = solve_graph( dij, gi.name, gj.name )
1746
1747 if path:#{
1748 for pi in range(len(path)):#{
1749 pathindice = ent_path_index()
1750 pathindice.index = routenode_count + path[pi]
1751 sr_ent_push( pathindice )
1752
1753 checkpoint.path_count += 1
1754 pathindice_count += 1
1755 #}
1756 #}
1757
1758 sr_ent_push( checkpoint )
1759 route.checkpoints_count += 1
1760 checkpoint_count += 1
1761 #}
1762
1763 sr_ent_push( route )
1764 #}
1765
1766 for obj in traffics:#{
1767 traffic = ent_traffic()
1768 compile_obj_transform( obj, traffic.transform )
1769 traffic.submesh_start, traffic.submesh_count, _ = \
1770 sr_compile_mesh_internal( obj )
1771
1772 # find best subsection
1773
1774 graph_keys = list(dij.graph)
1775 min_dist = 100.0
1776 best_point = 0
1777
1778 for j in range(len(dij.points)):#{
1779 point = dij.points[j]
1780 dist = (point-obj.location).magnitude
1781
1782 if dist < min_dist:#{
1783 min_dist = dist
1784 best_point = j
1785 #}
1786 #}
1787
1788 # scan to each edge
1789 best_begin = best_point
1790 best_end = best_point
1791
1792 while True:#{
1793 map0 = dij.subsections[best_begin]
1794 if map0[1] == -1: break
1795 best_begin = map0[1]
1796 #}
1797 while True:#{
1798 map1 = dij.subsections[best_end]
1799 if map1[2] == -1: break
1800 best_end = map1[2]
1801 #}
1802
1803 traffic.start_node = routenode_count + best_begin
1804 traffic.node_count = best_end - best_begin
1805 traffic.index = best_point - best_begin
1806 traffic.speed = obj.SR_data.ent_traffic[0].speed
1807 traffic.t = 0.0
1808
1809 sr_ent_push(traffic)
1810 #}
1811
1812 for point in dij.points:#{
1813 rn = ent_route_node()
1814 rn.co[0] = point[0]
1815 rn.co[1] = point[2]
1816 rn.co[2] = -point[1]
1817 sr_ent_push( rn )
1818 #}
1819
1820 routenode_count += len(dij.points)
1821 #}
1822
1823 print( F"[SR] Writing file" )
1824
1825 file_array_instructions = {}
1826 file_offset = 0
1827
1828 def _write_array( name, item_size, data ):#{
1829 nonlocal file_array_instructions, file_offset
1830
1831 count = len(data)//item_size
1832 file_array_instructions[name] = {'count':count, 'size':item_size,\
1833 'data':data, 'offset': file_offset}
1834 file_offset += len(data)
1835 file_offset = int_align_to( file_offset, 8 )
1836 #}
1837
1838 _write_array( 'strings', 1, sr_compile.string_data )
1839 _write_array( 'mdl_mesh', sizeof(mdl_mesh), sr_compile.mesh_data )
1840 _write_array( 'mdl_submesh', sizeof(mdl_submesh), sr_compile.submesh_data )
1841 _write_array( 'mdl_material', sizeof(mdl_material), sr_compile.material_data)
1842 _write_array( 'mdl_texture', sizeof(mdl_texture), sr_compile.texture_data)
1843 _write_array( 'mdl_armature', sizeof(mdl_armature), sr_compile.armature_data)
1844 _write_array( 'mdl_bone', sizeof(mdl_bone), sr_compile.bone_data )
1845
1846 for name, buffer in sr_compile.entity_data.items():#{
1847 _write_array( name, sr_compile.entity_info[name]['size'], buffer )
1848 #}
1849
1850 _write_array( 'mdl_animation', sizeof(mdl_animation), sr_compile.anim_data)
1851 _write_array( 'mdl_keyframe', sizeof(mdl_transform),sr_compile.keyframe_data)
1852 _write_array( 'mdl_vert', sizeof(mdl_vert), sr_compile.vertex_data )
1853 _write_array( 'mdl_indice', sizeof(c_uint32), sr_compile.indice_data )
1854 _write_array( 'pack', 1, sr_compile.pack_data )
1855
1856 header_size = int_align_to( sizeof(mdl_header), 8 )
1857 index_size = int_align_to( sizeof(mdl_array)*len(file_array_instructions),8 )
1858
1859 folder = bpy.path.abspath(bpy.context.scene.SR_data.export_dir)
1860 path = F"{folder}{collection.name}.mdl"
1861 print( path )
1862
1863 fp = open( path, "wb" )
1864 header = mdl_header()
1865 header.version = 101
1866 sr_array_title( header.arrays, \
1867 'index', len(file_array_instructions), \
1868 sizeof(mdl_array), header_size )
1869
1870 fp.write( bytearray_align_to( bytearray(header), 8 ) )
1871
1872 print( F'[SR] {"name":>16}| count | offset' )
1873 index = bytearray()
1874 for name,info in file_array_instructions.items():#{
1875 arr = mdl_array()
1876 offset = info['offset'] + header_size + index_size
1877 sr_array_title( arr, name, info['count'], info['size'], offset )
1878 index.extend( bytearray(arr) )
1879
1880 print( F'[SR] {name:>16}| {info["count"]: 8} '+\
1881 F' 0x{info["offset"]:02x}' )
1882 #}
1883 fp.write( bytearray_align_to( index, 8 ) )
1884 #bytearray_print_hex( index )
1885
1886 for name,info in file_array_instructions.items():#{
1887 fp.write( bytearray_align_to( info['data'], 8 ) )
1888 #}
1889
1890 fp.close()
1891
1892 print( '[SR] done' )
1893 #}
1894
1895 class SR_SCENE_SETTINGS(bpy.types.PropertyGroup):
1896 #{
1897 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
1898 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
1899 gizmos: bpy.props.BoolProperty( name="Draw Gizmos", default=True )
1900
1901 panel: bpy.props.EnumProperty(
1902 name='Panel',
1903 description='',
1904 items=[
1905 ('EXPORT', 'Export', '', 'MOD_BUILD',0),
1906 ('ENTITY', 'Entity', '', 'MONKEY',1),
1907 ('SETTINGS', 'Settings', 'Settings', 'PREFERENCES',2),
1908 ],
1909 )
1910 #}
1911
1912 class SR_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
1913 #{
1914 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
1915 animations: bpy.props.BoolProperty( name="Export animation", default=True)
1916 #}
1917
1918 def sr_get_mirror_bone( bones ):
1919 #{
1920 side = bones.active.name[-1:]
1921 other_name = bones.active.name[:-1]
1922 if side == 'L': other_name += 'R'
1923 elif side == 'R': other_name += 'L'
1924 else: return None
1925
1926 for b in bones:#{
1927 if b.name == other_name:
1928 return b
1929 #}
1930
1931 return None
1932 #}
1933
1934 class SR_MIRROR_BONE_X(bpy.types.Operator):
1935 #{
1936 bl_idname="skaterift.mirror_bone"
1937 bl_label="Mirror bone attributes - SkateRift"
1938
1939 def execute(_,context):
1940 #{
1941 active_object = context.active_object
1942 bones = active_object.data.bones
1943 a = bones.active
1944 b = sr_get_mirror_bone( bones )
1945
1946 if not b: return {'FINISHED'}
1947
1948 b.SR_data.collider = a.SR_data.collider
1949
1950 def _v3copyflipy( a, b ):#{
1951 b[0] = a[0]
1952 b[1] = -a[1]
1953 b[2] = a[2]
1954 #}
1955
1956 _v3copyflipy( a.SR_data.collider_min, b.SR_data.collider_min )
1957 _v3copyflipy( a.SR_data.collider_max, b.SR_data.collider_max )
1958 b.SR_data.collider_min[1] = -a.SR_data.collider_max[1]
1959 b.SR_data.collider_max[1] = -a.SR_data.collider_min[1]
1960
1961 b.SR_data.cone_constraint = a.SR_data.cone_constraint
1962
1963 _v3copyflipy( a.SR_data.conevx, b.SR_data.conevy )
1964 _v3copyflipy( a.SR_data.conevy, b.SR_data.conevx )
1965 _v3copyflipy( a.SR_data.coneva, b.SR_data.coneva )
1966
1967 b.SR_data.conet = a.SR_data.conet
1968
1969 # redraw
1970 ob = bpy.context.scene.objects[0]
1971 ob.hide_render = ob.hide_render
1972 return {'FINISHED'}
1973 #}
1974 #}
1975
1976 class SR_COMPILE(bpy.types.Operator):
1977 #{
1978 bl_idname="skaterift.compile_all"
1979 bl_label="Compile All"
1980
1981 def execute(_,context):
1982 #{
1983 view_layer = bpy.context.view_layer
1984 for col in view_layer.layer_collection.children["export"].children:
1985 if not col.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1986 sr_compile( bpy.data.collections[col.name] )
1987
1988 return {'FINISHED'}
1989 #}
1990 #}
1991
1992 class SR_COMPILE_THIS(bpy.types.Operator):
1993 #{
1994 bl_idname="skaterift.compile_this"
1995 bl_label="Compile This collection"
1996
1997 def execute(_,context):
1998 #{
1999 col = bpy.context.collection
2000 sr_compile( col )
2001
2002 return {'FINISHED'}
2003 #}
2004 #}
2005
2006 class SR_INTERFACE(bpy.types.Panel):
2007 #{
2008 bl_idname = "VIEW3D_PT_skate_rift"
2009 bl_label = "Skate Rift"
2010 bl_space_type = 'VIEW_3D'
2011 bl_region_type = 'UI'
2012 bl_category = "Skate Rift"
2013
2014 def draw(_, context):
2015 #{
2016 # Compiler section
2017
2018 row = _.layout.row()
2019 row.scale_y = 1.75
2020 row.prop( context.scene.SR_data, 'panel', expand=True )
2021
2022 if context.scene.SR_data.panel == 'SETTINGS': #{
2023 _.layout.prop( context.scene.SR_data, 'gizmos' )
2024 #}
2025 elif context.scene.SR_data.panel == 'EXPORT': #{
2026 _.layout.prop( context.scene.SR_data, "export_dir" )
2027 col = bpy.context.collection
2028
2029 found_in_export = False
2030 export_count = 0
2031 view_layer = bpy.context.view_layer
2032 for c1 in view_layer.layer_collection.children["export"].children: #{
2033 if not c1.hide_viewport or bpy.context.scene.SR_data.use_hidden:
2034 export_count += 1
2035
2036 if c1.name == col.name: #{
2037 found_in_export = True
2038 #}
2039 #}
2040
2041 box = _.layout.box()
2042 row = box.row()
2043 row.alignment = 'CENTER'
2044 row.scale_y = 1.5
2045
2046 if found_in_export: #{
2047 row.label( text=col.name + ".mdl" )
2048 box.prop( col.SR_data, "pack_textures" )
2049 box.prop( col.SR_data, "animations" )
2050 box.operator( "skaterift.compile_this" )
2051 #}
2052 else: #{
2053 row.enabled=False
2054 row.label( text=col.name )
2055
2056 row = box.row()
2057 row.enabled=False
2058 row.alignment = 'CENTER'
2059 row.scale_y = 1.5
2060 row.label( text="This collection is not in the export group" )
2061 #}
2062
2063 box = _.layout.box()
2064 row = box.row()
2065
2066 split = row.split( factor=0.3, align=True )
2067 split.prop( context.scene.SR_data, "use_hidden", text="hidden" )
2068
2069 row1 = split.row()
2070 if export_count == 0:
2071 row1.enabled=False
2072 row1.operator( "skaterift.compile_all", \
2073 text=F"Compile all ({export_count} collections)" )
2074 #}
2075 elif context.scene.SR_data.panel == 'ENTITY': #{
2076 active_object = context.active_object
2077 if not active_object: return
2078
2079 _.layout.operator( 'skaterift.copy_entity_data', \
2080 text=F'Copy entity data to {len(context.selected_objects)-1} '+\
2081 F'other objects' )
2082
2083 box = _.layout.box()
2084 row = box.row()
2085 row.alignment = 'CENTER'
2086 row.label( text=active_object.name )
2087 row.scale_y = 1.5
2088
2089 def _draw_prop_collection( data ): #{
2090 nonlocal box
2091 row = box.row()
2092 row.alignment = 'CENTER'
2093 row.enabled = False
2094 row.scale_y = 1.5
2095 row.label( text=F'{data[0]}' )
2096
2097 if hasattr(type(data[0]),'sr_inspector'):#{
2098 type(data[0]).sr_inspector( box, data )
2099 #}
2100 else:#{
2101 for a in data[0].__annotations__:
2102 box.prop( data[0], a )
2103 #}
2104 #}
2105
2106 if active_object.type == 'ARMATURE': #{
2107 if active_object.mode == 'POSE': #{
2108 bones = active_object.data.bones
2109 mb = sr_get_mirror_bone( bones )
2110 if mb:#{
2111 box.operator( "skaterift.mirror_bone", \
2112 text=F'Mirror attributes to {mb.name}' )
2113 #}
2114
2115 _draw_prop_collection( [bones.active.SR_data ] )
2116 #}
2117 else: #{
2118 row = box.row()
2119 row.alignment='CENTER'
2120 row.scale_y=2.0
2121 row.enabled=False
2122 row.label( text="Enter pose mode to modify bone properties" )
2123 #}
2124 #}
2125 elif active_object.type == 'LIGHT': #{
2126 _draw_prop_collection( [active_object.data.SR_data] )
2127 #}
2128 elif active_object.type in ['EMPTY','CURVE','MESH']:#{
2129 box.prop( active_object.SR_data, "ent_type" )
2130 ent_type = active_object.SR_data.ent_type
2131
2132 col = getattr( active_object.SR_data, ent_type, None )
2133 if col != None and len(col)!=0: _draw_prop_collection( col )
2134
2135 if active_object.type == 'MESH':#{
2136 col = getattr( active_object.data.SR_data, ent_type, None )
2137 if col != None and len(col)!=0: _draw_prop_collection( col )
2138 #}
2139 #}
2140 #}
2141 #}
2142 #}
2143
2144 class SR_MATERIAL_PANEL(bpy.types.Panel):
2145 #{
2146 bl_label="Skate Rift material"
2147 bl_idname="MATERIAL_PT_sr_material"
2148 bl_space_type='PROPERTIES'
2149 bl_region_type='WINDOW'
2150 bl_context="material"
2151
2152 def draw(_,context):
2153 #{
2154 active_object = bpy.context.active_object
2155 if active_object == None: return
2156 active_mat = active_object.active_material
2157 if active_mat == None: return
2158
2159 info = material_info( active_mat )
2160
2161 if 'tex_diffuse' in info:#{
2162 _.layout.label( icon='INFO', \
2163 text=F"{info['tex_diffuse'].name} will be compiled" )
2164 #}
2165
2166 _.layout.prop( active_mat.SR_data, "shader" )
2167 _.layout.prop( active_mat.SR_data, "surface_prop" )
2168 _.layout.prop( active_mat.SR_data, "collision" )
2169
2170 if active_mat.SR_data.collision:#{
2171 box = _.layout.box()
2172 row = box.row()
2173
2174 if (active_mat.SR_data.shader != 'invisible') and \
2175 (active_mat.SR_data.shader != 'boundary'):#{
2176 row.prop( active_mat.SR_data, "skate_surface" )
2177 row.prop( active_mat.SR_data, "grind_surface" )
2178 row.prop( active_mat.SR_data, "grow_grass" )
2179 #}
2180 #}
2181
2182 if active_mat.SR_data.shader == "terrain_blend":#{
2183 box = _.layout.box()
2184 box.prop( active_mat.SR_data, "blend_offset" )
2185 box.prop( active_mat.SR_data, "sand_colour" )
2186 #}
2187 elif active_mat.SR_data.shader == "vertex_blend":#{
2188 box = _.layout.box()
2189 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
2190 box.prop( active_mat.SR_data, "blend_offset" )
2191 #}
2192 elif active_mat.SR_data.shader == "water":#{
2193 box = _.layout.box()
2194 box.label( icon='INFO', text="Depth scale of 16 meters" )
2195 box.prop( active_mat.SR_data, "shore_colour" )
2196 box.prop( active_mat.SR_data, "ocean_colour" )
2197 #}
2198 #}
2199 #}
2200
2201 def sr_get_type_enum( scene, context ):
2202 #{
2203 items = [('none','None',"")]
2204 mesh_entities=['ent_gate','ent_water']
2205 point_entities=['ent_spawn','ent_route_node','ent_route']
2206
2207 for e in point_entities: items += [(e,e,'')]
2208
2209 if context.scene.SR_data.panel == 'ENTITY': #{
2210 if context.active_object.type == 'MESH': #{
2211 for e in mesh_entities: items += [(e,e,'')]
2212 #}
2213 #}
2214 else: #{
2215 for e in mesh_entities: items += [(e,e,'')]
2216 #}
2217
2218 return items
2219 #}
2220
2221 def sr_on_type_change( _, context ):
2222 #{
2223 obj = context.active_object
2224 ent_type = obj.SR_data.ent_type
2225 if ent_type == 'none': return
2226 if obj.type == 'MESH':#{
2227 col = getattr( obj.data.SR_data, ent_type, None )
2228 if col != None and len(col)==0: col.add()
2229 #}
2230
2231 col = getattr( obj.SR_data, ent_type, None )
2232 if col != None and len(col)==0: col.add()
2233 #}
2234
2235 class SR_OBJECT_ENT_SPAWN(bpy.types.PropertyGroup):
2236 #{
2237 alias: bpy.props.StringProperty( name='alias' )
2238 #}
2239
2240 class SR_OBJECT_ENT_GATE(bpy.types.PropertyGroup):
2241 #{
2242 target: bpy.props.PointerProperty( \
2243 type=bpy.types.Object, name="destination", \
2244 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
2245
2246 key: bpy.props.StringProperty()
2247 tipo: bpy.props.EnumProperty(items=(('default', 'Default', ""),
2248 ('nonlocal', 'Non-Local', ""),))
2249
2250 @staticmethod
2251 def sr_inspector( layout, data ):
2252 #{
2253 box = layout.box()
2254 box.prop( data[0], 'tipo', text="subtype" )
2255
2256 if data[0].tipo == 'default': box.prop( data[0], 'target' )
2257 elif data[0].tipo == 'nonlocal': box.prop( data[0], 'key' )
2258 #}
2259 #}
2260
2261 class SR_MESH_ENT_GATE(bpy.types.PropertyGroup):
2262 #{
2263 dimensions: bpy.props.FloatVectorProperty(name="dimensions",size=3)
2264 #}
2265
2266 class SR_OBJECT_ENT_ROUTE_ENTRY(bpy.types.PropertyGroup):
2267 #{
2268 target: bpy.props.PointerProperty( \
2269 type=bpy.types.Object, name='target', \
2270 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
2271 #}
2272
2273 class SR_UL_ROUTE_NODE_LIST(bpy.types.UIList):
2274 #{
2275 bl_idname = 'SR_UL_ROUTE_NODE_LIST'
2276
2277 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2278 #{
2279 layout.prop( item, 'target', text='', emboss=False )
2280 #}
2281 #}
2282
2283 def internal_listdel_execute(self,context,ent_name,collection_name):
2284 #{
2285 active_object = context.active_object
2286 data = getattr(active_object.SR_data,ent_name)[0]
2287 lista = getattr(data,collection_name)
2288 index = getattr(data,F'{collection_name}_index')
2289
2290 lista.remove(index)
2291
2292 setattr(data,F'{collection_name}_index', min(max(0,index-1), len(lista)-1))
2293 return{'FINISHED'}
2294 #}
2295
2296 def internal_listadd_execute(self,context,ent_name,collection_name):
2297 #{
2298 active_object = context.active_object
2299 getattr(getattr(active_object.SR_data,ent_name)[0],collection_name).add()
2300 return{'FINISHED'}
2301 #}
2302
2303 def copy_propgroup( de, to ):
2304 #{
2305 for a in de.__annotations__:#{
2306 if isinstance(getattr(de,a), bpy.types.bpy_prop_collection):#{
2307 ca = getattr(de,a)
2308 cb = getattr(to,a)
2309
2310 while len(cb) != len(ca):#{
2311 if len(cb) < len(ca): cb.add()
2312 else: cb.remove(0)
2313 #}
2314 for i in range(len(ca)):#{
2315 copy_propgroup(ca[i],cb[i])
2316 #}
2317 #}
2318 else:#{
2319 setattr(to,a,getattr(de,a))
2320 #}
2321 #}
2322 #}
2323
2324 class SR_OT_COPY_ENTITY_DATA(bpy.types.Operator):
2325 #{
2326 bl_idname = "skaterift.copy_entity_data"
2327 bl_label = "Copy entity data"
2328
2329 def execute(self, context):#{
2330 data = context.active_object.SR_data
2331 new_type = data.ent_type
2332 print( F"Copy entity data from: {context.active_object.name}" )
2333
2334 for obj in context.selected_objects:#{
2335 if obj != context.active_object:#{
2336 print( F" To: {obj.name}" )
2337
2338 obj.SR_data.ent_type = new_type
2339
2340 if active_object.type == 'MESH':#{
2341 col = getattr( obj.data.SR_data, new_type, None )
2342 if col != None and len(col)==0: col.add()
2343 mdata = context.active_object.data.SR_data
2344 copy_propgroup( getattr(mdata,new_type)[0], col[0] )
2345 #}
2346
2347 col = getattr( obj.SR_data, new_type, None )
2348 if col != None and len(col)==0: col.add()
2349 copy_propgroup( getattr(data,new_type)[0], col[0] )
2350 #}
2351 #}
2352 return{'FINISHED'}
2353 #}
2354 #}
2355
2356 class SR_OT_ROUTE_LIST_NEW_ITEM(bpy.types.Operator):
2357 #{
2358 bl_idname = "skaterift.new_entry"
2359 bl_label = "Add gate"
2360
2361 def execute(self, context):#{
2362 return internal_listadd_execute(self,context,'ent_route','gates')
2363 #}
2364 #}
2365
2366 class SR_OT_ROUTE_LIST_DEL_ITEM(bpy.types.Operator):
2367 #{
2368 bl_idname = "skaterift.del_entry"
2369 bl_label = "Remove gate"
2370
2371 @classmethod
2372 def poll(cls, context):#{
2373 active_object = context.active_object
2374 if obj_ent_type(active_object) == 'ent_route':#{
2375 return active_object.SR_data.ent_route[0].gates
2376 #}
2377 else: return False
2378 #}
2379
2380 def execute(self, context):#{
2381 return internal_listdel_execute(self,context,'ent_route','gates')
2382 #}
2383 #}
2384
2385 class SR_OT_AUDIO_LIST_NEW_ITEM(bpy.types.Operator):
2386 #{
2387 bl_idname = "skaterift.al_new_entry"
2388 bl_label = "Add file"
2389
2390 def execute(self, context):#{
2391 return internal_listadd_execute(self,context,'ent_audio','files')
2392 #}
2393 #}
2394
2395 class SR_OT_AUDIO_LIST_DEL_ITEM(bpy.types.Operator):
2396 #{
2397 bl_idname = "skaterift.al_del_entry"
2398 bl_label = "Remove file"
2399
2400 @classmethod
2401 def poll(cls, context):#{
2402 active_object = context.active_object
2403 if obj_ent_type(active_object) == 'ent_audio':#{
2404 return active_object.SR_data.ent_audio[0].files
2405 #}
2406 else: return False
2407 #}
2408
2409 def execute(self, context):#{
2410 return internal_listdel_execute(self,context,'ent_audio','files')
2411 return{'FINISHED'}
2412 #}
2413 #}
2414
2415 class SR_OT_GLYPH_LIST_NEW_ITEM(bpy.types.Operator):
2416 #{
2417 bl_idname = "skaterift.gl_new_entry"
2418 bl_label = "Add glyph"
2419
2420 def execute(self, context):#{
2421 active_object = context.active_object
2422
2423 font = active_object.SR_data.ent_font[0]
2424 font.glyphs.add()
2425
2426 if len(font.glyphs) > 1:#{
2427 prev = font.glyphs[-2]
2428 cur = font.glyphs[-1]
2429
2430 cur.bounds = prev.bounds
2431 cur.utf32 = prev.utf32+1
2432 #}
2433
2434 return{'FINISHED'}
2435 #}
2436 #}
2437
2438 class SR_OT_GLYPH_LIST_DEL_ITEM(bpy.types.Operator):
2439 #{
2440 bl_idname = "skaterift.gl_del_entry"
2441 bl_label = "Remove Glyph"
2442
2443 @classmethod
2444 def poll(cls, context):#{
2445 active_object = context.active_object
2446 if obj_ent_type(active_object) == 'ent_font':#{
2447 return active_object.SR_data.ent_font[0].glyphs
2448 #}
2449 else: return False
2450 #}
2451
2452 def execute(self, context):#{
2453 return internal_listdel_execute(self,context,'ent_font','glyphs')
2454 #}
2455 #}
2456
2457 class SR_OT_GLYPH_LIST_MOVE_ITEM(bpy.types.Operator):
2458 #{
2459 bl_idname = "skaterift.gl_move_item"
2460 bl_label = "aa"
2461 direction: bpy.props.EnumProperty(items=(('UP', 'Up', ""),
2462 ('DOWN', 'Down', ""),))
2463
2464 @classmethod
2465 def poll(cls, context):#{
2466 active_object = context.active_object
2467 if obj_ent_type(active_object) == 'ent_font':#{
2468 return active_object.SR_data.ent_font[0].glyphs
2469 #}
2470 else: return False
2471 #}
2472
2473 def execute(_, context):#{
2474 active_object = context.active_object
2475 data = active_object.SR_data.ent_font[0]
2476
2477 index = data.glyphs_index
2478 neighbor = index + (-1 if _.direction == 'UP' else 1)
2479 data.glyphs.move( neighbor, index )
2480
2481 list_length = len(data.glyphs) - 1
2482 new_index = index + (-1 if _.direction == 'UP' else 1)
2483
2484 data.glyphs_index = max(0, min(new_index, list_length))
2485
2486 return{'FINISHED'}
2487 #}
2488 #}
2489
2490 class SR_OT_FONT_VARIANT_LIST_NEW_ITEM(bpy.types.Operator):
2491 #{
2492 bl_idname = "skaterift.fv_new_entry"
2493 bl_label = "Add variant"
2494
2495 def execute(self, context):#{
2496 return internal_listadd_execute(self,context,'ent_font','variants')
2497 #}
2498 #}
2499
2500 class SR_OT_FONT_VARIANT_LIST_DEL_ITEM(bpy.types.Operator):
2501 #{
2502 bl_idname = "skaterift.fv_del_entry"
2503 bl_label = "Remove variant"
2504
2505 @classmethod
2506 def poll(cls, context):#{
2507 active_object = context.active_object
2508 if obj_ent_type(active_object) == 'ent_font':#{
2509 return active_object.SR_data.ent_font[0].variants
2510 #}
2511 else: return False
2512 #}
2513
2514 def execute(self, context):#{
2515 return internal_listdel_execute(self,context,'ent_font','variants')
2516 #}
2517 #}
2518
2519 class SR_OBJECT_ENT_AUDIO_FILE_ENTRY(bpy.types.PropertyGroup):
2520 #{
2521 path: bpy.props.StringProperty( name="Path" )
2522 probability: bpy.props.FloatProperty( name="Probability",default=100.0 )
2523 #}
2524
2525 class SR_UL_AUDIO_LIST(bpy.types.UIList):
2526 #{
2527 bl_idname = 'SR_UL_AUDIO_LIST'
2528
2529 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2530 #{
2531 split = layout.split(factor=0.7)
2532 c = split.column()
2533 c.prop( item, 'path', text='', emboss=False )
2534 c = split.column()
2535 c.prop( item, 'probability', text='%', emboss=True )
2536 #}
2537 #}
2538
2539 class SR_UL_FONT_VARIANT_LIST(bpy.types.UIList):
2540 #{
2541 bl_idname = 'SR_UL_FONT_VARIANT_LIST'
2542
2543 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2544 #{
2545 layout.prop( item, 'mesh', emboss=False )
2546 layout.prop( item, 'tipo' )
2547 #}
2548 #}
2549
2550 class SR_UL_FONT_GLYPH_LIST(bpy.types.UIList):
2551 #{
2552 bl_idname = 'SR_UL_FONT_GLYPH_LIST'
2553
2554 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2555 #{
2556 s0 = layout.split(factor=0.3)
2557 c = s0.column()
2558 s1 = c.split(factor=0.3)
2559 c = s1.column()
2560 row = c.row()
2561 lbl = chr(item.utf32) if item.utf32 >= 32 and item.utf32 <= 126 else \
2562 f'x{item.utf32:x}'
2563 row.label(text=lbl)
2564 c = s1.column()
2565 c.prop( item, 'utf32', text='', emboss=True )
2566 c = s0.column()
2567 row = c.row()
2568 row.prop( item, 'bounds', text='', emboss=False )
2569 #}
2570 #}
2571
2572 class SR_OBJECT_ENT_ROUTE(bpy.types.PropertyGroup):
2573 #{
2574 gates: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE_ENTRY)
2575 gates_index: bpy.props.IntProperty()
2576
2577 colour: bpy.props.FloatVectorProperty( \
2578 name="Colour",\
2579 subtype='COLOR',\
2580 min=0.0,max=1.0,\
2581 default=Vector((0.79,0.63,0.48)),\
2582 description="Route colour"\
2583 )
2584
2585 alias: bpy.props.StringProperty(\
2586 name="Alias",\
2587 default="Untitled Course")
2588
2589 @staticmethod
2590 def sr_inspector( layout, data ):
2591 #{
2592 layout.prop( data[0], 'alias' )
2593 layout.prop( data[0], 'colour' )
2594
2595 layout.label( text='Checkpoints' )
2596 layout.template_list('SR_UL_ROUTE_NODE_LIST', 'Checkpoints', \
2597 data[0], 'gates', data[0], 'gates_index', rows=5)
2598
2599 row = layout.row()
2600 row.operator( 'skaterift.new_entry', text='Add' )
2601 row.operator( 'skaterift.del_entry', text='Remove' )
2602 #}
2603 #}
2604
2605 class SR_OBJECT_ENT_VOLUME(bpy.types.PropertyGroup):
2606 #{
2607 subtype: bpy.props.EnumProperty(
2608 name="Subtype",
2609 items=[('0','Trigger',''),
2610 ('1','Particles (0.1s)','')]
2611 )
2612
2613 target: bpy.props.PointerProperty( \
2614 type=bpy.types.Object, name="Target", \
2615 poll=lambda self,obj: sr_filter_ent_type(obj,\
2616 ['ent_audio','ent_skateshop']))
2617
2618 @staticmethod
2619 def sr_inspector( layout, data ):
2620 #{
2621 data = data[0]
2622 layout.prop( data, 'subtype' )
2623 layout.prop( data, 'target' )
2624 #}
2625 #}
2626
2627 class SR_OBJECT_ENT_AUDIO(bpy.types.PropertyGroup):
2628 #{
2629 files: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO_FILE_ENTRY)
2630 files_index: bpy.props.IntProperty()
2631
2632 flag_3d: bpy.props.BoolProperty( name="3D audio",default=True )
2633 flag_loop: bpy.props.BoolProperty( name="Loop",default=False )
2634 flag_auto: bpy.props.BoolProperty( name="Play at start",default=False )
2635 flag_nodoppler: bpy.props.BoolProperty( name="No Doppler",default=False )
2636
2637 group: bpy.props.IntProperty( name="Group ID", default=0 )
2638 formato: bpy.props.EnumProperty(
2639 name="Format",
2640 items=[('0','Uncompressed Mono',''),
2641 ('1','Compressed Vorbis',''),
2642 ('2','[vg] Bird Synthesis','')]
2643 )
2644 probability_curve: bpy.props.EnumProperty(
2645 name="Probability Curve",
2646 items=[('0','Constant',''),
2647 ('1','Wildlife Daytime',''),
2648 ('2','Wildlife Nighttime','')])
2649 channel_behaviour: bpy.props.EnumProperty(
2650 name="Channel Behaviour",
2651 items=[('0','Unlimited',''),
2652 ('1','Discard if group full', ''),
2653 ('2','Crossfade if group full','')])
2654
2655 transition_duration: bpy.props.FloatProperty(name="Transition Time",\
2656 default=0.2)
2657
2658 max_channels: bpy.props.IntProperty( name="Max Channels", default=1 )
2659 volume: bpy.props.FloatProperty( name="Volume",default=1.0 )
2660
2661 @staticmethod
2662 def sr_inspector( layout, data ):
2663 #{
2664 layout.prop( data[0], 'formato' )
2665 layout.prop( data[0], 'volume' )
2666
2667 box = layout.box()
2668 box.label( text='Channels' )
2669 split = box.split(factor=0.3)
2670 c = split.column()
2671 c.prop( data[0], 'max_channels' )
2672 c = split.column()
2673 c.prop( data[0], 'channel_behaviour', text='Behaviour' )
2674 if data[0].channel_behaviour >= '1':
2675 box.prop( data[0], 'group' )
2676 if data[0].channel_behaviour == '2':
2677 box.prop( data[0], 'transition_duration' )
2678
2679 box = layout.box()
2680 box.label( text='Flags' )
2681 box.prop( data[0], 'flag_3d' )
2682 if data[0].flag_3d: box.prop( data[0], 'flag_nodoppler' )
2683
2684 box.prop( data[0], 'flag_loop' )
2685 box.prop( data[0], 'flag_auto' )
2686
2687 split = layout.split(factor=0.7)
2688 c = split.column()
2689 c.label( text='Filepath' )
2690 c = split.column()
2691 c.label( text='Chance (0.1s)' )
2692
2693 layout.prop( data[0], 'probability_curve' )
2694
2695 layout.template_list('SR_UL_AUDIO_LIST', 'Files', \
2696 data[0], 'files', data[0], 'file_index', rows=5)
2697
2698 row = layout.row()
2699 row.operator( 'skaterift.al_new_entry', text='Add' )
2700 row.operator( 'skaterift.al_del_entry', text='Remove' )
2701 #}
2702 #}
2703
2704 class SR_OBJECT_ENT_MARKER(bpy.types.PropertyGroup):
2705 #{
2706 alias: bpy.props.StringProperty()
2707 #}
2708
2709 class SR_OBJECT_ENT_GLYPH(bpy.types.PropertyGroup):
2710 #{
2711 mini: bpy.props.FloatVectorProperty(size=2)
2712 maxi: bpy.props.FloatVectorProperty(size=2)
2713 utf32: bpy.props.IntProperty()
2714 #}
2715
2716 class SR_OBJECT_ENT_GLYPH_ENTRY(bpy.types.PropertyGroup):
2717 #{
2718 bounds: bpy.props.FloatVectorProperty(size=4,subtype='NONE')
2719 utf32: bpy.props.IntProperty()
2720 #}
2721
2722 class SR_OBJECT_ENT_FONT_VARIANT(bpy.types.PropertyGroup):
2723 #{
2724 mesh: bpy.props.PointerProperty(type=bpy.types.Object)
2725 tipo: bpy.props.StringProperty()
2726 #}
2727
2728 class SR_OBJECT_ENT_FONT(bpy.types.PropertyGroup):
2729 #{
2730 variants: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_FONT_VARIANT)
2731 glyphs: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GLYPH_ENTRY)
2732 alias: bpy.props.StringProperty()
2733
2734 glyphs_index: bpy.props.IntProperty()
2735 variants_index: bpy.props.IntProperty()
2736
2737 @staticmethod
2738 def sr_inspector( layout, data ):
2739 #{
2740 layout.prop( data[0], 'alias' )
2741
2742 layout.label( text='Variants' )
2743 layout.template_list('SR_UL_FONT_VARIANT_LIST', 'Variants', \
2744 data[0], 'variants', data[0], 'variants_index',\
2745 rows=5 )
2746 row = layout.row()
2747 row.operator( 'skaterift.fv_new_entry', text='Add' )
2748 row.operator( 'skaterift.fv_del_entry', text='Remove' )
2749
2750 layout.label( text='ASCII Glyphs' )
2751 layout.template_list('SR_UL_FONT_GLYPH_LIST', 'Glyphs', \
2752 data[0], 'glyphs', data[0], 'glyphs_index', rows=5)
2753
2754 row = layout.row()
2755 row.operator( 'skaterift.gl_new_entry', text='Add' )
2756 row.operator( 'skaterift.gl_del_entry', text='Remove' )
2757 row.operator( 'skaterift.gl_move_item', text='^' ).direction='UP'
2758 row.operator( 'skaterift.gl_move_item', text='v' ).direction='DOWN'
2759 #}
2760 #}
2761
2762 class SR_OBJECT_ENT_TRAFFIC(bpy.types.PropertyGroup):
2763 #{
2764 speed: bpy.props.FloatProperty(default=1.0)
2765 #}
2766
2767 class SR_OBJECT_ENT_SKATESHOP(bpy.types.PropertyGroup):
2768 #{
2769 mark_rack: bpy.props.PointerProperty( \
2770 type=bpy.types.Object, name="Board Rack", \
2771 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2772 mark_display: bpy.props.PointerProperty( \
2773 type=bpy.types.Object, name="Selected Board Display", \
2774 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2775 mark_info: bpy.props.PointerProperty( \
2776 type=bpy.types.Object, name="Selected Board Info", \
2777 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2778 cam: bpy.props.PointerProperty( \
2779 type=bpy.types.Object, name="Viewpoint", \
2780 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_camera']))
2781 #}
2782
2783 class SR_OBJECT_ENT_WORKSHOP_PREVIEW(bpy.types.PropertyGroup):
2784 #{
2785 mark_display: bpy.props.PointerProperty( \
2786 type=bpy.types.Object, name="Board Display", \
2787 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2788 mark_display1: bpy.props.PointerProperty( \
2789 type=bpy.types.Object, name="Board Display (other side)", \
2790 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2791 cam: bpy.props.PointerProperty( \
2792 type=bpy.types.Object, name="Viewpoint", \
2793 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_camera']))
2794 #}
2795
2796 class SR_OBJECT_ENT_MENU_ITEM(bpy.types.PropertyGroup):
2797 #{
2798 link0: bpy.props.PointerProperty( \
2799 type=bpy.types.Object, name="Link 0", \
2800 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2801 link1: bpy.props.PointerProperty( \
2802 type=bpy.types.Object, name="Link 1", \
2803 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2804 link2: bpy.props.PointerProperty( \
2805 type=bpy.types.Object, name="Link 2", \
2806 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2807 link3: bpy.props.PointerProperty( \
2808 type=bpy.types.Object, name="Link 3", \
2809 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2810
2811 newloc: bpy.props.PointerProperty( \
2812 type=bpy.types.Object, name="New location", \
2813 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2814 camera: bpy.props.PointerProperty( \
2815 type=bpy.types.Object, name="Camera", \
2816 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_camera']))
2817
2818 slider_minloc: bpy.props.PointerProperty( \
2819 type=bpy.types.Object, name="Slider min", \
2820 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2821 slider_maxloc: bpy.props.PointerProperty( \
2822 type=bpy.types.Object, name="Slider max", \
2823 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2824 slider_handle: bpy.props.PointerProperty( \
2825 type=bpy.types.Object, name="Slider handle", \
2826 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2827
2828 checkmark: bpy.props.PointerProperty( \
2829 type=bpy.types.Object, name="Checked", \
2830 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2831
2832 string: bpy.props.StringProperty( name="String" )
2833 tipo: bpy.props.EnumProperty( name='Type',
2834 items=[('0','visual',''),
2835 ('1','event button',''),
2836 ('2','page button',''),
2837 ('3','toggle', ''),
2838 ('4','slider',''),
2839 ('5','page','')])
2840
2841 @staticmethod
2842 def sr_inspector( layout, data ):
2843 #{
2844 data = data[0]
2845 box = layout.box()
2846 box.prop( data, 'tipo' )
2847
2848 if data.tipo == '0':#{
2849 return
2850 #}
2851 elif data.tipo == '1':#{
2852 box.prop( data, 'string', text='Event' )
2853 #}
2854 elif data.tipo == '2':#{
2855 box.prop( data, 'string', text='Page' )
2856 box.prop( data, 'newloc' )
2857 #}
2858 elif data.tipo == '3':#{
2859 box.prop( data, 'string', text='Data (i32)' )
2860 box.prop( data, 'checkmark' )
2861 #}
2862 elif data.tipo == '4':#{
2863 box.prop( data, 'string', text='Data (f32)' )
2864 box.prop( data, 'slider_minloc' )
2865 box.prop( data, 'slider_maxloc' )
2866 box.prop( data, 'slider_handle' )
2867 box = box.box()
2868 box.label( text="Links" )
2869 box.prop( data, 'link0', text='v0' )
2870 box.prop( data, 'link1', text='v1' )
2871 return
2872 #}
2873 elif data.tipo == '5':#{
2874 box.prop( data, 'string', text='Page Name' )
2875 box.prop( data, 'newloc', text='Entry Point' )
2876 box.prop( data, 'camera', text='Viewpoint' )
2877 return
2878 #}
2879
2880 box = box.box()
2881 box.label( text="Links" )
2882 box.prop( data, 'link0' )
2883 box.prop( data, 'link1' )
2884 box.prop( data, 'link2' )
2885 box.prop( data, 'link3' )
2886 #}
2887 #}
2888
2889 class SR_OBJECT_PROPERTIES(bpy.types.PropertyGroup):
2890 #{
2891 ent_gate: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GATE)
2892 ent_spawn: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SPAWN)
2893 ent_route: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE)
2894 ent_volume: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_VOLUME)
2895 ent_audio: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO)
2896 ent_marker: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_MARKER)
2897 ent_glyph: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GLYPH)
2898 ent_font: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_FONT)
2899 ent_traffic: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_TRAFFIC)
2900 ent_skateshop: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SKATESHOP)
2901 ent_swspreview: \
2902 bpy.props.CollectionProperty(type=SR_OBJECT_ENT_WORKSHOP_PREVIEW)
2903 ent_menuitem: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_MENU_ITEM)
2904
2905 ent_type: bpy.props.EnumProperty(
2906 name="Type",
2907 items=sr_entity_list,
2908 update=sr_on_type_change
2909 )
2910 #}
2911
2912 class SR_MESH_PROPERTIES(bpy.types.PropertyGroup):
2913 #{
2914 ent_gate: bpy.props.CollectionProperty(type=SR_MESH_ENT_GATE)
2915 #}
2916
2917 class SR_LIGHT_PROPERTIES(bpy.types.PropertyGroup):
2918 #{
2919 daytime: bpy.props.BoolProperty( name='Daytime' )
2920 #}
2921
2922 class SR_BONE_PROPERTIES(bpy.types.PropertyGroup):
2923 #{
2924 collider: bpy.props.EnumProperty( name='Collider Type',
2925 items=[('0','none',''),
2926 ('1','box',''),
2927 ('2','capsule','')])
2928
2929 collider_min: bpy.props.FloatVectorProperty( name='Collider Min', size=3 )
2930 collider_max: bpy.props.FloatVectorProperty( name='Collider Max', size=3 )
2931
2932 cone_constraint: bpy.props.BoolProperty( name='Cone constraint' )
2933
2934 conevx: bpy.props.FloatVectorProperty( name='vx' )
2935 conevy: bpy.props.FloatVectorProperty( name='vy' )
2936 coneva: bpy.props.FloatVectorProperty( name='va' )
2937 conet: bpy.props.FloatProperty( name='t' )
2938
2939 @staticmethod
2940 def sr_inspector( layout, data ):
2941 #{
2942 data = data[0]
2943 box = layout.box()
2944 box.prop( data, 'collider' )
2945
2946 if int(data.collider)>0:#{
2947 row = box.row()
2948 row.prop( data, 'collider_min' )
2949 row = box.row()
2950 row.prop( data, 'collider_max' )
2951 #}
2952
2953 box = layout.box()
2954 box.prop( data, 'cone_constraint' )
2955 if data.cone_constraint:#{
2956 row = box.row()
2957 row.prop( data, 'conevx' )
2958 row = box.row()
2959 row.prop( data, 'conevy' )
2960 row = box.row()
2961 row.prop( data, 'coneva' )
2962 box.prop( data, 'conet' )
2963 #}
2964 #}
2965 #}
2966
2967 class SR_MATERIAL_PROPERTIES(bpy.types.PropertyGroup):
2968 #{
2969 shader: bpy.props.EnumProperty(
2970 name="Format",
2971 items = [
2972 ('standard',"standard",''),
2973 ('standard_cutout', "standard_cutout", ''),
2974 ('terrain_blend', "terrain_blend", ''),
2975 ('vertex_blend', "vertex_blend", ''),
2976 ('water',"water",''),
2977 ('invisible','Invisible',''),
2978 ('boundary','Boundary','')
2979 ])
2980
2981 surface_prop: bpy.props.EnumProperty(
2982 name="Surface Property",
2983 items = [
2984 ('0','concrete',''),
2985 ('1','wood',''),
2986 ('2','grass',''),
2987 ('3','tiles',''),
2988 ('4','metal','')
2989 ])
2990
2991 collision: bpy.props.BoolProperty( \
2992 name="Collisions Enabled",\
2993 default=True,\
2994 description = "Can the player collide with this material?"\
2995 )
2996 skate_surface: bpy.props.BoolProperty( \
2997 name="Skate Target", \
2998 default=True,\
2999 description = "Should the game try to target this surface?" \
3000 )
3001 grind_surface: bpy.props.BoolProperty( \
3002 name="Grindable", \
3003 default=True,\
3004 description = "Can you grind on this surface?" \
3005 )
3006 grow_grass: bpy.props.BoolProperty( \
3007 name="Grow Grass", \
3008 default=False,\
3009 description = "Spawn grass sprites on this surface?" \
3010 )
3011 blend_offset: bpy.props.FloatVectorProperty( \
3012 name="Blend Offset", \
3013 size=2, \
3014 default=Vector((0.5,0.0)),\
3015 description="When surface is more than 45 degrees, add this vector " +\
3016 "to the UVs" \
3017 )
3018 sand_colour: bpy.props.FloatVectorProperty( \
3019 name="Sand Colour",\
3020 subtype='COLOR',\
3021 min=0.0,max=1.0,\
3022 default=Vector((0.79,0.63,0.48)),\
3023 description="Blend to this colour near the 0 coordinate on UP axis"\
3024 )
3025 shore_colour: bpy.props.FloatVectorProperty( \
3026 name="Shore Colour",\
3027 subtype='COLOR',\
3028 min=0.0,max=1.0,\
3029 default=Vector((0.03,0.32,0.61)),\
3030 description="Water colour at the shoreline"\
3031 )
3032 ocean_colour: bpy.props.FloatVectorProperty( \
3033 name="Ocean Colour",\
3034 subtype='COLOR',\
3035 min=0.0,max=1.0,\
3036 default=Vector((0.0,0.006,0.03)),\
3037 description="Water colour in the deep bits"\
3038 )
3039 #}
3040
3041 # ---------------------------------------------------------------------------- #
3042 # #
3043 # GUI section #
3044 # #
3045 # ---------------------------------------------------------------------------- #
3046
3047 cv_view_draw_handler = None
3048 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
3049 cv_view_verts = []
3050 cv_view_colours = []
3051 cv_view_course_i = 0
3052
3053 # Draw axis alligned sphere at position with radius
3054 #
3055 def cv_draw_sphere( pos, radius, colour ):
3056 #{
3057 global cv_view_verts, cv_view_colours
3058
3059 ly = pos + Vector((0,0,radius))
3060 lx = pos + Vector((0,radius,0))
3061 lz = pos + Vector((0,0,radius))
3062
3063 pi = 3.14159265358979323846264
3064
3065 for i in range(16):#{
3066 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
3067 s = math.sin(t)
3068 c = math.cos(t)
3069
3070 py = pos + Vector((s*radius,0.0,c*radius))
3071 px = pos + Vector((s*radius,c*radius,0.0))
3072 pz = pos + Vector((0.0,s*radius,c*radius))
3073
3074 cv_view_verts += [ px, lx ]
3075 cv_view_verts += [ py, ly ]
3076 cv_view_verts += [ pz, lz ]
3077
3078 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
3079
3080 ly = py
3081 lx = px
3082 lz = pz
3083 #}
3084 cv_draw_lines()
3085 #}
3086
3087 # Draw axis alligned sphere at position with radius
3088 #
3089 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
3090 #{
3091 global cv_view_verts, cv_view_colours
3092
3093 ly = pos + tz*radius
3094 lx = pos + ty*radius
3095 lz = pos + tz*radius
3096
3097 pi = 3.14159265358979323846264
3098
3099 for i in range(16):#{
3100 t = ((i+1.0) * 1.0/16.0) * pi
3101 s = math.sin(t)
3102 c = math.cos(t)
3103
3104 s1 = math.sin(t*2.0)
3105 c1 = math.cos(t*2.0)
3106
3107 py = pos + s*tx*radius + c *tz*radius
3108 px = pos + s*tx*radius + c *ty*radius
3109 pz = pos + s1*ty*radius + c1*tz*radius
3110
3111 cv_view_verts += [ px, lx ]
3112 cv_view_verts += [ py, ly ]
3113 cv_view_verts += [ pz, lz ]
3114
3115 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
3116
3117 ly = py
3118 lx = px
3119 lz = pz
3120 #}
3121 cv_draw_lines()
3122 #}
3123
3124 # Draw transformed -1 -> 1 cube
3125 #
3126 def cv_draw_ucube( transform, colour, s=Vector((1,1,1)), o=Vector((0,0,0)) ):
3127 #{
3128 global cv_view_verts, cv_view_colours
3129
3130 a = o + -1.0 * s
3131 b = o + 1.0 * s
3132
3133 vs = [None]*8
3134 vs[0] = transform @ Vector((a[0], a[1], a[2]))
3135 vs[1] = transform @ Vector((a[0], b[1], a[2]))
3136 vs[2] = transform @ Vector((b[0], b[1], a[2]))
3137 vs[3] = transform @ Vector((b[0], a[1], a[2]))
3138 vs[4] = transform @ Vector((a[0], a[1], b[2]))
3139 vs[5] = transform @ Vector((a[0], b[1], b[2]))
3140 vs[6] = transform @ Vector((b[0], b[1], b[2]))
3141 vs[7] = transform @ Vector((b[0], a[1], b[2]))
3142
3143 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
3144 (0,4),(1,5),(2,6),(3,7)]
3145
3146 for l in indices:#{
3147 v0 = vs[l[0]]
3148 v1 = vs[l[1]]
3149 cv_view_verts += [(v0[0],v0[1],v0[2])]
3150 cv_view_verts += [(v1[0],v1[1],v1[2])]
3151 cv_view_colours += [colour, colour]
3152 #}
3153 cv_draw_lines()
3154 #}
3155
3156 # Draw line with colour
3157 #
3158 def cv_draw_line( p0, p1, colour ):
3159 #{
3160 global cv_view_verts, cv_view_colours
3161
3162 cv_view_verts += [p0,p1]
3163 cv_view_colours += [colour, colour]
3164 cv_draw_lines()
3165 #}
3166
3167 # Draw line with colour(s)
3168 #
3169 def cv_draw_line2( p0, p1, c0, c1 ):
3170 #{
3171 global cv_view_verts, cv_view_colours
3172
3173 cv_view_verts += [p0,p1]
3174 cv_view_colours += [c0,c1]
3175 cv_draw_lines()
3176 #}
3177
3178 #
3179 #
3180 def cv_tangent_basis( n, tx, ty ):
3181 #{
3182 if abs( n[0] ) >= 0.57735027:#{
3183 tx[0] = n[1]
3184 tx[1] = -n[0]
3185 tx[2] = 0.0
3186 #}
3187 else:#{
3188 tx[0] = 0.0
3189 tx[1] = n[2]
3190 tx[2] = -n[1]
3191 #}
3192
3193 tx.normalize()
3194 _ty = n.cross( tx )
3195
3196 ty[0] = _ty[0]
3197 ty[1] = _ty[1]
3198 ty[2] = _ty[2]
3199 #}
3200
3201 # Draw coloured arrow
3202 #
3203 def cv_draw_arrow( p0, p1, c0, size=0.15 ):
3204 #{
3205 global cv_view_verts, cv_view_colours
3206
3207 n = p1-p0
3208 midpt = p0 + n*0.5
3209 n.normalize()
3210
3211 tx = Vector((1,0,0))
3212 ty = Vector((1,0,0))
3213 cv_tangent_basis( n, tx, ty )
3214
3215 cv_view_verts += [p0,p1, midpt+(tx-n)*size,midpt, midpt+(-tx-n)*size,midpt ]
3216 cv_view_colours += [c0,c0,c0,c0,c0,c0]
3217 #cv_draw_lines()
3218 #}
3219
3220 def cv_draw_line_dotted( p0, p1, c0, dots=10 ):
3221 #{
3222 global cv_view_verts, cv_view_colours
3223
3224 for i in range(dots):#{
3225 t0 = i/dots
3226 t1 = (i+0.25)/dots
3227
3228 p2 = p0*(1.0-t0)+p1*t0
3229 p3 = p0*(1.0-t1)+p1*t1
3230
3231 cv_view_verts += [p2,p3]
3232 cv_view_colours += [c0,c0]
3233 #}
3234 #cv_draw_lines()
3235 #}
3236
3237 # Drawhandles of a bezier control point
3238 #
3239 def cv_draw_bhandle( obj, direction, colour ):
3240 #{
3241 global cv_view_verts, cv_view_colours
3242
3243 p0 = obj.location
3244 h0 = obj.matrix_world @ Vector((0,direction,0))
3245
3246 cv_view_verts += [p0]
3247 cv_view_verts += [h0]
3248 cv_view_colours += [colour,colour]
3249 cv_draw_lines()
3250 #}
3251
3252 # Draw a bezier curve (at fixed resolution 10)
3253 #
3254 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
3255 #{
3256 global cv_view_verts, cv_view_colours
3257
3258 last = p0
3259 for i in range(10):#{
3260 t = (i+1)/10
3261 a0 = 1-t
3262
3263 tt = t*t
3264 ttt = tt*t
3265 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
3266
3267 cv_view_verts += [(last[0],last[1],last[2])]
3268 cv_view_verts += [(p[0],p[1],p[2])]
3269 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
3270
3271 last = p
3272 #}
3273 cv_draw_lines()
3274 #}
3275
3276 # I think this one extends the handles of the bezier otwards......
3277 #
3278 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
3279 #{
3280 global cv_view_course_i
3281
3282 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
3283
3284 p0 = o0.matrix_world @ Vector((offs, 0,0))
3285 h0 = o0.matrix_world @ Vector((offs, s0,0))
3286 p1 = o1.matrix_world @ Vector((offs, 0,0))
3287 h1 = o1.matrix_world @ Vector((offs,-s1,0))
3288
3289 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
3290 cv_draw_lines()
3291 #}
3292
3293 # Flush the lines buffers. This is called often because god help you if you want
3294 # to do fixed, fast buffers in this catastrophic programming language.
3295 #
3296 def cv_draw_lines():
3297 #{
3298 global cv_view_shader, cv_view_verts, cv_view_colours
3299
3300 if len(cv_view_verts) < 2:
3301 return
3302
3303 lines = batch_for_shader(\
3304 cv_view_shader, 'LINES', \
3305 { "pos":cv_view_verts, "color":cv_view_colours })
3306
3307 lines.draw( cv_view_shader )
3308
3309 cv_view_verts = []
3310 cv_view_colours = []
3311 #}
3312
3313 # I dont remember what this does exactly
3314 #
3315 def cv_draw_bpath( o0,o1,c0,c1 ):
3316 #{
3317 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
3318 #}
3319
3320 # Semi circle to show the limit. and some lines
3321 #
3322 def draw_limit( obj, center, major, minor, amin, amax, colour ):
3323 #{
3324 global cv_view_verts, cv_view_colours
3325 f = 0.05
3326 ay = major*f
3327 ax = minor*f
3328
3329 for x in range(16):#{
3330 t0 = x/16
3331 t1 = (x+1)/16
3332 a0 = amin*(1.0-t0)+amax*t0
3333 a1 = amin*(1.0-t1)+amax*t1
3334
3335 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
3336 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
3337
3338 p0=obj.matrix_world @ p0
3339 p1=obj.matrix_world @ p1
3340 cv_view_verts += [p0,p1]
3341 cv_view_colours += [colour,colour]
3342
3343 if x == 0:#{
3344 cv_view_verts += [p0,center]
3345 cv_view_colours += [colour,colour]
3346 #}
3347 if x == 15:#{
3348 cv_view_verts += [p1,center]
3349 cv_view_colours += [colour,colour]
3350 #}
3351 #}
3352
3353 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
3354 cv_view_colours += [colour,colour]
3355
3356 cv_draw_lines()
3357 #}
3358
3359 # Cone and twist limit
3360 #
3361 def draw_cone_twist( center, vx, vy, va ):
3362 #{
3363 global cv_view_verts, cv_view_colours
3364 axis = vy.cross( vx )
3365 axis.normalize()
3366
3367 size = 0.12
3368
3369 cv_view_verts += [center, center+va*size]
3370 cv_view_colours += [ (1,1,1), (1,1,1) ]
3371
3372 for x in range(32):#{
3373 t0 = (x/32) * math.tau
3374 t1 = ((x+1)/32) * math.tau
3375
3376 c0 = math.cos(t0)
3377 s0 = math.sin(t0)
3378 c1 = math.cos(t1)
3379 s1 = math.sin(t1)
3380
3381 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
3382 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
3383
3384 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
3385 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
3386
3387 cv_view_verts += [center, p0, p0, p1]
3388 cv_view_colours += [ (0,0,0), col0, col0, col1 ]
3389 #}
3390
3391 cv_draw_lines()
3392 #}
3393
3394 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
3395 #
3396 def draw_skeleton_helpers( obj ):
3397 #{
3398 global cv_view_verts, cv_view_colours
3399
3400 if obj.data.pose_position != 'REST':#{
3401 return
3402 #}
3403
3404 for bone in obj.data.bones:#{
3405 c = bone.head_local
3406 a = Vector((bone.SR_data.collider_min[0],
3407 bone.SR_data.collider_min[1],
3408 bone.SR_data.collider_min[2]))
3409 b = Vector((bone.SR_data.collider_max[0],
3410 bone.SR_data.collider_max[1],
3411 bone.SR_data.collider_max[2]))
3412
3413 if bone.SR_data.collider == '1':#{
3414 vs = [None]*8
3415 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
3416 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
3417 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
3418 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
3419 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
3420 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
3421 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
3422 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
3423
3424 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
3425 (0,4),(1,5),(2,6),(3,7)]
3426
3427 for l in indices:#{
3428 v0 = vs[l[0]]
3429 v1 = vs[l[1]]
3430
3431 cv_view_verts += [(v0[0],v0[1],v0[2])]
3432 cv_view_verts += [(v1[0],v1[1],v1[2])]
3433 cv_view_colours += [(0.5,0.5,0.5),(0.5,0.5,0.5)]
3434 #}
3435 #}
3436 elif bone.SR_data.collider == '2':#{
3437 v0 = b-a
3438 major_axis = 0
3439 largest = -1.0
3440
3441 for i in range(3):#{
3442 if abs(v0[i]) > largest:#{
3443 largest = abs(v0[i])
3444 major_axis = i
3445 #}
3446 #}
3447
3448 v1 = Vector((0,0,0))
3449 v1[major_axis] = 1.0
3450
3451 tx = Vector((0,0,0))
3452 ty = Vector((0,0,0))
3453
3454 cv_tangent_basis( v1, tx, ty )
3455 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
3456 l = v0[ major_axis ] - r*2
3457
3458 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
3459 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
3460
3461 colour = [0.2,0.2,0.2]
3462 colour[major_axis] = 0.5
3463
3464 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
3465 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
3466 cv_draw_line( p0+tx* r, p1+tx* r, colour )
3467 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
3468 cv_draw_line( p0+ty* r, p1+ty* r, colour )
3469 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
3470 #}
3471 else:#{
3472 continue
3473 #}
3474
3475 center = obj.matrix_world @ c
3476 if bone.SR_data.cone_constraint:#{
3477 vx = Vector([bone.SR_data.conevx[_] for _ in range(3)])
3478 vy = Vector([bone.SR_data.conevy[_] for _ in range(3)])
3479 va = Vector([bone.SR_data.coneva[_] for _ in range(3)])
3480 draw_cone_twist( center, vx, vy, va )
3481 #}
3482 #}
3483 #}
3484
3485 def cv_ent_gate( obj ):
3486 #{
3487 global cv_view_verts, cv_view_colours
3488
3489 if obj.type != 'MESH': return
3490
3491 mesh_data = obj.data.SR_data.ent_gate[0]
3492 data = obj.SR_data.ent_gate[0]
3493 dims = mesh_data.dimensions
3494
3495 vs = [None]*9
3496 c = Vector((0,0,dims[2]))
3497
3498 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
3499 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
3500 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
3501 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
3502 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
3503 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
3504 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
3505 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
3506 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
3507
3508 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
3509
3510 r3d = bpy.context.area.spaces.active.region_3d
3511
3512 p0 = r3d.view_matrix.inverted().translation
3513 v0 = (obj.matrix_world@Vector((0,0,0))) - p0
3514 v1 = obj.matrix_world.to_3x3() @ Vector((0,1,0))
3515
3516 if v0.dot(v1) > 0.0: cc = (0,1,0)
3517 else: cc = (1,0,0)
3518
3519 for l in indices:#{
3520 v0 = vs[l[0]]
3521 v1 = vs[l[1]]
3522 cv_view_verts += [(v0[0],v0[1],v0[2])]
3523 cv_view_verts += [(v1[0],v1[1],v1[2])]
3524 cv_view_colours += [cc,cc]
3525 #}
3526
3527 sw = (0.4,0.4,0.4)
3528 if data.target != None:
3529 cv_draw_arrow( obj.location, data.target.location, sw )
3530 #}
3531
3532 def cv_ent_volume( obj ):
3533 #{
3534 global cv_view_verts, cv_view_colours
3535
3536 data = obj.SR_data.ent_volume[0]
3537
3538 if data.subtype == '0':#{
3539 cv_draw_ucube( obj.matrix_world, (0,1,0) )
3540
3541 if data.target:#{
3542 cv_draw_line( obj.location, data.target.location, (0,1,0) )
3543 #}
3544 #}
3545 elif data.subtype == '1':#{
3546 cv_draw_ucube( obj.matrix_world, (1,1,0) )
3547
3548 if data.target:#{
3549 cv_draw_line( obj.location, data.target.location, (1,1,0) )
3550 #}
3551 #}
3552 #}
3553
3554 def dijkstra( graph, start_node, target_node ):
3555 #{
3556 unvisited = [_ for _ in graph]
3557 shortest_path = {}
3558 previous_nodes = {}
3559
3560 for n in unvisited:
3561 shortest_path[n] = 9999999.999999
3562 shortest_path[start_node] = 0
3563
3564 while unvisited:#{
3565 current_min_node = None
3566 for n in unvisited:#{
3567 if current_min_node == None:
3568 current_min_node = n
3569 elif shortest_path[n] < shortest_path[current_min_node]:
3570 current_min_node = n
3571 #}
3572
3573 for branch in graph[current_min_node]:#{
3574 tentative_value = shortest_path[current_min_node]
3575 tentative_value += graph[current_min_node][branch]
3576 if tentative_value < shortest_path[branch]:#{
3577 shortest_path[branch] = tentative_value
3578 previous_nodes[branch] = current_min_node
3579 #}
3580 #}
3581
3582 unvisited.remove(current_min_node)
3583 #}
3584
3585 path = []
3586 node = target_node
3587 while node != start_node:#{
3588 path.append(node)
3589
3590 if node not in previous_nodes: return None
3591 node = previous_nodes[node]
3592 #}
3593
3594 # Add the start node manually
3595 path.append(start_node)
3596 return path
3597 #}
3598
3599 class dij_graph():
3600 #{
3601 def __init__(_,points,graph,subsections):#{
3602 _.points = points
3603 _.graph = graph
3604 _.subsections = subsections
3605 #}
3606 #}
3607
3608 def create_node_graph( curves, gates ):
3609 #{
3610 # add endpoints of curves
3611 graph = {}
3612 route_points = []
3613 subsections = []
3614 point_count = 0
3615 spline_count = 0
3616
3617 for c in range(len(curves)):#{
3618 for s in range(len(curves[c].data.splines)):#{
3619 spline = curves[c].data.splines[s]
3620 l = len(spline.points)
3621 if l < 2: continue
3622
3623 dist = round(spline.calc_length(),2)
3624
3625 ia = point_count
3626 ib = point_count+l-1
3627
3628 graph[ia] = { ib: dist }
3629 graph[ib] = { ia: dist }
3630
3631 for i in range(len(spline.points)):#{
3632 wco = curves[c].matrix_world @ spline.points[i].co
3633 route_points.append(Vector((wco[0],wco[1],wco[2]+0.5)))
3634
3635 previous = ia+i-1
3636 proxima = ia+i+1
3637
3638 if i == 0: previous = -1
3639 if i == len(spline.points)-1: proxima = -1
3640
3641 subsections.append((spline_count,previous,proxima))
3642 point_count += 1
3643 #}
3644
3645 spline_count += 1
3646 #}
3647 #}
3648
3649 # link endpoints
3650 graph_keys = list(graph)
3651 for i in range(len(graph_keys)-1):#{
3652 for j in range(i+1, len(graph_keys)):#{
3653 if i%2==0 and i+1==j: continue
3654
3655 ni = graph_keys[i]
3656 nj = graph_keys[j]
3657 pi = route_points[ni]
3658 pj = route_points[nj]
3659
3660 dist = round((pj-pi).magnitude,2)
3661
3662 if dist < 10.0:#{
3663 graph[ni][nj] = dist
3664 graph[nj][ni] = dist
3665 #}
3666 #}
3667 #}
3668
3669 # add and link gates( by name )
3670 for gate in gates:#{
3671 v1 = gate.matrix_world.to_3x3() @ Vector((0,1,0))
3672 if gate.SR_data.ent_gate[0].target:
3673 v1 = v1 * -1.0
3674
3675 graph[ gate.name ] = {}
3676
3677 for i in range(len(graph_keys)):#{
3678 ni = graph_keys[i]
3679 pi = route_points[ni]
3680
3681 v0 = pi-gate.location
3682 if v0.dot(v1) < 0.0: continue
3683
3684 dist = round(v0.magnitude,2)
3685
3686 if dist < 10.0:#{
3687 graph[ gate.name ][ ni ] = dist
3688 graph[ ni ][ gate.name ] = dist
3689 #}
3690 #}
3691 #}
3692
3693 return dij_graph(route_points,graph,subsections)
3694 #}
3695
3696 def solve_graph( dij, start, end ):
3697 #{
3698 path = dijkstra( dij.graph, end, start )
3699 full = []
3700
3701 if path:#{
3702 for sj in range(1,len(path)-2):#{
3703 i0 = path[sj]
3704 i1 = path[sj+1]
3705 map0 = dij.subsections[i0]
3706 map1 = dij.subsections[i1]
3707
3708 if map0[0] == map1[0]:#{
3709 if map0[1] == -1: direction = 2
3710 else: direction = 1
3711 sent = 0
3712
3713 while True:#{
3714 map0 = dij.subsections[i0]
3715 i1 = map0[direction]
3716 if i1 == -1: break
3717
3718 full.append( i0 )
3719 sent += 1
3720 i0 = i1
3721 if sent > 50: break
3722 #}
3723 #}
3724 else:#{
3725 full.append( i0 )
3726 #}
3727 #}
3728
3729 full.append( path[-2] )
3730 #}
3731 return full
3732 #}
3733
3734 def cv_draw_route( route, dij ):
3735 #{
3736 pole = Vector((0.2,0.2,10))
3737 hat = Vector((1,8,0.2))
3738 cc = (route.SR_data.ent_route[0].colour[0],
3739 route.SR_data.ent_route[0].colour[1],
3740 route.SR_data.ent_route[0].colour[2])
3741
3742 cv_draw_ucube(route.matrix_world,cc,Vector((0.5,-7.5,6)),\
3743 Vector((0,-6.5,5.5)))
3744 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5, 0.5,0)) )
3745 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5,-13.5,0)) )
3746 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5, 12)) )
3747 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5,-1)) )
3748
3749 checkpoints = route.SR_data.ent_route[0].gates
3750
3751 for i in range(len(checkpoints)):#{
3752 gi = checkpoints[i].target
3753 gj = checkpoints[(i+1)%len(checkpoints)].target
3754
3755 if gi:#{
3756 dest = gi.SR_data.ent_gate[0].target
3757 if dest:
3758 cv_draw_line_dotted( gi.location, dest.location, cc )
3759 gi = dest
3760 #}
3761
3762 if gi==gj: continue # error?
3763 if not gi or not gj: continue
3764
3765 path = solve_graph( dij, gi.name, gj.name )
3766
3767 if path:#{
3768 cv_draw_arrow(gi.location,dij.points[path[0]],cc,1.5)
3769 cv_draw_arrow(dij.points[path[len(path)-1]],gj.location,cc,1.5)
3770 for j in range(len(path)-1):#{
3771 i0 = path[j]
3772 i1 = path[j+1]
3773 o0 = dij.points[ i0 ]
3774 o1 = dij.points[ i1 ]
3775 cv_draw_arrow(o0,o1,cc,1.5)
3776 #}
3777 #}
3778 else:#{
3779 cv_draw_line_dotted( gi.location, gj.location, cc )
3780 #}
3781 #}
3782 #}
3783
3784 def cv_draw():
3785 #{
3786 global cv_view_shader
3787 global cv_view_verts
3788 global cv_view_colours
3789 global cv_view_course_i
3790
3791 cv_view_course_i = 0
3792 cv_view_verts = []
3793 cv_view_colours = []
3794
3795 cv_view_shader.bind()
3796 gpu.state.depth_mask_set(False)
3797 gpu.state.line_width_set(2.0)
3798 gpu.state.face_culling_set('BACK')
3799 gpu.state.depth_test_set('LESS')
3800 gpu.state.blend_set('NONE')
3801
3802 route_gates = []
3803 route_curves = []
3804 routes = []
3805
3806 for obj in bpy.context.collection.objects:#{
3807 if obj.type == 'ARMATURE':#{
3808 if obj.data.pose_position == 'REST':
3809 draw_skeleton_helpers( obj )
3810 #}
3811 else:#{
3812 ent_type = obj_ent_type( obj )
3813
3814 if ent_type == 'ent_gate':#{
3815 cv_ent_gate( obj )
3816 route_gates += [obj]
3817 #}
3818 elif ent_type == 'ent_route_node':#{
3819 if obj.type == 'CURVE':#{
3820 route_curves += [obj]
3821 #}
3822 #}
3823 elif ent_type == 'ent_route':
3824 routes += [obj]
3825 elif ent_type == 'ent_volume':#{
3826 cv_ent_volume( obj )
3827 #}
3828 elif ent_type == 'ent_audio':#{
3829 if obj.SR_data.ent_audio[0].flag_3d:
3830 cv_draw_sphere( obj.location, obj.scale[0], (1,1,0) )
3831 #}
3832 elif ent_type == 'ent_font':#{
3833 data = obj.SR_data.ent_font[0]
3834
3835 for i in range(len(data.variants)):#{
3836 sub = data.variants[i].mesh
3837 if not sub: continue
3838
3839 for ch in data.glyphs:#{
3840 mini = (ch.bounds[0],ch.bounds[1])
3841 maxi = (ch.bounds[2]+mini[0],ch.bounds[3]+mini[1])
3842 p0 = sub.matrix_world @ Vector((mini[0],0.0,mini[1]))
3843 p1 = sub.matrix_world @ Vector((maxi[0],0.0,mini[1]))
3844 p2 = sub.matrix_world @ Vector((maxi[0],0.0,maxi[1]))
3845 p3 = sub.matrix_world @ Vector((mini[0],0.0,maxi[1]))
3846
3847 if i == data.variants_index: cc = (0.5,0.5,0.5)
3848 else: cc = (0,0,0)
3849
3850 cv_view_verts += [p0,p1,p1,p2,p2,p3,p3,p0]
3851 cv_view_colours += [cc,cc,cc,cc,cc,cc,cc,cc]
3852 #}
3853 #}
3854 #}
3855 elif ent_type == 'ent_skateshop':#{
3856 cc = (0.0,0.9,0.6)
3857 cc1 = (0.4,0.9,0.2)
3858 cc2 = (0.9,0.6,0.1)
3859
3860 data = obj.SR_data.ent_skateshop[0]
3861 display = data.mark_display
3862 info = data.mark_info
3863 rack = data.mark_rack
3864
3865 rack_cu = Vector((3.15,2.0,0.1))*0.5
3866 rack_co = Vector((0.0,0.0,0.0))
3867 display_cu = Vector((0.3,1.2,0.1))*0.5
3868 display_co = Vector((0.0,0.0,0.1))*0.5
3869 info_cu = Vector((1.2,0.01,0.3))*0.5
3870 info_co = Vector((0.0,0.0,0.0))*0.5
3871
3872 if rack:
3873 cv_draw_ucube( rack.matrix_world, cc, rack_cu, rack_co )
3874 if display:
3875 cv_draw_ucube( display.matrix_world, cc1, display_cu, display_co)
3876 if info:
3877 cv_draw_ucube( info.matrix_world, cc2, info_cu, info_co )
3878 #}
3879 elif ent_type == 'ent_swspreview':#{
3880 cc1 = (0.4,0.9,0.2)
3881 data = obj.SR_data.ent_swspreview[0]
3882 display = data.mark_display
3883 display1 = data.mark_display1
3884 display_cu = Vector((0.3,1.2,0.1))*0.5
3885 display_co = Vector((0.0,0.0,0.1))*0.5
3886 if display:
3887 cv_draw_ucube( display.matrix_world, cc1, display_cu, display_co)
3888 if display1:
3889 cv_draw_ucube(display1.matrix_world, cc1, display_cu, display_co)
3890 #}
3891 elif ent_type == 'ent_menuitem':#{
3892 for i,col in enumerate(obj.users_collection):#{
3893 colour32 = hash_djb2( col.name )
3894 r = pow(((colour32 ) & 0xff) / 255.0, 2.2 )
3895 g = pow(((colour32>>8 ) & 0xff) / 255.0, 2.2 )
3896 b = pow(((colour32>>16) & 0xff) / 255.0, 2.2 )
3897 cc = (r,g,b)
3898 vs = [None for _ in range(8)]
3899 scale = i*0.02
3900 for j in range(8):#{
3901 v0 = Vector([(obj.bound_box[j][z]+\
3902 ((-1.0 if obj.bound_box[j][z]<0.0 else 1.0)*scale)) \
3903 for z in range(3)])
3904 vs[j] = obj.matrix_world @ v0
3905 #}
3906 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
3907 (0,4),(1,5),(2,6),(3,7)]
3908 for l in indices:#{
3909 v0 = vs[l[0]]
3910 v1 = vs[l[1]]
3911 cv_view_verts += [(v0[0],v0[1],v0[2])]
3912 cv_view_verts += [(v1[0],v1[1],v1[2])]
3913 cv_view_colours += [cc,cc]
3914 #}
3915 #}
3916 cv_draw_lines()
3917 cc = (1.0,1.0,1.0)
3918 data = obj.SR_data.ent_menuitem[0]
3919 if data.tipo == '4':#{
3920 if data.slider_minloc and data.slider_maxloc:#{
3921 v0 = data.slider_minloc.location
3922 v1 = data.slider_maxloc.location
3923 cv_draw_line( v0, v1, cc )
3924 #}
3925 #}
3926
3927 colour32 = hash_djb2(obj.name)
3928 r = ((colour32 ) & 0xff) / 255.0
3929 g = ((colour32>>8 ) & 0xff) / 255.0
3930 b = ((colour32>>16) & 0xff) / 255.0
3931 cc = (r,g,b)
3932 origin = obj.location + (Vector((r,g,b))*2.0-Vector((1.0,1.0,1.0)))\
3933 * 0.04
3934
3935 size = 0.01
3936
3937 if data.tipo != '0':#{
3938 if data.tipo == '4':#{
3939 if data.link0:#{
3940 cv_draw_arrow( origin, data.link0.location, cc, size )
3941 #}
3942 if data.link1:#{
3943 cv_draw_arrow( origin, data.link1.location, cc, size )
3944 #}
3945 #}
3946 else:#{
3947 if data.link0:#{
3948 cv_draw_arrow( origin, data.link0.location, cc, size )
3949 #}
3950 if data.link1:#{
3951 cv_draw_arrow( origin, data.link1.location, cc, size )
3952 #}
3953 if data.link2:#{
3954 cv_draw_arrow( origin, data.link2.location, cc, size )
3955 #}
3956 if data.link3:#{
3957 cv_draw_arrow( origin, data.link3.location, cc, size )
3958 #}
3959 #}
3960 #}
3961 #}
3962 #}
3963 #}
3964
3965 dij = create_node_graph( route_curves, route_gates )
3966
3967 #cv_draw_route_map( route_nodes )
3968 for route in routes:#{
3969 cv_draw_route( route, dij )
3970 #}
3971
3972 cv_draw_lines()
3973 return
3974 #}
3975
3976 classes = [ SR_INTERFACE, SR_MATERIAL_PANEL,\
3977 SR_COLLECTION_SETTINGS, SR_SCENE_SETTINGS, \
3978 SR_COMPILE, SR_COMPILE_THIS, SR_MIRROR_BONE_X,\
3979 \
3980 SR_OBJECT_ENT_GATE, SR_MESH_ENT_GATE, SR_OBJECT_ENT_SPAWN, \
3981 SR_OBJECT_ENT_ROUTE_ENTRY, SR_UL_ROUTE_NODE_LIST, \
3982 SR_OBJECT_ENT_ROUTE, SR_OT_ROUTE_LIST_NEW_ITEM,\
3983 SR_OT_GLYPH_LIST_NEW_ITEM, SR_OT_GLYPH_LIST_DEL_ITEM,\
3984 SR_OT_GLYPH_LIST_MOVE_ITEM,\
3985 SR_OT_AUDIO_LIST_NEW_ITEM,SR_OT_AUDIO_LIST_DEL_ITEM,\
3986 SR_OT_FONT_VARIANT_LIST_NEW_ITEM,SR_OT_FONT_VARIANT_LIST_DEL_ITEM,\
3987 SR_OT_COPY_ENTITY_DATA, \
3988 SR_OBJECT_ENT_VOLUME, \
3989 SR_UL_AUDIO_LIST, SR_OBJECT_ENT_AUDIO_FILE_ENTRY,\
3990 SR_OT_ROUTE_LIST_DEL_ITEM,\
3991 SR_OBJECT_ENT_AUDIO,SR_OBJECT_ENT_MARKER,SR_OBJECT_ENT_GLYPH,\
3992 SR_OBJECT_ENT_FONT_VARIANT,
3993 SR_OBJECT_ENT_GLYPH_ENTRY,\
3994 SR_UL_FONT_VARIANT_LIST,SR_UL_FONT_GLYPH_LIST,\
3995 SR_OBJECT_ENT_FONT,SR_OBJECT_ENT_TRAFFIC,SR_OBJECT_ENT_SKATESHOP,\
3996 SR_OBJECT_ENT_WORKSHOP_PREVIEW,SR_OBJECT_ENT_MENU_ITEM,\
3997 \
3998 SR_OBJECT_PROPERTIES, SR_LIGHT_PROPERTIES, SR_BONE_PROPERTIES,
3999 SR_MESH_PROPERTIES, SR_MATERIAL_PROPERTIES \
4000 ]
4001
4002 def register():
4003 #{
4004 for c in classes:
4005 bpy.utils.register_class(c)
4006
4007 bpy.types.Scene.SR_data = \
4008 bpy.props.PointerProperty(type=SR_SCENE_SETTINGS)
4009 bpy.types.Collection.SR_data = \
4010 bpy.props.PointerProperty(type=SR_COLLECTION_SETTINGS)
4011
4012 bpy.types.Object.SR_data = \
4013 bpy.props.PointerProperty(type=SR_OBJECT_PROPERTIES)
4014 bpy.types.Light.SR_data = \
4015 bpy.props.PointerProperty(type=SR_LIGHT_PROPERTIES)
4016 bpy.types.Bone.SR_data = \
4017 bpy.props.PointerProperty(type=SR_BONE_PROPERTIES)
4018 bpy.types.Mesh.SR_data = \
4019 bpy.props.PointerProperty(type=SR_MESH_PROPERTIES)
4020 bpy.types.Material.SR_data = \
4021 bpy.props.PointerProperty(type=SR_MATERIAL_PROPERTIES)
4022
4023 global cv_view_draw_handler
4024 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
4025 cv_draw,(),'WINDOW','POST_VIEW')
4026 #}
4027
4028 def unregister():
4029 #{
4030 for c in classes:
4031 bpy.utils.unregister_class(c)
4032
4033 global cv_view_draw_handler
4034 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
4035 #}
4036
4037 # ---------------------------------------------------------------------------- #
4038 # #
4039 # QOI encoder #
4040 # #
4041 # ---------------------------------------------------------------------------- #
4042 # #
4043 # Transliteration of: #
4044 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
4045 # #
4046 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
4047 # SPDX-License-Identifier: MIT #
4048 # QOI - The "Quite OK Image" format for fast, lossless image compression #
4049 # #
4050 # ---------------------------------------------------------------------------- #
4051
4052 class qoi_rgba_t(Structure):
4053 #{
4054 _pack_ = 1
4055 _fields_ = [("r",c_uint8),
4056 ("g",c_uint8),
4057 ("b",c_uint8),
4058 ("a",c_uint8)]
4059 #}
4060
4061 QOI_OP_INDEX = 0x00 # 00xxxxxx
4062 QOI_OP_DIFF = 0x40 # 01xxxxxx
4063 QOI_OP_LUMA = 0x80 # 10xxxxxx
4064 QOI_OP_RUN = 0xc0 # 11xxxxxx
4065 QOI_OP_RGB = 0xfe # 11111110
4066 QOI_OP_RGBA = 0xff # 11111111
4067
4068 QOI_MASK_2 = 0xc0 # 11000000
4069
4070 def qoi_colour_hash( c ):
4071 #{
4072 return c.r*3 + c.g*5 + c.b*7 + c.a*11
4073 #}
4074
4075 def qoi_eq( a, b ):
4076 #{
4077 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
4078 #}
4079
4080 def qoi_32bit( v ):
4081 #{
4082 return bytearray([ (0xff000000 & v) >> 24, \
4083 (0x00ff0000 & v) >> 16, \
4084 (0x0000ff00 & v) >> 8, \
4085 (0x000000ff & v) ])
4086 #}
4087
4088 def qoi_encode( img ):
4089 #{
4090 data = bytearray()
4091
4092 print(F"{' ':<30}",end='\r')
4093 print(F"[QOI] Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]",end='\r')
4094
4095 index = [ qoi_rgba_t() for _ in range(64) ]
4096
4097 # Header
4098 #
4099 data.extend( bytearray(c_uint32(0x66696f71)) )
4100 data.extend( qoi_32bit( img.size[0] ) )
4101 data.extend( qoi_32bit( img.size[1] ) )
4102 data.extend( bytearray(c_uint8(4)) )
4103 data.extend( bytearray(c_uint8(0)) )
4104
4105 run = 0
4106 px_prev = qoi_rgba_t()
4107 px_prev.r = c_uint8(0)
4108 px_prev.g = c_uint8(0)
4109 px_prev.b = c_uint8(0)
4110 px_prev.a = c_uint8(255)
4111
4112 px = qoi_rgba_t()
4113 px.r = c_uint8(0)
4114 px.g = c_uint8(0)
4115 px.b = c_uint8(0)
4116 px.a = c_uint8(255)
4117
4118 px_len = img.size[0] * img.size[1]
4119 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
4120
4121 for px_pos in range( px_len ): #{
4122 idx = px_pos * img.channels
4123 nc = img.channels-1
4124
4125 px.r = paxels[idx+min(0,nc)]
4126 px.g = paxels[idx+min(1,nc)]
4127 px.b = paxels[idx+min(2,nc)]
4128 px.a = paxels[idx+min(3,nc)]
4129
4130 if qoi_eq( px, px_prev ): #{
4131 run += 1
4132
4133 if (run == 62) or (px_pos == px_len-1): #{
4134 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
4135 run = 0
4136 #}
4137 #}
4138 else: #{
4139 if run > 0: #{
4140 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
4141 run = 0
4142 #}
4143
4144 index_pos = qoi_colour_hash(px) % 64
4145
4146 if qoi_eq( index[index_pos], px ): #{
4147 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
4148 #}
4149 else: #{
4150 index[ index_pos ].r = px.r
4151 index[ index_pos ].g = px.g
4152 index[ index_pos ].b = px.b
4153 index[ index_pos ].a = px.a
4154
4155 if px.a == px_prev.a: #{
4156 vr = int(px.r) - int(px_prev.r)
4157 vg = int(px.g) - int(px_prev.g)
4158 vb = int(px.b) - int(px_prev.b)
4159
4160 vg_r = vr - vg
4161 vg_b = vb - vg
4162
4163 if (vr > -3) and (vr < 2) and\
4164 (vg > -3) and (vg < 2) and\
4165 (vb > -3) and (vb < 2):
4166 #{
4167 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
4168 data.extend( bytearray( c_uint8(op) ))
4169 #}
4170 elif (vg_r > -9) and (vg_r < 8) and\
4171 (vg > -33) and (vg < 32 ) and\
4172 (vg_b > -9) and (vg_b < 8):
4173 #{
4174 op = QOI_OP_LUMA | (vg+32)
4175 delta = (vg_r+8) << 4 | (vg_b + 8)
4176 data.extend( bytearray( c_uint8(op) ) )
4177 data.extend( bytearray( c_uint8(delta) ))
4178 #}
4179 else: #{
4180 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
4181 data.extend( bytearray( c_uint8(px.r) ))
4182 data.extend( bytearray( c_uint8(px.g) ))
4183 data.extend( bytearray( c_uint8(px.b) ))
4184 #}
4185 #}
4186 else: #{
4187 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
4188 data.extend( bytearray( c_uint8(px.r) ))
4189 data.extend( bytearray( c_uint8(px.g) ))
4190 data.extend( bytearray( c_uint8(px.b) ))
4191 data.extend( bytearray( c_uint8(px.a) ))
4192 #}
4193 #}
4194 #}
4195
4196 px_prev.r = px.r
4197 px_prev.g = px.g
4198 px_prev.b = px.b
4199 px_prev.a = px.a
4200 #}
4201
4202 # Padding
4203 for i in range(7):
4204 data.extend( bytearray( c_uint8(0) ))
4205 data.extend( bytearray( c_uint8(1) ))
4206 bytearray_align_to( data, 16, b'\x00' )
4207
4208 return data
4209 #}