Merge: doc/commands: extract CmdCode superclass
[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 var gl_error = glGetError
436 assert gl_error == gl_NO_ERROR else print_error gl_error
437
438 # Prepare program
439 var program = simple_2d_program
440 program.compile_and_link
441
442 var gamnit_error = program.error
443 assert gamnit_error == null else print_error gamnit_error
444
445 # Enable blending
446 gl.capabilities.blend.enable
447 glBlendFunc(gl_ONE, gl_ONE_MINUS_SRC_ALPHA)
448
449 # Enable depth test
450 gl.capabilities.depth_test.enable
451 glDepthFunc gl_LEQUAL
452 glDepthMask true
453
454 # Prepare viewport and background color
455 glViewport(0, 0, display.width, display.height)
456 glClearColor(0.0, 0.0, 0.0, 1.0)
457
458 gl_error = glGetError
459 assert gl_error == gl_NO_ERROR else print_error gl_error
460
461 # Prepare to draw
462 for tex in all_root_textures do
463 tex.load
464 gamnit_error = tex.error
465 if gamnit_error != null then print_error gamnit_error
466
467 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
468 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
469 end
470
471 sprites.reset
472 ui_sprites.reset
473 end
474
475 redef fun on_stop
476 do
477 super
478
479 # Clean up
480 simple_2d_program.delete
481
482 # Close gamnit
483 var display = display
484 if display != null then display.close
485 end
486
487 redef fun on_resize(display)
488 do
489 super
490
491 world_camera.mvp_matrix_cache = null
492 ui_camera.mvp_matrix_cache = null
493
494 # Update all sprites in the UI
495 for sprite in ui_sprites do sprite.needs_update
496 end
497
498 redef fun on_resume
499 do
500 clock.lapse
501 super
502 end
503
504 redef fun frame_core(display)
505 do
506 # Check errors
507 var gl_error = glGetError
508 assert gl_error == gl_NO_ERROR else print_error gl_error
509
510 # Update game logic and set sprites
511 perf_clock_main.lapse
512 var dt = clock.lapse.to_f
513 update dt
514 frame_dt = dt
515 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
516
517 # Draw and flip screen
518 frame_core_draw display
519 display.flip
520
521 # Check errors
522 gl_error = glGetError
523 assert gl_error == gl_NO_ERROR else print_error gl_error
524 end
525
526 private var frame_dt = 0.0
527
528 # Draw the whole screen, all `glDraw...` calls should be executed here
529 protected fun frame_core_draw(display: GamnitDisplay)
530 do
531 frame_core_dynamic_resolution_before display
532
533 perf_clock_main.lapse
534 frame_core_world_sprites display
535 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
536
537 frame_core_ui_sprites display
538 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
539
540 frame_core_dynamic_resolution_after display
541 end
542
543 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
544 do
545 var simple_2d_program = app.simple_2d_program
546 simple_2d_program.use
547 simple_2d_program.mvp.uniform camera.mvp_matrix
548
549 sprite_set.time += frame_dt*sprite_set.time_mod
550 simple_2d_program.time.uniform sprite_set.time
551
552 # draw
553 sprite_set.draw
554
555 assert glGetError == gl_NO_ERROR
556 end
557
558 # Draw world sprites from `sprites`
559 protected fun frame_core_world_sprites(display: GamnitDisplay)
560 do
561 frame_core_sprites(display, sprites, world_camera)
562 end
563
564 # Draw UI sprites from `ui_sprites`
565 protected fun frame_core_ui_sprites(display: GamnitDisplay)
566 do
567 # Reset only the depth buffer
568 glClear gl_DEPTH_BUFFER_BIT
569
570 frame_core_sprites(display, ui_sprites, ui_camera)
571 end
572 end
573
574 redef class Texture
575
576 # Vertices coordinates of the base geometry
577 #
578 # Defines the default width and height of related sprites.
579 private var vertices: Array[Float] is lazy do
580 var w = width
581 var h = height
582 return [-0.5*w, 0.5*h, 0.0,
583 0.5*w, 0.5*h, 0.0,
584 -0.5*w, -0.5*h, 0.0,
585 0.5*w, -0.5*h, 0.0]
586 end
587
588 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
589 private var texture_coords: Array[Float] is lazy do
590 var l = offset_left
591 var r = offset_right
592 var b = offset_bottom
593 var t = offset_top
594 return [l, t,
595 r, t,
596 l, b,
597 r, b]
598 end
599
600 # Coordinates of this texture on the `root` texture, inverting the X axis
601 private var texture_coords_invert_x: Array[Float] is lazy do
602 var l = offset_left
603 var r = offset_right
604 var b = offset_bottom
605 var t = offset_top
606 return [r, t,
607 l, t,
608 r, b,
609 l, b]
610 end
611
612 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
613 #
614 # The arguments `x` and `y` set the number of frames in the texture.
615 # Use `x` for an horizontal arrangement or `y` for vertical.
616 # One and only one of the arguments must be different than 0,
617 # as an animation can only be on a line and cannot wrap.
618 fun to_animation(fps: Float, x, y: Int): Animation
619 do
620 assert (x == 0) != (y == 0)
621
622 var n_frames = x.max(y)
623 var frames = new Array[Texture]
624
625 var dx = (x/n_frames).to_f/n_frames.to_f
626 var dy = (y/n_frames).to_f/n_frames.to_f
627 var w = if x == 0 then 1.0 else dx
628 var h = if y == 0 then 1.0 else dy
629 var left = 0.0
630 var top = 0.0
631 for i in n_frames.times do
632 frames.add new RelativeSubtexture(root, left, top, left+w, top+h)
633 left += dx
634 top += dy
635 end
636
637 return new Animation(frames, fps)
638 end
639 end
640
641 # Graphic program to display simple models with a texture, translation, rotation and scale
642 private class Simple2dProgram
643 super GamnitProgramFromSource
644
645 redef var vertex_shader_source = """
646 // Vertex coordinates
647 attribute vec4 coord;
648
649 // Vertex color tint
650 attribute vec4 color;
651
652 // Vertex translation
653 attribute vec4 translation;
654
655 // Vertex scaling
656 attribute float scale;
657
658 // Vertex coordinates on textures
659 attribute vec2 tex_coord;
660
661 // Model view projection matrix
662 uniform mat4 mvp;
663
664 // Current world time, in seconds
665 uniform float time;
666
667 // Rotation matrix
668 attribute vec4 rotation_row0;
669 attribute vec4 rotation_row1;
670 attribute vec4 rotation_row2;
671 attribute vec4 rotation_row3;
672
673 // Animation speed, frames per seconds
674 attribute float a_fps;
675
676 // Number of frames in the animation
677 attribute float a_n_frames;
678
679 // World coordinate of the animation (for aspect ratio)
680 attribute vec2 a_coord;
681
682 // Animation texture coordinates of the first frame
683 attribute vec2 a_tex_coord;
684
685 // Animation texture coordinates difference between frames
686 attribute vec2 a_tex_diff;
687
688 // Animation start time, in reference to `time`
689 attribute float a_start;
690
691 // Number of loops to play of the animation
692 attribute float a_loops;
693
694 mat4 rotation()
695 {
696 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
697 }
698
699 // Output to the fragment shader
700 varying vec4 v_color;
701 varying vec2 v_coord;
702
703 // Is there an active animation?
704 varying float v_animated;
705
706 void main()
707 {
708 vec3 c; // coords
709
710 float end = a_start + a_loops/a_fps*a_n_frames;
711 if (a_fps != 0.0 && (a_loops == -1.0 || time < end)) {
712 // in animation
713 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
714 v_coord = a_tex_coord + a_tex_diff*frame;
715 c = vec3(a_coord, coord.z);
716 v_animated = 1.0;
717 } else {
718 // static
719 v_coord = tex_coord;
720 c = coord.xyz;
721 v_animated = 0.0;
722 }
723
724 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
725 v_color = vec4(color.rgb*color.a, color.a);
726 }
727 """ @ glsl_vertex_shader
728
729 redef var fragment_shader_source = """
730 precision mediump float;
731
732 // Does this object use a texture?
733 uniform bool use_texture;
734
735 // Texture to apply on this object
736 uniform sampler2D texture0;
737
738 // Texture to apply on this object
739 uniform sampler2D animation;
740
741 // Input from the vertex shader
742 varying vec4 v_color;
743 varying vec2 v_coord;
744 varying float v_animated;
745
746 void main()
747 {
748 if (v_animated > 0.5) {
749 gl_FragColor = v_color * texture2D(animation, v_coord);
750 if (gl_FragColor.a <= 0.01) discard;
751 } else if (use_texture) {
752 gl_FragColor = v_color * texture2D(texture0, v_coord);
753 if (gl_FragColor.a <= 0.01) discard;
754 } else {
755 gl_FragColor = v_color;
756 }
757 }
758 """ @ glsl_fragment_shader
759
760 # Vertices coordinates
761 var coord = attributes["coord"].as(AttributeVec4) is lazy
762
763 # Should this program use the texture `texture`?
764 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
765
766 # Visible texture unit
767 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
768
769 # Coordinates on the textures, per vertex
770 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
771
772 # Color tint per vertex
773 var color = attributes["color"].as(AttributeVec4) is lazy
774
775 # Translation applied to each vertex
776 var translation = attributes["translation"].as(AttributeVec4) is lazy
777
778 # Rotation matrix, row 0
779 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
780
781 # Rotation matrix, row 1
782 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
783
784 # Rotation matrix, row 2
785 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
786
787 # Rotation matrix, row 3
788 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
789
790 # Scaling per vertex
791 var scale = attributes["scale"].as(AttributeFloat) is lazy
792
793 # Model view projection matrix
794 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
795
796 # World time, in seconds
797 var time = uniforms["time"].as(UniformFloat) is lazy
798
799 # ---
800 # Animations
801
802 # Texture of all the frames of the animation
803 var animation_texture = uniforms["animation"].as(UniformSampler2D) is lazy
804
805 # Frame per second of the animation
806 var animation_fps = attributes["a_fps"].as(AttributeFloat) is lazy
807
808 # Number of frames in the animation
809 var animation_n_frames = attributes["a_n_frames"].as(AttributeFloat) is lazy
810
811 # Coordinates of each frame (mush be shared by all frames)
812 var animation_coord = attributes["a_coord"].as(AttributeVec2) is lazy
813
814 # Texture coordinates of the first frame
815 var animation_tex_coord = attributes["a_tex_coord"].as(AttributeVec2) is lazy
816
817 # Coordinate difference between each frame
818 var animation_tex_diff = attributes["a_tex_diff"].as(AttributeVec2) is lazy
819
820 # Animation start time, in seconds and in reference to `dt`
821 var animation_start = attributes["a_start"].as(AttributeFloat) is lazy
822
823 # Number of loops of the animation, -1 for infinite
824 var animation_loops = attributes["a_loops"].as(AttributeFloat) is lazy
825 end
826
827 redef class Point3d[N]
828 # ---
829 # Associate each point to its sprites
830
831 private var sprites: nullable Array[Sprite] = null
832
833 private fun sprites_add(sprite: Sprite)
834 do
835 var sprites = sprites
836 if sprites == null then
837 sprites = new Array[Sprite]
838 self.sprites = sprites
839 end
840 sprites.add sprite
841 end
842
843 private fun sprites_remove(sprite: Sprite)
844 do
845 var sprites = sprites
846 assert sprites != null
847 sprites.remove sprite
848 end
849
850 # ---
851 # Notify `sprites` on attribute modification
852
853 private fun needs_update
854 do
855 var sprites = sprites
856 if sprites != null then for s in sprites do s.needs_update
857 end
858
859 redef fun x=(v)
860 do
861 if isset _x and v != x then needs_update
862 super
863 end
864
865 redef fun y=(v)
866 do
867 if isset _y and v != y then needs_update
868 super
869 end
870
871 redef fun z=(v)
872 do
873 if isset _z and v != z then needs_update
874 super
875 end
876 end
877
878 redef class OffsetPoint3d
879 redef fun x=(v)
880 do
881 if isset _x and v != x then needs_update
882 super
883 end
884
885 redef fun y=(v)
886 do
887 if isset _y and v != y then needs_update
888 super
889 end
890
891 redef fun z=(v)
892 do
893 if isset _z and v != z then needs_update
894 super
895 end
896 end
897
898 # Set of sprites sorting them into different `SpriteContext`
899 class SpriteSet
900 super HashSet[Sprite]
901
902 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
903 var time_mod = 1.0 is writable
904
905 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
906 var time = 0.0
907
908 # Map texture then static vs dynamic to a `SpriteContext`
909 private var contexts_map = new HashMap4[RootTexture, nullable RootTexture, Bool, Int, Array[SpriteContext]]
910
911 # Contexts in `contexts_map`, sorted by draw order
912 private var contexts_items = new Array[SpriteContext]
913
914 # Sprites needing resorting in `contexts_map`
915 private var sprites_to_remap = new Array[Sprite]
916
917 # Add a sprite to the appropriate context
918 private fun map_sprite(sprite: Sprite)
919 do
920 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
921
922 # Sort by texture and animation texture
923 var texture = sprite.texture.root
924 var animation = sprite.animation
925 var animation_texture = if animation != null then
926 animation.frames.first.root else null
927 var draw_order = sprite.draw_order
928 var contexts = contexts_map[texture, animation_texture, sprite.static, draw_order]
929
930 var context = null
931 if contexts != null then
932 for c in contexts.reverse_iterator do
933 var size = c.sprites.length + 1
934 if size * 4 <= 0xffff then
935 context = c
936 break
937 end
938 end
939 end
940
941 if context == null then
942 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
943 context = new SpriteContext(texture, animation_texture, usage, draw_order)
944
945 if contexts == null then
946 contexts = new Array[SpriteContext]
947 contexts_map[texture, animation_texture, sprite.static, draw_order] = contexts
948 end
949
950 contexts.add context
951
952 contexts_items.add context
953 sprite_draw_order_sorter.sort(contexts_items)
954 end
955
956 context.sprites.add sprite
957 context.sprites_to_update.add sprite
958 context.last_sprite_to_update = sprite
959
960 sprite.context = context
961 sprite.sprite_set = self
962
963 if animation != null and sprite.animation_start == -1.0 then
964 # Start animation
965 sprite.animation_start = time
966 end
967 end
968
969 # Remove a sprite from its context
970 private fun unmap_sprite(sprite: Sprite)
971 do
972 var context = sprite.context
973 assert context != null
974 context.sprites.remove sprite
975
976 sprite.context = null
977 sprite.sprite_set = null
978 end
979
980 # Draw all sprites by all contexts
981 private fun draw
982 do
983 # Remap sprites that may need to change context
984 for sprite in sprites_to_remap do
985
986 # Skip if it was removed from this set after being modified
987 if sprite.sprite_set != self then continue
988
989 unmap_sprite sprite
990 map_sprite sprite
991 end
992 sprites_to_remap.clear
993
994 # Sort by draw order
995 for context in contexts_items do context.draw
996 end
997
998 redef fun add(e)
999 do
1000 if contexts_items.has(e.context) then return
1001 map_sprite e
1002 super
1003 end
1004
1005 redef fun remove(e)
1006 do
1007 super
1008 if e isa Sprite then unmap_sprite e
1009 end
1010
1011 redef fun remove_all(e)
1012 do
1013 if not has(e) then return
1014 remove e
1015 end
1016
1017 redef fun clear
1018 do
1019 for sprite in self do
1020 sprite.context = null
1021 sprite.sprite_set = null
1022 end
1023 super
1024 for c in contexts_items do c.destroy
1025 contexts_map.clear
1026 contexts_items.clear
1027 sprites_to_remap.clear
1028 end
1029
1030 private fun reset
1031 do
1032 for sprite in self do
1033 sprite.context = null
1034 end
1035
1036 for c in contexts_items do c.destroy
1037 contexts_map.clear
1038 contexts_items.clear
1039 sprites_to_remap.clear
1040
1041 for sprite in self do
1042 map_sprite sprite
1043 end
1044 end
1045 end
1046
1047 # Context for calls to `glDrawElements`
1048 #
1049 # Each context has only one `texture` and `usage`, but many sprites.
1050 private class SpriteContext
1051
1052 # ---
1053 # Context config and state
1054
1055 # Only root texture drawn by this context
1056 var texture: nullable RootTexture
1057
1058 # Only animation texture drawn by this context
1059 var animation_texture: nullable RootTexture
1060
1061 # OpenGL ES usage of `buffer_array` and `buffer_element`
1062 var usage: GLBufferUsage
1063
1064 # Draw order shared by all `sprites`
1065 var draw_order: Int
1066
1067 # Sprites drawn by this context
1068 var sprites = new GroupedSprites
1069
1070 # Sprites to update since last `draw`
1071 var sprites_to_update = new Set[Sprite]
1072
1073 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
1074 var last_sprite_to_update: nullable Sprite = null
1075
1076 # Sprites that have been update and for which `needs_update` can be set to false
1077 var updated_sprites = new Array[Sprite]
1078
1079 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
1080 #
1081 # Require: `resize_ratio >= 1.0`
1082 var resize_ratio = 1.2
1083
1084 # ---
1085 # OpenGL ES data
1086
1087 # OpenGL ES buffer name for vertex data
1088 var buffer_array: Int = -1
1089
1090 # OpenGL ES buffer name for indices
1091 var buffer_element: Int = -1
1092
1093 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1094 var buffer_capacity = 0
1095
1096 # C buffers used to pass the data of a single sprite
1097 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
1098 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
1099
1100 # ---
1101 # Constants
1102
1103 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1104 var float_per_vertex: Int is lazy do
1105 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1106 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1107 1 + 1 + # float a_fps, float a_n_frames,
1108 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1109 1 + 1 # float a_start, float a_loops
1110 end
1111
1112 # Number of bytes per vertex of `Simple2dProgram`
1113 var bytes_per_vertex: Int is lazy do
1114 var fs = 4 # sizeof(GL_FLOAT)
1115 return fs * float_per_vertex
1116 end
1117
1118 # Number of bytes per sprite
1119 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
1120
1121 # Number of vertex indices per sprite draw call (2 triangles)
1122 var indices_per_sprite = 6
1123
1124 # ---
1125 # Main services
1126
1127 # Allocate `buffer_array` and `buffer_element`
1128 fun prepare
1129 do
1130 var bufs = glGenBuffers(2)
1131 buffer_array = bufs[0]
1132 buffer_element = bufs[1]
1133
1134 var gl_error = glGetError
1135 assert gl_error == gl_NO_ERROR else print_error gl_error
1136 end
1137
1138 # Destroy `buffer_array` and `buffer_element`
1139 fun destroy
1140 do
1141 glDeleteBuffers([buffer_array, buffer_element])
1142 var gl_error = glGetError
1143 assert gl_error == gl_NO_ERROR else print_error gl_error
1144
1145 buffer_array = -1
1146 buffer_element = -1
1147 end
1148
1149 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1150 fun resize
1151 do
1152 app.perf_clock_sprites.lapse
1153
1154 # Allocate a bit more space
1155 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
1156
1157 var array_bytes = capacity * bytes_per_sprite
1158 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1159 assert glIsBuffer(buffer_array)
1160 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
1161 var gl_error = glGetError
1162 assert gl_error == gl_NO_ERROR else print_error gl_error
1163
1164 # GL_TRIANGLES 6 vertices * sprite
1165 var n_indices = capacity * indices_per_sprite
1166 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
1167 var element_bytes = n_indices * ius
1168 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1169 assert glIsBuffer(buffer_element)
1170 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
1171 gl_error = glGetError
1172 assert gl_error == gl_NO_ERROR else print_error gl_error
1173
1174 buffer_capacity = capacity
1175
1176 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
1177 end
1178
1179 # Update GPU data of `sprite`
1180 fun update_sprite(sprite: Sprite)
1181 do
1182 var context = sprite.context
1183 if context != self then return
1184
1185 var sprite_index = sprite.context_index
1186 assert sprite_index != -1
1187
1188 # Vertices data
1189
1190 var data = local_data_buffer
1191 var o = 0
1192 for v in [0..4[ do
1193 # vec4 translation
1194 data[o+ 0] = sprite.center.x
1195 data[o+ 1] = sprite.center.y
1196 data[o+ 2] = sprite.center.z
1197 data[o+ 3] = 0.0
1198
1199 # vec4 color
1200 data[o+ 4] = sprite.tint[0]
1201 data[o+ 5] = sprite.tint[1]
1202 data[o+ 6] = sprite.tint[2]
1203 data[o+ 7] = sprite.tint[3]
1204
1205 # float scale
1206 data[o+ 8] = sprite.scale
1207
1208 # vec4 coord
1209 data[o+ 9] = sprite.texture.vertices[v*3+0]
1210 data[o+10] = sprite.texture.vertices[v*3+1]
1211 data[o+11] = sprite.texture.vertices[v*3+2]
1212 data[o+12] = 0.0
1213
1214 # vec2 tex_coord
1215 var texture = texture
1216 if texture != null then
1217 var tc = if sprite.invert_x then
1218 sprite.texture.texture_coords_invert_x
1219 else sprite.texture.texture_coords
1220 data[o+13] = tc[v*2+0]
1221 data[o+14] = tc[v*2+1]
1222 end
1223
1224 # mat4 rotation
1225 var rot
1226 if sprite.rotation == 0.0 then
1227 # Cache the matrix at no rotation
1228 rot = once new Matrix.identity(4)
1229 else
1230 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
1231 end
1232 data.fill_from_matrix(rot, o+15)
1233
1234 var animation = sprite.animation
1235 if animation == null then
1236 for i in [31..40] do data[o+i] = 0.0
1237 else
1238 # a_fps
1239 data[o+31] = animation.fps
1240
1241 # a_n_frames
1242 data[o+32] = animation.frames.length.to_f
1243
1244 # a_coord
1245 data[o+33] = animation.frames.first.vertices[v*3+0]
1246 data[o+34] = animation.frames.first.vertices[v*3+1]
1247
1248 # a_tex_coord
1249 var tc = if sprite.invert_x then
1250 animation.frames.first.texture_coords_invert_x
1251 else animation.frames.first.texture_coords
1252 data[o+35] = tc[v*2]
1253 data[o+36] = tc[v*2+1]
1254
1255 # a_tex_diff
1256 var dx = 0.0
1257 var dy = 0.0
1258 if animation.frames.length > 1 then
1259 dx = animation.frames[1].texture_coords[0] - animation.frames[0].texture_coords[0]
1260 dy = animation.frames[1].texture_coords[1] - animation.frames[0].texture_coords[1]
1261 end
1262 data[o+37] = dx
1263 data[o+38] = dy
1264
1265 # a_start
1266 data[o+39] = sprite.animation_start
1267
1268 # a_loops
1269 data[o+40] = sprite.animation_loops
1270 end
1271
1272 o += float_per_vertex
1273 end
1274
1275 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1276 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
1277
1278 var gl_error = glGetError
1279 assert gl_error == gl_NO_ERROR else print_error gl_error
1280
1281 # Element / indices
1282 #
1283 # 0--1
1284 # | /|
1285 # |/ |
1286 # 2--3
1287
1288 var indices = local_indices_buffer
1289 var io = sprite_index*4
1290 indices[0] = io+0
1291 indices[1] = io+2
1292 indices[2] = io+1
1293 indices[3] = io+1
1294 indices[4] = io+2
1295 indices[5] = io+3
1296
1297 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1298 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
1299
1300 gl_error = glGetError
1301 assert gl_error == gl_NO_ERROR else print_error gl_error
1302 end
1303
1304 # Draw all `sprites`
1305 #
1306 # Call `resize` and `update_sprite` as needed before actual draw operation.
1307 #
1308 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1309 fun draw
1310 do
1311 if buffer_array == -1 then prepare
1312
1313 assert buffer_array > 0 and buffer_element > 0 else
1314 print_error "Internal error: {self} was destroyed"
1315 end
1316
1317 # Setup
1318 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1319 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1320
1321 # Resize GPU buffers?
1322 var update_everything = false
1323 if sprites.capacity > buffer_capacity then
1324 # Try to defragment first
1325 var moved = sprites.defragment
1326
1327 if sprites.capacity > buffer_capacity then
1328 # Defragmentation wasn't enough, grow
1329 resize
1330
1331 # We must update everything
1332 update_everything = true
1333 for s in sprites.items do if s != null then sprites_to_update.add s
1334 else
1335 # Just update the moved sprites
1336 for s in moved do sprites_to_update.add s
1337 end
1338 else if sprites.available.not_empty then
1339 # Defragment a bit anyway
1340 # TODO defrag only when there's time left on a frame
1341 var moved = sprites.defragment(1)
1342 for s in moved do sprites_to_update.add s
1343 end
1344
1345 # Update GPU sprites data
1346 if sprites_to_update.not_empty or update_everything then
1347 app.perf_clock_sprites.lapse
1348
1349 if update_everything then
1350 for sprite in sprites.items do if sprite != null then
1351 update_sprite(sprite)
1352 end
1353 else
1354 for sprite in sprites_to_update do update_sprite(sprite)
1355 end
1356
1357 sprites_to_update.clear
1358 last_sprite_to_update = null
1359
1360 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
1361 end
1362
1363 # Update uniforms specific to this context
1364 var texture = texture
1365 app.simple_2d_program.use_texture.uniform texture != null
1366 if texture != null then
1367 glActiveTexture gl_TEXTURE0
1368 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
1369 app.simple_2d_program.texture.uniform 0
1370 end
1371 var gl_error = glGetError
1372 assert gl_error == gl_NO_ERROR else print_error gl_error
1373
1374 var animation = animation_texture
1375 if animation != null then
1376 glActiveTexture gl_TEXTURE1
1377 glBindTexture(gl_TEXTURE_2D, animation.gl_texture)
1378 app.simple_2d_program.animation_texture.uniform 1
1379 end
1380 gl_error = glGetError
1381 assert gl_error == gl_NO_ERROR else print_error gl_error
1382
1383 # Configure attributes, in order:
1384 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1385 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1386
1387 var offset = 0
1388 var p = app.simple_2d_program
1389 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1390
1391 var size = 4 # Number of floats
1392 glEnableVertexAttribArray p.translation.location
1393 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1394 offset += size * sizeof_gl_float
1395 gl_error = glGetError
1396 assert gl_error == gl_NO_ERROR else print_error gl_error
1397
1398 size = 4
1399 glEnableVertexAttribArray p.color.location
1400 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1401 offset += size * sizeof_gl_float
1402 gl_error = glGetError
1403 assert gl_error == gl_NO_ERROR else print_error gl_error
1404
1405 size = 1
1406 glEnableVertexAttribArray p.scale.location
1407 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1408 offset += size * sizeof_gl_float
1409 gl_error = glGetError
1410 assert gl_error == gl_NO_ERROR else print_error gl_error
1411
1412 size = 4
1413 glEnableVertexAttribArray p.coord.location
1414 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1415 offset += size * sizeof_gl_float
1416 gl_error = glGetError
1417 assert gl_error == gl_NO_ERROR else print_error gl_error
1418
1419 size = 2
1420 glEnableVertexAttribArray p.tex_coord.location
1421 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1422 offset += size * sizeof_gl_float
1423 gl_error = glGetError
1424 assert gl_error == gl_NO_ERROR else print_error gl_error
1425
1426 size = 4
1427 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1428 if r.is_active then
1429 glEnableVertexAttribArray r.location
1430 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1431 end
1432 offset += size * sizeof_gl_float
1433 gl_error = glGetError
1434 assert gl_error == gl_NO_ERROR else print_error gl_error
1435 end
1436
1437 size = 1
1438 glEnableVertexAttribArray p.animation_fps.location
1439 glVertexAttribPointeri(p.animation_fps.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1440 offset += size * sizeof_gl_float
1441 gl_error = glGetError
1442 assert gl_error == gl_NO_ERROR else print_error gl_error
1443
1444 size = 1
1445 glEnableVertexAttribArray p.animation_n_frames.location
1446 glVertexAttribPointeri(p.animation_n_frames.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1447 offset += size * sizeof_gl_float
1448 gl_error = glGetError
1449 assert gl_error == gl_NO_ERROR else print_error gl_error
1450
1451 size = 2
1452 glEnableVertexAttribArray p.animation_coord.location
1453 glVertexAttribPointeri(p.animation_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1454 offset += size * sizeof_gl_float
1455 gl_error = glGetError
1456 assert gl_error == gl_NO_ERROR else print_error gl_error
1457
1458 size = 2
1459 glEnableVertexAttribArray p.animation_tex_coord.location
1460 glVertexAttribPointeri(p.animation_tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1461 offset += size * sizeof_gl_float
1462 gl_error = glGetError
1463 assert gl_error == gl_NO_ERROR else print_error gl_error
1464
1465 size = 2
1466 glEnableVertexAttribArray p.animation_tex_diff.location
1467 glVertexAttribPointeri(p.animation_tex_diff.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1468 offset += size * sizeof_gl_float
1469 gl_error = glGetError
1470 assert gl_error == gl_NO_ERROR else print_error gl_error
1471
1472 size = 1
1473 glEnableVertexAttribArray p.animation_start.location
1474 glVertexAttribPointeri(p.animation_start.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1475 offset += size * sizeof_gl_float
1476 gl_error = glGetError
1477 assert gl_error == gl_NO_ERROR else print_error gl_error
1478
1479 size = 1
1480 glEnableVertexAttribArray p.animation_loops.location
1481 glVertexAttribPointeri(p.animation_loops.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1482 offset += size * sizeof_gl_float
1483 gl_error = glGetError
1484 assert gl_error == gl_NO_ERROR else print_error gl_error
1485
1486 # Actual draw
1487 for s in sprites.starts, e in sprites.ends do
1488 var l = e-s
1489 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1490 gl_error = glGetError
1491 assert gl_error == gl_NO_ERROR else print_error gl_error
1492 end
1493
1494 # Take down
1495 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1496 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1497 if not attr.is_active then continue
1498 glDisableVertexAttribArray(attr.location)
1499 gl_error = glGetError
1500 assert gl_error == gl_NO_ERROR else print_error gl_error
1501 end
1502
1503 glBindBuffer(gl_ARRAY_BUFFER, 0)
1504 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1505 gl_error = glGetError
1506 assert gl_error == gl_NO_ERROR else print_error gl_error
1507 end
1508 end
1509
1510 # Representation of sprite data on the GPU
1511 #
1512 # The main purpose of this class is to optimize the use of contiguous
1513 # space in GPU memory. Each contiguous memory block can be drawn in a
1514 # single call. The starts index of each block is kept by `starts,
1515 # and the end + 1 by `ends`.
1516 #
1517 # The data can be compressed by a call to `defragment`.
1518 #
1519 # ~~~
1520 # intrude import gamnit::flat
1521 #
1522 # var array = new GroupedArray[String]
1523 # assert array.to_s == ""
1524 #
1525 # array.add "a"
1526 # array.add "b"
1527 # array.add "c"
1528 # array.add "d"
1529 # array.add "e"
1530 # array.add "f"
1531 # assert array.to_s == "[a,b,c,d,e,f]"
1532 # assert array.capacity == 6
1533 #
1534 # array.remove "a"
1535 # assert array.to_s == "[b,c,d,e,f]"
1536 #
1537 # array.remove "b"
1538 # assert array.to_s == "[c,d,e,f]"
1539 #
1540 # array.remove "f"
1541 # assert array.to_s == "[c,d,e]"
1542 #
1543 # array.remove "d"
1544 # assert array.to_s == "[c][e]"
1545 #
1546 # array.add "A"
1547 # assert array.to_s == "[A][c][e]"
1548 #
1549 # array.add "B"
1550 # assert array.to_s == "[A,B,c][e]"
1551 #
1552 # array.remove "e"
1553 # assert array.to_s == "[A,B,c]"
1554 #
1555 # array.add "D"
1556 # assert array.to_s == "[A,B,c,D]"
1557 #
1558 # array.add "E"
1559 # assert array.to_s == "[A,B,c,D,E]"
1560 # assert array.capacity == 6
1561 # assert array.length == 5
1562 #
1563 # array.remove "A"
1564 # array.remove "B"
1565 # array.remove "c"
1566 # array.remove "D"
1567 # array.remove "E"
1568 # assert array.to_s == ""
1569 #
1570 # array.add "a"
1571 # assert array.to_s == "[a]"
1572 # ~~~
1573 private class GroupedArray[E]
1574
1575 # Memory with actual objects, and null in empty slots
1576 var items = new Array[nullable E]
1577
1578 # Number of items in the array
1579 var length = 0
1580
1581 # Number of item slots in the array
1582 fun capacity: Int do return items.length
1583
1584 # List of available slots
1585 var available = new MinHeap[Int].default
1586
1587 # Start index of filled chunks
1588 var starts = new List[Int]
1589
1590 # Index of the spots after filled chunks
1591 var ends = new List[Int]
1592
1593 # Add `item` to the first available slot and return its index
1594 fun add(item: E): Int
1595 do
1596 length += 1
1597
1598 if available.not_empty then
1599 # starts & ends can't be empty
1600
1601 var i = available.take
1602 items[i] = item
1603
1604 if i == starts.first - 1 then
1605 # slot 0 free, 1 taken
1606 starts.first -= 1
1607 else if i == 0 then
1608 # slot 0 and more free
1609 starts.unshift 0
1610 ends.unshift 1
1611 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1612 # merge 2 chunks
1613 ends.remove_at 0
1614 starts.remove_at 1
1615 else
1616 # at end of first chunk
1617 ends.first += 1
1618 end
1619 return i
1620 end
1621
1622 items.add item
1623 if ends.is_empty then
1624 starts.add 0
1625 ends.add 1
1626 else ends.last += 1
1627 return ends.last - 1
1628 end
1629
1630 # Remove the first instance of `item`
1631 fun remove(item: E)
1632 do
1633 var index = items.index_of(item)
1634 remove_at(item, index)
1635 end
1636
1637 # Remove `item` at `index`
1638 fun remove_at(item: E, index: Int)
1639 do
1640 var i = index
1641 length -= 1
1642 items[i] = null
1643
1644 var ii = 0
1645 for s in starts, e in ends do
1646 if s <= i and i < e then
1647 if s == e-1 then
1648 # single item chunk
1649 starts.remove_at ii
1650 ends.remove_at ii
1651
1652 if starts.is_empty then
1653 items.clear
1654 available.clear
1655 return
1656 end
1657 else if e-1 == i then
1658 # last item of chunk
1659 ends[ii] -= 1
1660
1661 else if s == i then
1662 # first item of chunk
1663 starts[ii] += 1
1664 else
1665 # break up chunk
1666 ends.insert(ends[ii], ii+1)
1667 ends[ii] = i
1668 starts.insert(i+1, ii+1)
1669 end
1670
1671 available.add i
1672 return
1673 end
1674 ii += 1
1675 end
1676
1677 abort
1678 end
1679
1680 # Defragment and compress everything into a single chunks beginning at 0
1681 #
1682 # Returns the elements that moved as a list.
1683 #
1684 # ~~~
1685 # intrude import gamnit::flat
1686 #
1687 # var array = new GroupedArray[String]
1688 # array.add "a"
1689 # array.add "b"
1690 # array.add "c"
1691 # array.add "d"
1692 # array.remove "c"
1693 # array.remove "a"
1694 # assert array.to_s == "[b][d]"
1695 #
1696 # var moved = array.defragment
1697 # assert moved.to_s == "[d]"
1698 # assert array.to_s == "[d,b]"
1699 # assert array.length == 2
1700 # assert array.capacity == 2
1701 #
1702 # array.add "e"
1703 # array.add "f"
1704 # assert array.to_s == "[d,b,e,f]"
1705 # ~~~
1706 fun defragment(max: nullable Int): Array[E]
1707 do
1708 app.perf_clock_sprites.lapse
1709 max = max or else length
1710
1711 var moved = new Array[E]
1712 while max > 0 and (starts.length > 1 or starts.first != 0) do
1713 var i = ends.last - 1
1714 var e = items[i]
1715 assert e != null
1716 remove e
1717 add e
1718 moved.add e
1719 max -= 1
1720 end
1721
1722 if starts.length == 1 and starts.first == 0 then
1723 for i in [length..capacity[ do items.pop
1724 available.clear
1725 end
1726
1727 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1728 return moved
1729 end
1730
1731 redef fun to_s
1732 do
1733 var ss = new Array[String]
1734 for s in starts, e in ends do
1735 ss.add "["
1736 for i in [s..e[ do
1737 var item: nullable Object = items[i]
1738 if item == null then item = "null"
1739 ss.add item.to_s
1740 if i != e-1 then ss.add ","
1741 end
1742 ss.add "]"
1743 end
1744 return ss.join
1745 end
1746 end
1747
1748 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1749 private class GroupedSprites
1750 super GroupedArray[Sprite]
1751
1752 redef fun add(item)
1753 do
1754 var index = super
1755 item.context_index = index
1756 return index
1757 end
1758
1759 redef fun remove(item) do remove_at(item, item.context_index)
1760 end
1761
1762 redef class GLfloatArray
1763 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1764 do
1765 dst_offset = dst_offset or else add_index
1766 var mat_len = matrix.width*matrix.height
1767 assert length >= mat_len + dst_offset
1768 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1769 add_index += mat_len
1770 end
1771 end
1772
1773 redef class NativeGLfloatArray
1774 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1775 int i;
1776 for (i = 0; i < len; i ++)
1777 self[i+dst_offset] = (GLfloat)matrix[i];
1778 `}
1779 end
1780
1781 redef class Sys
1782 private var sprite_draw_order_sorter = new DrawOrderComparator is lazy
1783 end
1784
1785 # Sort `SpriteContext` by their `draw_order`
1786 private class DrawOrderComparator
1787 super Comparator
1788
1789 # This class can't set COMPARED because
1790 # `the public property cannot contain the private type...`
1791 #redef type COMPARED: SpriteContext
1792
1793 # Require: `a isa SpriteContext and b isa SpriteContext`
1794 redef fun compare(a, b)
1795 do return a.as(SpriteContext).draw_order <=> b.as(SpriteContext).draw_order
1796 end