Merge: doc: fixed some typos and other misc. corrections
[nit.git] / lib / gamnit / flat / flat_core.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Core services for the `flat` API for 2D games
16 module flat_core
17
18 import glesv2
19 intrude import geometry::points_and_lines # For _x, _y and _z
20 intrude import matrix
21 import matrix::projection
22 import more_collections
23 import performance_analysis
24
25 import gamnit
26 intrude import gamnit::cameras
27 intrude import gamnit::cameras_cache
28 import gamnit::dynamic_resolution
29
30 # Visible 2D entity in the game world or UI
31 #
32 # Similar to `gamnit::Actor` which is in 3D.
33 #
34 # Each sprite associates a `texture` to the position `center`.
35 # The appearance is modified by `rotation`, `invert_x`,
36 # `scale`, `red`, `green`, `blue` and `alpha`.
37 # These values can be changed at any time and will trigger an update
38 # of the data on the GPU side, having a small performance cost.
39 #
40 # For a sprite to be visible, it must be added to either the world `sprites`
41 # or the `ui_sprites`.
42 # However, an instance of `Sprite` can only belong to a single `SpriteSet`
43 # at a time. The final on-screen position depends on the camera associated
44 # to the `SpriteSet`.
45 #
46 # ~~~
47 # # Load texture and create sprite
48 # var texture = new Texture("path/in/assets.png")
49 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
50 #
51 # # Add sprite to the visible game world
52 # app.sprites.add sprite
53 #
54 # # Extra configuration of the sprite
55 # sprite.rotation = pi/2.0
56 # sprite.scale = 2.0
57 #
58 # # Show only the blue colors
59 # sprite.red = 0.0
60 # sprite.green = 0.0
61 # ~~~
62 #
63 # To add a sprite to the UI it can be anchored to screen borders
64 # with `ui_camera.top_left` and the likes.
65 #
66 # ~~~nitish
67 # # Place it a bit off the top left of the screen
68 # var pos = app.ui_camera.top_left.offset(128.0, -128.0, 0)
69 #
70 # # Load texture and create sprite
71 # var texture = new Texture("path/in/assets.png")
72 # var sprite = new Sprite(texture, pos)
73 #
74 # # Add it to the UI (above world sprites)
75 # app.ui_sprites.add sprite
76 # ~~~
77 class Sprite
78
79 # Texture drawn to screen
80 var texture: Texture is writable(texture_direct=)
81
82 # Texture drawn to screen
83 fun texture=(texture: Texture)
84 do
85 if isset _texture and texture != self.texture then
86 needs_update
87 if texture.root != self.texture.root then needs_remap
88 end
89 texture_direct = texture
90 end
91
92 # Center position of this sprite in world coordinates
93 var center: Point3d[Float] is writable(center_direct=), noautoinit
94
95 # Center position of this sprite in world coordinates
96 fun center=(center: Point3d[Float]) is autoinit do
97 if isset _center and center != self.center then
98 needs_update
99 self.center.sprites_remove self
100 end
101
102 center.sprites_add self
103 center_direct = center
104 end
105
106 # Last animation set with `animate`
107 var animation: nullable Animation = null
108
109 # Animation on the shader, if this changes it `needs_remap`
110 private var shader_animation: nullable Animation = null
111
112 # Animation start time, relative to `sprite_set.time`
113 #
114 # At -1.0 if animation started before being assigned a `sprite_set`.
115 private var animation_start = 0.0
116
117 # Number of loops to show `animation`
118 private var animation_loops = 0.0
119
120 # Start the `animation` for `n_loops`, replacing the static `texture`
121 #
122 # By default, if `n_loops` is not set, the animation plays once.
123 # If `n_loops == -1.0` then the animation loops infinitely.
124 # Otherwise, the animation repeats, e.g. it repeats twice and a half
125 # if `n_loops == 2.5`.
126 #
127 # The animation can be stopped using `animate_stop`.
128 fun animate(animation: Animation, n_loops: nullable Float)
129 do
130 if not animation.valid then print_error "{class_name}::animate: invalid animation {animation}"
131
132 var shader_animation = shader_animation
133 if shader_animation == null or animation.frames.first.root != shader_animation.frames.first.root then
134 # Resort with the new animation texture
135 needs_remap
136 else
137 needs_update
138 end
139
140 var sprite_set = sprite_set
141 animation_start = if sprite_set != null then sprite_set.time else -1.0
142 animation_loops = n_loops or else 1.0
143 self.shader_animation = animation
144 self.animation = animation
145 end
146
147 # Stop any active `animation` to display the static `texture`
148 fun animate_stop
149 do
150 if animation == null then return
151 needs_update
152 animation = null
153 end
154
155 # Rotation on the Z axis, positive values turn counterclockwise
156 var rotation = 0.0 is writable(rotation_direct=)
157
158 # Rotation on the Z axis, positive values turn counterclockwise
159 fun rotation=(value: Float)
160 do
161 if isset _rotation and value != rotation then needs_update
162 rotation_direct = value
163 end
164
165 # Mirror `texture` horizontally, inverting each pixel on the X axis
166 var invert_x = false is writable(invert_x_direct=)
167
168 # Mirror `texture` horizontally, inverting each pixel on the X axis
169 fun invert_x=(value: Bool)
170 do
171 if isset _invert_x and value != invert_x then needs_update
172 invert_x_direct = value
173 end
174
175 # Scale applied to this sprite
176 #
177 # The basic size of `self` depends on the size in pixels of `texture`.
178 var scale = 1.0 is writable(scale_direct=)
179
180 # Scale applied to this sprite
181 #
182 # The basic size of `self` depends on the size in pixels of `texture`.
183 fun scale=(value: Float)
184 do
185 if isset _scale and value != scale then needs_update
186 scale_direct = value
187 end
188
189 # Red tint applied to `texture` on draw
190 fun red: Float do return tint[0]
191
192 # Red tint applied to `texture` on draw
193 fun red=(value: Float)
194 do
195 if isset _tint and value != red then needs_update
196 tint[0] = value
197 end
198
199 # Green tint applied to `texture` on draw
200 fun green: Float do return tint[1]
201
202 # Green tint applied to `texture` on draw
203 fun green=(value: Float)
204 do
205 if isset _tint and value != green then needs_update
206 tint[1] = value
207 end
208
209 # Blue tint applied to `texture` on draw
210 fun blue: Float do return tint[2]
211
212 # Blue tint applied to `texture` on draw
213 fun blue=(value: Float)
214 do
215 if isset _tint and value != blue then needs_update
216 tint[2] = value
217 end
218
219 # Transparency applied to `texture` on draw
220 fun alpha: Float do return tint[3]
221
222 # Transparency applied to `texture` on draw
223 fun alpha=(value: Float)
224 do
225 if isset _tint and value != alpha then needs_update
226 tint[3] = value
227 end
228
229 # Tint applied to `texture` on draw
230 #
231 # Alternative to the accessors `red, green, blue & alpha`.
232 # Changes inside the array do not automatically set `needs_update`.
233 #
234 # Require: `tint.length == 4`
235 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct=)
236
237 # Tint applied to `texture` on draw, see `tint`
238 fun tint=(value: Array[Float])
239 do
240 if isset _tint and value != tint then needs_update
241 tint_direct = value
242 end
243
244 # Draw order, higher values cause this sprite to be drawn latter
245 #
246 # Change this value to avoid artifacts when drawing non-opaque sprites.
247 # In general, sprites with a non-opaque `texture` and sprites closer to
248 # the camera should have a higher value to be drawn last.
249 #
250 # Sprites sharing a `draw_order` are drawn in the same pass.
251 # The sprite to sprite draw order is undefined and may change when adding
252 # and removing sprites, or changing their attributes.
253 #
254 # ### Warning
255 #
256 # Changing this value may have a negative performance impact if there are
257 # many different `draw_order` values across many sprites.
258 # Sprites sharing some attributes are drawn as group to reduce
259 # the communication overhead between the CPU and GPU,
260 # and changing `draw_order` may break up large groups into smaller groups.
261 var draw_order = 0 is writable(draw_order_direct=)
262
263 # Set draw order, see `draw_order`
264 fun draw_order=(value: Int)
265 do
266 if isset _draw_order and value != draw_order then needs_remap
267 draw_order_direct = value
268 end
269
270 # Is this sprite static and added in bulk?
271 #
272 # Set to `true` to give a hint to the framework that this sprite won't
273 # change often and that it is added in bulk with other static sprites.
274 # This value can be ignored in the prototyping phase of a game and
275 # added only when better performance are needed.
276 var static = false is writable(static_direct=)
277
278 # Is this sprite static and added in bulk? see `static`
279 fun static=(value: Bool)
280 do
281 if isset _static and value != static then needs_remap
282 static_direct = value
283 end
284
285 # Request an update on the CPU
286 #
287 # This is called automatically on modification of any value of `Sprite`.
288 # However, it can still be set manually if a modification can't be
289 # detected or by subclasses.
290 fun needs_update
291 do
292 var c = context
293 if c == null then return
294 if c.last_sprite_to_update == self then return
295 c.sprites_to_update.add self
296 c.last_sprite_to_update = self
297 end
298
299 # Request a resorting of this sprite in its sprite list
300 #
301 # Resorting is required when `static` or the root of `texture` changes.
302 # This is called automatically when such changes are detected.
303 # However, it can still be set manually if a modification can't be
304 # detected or by subclasses.
305 fun needs_remap
306 do
307 var l = sprite_set
308 if l != null then l.sprites_to_remap.add self
309 end
310
311 # Current context to which `self` was sorted
312 private var context: nullable SpriteContext = null
313
314 # Index in `context`
315 private var context_index: Int = -1
316
317 # Current context to which `self` belongs
318 private var sprite_set: nullable SpriteSet = null
319 end
320
321 # Animation for sprites, set with `Sprite.animate`
322 #
323 # Two main services create animations:
324 # * The constructors accepts an array of textures and the number of frames per
325 # seconds: `new Animation(array_of_subtextures, 10.0)`
326 # * The method `Texture::to_animation` uses the whole texture
327 # dividing it in frames either on X or Y:
328 # `new Texture("path/in/assets.png").to_animation(30.0, 0, 12)`
329 class Animation
330
331 # Frames composing this animation
332 #
333 # All frames must share the same `Texture::root`, be on a vertical or
334 # horizontal line, be spaced equally and share the same dimensions.
335 var frames: SequenceRead[Texture]
336
337 # Frames per seconds, a higher value makes this animation faster
338 #
339 # The animation speed is also affected by `SpriteSet::time_mod`.
340 var fps: Float
341
342 # Are the `frames` valid for an animation? (see the requirements in `frames`)
343 var valid: Bool is lazy do
344 var r: nullable RootTexture = null
345 for f in frames do
346 if r == null then
347 r = f.root
348 else
349 if r != f.root then return false
350 end
351 end
352
353 # TODO check for line, constant distance, and same aspect ratio.
354
355 return true
356 end
357 end
358
359 redef class App
360 # Default graphic program to draw `sprites`
361 private var simple_2d_program = new Simple2dProgram is lazy
362
363 # Camera for world `sprites` and `depth::actors` with perspective
364 #
365 # By default, the camera is configured to a height of 1080 units
366 # of world coordinates at `z == 0.0`.
367 var world_camera: EulerCamera is lazy do
368 var camera = new EulerCamera(app.display.as(not null))
369
370 # Aim for full HD pixel resolution at level 0
371 camera.reset_height 1080.0
372 camera.near = 10.0
373
374 return camera
375 end
376
377 # Camera for `ui_sprites` using an orthogonal view
378 var ui_camera = new UICamera(app.display.as(not null)) is lazy
379
380 # World sprites drawn as seen by `world_camera`
381 var sprites = new SpriteSet
382
383 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
384 var ui_sprites = new SpriteSet
385
386 # Main method to refine in clients to update game logic and `sprites`
387 fun update(dt: Float) do end
388
389 # Display `texture` as a splash screen
390 #
391 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
392 fun show_splash_screen(texture: Texture)
393 do
394 texture.load
395
396 var splash = new Sprite(texture, ui_camera.center.offset(0.0, 0.0, 0.0))
397 ui_sprites.add splash
398
399 var display = display
400 assert display != null
401 glClear gl_COLOR_BUFFER_BIT
402
403 ui_camera.reset_height 1080.0
404 glViewport(0, 0, display.width, display.height)
405 frame_core_ui_sprites display
406 display.flip
407
408 ui_sprites.remove splash
409 end
410
411 # ---
412 # Support and implementation
413
414 # Main clock used to count each frame `dt`, lapsed for `update` only
415 private var clock = new Clock is lazy
416
417 # Performance clock to for `frame_core_draw` operations
418 private var perf_clock_main = new Clock
419
420 # Second performance clock for smaller operations
421 private var perf_clock_sprites = new Clock is lazy
422
423 redef fun create_gamnit
424 do
425 super
426 create_flat
427 end
428
429 # Prepare the flat framework services
430 fun create_flat
431 do
432 var display = display
433 assert display != null
434
435 assert glGetError == gl_NO_ERROR
436
437 # Prepare program
438 var program = simple_2d_program
439 program.compile_and_link
440
441 var gamnit_error = program.error
442 assert gamnit_error == null else print_error gamnit_error
443
444 # Enable blending
445 gl.capabilities.blend.enable
446 glBlendFunc(gl_ONE, gl_ONE_MINUS_SRC_ALPHA)
447
448 # Enable depth test
449 gl.capabilities.depth_test.enable
450 glDepthFunc gl_LEQUAL
451 glDepthMask true
452
453 # Prepare viewport and background color
454 glViewport(0, 0, display.width, display.height)
455 glClearColor(0.0, 0.0, 0.0, 1.0)
456
457 assert glGetError == gl_NO_ERROR
458
459 # Prepare to draw
460 for tex in all_root_textures do
461 tex.load
462 gamnit_error = tex.error
463 if gamnit_error != null then print_error gamnit_error
464
465 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
466 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
467 end
468
469 sprites.reset
470 ui_sprites.reset
471 end
472
473 redef fun on_stop
474 do
475 super
476
477 # Close gamnit
478 var display = display
479 if display != null then display.close
480 end
481
482 redef fun on_resize(display)
483 do
484 super
485
486 world_camera.mvp_matrix_cache = null
487 ui_camera.mvp_matrix_cache = null
488
489 # Update all sprites in the UI
490 for sprite in ui_sprites do sprite.needs_update
491 end
492
493 redef fun on_resume
494 do
495 clock.lapse
496 super
497 end
498
499 redef fun frame_core(display)
500 do
501 # Check errors
502 assert glGetError == gl_NO_ERROR
503
504 # Update game logic and set sprites
505 perf_clock_main.lapse
506 var dt = clock.lapse.to_f
507 update dt
508 frame_dt = dt
509 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
510
511 # Draw and flip screen
512 frame_core_draw display
513 display.flip
514
515 # Check errors
516 assert glGetError == gl_NO_ERROR
517 end
518
519 private var frame_dt = 0.0
520
521 # Draw the whole screen, all `glDraw...` calls should be executed here
522 protected fun frame_core_draw(display: GamnitDisplay)
523 do
524 frame_core_dynamic_resolution_before display
525
526 perf_clock_main.lapse
527 frame_core_world_sprites display
528 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
529
530 frame_core_ui_sprites display
531 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
532
533 frame_core_dynamic_resolution_after display
534 end
535
536 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
537 do
538 var simple_2d_program = app.simple_2d_program
539 simple_2d_program.use
540 simple_2d_program.mvp.uniform camera.mvp_matrix
541
542 sprite_set.time += frame_dt*sprite_set.time_mod
543 simple_2d_program.time.uniform sprite_set.time
544
545 # draw
546 sprite_set.draw
547
548 assert glGetError == gl_NO_ERROR
549 end
550
551 # Draw world sprites from `sprites`
552 protected fun frame_core_world_sprites(display: GamnitDisplay)
553 do
554 frame_core_sprites(display, sprites, world_camera)
555 end
556
557 # Draw UI sprites from `ui_sprites`
558 protected fun frame_core_ui_sprites(display: GamnitDisplay)
559 do
560 # Reset only the depth buffer
561 glClear gl_DEPTH_BUFFER_BIT
562
563 frame_core_sprites(display, ui_sprites, ui_camera)
564 end
565 end
566
567 redef class Texture
568
569 # Vertices coordinates of the base geometry
570 #
571 # Defines the default width and height of related sprites.
572 private var vertices: Array[Float] is lazy do
573 var w = width
574 var h = height
575 return [-0.5*w, 0.5*h, 0.0,
576 0.5*w, 0.5*h, 0.0,
577 -0.5*w, -0.5*h, 0.0,
578 0.5*w, -0.5*h, 0.0]
579 end
580
581 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
582 private var texture_coords: Array[Float] is lazy do
583 var l = offset_left
584 var r = offset_right
585 var b = offset_bottom
586 var t = offset_top
587 return [l, t,
588 r, t,
589 l, b,
590 r, b]
591 end
592
593 # Coordinates of this texture on the `root` texture, inverting the X axis
594 private var texture_coords_invert_x: Array[Float] is lazy do
595 var l = offset_left
596 var r = offset_right
597 var b = offset_bottom
598 var t = offset_top
599 return [r, t,
600 l, t,
601 r, b,
602 l, b]
603 end
604
605 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
606 #
607 # The arguments `x` and `y` set the number of frames in the texture.
608 # Use `x` for an horizontal arrangement or `y` for vertical.
609 # One and only one of the arguments must be different than 0,
610 # as an animation can only be on a line and cannot wrap.
611 fun to_animation(fps: Float, x, y: Int): Animation
612 do
613 assert (x == 0) != (y == 0)
614
615 var n_frames = x.max(y)
616 var frames = new Array[Texture]
617
618 var dx = (x/n_frames).to_f/n_frames.to_f
619 var dy = (y/n_frames).to_f/n_frames.to_f
620 var w = if x == 0 then 1.0 else dx
621 var h = if y == 0 then 1.0 else dy
622 var left = 0.0
623 var top = 0.0
624 for i in n_frames.times do
625 frames.add new RelativeSubtexture(root, left, top, left+w, top+h)
626 left += dx
627 top += dy
628 end
629
630 return new Animation(frames, fps)
631 end
632 end
633
634 # Graphic program to display simple models with a texture, translation, rotation and scale
635 private class Simple2dProgram
636 super GamnitProgramFromSource
637
638 redef var vertex_shader_source = """
639 // Vertex coordinates
640 attribute vec4 coord;
641
642 // Vertex color tint
643 attribute vec4 color;
644
645 // Vertex translation
646 attribute vec4 translation;
647
648 // Vertex scaling
649 attribute float scale;
650
651 // Vertex coordinates on textures
652 attribute vec2 tex_coord;
653
654 // Model view projection matrix
655 uniform mat4 mvp;
656
657 // Current world time, in seconds
658 uniform float time;
659
660 // Rotation matrix
661 attribute vec4 rotation_row0;
662 attribute vec4 rotation_row1;
663 attribute vec4 rotation_row2;
664 attribute vec4 rotation_row3;
665
666 // Animation speed, frames per seconds
667 attribute float a_fps;
668
669 // Number of frames in the animation
670 attribute float a_n_frames;
671
672 // World coordinate of the animation (for aspect ratio)
673 attribute vec2 a_coord;
674
675 // Animation texture coordinates of the first frame
676 attribute vec2 a_tex_coord;
677
678 // Animation texture coordinates difference between frames
679 attribute vec2 a_tex_diff;
680
681 // Animation start time, in reference to `time`
682 attribute float a_start;
683
684 // Number of loops to play of the animation
685 attribute float a_loops;
686
687 mat4 rotation()
688 {
689 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
690 }
691
692 // Output to the fragment shader
693 varying vec4 v_color;
694 varying vec2 v_coord;
695
696 // Is there an active animation?
697 varying float v_animated;
698
699 void main()
700 {
701 vec3 c; // coords
702
703 float end = a_start + a_loops/a_fps*a_n_frames;
704 if (a_fps != 0.0 && (a_loops == -1.0 || time < end)) {
705 // in animation
706 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
707 v_coord = a_tex_coord + a_tex_diff*frame;
708 c = vec3(a_coord, coord.z);
709 v_animated = 1.0;
710 } else {
711 // static
712 v_coord = tex_coord;
713 c = coord.xyz;
714 v_animated = 0.0;
715 }
716
717 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
718 v_color = vec4(color.rgb*color.a, color.a);
719 }
720 """ @ glsl_vertex_shader
721
722 redef var fragment_shader_source = """
723 precision mediump float;
724
725 // Does this object use a texture?
726 uniform bool use_texture;
727
728 // Texture to apply on this object
729 uniform sampler2D texture0;
730
731 // Texture to apply on this object
732 uniform sampler2D animation;
733
734 // Input from the vertex shader
735 varying vec4 v_color;
736 varying vec2 v_coord;
737 varying float v_animated;
738
739 void main()
740 {
741 if (v_animated > 0.5) {
742 gl_FragColor = v_color * texture2D(animation, v_coord);
743 if (gl_FragColor.a <= 0.01) discard;
744 } else if (use_texture) {
745 gl_FragColor = v_color * texture2D(texture0, v_coord);
746 if (gl_FragColor.a <= 0.01) discard;
747 } else {
748 gl_FragColor = v_color;
749 }
750 }
751 """ @ glsl_fragment_shader
752
753 # Vertices coordinates
754 var coord = attributes["coord"].as(AttributeVec4) is lazy
755
756 # Should this program use the texture `texture`?
757 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
758
759 # Visible texture unit
760 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
761
762 # Coordinates on the textures, per vertex
763 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
764
765 # Color tint per vertex
766 var color = attributes["color"].as(AttributeVec4) is lazy
767
768 # Translation applied to each vertex
769 var translation = attributes["translation"].as(AttributeVec4) is lazy
770
771 # Rotation matrix, row 0
772 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
773
774 # Rotation matrix, row 1
775 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
776
777 # Rotation matrix, row 2
778 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
779
780 # Rotation matrix, row 3
781 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
782
783 # Scaling per vertex
784 var scale = attributes["scale"].as(AttributeFloat) is lazy
785
786 # Model view projection matrix
787 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
788
789 # World time, in seconds
790 var time = uniforms["time"].as(UniformFloat) is lazy
791
792 # ---
793 # Animations
794
795 # Texture of all the frames of the animation
796 var animation_texture = uniforms["animation"].as(UniformSampler2D) is lazy
797
798 # Frame per second of the animation
799 var animation_fps = attributes["a_fps"].as(AttributeFloat) is lazy
800
801 # Number of frames in the animation
802 var animation_n_frames = attributes["a_n_frames"].as(AttributeFloat) is lazy
803
804 # Coordinates of each frame (mush be shared by all frames)
805 var animation_coord = attributes["a_coord"].as(AttributeVec2) is lazy
806
807 # Texture coordinates of the first frame
808 var animation_tex_coord = attributes["a_tex_coord"].as(AttributeVec2) is lazy
809
810 # Coordinate difference between each frame
811 var animation_tex_diff = attributes["a_tex_diff"].as(AttributeVec2) is lazy
812
813 # Animation start time, in seconds and in reference to `dt`
814 var animation_start = attributes["a_start"].as(AttributeFloat) is lazy
815
816 # Number of loops of the animation, -1 for infinite
817 var animation_loops = attributes["a_loops"].as(AttributeFloat) is lazy
818 end
819
820 redef class Point3d[N]
821 # ---
822 # Associate each point to its sprites
823
824 private var sprites: nullable Array[Sprite] = null
825
826 private fun sprites_add(sprite: Sprite)
827 do
828 var sprites = sprites
829 if sprites == null then
830 sprites = new Array[Sprite]
831 self.sprites = sprites
832 end
833 sprites.add sprite
834 end
835
836 private fun sprites_remove(sprite: Sprite)
837 do
838 var sprites = sprites
839 assert sprites != null
840 sprites.remove sprite
841 end
842
843 # ---
844 # Notify `sprites` on attribute modification
845
846 private fun needs_update
847 do
848 var sprites = sprites
849 if sprites != null then for s in sprites do s.needs_update
850 end
851
852 redef fun x=(v)
853 do
854 if isset _x and v != x then needs_update
855 super
856 end
857
858 redef fun y=(v)
859 do
860 if isset _y and v != y then needs_update
861 super
862 end
863
864 redef fun z=(v)
865 do
866 if isset _z and v != z then needs_update
867 super
868 end
869 end
870
871 redef class OffsetPoint3d
872 redef fun x=(v)
873 do
874 if isset _x and v != x then needs_update
875 super
876 end
877
878 redef fun y=(v)
879 do
880 if isset _y and v != y then needs_update
881 super
882 end
883
884 redef fun z=(v)
885 do
886 if isset _z and v != z then needs_update
887 super
888 end
889 end
890
891 # Set of sprites sorting them into different `SpriteContext`
892 class SpriteSet
893 super HashSet[Sprite]
894
895 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
896 var time_mod = 1.0 is writable
897
898 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
899 var time = 0.0
900
901 # Map texture then static vs dynamic to a `SpriteContext`
902 private var contexts_map = new HashMap4[RootTexture, nullable RootTexture, Bool, Int, Array[SpriteContext]]
903
904 # Contexts in `contexts_map`, sorted by draw order
905 private var contexts_items = new Array[SpriteContext]
906
907 # Sprites needing resorting in `contexts_map`
908 private var sprites_to_remap = new Array[Sprite]
909
910 # Add a sprite to the appropriate context
911 private fun map_sprite(sprite: Sprite)
912 do
913 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
914
915 # Sort by texture and animation texture
916 var texture = sprite.texture.root
917 var animation = sprite.animation
918 var animation_texture = if animation != null then
919 animation.frames.first.root else null
920 var draw_order = sprite.draw_order
921 var contexts = contexts_map[texture, animation_texture, sprite.static, draw_order]
922
923 var context = null
924 if contexts != null then
925 for c in contexts.reverse_iterator do
926 var size = c.sprites.length + 1
927 if size * 4 <= 0xffff then
928 context = c
929 break
930 end
931 end
932 end
933
934 if context == null then
935 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
936 context = new SpriteContext(texture, animation_texture, usage, draw_order)
937
938 if contexts == null then
939 contexts = new Array[SpriteContext]
940 contexts_map[texture, animation_texture, sprite.static, draw_order] = contexts
941 end
942
943 contexts.add context
944
945 contexts_items.add context
946 sprite_draw_order_sorter.sort(contexts_items)
947 end
948
949 context.sprites.add sprite
950 context.sprites_to_update.add sprite
951 context.last_sprite_to_update = sprite
952
953 sprite.context = context
954 sprite.sprite_set = self
955
956 if animation != null and sprite.animation_start == -1.0 then
957 # Start animation
958 sprite.animation_start = time
959 end
960 end
961
962 # Remove a sprite from its context
963 private fun unmap_sprite(sprite: Sprite)
964 do
965 var context = sprite.context
966 assert context != null
967 context.sprites.remove sprite
968
969 sprite.context = null
970 sprite.sprite_set = null
971 end
972
973 # Draw all sprites by all contexts
974 private fun draw
975 do
976 # Remap sprites that may need to change context
977 for sprite in sprites_to_remap do
978
979 # Skip if it was removed from this set after being modified
980 if sprite.sprite_set != self then continue
981
982 unmap_sprite sprite
983 map_sprite sprite
984 end
985 sprites_to_remap.clear
986
987 # Sort by draw order
988 for context in contexts_items do context.draw
989 end
990
991 redef fun add(e)
992 do
993 if contexts_items.has(e.context) then return
994 map_sprite e
995 super
996 end
997
998 redef fun remove(e)
999 do
1000 super
1001 if e isa Sprite then unmap_sprite e
1002 end
1003
1004 redef fun remove_all(e)
1005 do
1006 if not has(e) then return
1007 remove e
1008 end
1009
1010 redef fun clear
1011 do
1012 for sprite in self do
1013 sprite.context = null
1014 sprite.sprite_set = null
1015 end
1016 super
1017 for c in contexts_items do c.destroy
1018 contexts_map.clear
1019 contexts_items.clear
1020 sprites_to_remap.clear
1021 end
1022
1023 private fun reset
1024 do
1025 for sprite in self do
1026 sprite.context = null
1027 end
1028
1029 for c in contexts_items do c.destroy
1030 contexts_map.clear
1031 contexts_items.clear
1032 sprites_to_remap.clear
1033
1034 for sprite in self do
1035 map_sprite sprite
1036 end
1037 end
1038 end
1039
1040 # Context for calls to `glDrawElements`
1041 #
1042 # Each context has only one `texture` and `usage`, but many sprites.
1043 private class SpriteContext
1044
1045 # ---
1046 # Context config and state
1047
1048 # Only root texture drawn by this context
1049 var texture: nullable RootTexture
1050
1051 # Only animation texture drawn by this context
1052 var animation_texture: nullable RootTexture
1053
1054 # OpenGL ES usage of `buffer_array` and `buffer_element`
1055 var usage: GLBufferUsage
1056
1057 # Draw order shared by all `sprites`
1058 var draw_order: Int
1059
1060 # Sprites drawn by this context
1061 var sprites = new GroupedSprites
1062
1063 # Sprites to update since last `draw`
1064 var sprites_to_update = new Set[Sprite]
1065
1066 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
1067 var last_sprite_to_update: nullable Sprite = null
1068
1069 # Sprites that have been update and for which `needs_update` can be set to false
1070 var updated_sprites = new Array[Sprite]
1071
1072 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
1073 #
1074 # Require: `resize_ratio >= 1.0`
1075 var resize_ratio = 1.2
1076
1077 # ---
1078 # OpenGL ES data
1079
1080 # OpenGL ES buffer name for vertex data
1081 var buffer_array: Int = -1
1082
1083 # OpenGL ES buffer name for indices
1084 var buffer_element: Int = -1
1085
1086 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1087 var buffer_capacity = 0
1088
1089 # C buffers used to pass the data of a single sprite
1090 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
1091 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
1092
1093 # ---
1094 # Constants
1095
1096 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1097 var float_per_vertex: Int is lazy do
1098 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1099 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1100 1 + 1 + # float a_fps, float a_n_frames,
1101 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1102 1 + 1 # float a_start, float a_loops
1103 end
1104
1105 # Number of bytes per vertex of `Simple2dProgram`
1106 var bytes_per_vertex: Int is lazy do
1107 var fs = 4 # sizeof(GL_FLOAT)
1108 return fs * float_per_vertex
1109 end
1110
1111 # Number of bytes per sprite
1112 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
1113
1114 # Number of vertex indices per sprite draw call (2 triangles)
1115 var indices_per_sprite = 6
1116
1117 # ---
1118 # Main services
1119
1120 # Allocate `buffer_array` and `buffer_element`
1121 fun prepare
1122 do
1123 var bufs = glGenBuffers(2)
1124 buffer_array = bufs[0]
1125 buffer_element = bufs[1]
1126
1127 assert glGetError == gl_NO_ERROR
1128 end
1129
1130 # Destroy `buffer_array` and `buffer_element`
1131 fun destroy
1132 do
1133 glDeleteBuffers([buffer_array, buffer_element])
1134 assert glGetError == gl_NO_ERROR
1135
1136 buffer_array = -1
1137 buffer_element = -1
1138 end
1139
1140 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1141 fun resize
1142 do
1143 app.perf_clock_sprites.lapse
1144
1145 # Allocate a bit more space
1146 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
1147
1148 var array_bytes = capacity * bytes_per_sprite
1149 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1150 assert glIsBuffer(buffer_array)
1151 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
1152 assert glGetError == gl_NO_ERROR
1153
1154 # GL_TRIANGLES 6 vertices * sprite
1155 var n_indices = capacity * indices_per_sprite
1156 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
1157 var element_bytes = n_indices * ius
1158 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1159 assert glIsBuffer(buffer_element)
1160 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
1161 assert glGetError == gl_NO_ERROR
1162
1163 buffer_capacity = capacity
1164
1165 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
1166 end
1167
1168 # Update GPU data of `sprite`
1169 fun update_sprite(sprite: Sprite)
1170 do
1171 var context = sprite.context
1172 if context != self then return
1173
1174 var sprite_index = sprite.context_index
1175 assert sprite_index != -1
1176
1177 # Vertices data
1178
1179 var data = local_data_buffer
1180 var o = 0
1181 for v in [0..4[ do
1182 # vec4 translation
1183 data[o+ 0] = sprite.center.x
1184 data[o+ 1] = sprite.center.y
1185 data[o+ 2] = sprite.center.z
1186 data[o+ 3] = 0.0
1187
1188 # vec4 color
1189 data[o+ 4] = sprite.tint[0]
1190 data[o+ 5] = sprite.tint[1]
1191 data[o+ 6] = sprite.tint[2]
1192 data[o+ 7] = sprite.tint[3]
1193
1194 # float scale
1195 data[o+ 8] = sprite.scale
1196
1197 # vec4 coord
1198 data[o+ 9] = sprite.texture.vertices[v*3+0]
1199 data[o+10] = sprite.texture.vertices[v*3+1]
1200 data[o+11] = sprite.texture.vertices[v*3+2]
1201 data[o+12] = 0.0
1202
1203 # vec2 tex_coord
1204 var texture = texture
1205 if texture != null then
1206 var tc = if sprite.invert_x then
1207 sprite.texture.texture_coords_invert_x
1208 else sprite.texture.texture_coords
1209 data[o+13] = tc[v*2+0]
1210 data[o+14] = tc[v*2+1]
1211 end
1212
1213 # mat4 rotation
1214 var rot
1215 if sprite.rotation == 0.0 then
1216 # Cache the matrix at no rotation
1217 rot = once new Matrix.identity(4)
1218 else
1219 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
1220 end
1221 data.fill_from_matrix(rot, o+15)
1222
1223 var animation = sprite.animation
1224 if animation == null then
1225 for i in [31..40] do data[o+i] = 0.0
1226 else
1227 # a_fps
1228 data[o+31] = animation.fps
1229
1230 # a_n_frames
1231 data[o+32] = animation.frames.length.to_f
1232
1233 # a_coord
1234 data[o+33] = animation.frames.first.vertices[v*3+0]
1235 data[o+34] = animation.frames.first.vertices[v*3+1]
1236
1237 # a_tex_coord
1238 var tc = if sprite.invert_x then
1239 animation.frames.first.texture_coords_invert_x
1240 else animation.frames.first.texture_coords
1241 data[o+35] = tc[v*2]
1242 data[o+36] = tc[v*2+1]
1243
1244 # a_tex_diff
1245 var dx = 0.0
1246 var dy = 0.0
1247 if animation.frames.length > 1 then
1248 dx = animation.frames[1].texture_coords[0] - animation.frames[0].texture_coords[0]
1249 dy = animation.frames[1].texture_coords[1] - animation.frames[0].texture_coords[1]
1250 end
1251 data[o+37] = dx
1252 data[o+38] = dy
1253
1254 # a_start
1255 data[o+39] = sprite.animation_start
1256
1257 # a_loops
1258 data[o+40] = sprite.animation_loops
1259 end
1260
1261 o += float_per_vertex
1262 end
1263
1264 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1265 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
1266
1267 var gl_error = glGetError
1268 assert gl_error == gl_NO_ERROR else print_error gl_error
1269
1270 # Element / indices
1271 #
1272 # 0--1
1273 # | /|
1274 # |/ |
1275 # 2--3
1276
1277 var indices = local_indices_buffer
1278 var io = sprite_index*4
1279 indices[0] = io+0
1280 indices[1] = io+2
1281 indices[2] = io+1
1282 indices[3] = io+1
1283 indices[4] = io+2
1284 indices[5] = io+3
1285
1286 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1287 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
1288
1289 assert glGetError == gl_NO_ERROR
1290 end
1291
1292 # Draw all `sprites`
1293 #
1294 # Call `resize` and `update_sprite` as needed before actual draw operation.
1295 #
1296 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1297 fun draw
1298 do
1299 if buffer_array == -1 then prepare
1300
1301 assert buffer_array > 0 and buffer_element > 0 else
1302 print_error "Internal error: {self} was destroyed"
1303 end
1304
1305 # Setup
1306 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1307 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1308
1309 # Resize GPU buffers?
1310 var update_everything = false
1311 if sprites.capacity > buffer_capacity then
1312 # Try to defragment first
1313 var moved = sprites.defragment
1314
1315 if sprites.capacity > buffer_capacity then
1316 # Defragmentation wasn't enough, grow
1317 resize
1318
1319 # We must update everything
1320 update_everything = true
1321 for s in sprites.items do if s != null then sprites_to_update.add s
1322 else
1323 # Just update the moved sprites
1324 for s in moved do sprites_to_update.add s
1325 end
1326 else if sprites.available.not_empty then
1327 # Defragment a bit anyway
1328 # TODO defrag only when there's time left on a frame
1329 var moved = sprites.defragment(1)
1330 for s in moved do sprites_to_update.add s
1331 end
1332
1333 # Update GPU sprites data
1334 if sprites_to_update.not_empty or update_everything then
1335 app.perf_clock_sprites.lapse
1336
1337 if update_everything then
1338 for sprite in sprites.items do if sprite != null then
1339 update_sprite(sprite)
1340 end
1341 else
1342 for sprite in sprites_to_update do update_sprite(sprite)
1343 end
1344
1345 sprites_to_update.clear
1346 last_sprite_to_update = null
1347
1348 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
1349 end
1350
1351 # Update uniforms specific to this context
1352 var texture = texture
1353 app.simple_2d_program.use_texture.uniform texture != null
1354 if texture != null then
1355 glActiveTexture gl_TEXTURE0
1356 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
1357 app.simple_2d_program.texture.uniform 0
1358 end
1359 assert glGetError == gl_NO_ERROR
1360
1361 var animation = animation_texture
1362 if animation != null then
1363 glActiveTexture gl_TEXTURE1
1364 glBindTexture(gl_TEXTURE_2D, animation.gl_texture)
1365 app.simple_2d_program.animation_texture.uniform 1
1366 end
1367 assert glGetError == gl_NO_ERROR
1368
1369 # Configure attributes, in order:
1370 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1371 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1372
1373 var offset = 0
1374 var p = app.simple_2d_program
1375 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1376
1377 var size = 4 # Number of floats
1378 glEnableVertexAttribArray p.translation.location
1379 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1380 offset += size * sizeof_gl_float
1381 assert glGetError == gl_NO_ERROR
1382
1383 size = 4
1384 glEnableVertexAttribArray p.color.location
1385 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1386 offset += size * sizeof_gl_float
1387 assert glGetError == gl_NO_ERROR
1388
1389 size = 1
1390 glEnableVertexAttribArray p.scale.location
1391 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1392 offset += size * sizeof_gl_float
1393 assert glGetError == gl_NO_ERROR
1394
1395 size = 4
1396 glEnableVertexAttribArray p.coord.location
1397 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1398 offset += size * sizeof_gl_float
1399 assert glGetError == gl_NO_ERROR
1400
1401 size = 2
1402 glEnableVertexAttribArray p.tex_coord.location
1403 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1404 offset += size * sizeof_gl_float
1405 assert glGetError == gl_NO_ERROR
1406
1407 size = 4
1408 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1409 if r.is_active then
1410 glEnableVertexAttribArray r.location
1411 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1412 end
1413 offset += size * sizeof_gl_float
1414 assert glGetError == gl_NO_ERROR
1415 end
1416
1417 size = 1
1418 glEnableVertexAttribArray p.animation_fps.location
1419 glVertexAttribPointeri(p.animation_fps.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1420 offset += size * sizeof_gl_float
1421 assert glGetError == gl_NO_ERROR
1422
1423 size = 1
1424 glEnableVertexAttribArray p.animation_n_frames.location
1425 glVertexAttribPointeri(p.animation_n_frames.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1426 offset += size * sizeof_gl_float
1427 assert glGetError == gl_NO_ERROR
1428
1429 size = 2
1430 glEnableVertexAttribArray p.animation_coord.location
1431 glVertexAttribPointeri(p.animation_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1432 offset += size * sizeof_gl_float
1433 assert glGetError == gl_NO_ERROR
1434
1435 size = 2
1436 glEnableVertexAttribArray p.animation_tex_coord.location
1437 glVertexAttribPointeri(p.animation_tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1438 offset += size * sizeof_gl_float
1439 assert glGetError == gl_NO_ERROR
1440
1441 size = 2
1442 glEnableVertexAttribArray p.animation_tex_diff.location
1443 glVertexAttribPointeri(p.animation_tex_diff.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1444 offset += size * sizeof_gl_float
1445 assert glGetError == gl_NO_ERROR
1446
1447 size = 1
1448 glEnableVertexAttribArray p.animation_start.location
1449 glVertexAttribPointeri(p.animation_start.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1450 offset += size * sizeof_gl_float
1451 assert glGetError == gl_NO_ERROR
1452
1453 size = 1
1454 glEnableVertexAttribArray p.animation_loops.location
1455 glVertexAttribPointeri(p.animation_loops.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1456 offset += size * sizeof_gl_float
1457 assert glGetError == gl_NO_ERROR
1458
1459 # Actual draw
1460 for s in sprites.starts, e in sprites.ends do
1461 var l = e-s
1462 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1463 assert glGetError == gl_NO_ERROR
1464 end
1465
1466 # Take down
1467 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1468 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1469 if not attr.is_active then continue
1470 glDisableVertexAttribArray(attr.location)
1471 assert glGetError == gl_NO_ERROR
1472 end
1473
1474 glBindBuffer(gl_ARRAY_BUFFER, 0)
1475 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1476 assert glGetError == gl_NO_ERROR
1477 end
1478 end
1479
1480 # Representation of sprite data on the GPU
1481 #
1482 # The main purpose of this class is to optimize the use of contiguous
1483 # space in GPU memory. Each contiguous memory block can be drawn in a
1484 # single call. The starts index of each block is kept by `starts,
1485 # and the end + 1 by `ends`.
1486 #
1487 # The data can be compressed by a call to `defragment`.
1488 #
1489 # ~~~
1490 # intrude import gamnit::flat
1491 #
1492 # var array = new GroupedArray[String]
1493 # assert array.to_s == ""
1494 #
1495 # array.add "a"
1496 # array.add "b"
1497 # array.add "c"
1498 # array.add "d"
1499 # array.add "e"
1500 # array.add "f"
1501 # assert array.to_s == "[a,b,c,d,e,f]"
1502 # assert array.capacity == 6
1503 #
1504 # array.remove "a"
1505 # assert array.to_s == "[b,c,d,e,f]"
1506 #
1507 # array.remove "b"
1508 # assert array.to_s == "[c,d,e,f]"
1509 #
1510 # array.remove "f"
1511 # assert array.to_s == "[c,d,e]"
1512 #
1513 # array.remove "d"
1514 # assert array.to_s == "[c][e]"
1515 #
1516 # array.add "A"
1517 # assert array.to_s == "[A][c][e]"
1518 #
1519 # array.add "B"
1520 # assert array.to_s == "[A,B,c][e]"
1521 #
1522 # array.remove "e"
1523 # assert array.to_s == "[A,B,c]"
1524 #
1525 # array.add "D"
1526 # assert array.to_s == "[A,B,c,D]"
1527 #
1528 # array.add "E"
1529 # assert array.to_s == "[A,B,c,D,E]"
1530 # assert array.capacity == 6
1531 # assert array.length == 5
1532 #
1533 # array.remove "A"
1534 # array.remove "B"
1535 # array.remove "c"
1536 # array.remove "D"
1537 # array.remove "E"
1538 # assert array.to_s == ""
1539 #
1540 # array.add "a"
1541 # assert array.to_s == "[a]"
1542 # ~~~
1543 private class GroupedArray[E]
1544
1545 # Memory with actual objects, and null in empty slots
1546 var items = new Array[nullable E]
1547
1548 # Number of items in the array
1549 var length = 0
1550
1551 # Number of item slots in the array
1552 fun capacity: Int do return items.length
1553
1554 # List of available slots
1555 var available = new MinHeap[Int].default
1556
1557 # Start index of filled chunks
1558 var starts = new List[Int]
1559
1560 # Index of the spots after filled chunks
1561 var ends = new List[Int]
1562
1563 # Add `item` to the first available slot and return its index
1564 fun add(item: E): Int
1565 do
1566 length += 1
1567
1568 if available.not_empty then
1569 # starts & ends can't be empty
1570
1571 var i = available.take
1572 items[i] = item
1573
1574 if i == starts.first - 1 then
1575 # slot 0 free, 1 taken
1576 starts.first -= 1
1577 else if i == 0 then
1578 # slot 0 and more free
1579 starts.unshift 0
1580 ends.unshift 1
1581 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1582 # merge 2 chunks
1583 ends.remove_at 0
1584 starts.remove_at 1
1585 else
1586 # at end of first chunk
1587 ends.first += 1
1588 end
1589 return i
1590 end
1591
1592 items.add item
1593 if ends.is_empty then
1594 starts.add 0
1595 ends.add 1
1596 else ends.last += 1
1597 return ends.last - 1
1598 end
1599
1600 # Remove the first instance of `item`
1601 fun remove(item: E)
1602 do
1603 var index = items.index_of(item)
1604 remove_at(item, index)
1605 end
1606
1607 # Remove `item` at `index`
1608 fun remove_at(item: E, index: Int)
1609 do
1610 var i = index
1611 length -= 1
1612 items[i] = null
1613
1614 var ii = 0
1615 for s in starts, e in ends do
1616 if s <= i and i < e then
1617 if s == e-1 then
1618 # single item chunk
1619 starts.remove_at ii
1620 ends.remove_at ii
1621
1622 if starts.is_empty then
1623 items.clear
1624 available.clear
1625 return
1626 end
1627 else if e-1 == i then
1628 # last item of chunk
1629 ends[ii] -= 1
1630
1631 else if s == i then
1632 # first item of chunk
1633 starts[ii] += 1
1634 else
1635 # break up chunk
1636 ends.insert(ends[ii], ii+1)
1637 ends[ii] = i
1638 starts.insert(i+1, ii+1)
1639 end
1640
1641 available.add i
1642 return
1643 end
1644 ii += 1
1645 end
1646
1647 abort
1648 end
1649
1650 # Defragment and compress everything into a single chunks beginning at 0
1651 #
1652 # Returns the elements that moved as a list.
1653 #
1654 # ~~~
1655 # intrude import gamnit::flat
1656 #
1657 # var array = new GroupedArray[String]
1658 # array.add "a"
1659 # array.add "b"
1660 # array.add "c"
1661 # array.add "d"
1662 # array.remove "c"
1663 # array.remove "a"
1664 # assert array.to_s == "[b][d]"
1665 #
1666 # var moved = array.defragment
1667 # assert moved.to_s == "[d]"
1668 # assert array.to_s == "[d,b]"
1669 # assert array.length == 2
1670 # assert array.capacity == 2
1671 #
1672 # array.add "e"
1673 # array.add "f"
1674 # assert array.to_s == "[d,b,e,f]"
1675 # ~~~
1676 fun defragment(max: nullable Int): Array[E]
1677 do
1678 app.perf_clock_sprites.lapse
1679 max = max or else length
1680
1681 var moved = new Array[E]
1682 while max > 0 and (starts.length > 1 or starts.first != 0) do
1683 var i = ends.last - 1
1684 var e = items[i]
1685 assert e != null
1686 remove e
1687 add e
1688 moved.add e
1689 max -= 1
1690 end
1691
1692 if starts.length == 1 and starts.first == 0 then
1693 for i in [length..capacity[ do items.pop
1694 available.clear
1695 end
1696
1697 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1698 return moved
1699 end
1700
1701 redef fun to_s
1702 do
1703 var ss = new Array[String]
1704 for s in starts, e in ends do
1705 ss.add "["
1706 for i in [s..e[ do
1707 var item: nullable Object = items[i]
1708 if item == null then item = "null"
1709 ss.add item.to_s
1710 if i != e-1 then ss.add ","
1711 end
1712 ss.add "]"
1713 end
1714 return ss.join
1715 end
1716 end
1717
1718 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1719 private class GroupedSprites
1720 super GroupedArray[Sprite]
1721
1722 redef fun add(item)
1723 do
1724 var index = super
1725 item.context_index = index
1726 return index
1727 end
1728
1729 redef fun remove(item) do remove_at(item, item.context_index)
1730 end
1731
1732 redef class GLfloatArray
1733 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1734 do
1735 dst_offset = dst_offset or else add_index
1736 var mat_len = matrix.width*matrix.height
1737 assert length >= mat_len + dst_offset
1738 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1739 add_index += mat_len
1740 end
1741 end
1742
1743 redef class NativeGLfloatArray
1744 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1745 int i;
1746 for (i = 0; i < len; i ++)
1747 self[i+dst_offset] = (GLfloat)matrix[i];
1748 `}
1749 end
1750
1751 redef class Sys
1752 private var sprite_draw_order_sorter = new DrawOrderComparator is lazy
1753 end
1754
1755 # Sort `SpriteContext` by their `draw_order`
1756 private class DrawOrderComparator
1757 super Comparator
1758
1759 # This class can't set COMPARED because
1760 # `the public property cannot contain the private type...`
1761 #redef type COMPARED: SpriteContext
1762
1763 # Require: `a isa SpriteContext and b isa SpriteContext`
1764 redef fun compare(a, b)
1765 do return a.as(SpriteContext).draw_order <=> b.as(SpriteContext).draw_order
1766 end