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