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