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