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