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