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