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