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