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