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