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