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