gamnit: fix color buffer clearing issues on some computers
[nit.git] / lib / gamnit / flat.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 # Simple API for 2D games, built around `Sprite` and `App::update`
16 #
17 # Client programs should implement `App::update` to execute game logic and
18 # add instances of `Sprite` to `App::sprites` and `App::ui_sprites`.
19 # At each frame, all sprites are drawn to the screen.
20 #
21 # This system relies on two cameras `App::world_camera` and `App::ui_camera`.
22 #
23 # * `App::world_camera` applies a perspective effect to draw the game world.
24 # This camera is designed to be moved around to see the world as well as to
25 # zoom in and out. It is used to position the sprites in `App::sprites`.
26 #
27 # * `App::ui_camera` is a simple orthogonal camera to display UI objects.
28 # This camera should mostly be still, it can still move for chock effects
29 # and the like. It can be used to standardize the size of the UI across
30 # devices. It is used to position the sprites in `App::ui_sprites`.
31 #
32 # See the sample game at `contrib/asteronits/` and the basic project template
33 # at `lib/gamnit/examples/template/`.
34 module flat
35
36 import glesv2
37 intrude import geometry::points_and_lines # For _x, _y and _z
38 intrude import matrix
39 import matrix::projection
40 import more_collections
41 import performance_analysis
42
43 import gamnit
44 import gamnit::cameras_cache
45 import gamnit::dynamic_resolution
46 import gamnit::limit_fps
47 import gamnit::camera_control
48
49 # Visible 2D entity in the game world or UI
50 #
51 # Similar to `gamnit::Actor` which is in 3D.
52 #
53 # Each sprite associates a `texture` to the position `center`.
54 # The appearance is modified by `rotation`, `invert_x`,
55 # `scale`, `red`, `green`, `blue` and `alpha`.
56 # These values can be changed at any time and will trigger an update
57 # of the data on the GPU side, having a small performance cost.
58 #
59 # For a sprite to be visible, it must be added to either the world `sprites`
60 # or the `ui_sprites`.
61 # However, an instance of `Sprite` can only belong to a single `SpriteSet`
62 # at a time. The final on-screen position depends on the camera associated
63 # to the `SpriteSet`.
64 #
65 # ~~~
66 # # Load texture and create sprite
67 # var texture = new Texture("path/in/assets.png")
68 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
69 #
70 # # Add sprite to the visible game world
71 # app.sprites.add sprite
72 #
73 # # Extra configuration of the sprite
74 # sprite.rotation = pi/2.0
75 # sprite.scale = 2.0
76 #
77 # # Show only the blue colors
78 # sprite.red = 0.0
79 # sprite.green = 0.0
80 # ~~~
81 #
82 # To add a sprite to the UI it can be anchored to screen borders
83 # with `ui_camera.top_left` and the likes.
84 #
85 # ~~~nitish
86 # # Place it a bit off the top left of the screen
87 # var pos = app.ui_camera.top_left.offset(128.0, -128.0, 0)
88 #
89 # # Load texture and create sprite
90 # var texture = new Texture("path/in/assets.png")
91 # var sprite = new Sprite(texture, pos)
92 #
93 # # Add it to the UI (above world sprites)
94 # app.ui_sprites.add sprite
95 # ~~~
96 class Sprite
97
98 # Texture drawn to screen
99 var texture: Texture is writable(texture_direct=)
100
101 # Texture drawn to screen
102 fun texture=(value: Texture)
103 do
104 if isset _texture and value != texture then
105 needs_update
106 if value.root != texture.root then needs_remap
107 end
108 texture_direct = value
109 end
110
111 # Center position of this sprite in world coordinates
112 var center: Point3d[Float] is writable(center_direct=), noautoinit
113
114 # Center position of this sprite in world coordinates
115 fun center=(value: Point3d[Float]) is autoinit do
116 if isset _center and value != center then
117 needs_update
118 center.sprites_remove self
119 end
120
121 value.sprites_add self
122 center_direct = value
123 end
124
125 # Rotation on the Z axis, positive values turn counterclockwise
126 var rotation = 0.0 is writable(rotation_direct=)
127
128 # Rotation on the Z axis, positive values turn counterclockwise
129 fun rotation=(value: Float)
130 do
131 if isset _rotation and value != rotation then needs_update
132 rotation_direct = value
133 end
134
135 # Mirror `texture` horizontally, inverting each pixel on the X axis
136 var invert_x = false is writable(invert_x_direct=)
137
138 # Mirror `texture` horizontally, inverting each pixel on the X axis
139 fun invert_x=(value: Bool)
140 do
141 if isset _invert_x and value != invert_x then needs_update
142 invert_x_direct = value
143 end
144
145 # Scale applied to this sprite
146 #
147 # The basic size of `self` depends on the size in pixels of `texture`.
148 var scale = 1.0 is writable(scale_direct=)
149
150 # Scale applied to this sprite
151 #
152 # The basic size of `self` depends on the size in pixels of `texture`.
153 fun scale=(value: Float)
154 do
155 if isset _scale and value != scale then needs_update
156 scale_direct = value
157 end
158
159 # Red tint applied to `texture` on draw
160 fun red: Float do return tint[0]
161
162 # Red tint applied to `texture` on draw
163 fun red=(value: Float)
164 do
165 if isset _tint and value != red then needs_update
166 tint[0] = value
167 end
168
169 # Green tint applied to `texture` on draw
170 fun green: Float do return tint[1]
171
172 # Green tint applied to `texture` on draw
173 fun green=(value: Float)
174 do
175 if isset _tint and value != green then needs_update
176 tint[1] = value
177 end
178
179 # Blue tint applied to `texture` on draw
180 fun blue: Float do return tint[2]
181
182 # Blue tint applied to `texture` on draw
183 fun blue=(value: Float)
184 do
185 if isset _tint and value != blue then needs_update
186 tint[2] = value
187 end
188
189 # Transparency applied to `texture` on draw
190 fun alpha: Float do return tint[3]
191
192 # Transparency applied to `texture` on draw
193 fun alpha=(value: Float)
194 do
195 if isset _tint and value != alpha then needs_update
196 tint[3] = value
197 end
198
199 # Tint applied to `texture` on draw
200 #
201 # Alternative to the accessors `red, green, blue & alpha`.
202 # Changes inside the array do not automatically set `needs_update`.
203 #
204 # Require: `tint.length == 4`
205 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct=)
206
207 # Tint applied to `texture` on draw, see `tint`
208 fun tint=(value: Array[Float])
209 do
210 if isset _tint and value != tint then needs_update
211 tint_direct = value
212 end
213
214 # Is this sprite static and added in bulk?
215 #
216 # Set to `true` to give a hint to the framework that this sprite won't
217 # change often and that it is added in bulk with other static sprites.
218 # This value can be ignored in the prototyping phase of a game and
219 # added only when better performance are needed.
220 var static = false is writable(static_direct=)
221
222 # Is this sprite static and added in bulk? see `static`
223 fun static=(value: Bool)
224 do
225 if isset _static and value != static then needs_remap
226 static_direct = value
227 end
228
229 # Request an update on the CPU
230 #
231 # This is called automatically on modification of any value of `Sprite`.
232 # However, it can still be set manually if a modification can't be
233 # detected or by subclasses.
234 fun needs_update
235 do
236 var c = context
237 if c != null then c.sprites_to_update.add self
238 end
239
240 # Request a resorting of this sprite in its sprite list
241 #
242 # Resorting is required when `static` or the root of `texture` changes.
243 # This is called automatically when such changes are detected.
244 # However, it can still be set manually if a modification can't be
245 # detected or by subclasses.
246 fun needs_remap
247 do
248 var l = sprite_set
249 if l != null then l.sprites_to_remap.add self
250 end
251
252 # Current context to which `self` was sorted
253 private var context: nullable SpriteContext = null
254
255 # Current context to which `self` belongs
256 private var sprite_set: nullable SpriteSet = null
257 end
258
259 redef class App
260 # Default graphic program to draw `sprites`
261 private var simple_2d_program = new Simple2dProgram is lazy
262
263 # Camera for world `sprites` and `depth::actors` with perspective
264 #
265 # By default, the camera is configured to a height of 1080 units
266 # of world coordinates at `z == 0.0`.
267 var world_camera: EulerCamera is lazy do
268 var camera = new EulerCamera(app.display.as(not null))
269
270 # Aim for full HD pixel resolution at level 0
271 camera.reset_height 1080.0
272 camera.near = 10.0
273
274 return camera
275 end
276
277 # Camera for `ui_sprites` using an orthogonal view
278 var ui_camera = new UICamera(app.display.as(not null)) is lazy
279
280 # World sprites drawn as seen by `world_camera`
281 var sprites: Set[Sprite] = new SpriteSet
282
283 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
284 var ui_sprites: Set[Sprite] = new SpriteSet
285
286 # Main method to refine in clients to update game logic and `sprites`
287 fun update(dt: Float) do end
288
289 # Display `texture` as a splash screen
290 #
291 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
292 fun show_splash_screen(texture: Texture)
293 do
294 texture.load
295
296 ui_camera.reset_height 1080.0
297
298 var splash = new Sprite(texture, ui_camera.center)
299 ui_sprites.add splash
300
301 var display = display
302 assert display != null
303 glClear gl_COLOR_BUFFER_BIT
304 frame_core_ui_sprites display
305 display.flip
306
307 ui_sprites.remove splash
308 end
309
310 # ---
311 # Support and implementation
312
313 # Main clock used to count each frame `dt`, lapsed for `update` only
314 private var clock = new Clock is lazy
315
316 # Performance clock to for `frame_core_draw` operations
317 private var perf_clock_main = new Clock
318
319 # Second performance clock for smaller operations
320 private var perf_clock_sprites = new Clock is lazy
321
322 redef fun on_create
323 do
324 super
325
326 var display = display
327 assert display != null
328
329 var gl_error = glGetError
330 assert gl_error == gl_NO_ERROR else print_error gl_error
331
332 # Prepare program
333 var program = simple_2d_program
334 program.compile_and_link
335
336 var gamnit_error = program.error
337 assert gamnit_error == null else print_error gamnit_error
338
339 # Enable blending
340 gl.capabilities.blend.enable
341 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
342
343 # Enable depth test
344 gl.capabilities.depth_test.enable
345 glDepthFunc gl_LEQUAL
346 glDepthMask true
347
348 # Prepare viewport and background color
349 glViewport(0, 0, display.width, display.height)
350 glClearColor(0.0, 0.0, 0.0, 1.0)
351
352 gl_error = glGetError
353 assert gl_error == gl_NO_ERROR else print_error gl_error
354
355 # Prepare to draw
356 for tex in all_root_textures do
357 tex.load
358 gamnit_error = tex.error
359 if gamnit_error != null then print_error gamnit_error
360
361 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
362 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
363 end
364 end
365
366 redef fun on_stop
367 do
368 # Clean up
369 simple_2d_program.delete
370
371 # Close gamnit
372 var display = display
373 if display != null then display.close
374 end
375
376 redef fun frame_core(display)
377 do
378 # Check errors
379 var gl_error = glGetError
380 assert gl_error == gl_NO_ERROR else print_error gl_error
381
382 # Update game logic and set sprites
383 perf_clock_main.lapse
384 var dt = clock.lapse.to_f
385 update dt
386 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
387
388 # Draw and flip screen
389 frame_core_draw display
390 display.flip
391
392 # Check errors
393 gl_error = glGetError
394 assert gl_error == gl_NO_ERROR else print_error gl_error
395 end
396
397 # Draw the whole screen, all `glDraw...` calls should be executed here
398 protected fun frame_core_draw(display: GamnitDisplay)
399 do
400 frame_core_dynamic_resolution_before display
401
402 perf_clock_main.lapse
403 frame_core_world_sprites display
404 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
405
406 frame_core_ui_sprites display
407 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
408
409 frame_core_dynamic_resolution_after display
410 end
411
412 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
413 do
414 var simple_2d_program = app.simple_2d_program
415 simple_2d_program.use
416 simple_2d_program.mvp.uniform camera.mvp_matrix
417
418 # draw
419 sprite_set.draw
420 end
421
422 # Draw world sprites from `sprites`
423 protected fun frame_core_world_sprites(display: GamnitDisplay)
424 do
425 frame_core_sprites(display, sprites.as(SpriteSet), world_camera)
426 end
427
428 # Draw UI sprites from `ui_sprites`
429 protected fun frame_core_ui_sprites(display: GamnitDisplay)
430 do
431 # Reset only the depth buffer
432 glClear gl_DEPTH_BUFFER_BIT
433
434 frame_core_sprites(display, ui_sprites.as(SpriteSet), ui_camera)
435 end
436 end
437
438 redef class Texture
439
440 # Vertices coordinates of the base geometry
441 #
442 # Defines the default width and height of related sprites.
443 private var vertices: Array[Float] is lazy do
444 var w = width
445 var h = height
446 return [-0.5*w, 0.5*h, 0.0,
447 0.5*w, 0.5*h, 0.0,
448 -0.5*w, -0.5*h, 0.0,
449 0.5*w, -0.5*h, 0.0]
450 end
451
452 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
453 private var texture_coords: Array[Float] is lazy do
454 var l = offset_left
455 var r = offset_right
456 var b = offset_bottom
457 var t = offset_top
458 return [l, t,
459 r, t,
460 l, b,
461 r, b]
462 end
463
464 # Coordinates of this texture on the `root` texture, inverting the X axis
465 private var texture_coords_invert_x: Array[Float] is lazy do
466 var l = offset_left
467 var r = offset_right
468 var b = offset_bottom
469 var t = offset_top
470 return [r, t,
471 l, t,
472 r, b,
473 l, b]
474 end
475 end
476
477 # Graphic program to display simple models with a texture, translation, rotation and scale
478 private class Simple2dProgram
479 super GamnitProgramFromSource
480
481 redef var vertex_shader_source = """
482 // Vertex coordinates
483 attribute vec4 coord;
484
485 // Vertex color tint
486 attribute vec4 color;
487
488 // Vertex translation
489 attribute vec4 translation;
490
491 // Vertex scaling
492 attribute float scale;
493
494 // Vertex coordinates on textures
495 attribute vec2 tex_coord;
496
497 // Model view projection matrix
498 uniform mat4 mvp;
499
500 // Rotation matrix
501 attribute vec4 rotation_row0;
502 attribute vec4 rotation_row1;
503 attribute vec4 rotation_row2;
504 attribute vec4 rotation_row3;
505
506 mat4 rotation()
507 {
508 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
509 }
510
511 // Output to the fragment shader
512 varying vec4 v_color;
513 varying vec2 v_coord;
514
515 void main()
516 {
517 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
518 v_color = color;
519 v_coord = tex_coord;
520 }
521 """ @ glsl_vertex_shader
522
523 redef var fragment_shader_source = """
524 precision mediump float;
525
526 // Does this object use a texture?
527 uniform bool use_texture;
528
529 // Texture to apply on this object
530 uniform sampler2D texture0;
531
532 // Input from the vertex shader
533 varying vec4 v_color;
534 varying vec2 v_coord;
535
536 void main()
537 {
538 if(use_texture) {
539 gl_FragColor = v_color * texture2D(texture0, v_coord);
540 if (gl_FragColor.a <= 0.01) discard;
541 } else {
542 gl_FragColor = v_color;
543 }
544 }
545 """ @ glsl_fragment_shader
546
547 # Vertices coordinates
548 var coord = attributes["coord"].as(AttributeVec4) is lazy
549
550 # Should this program use the texture `texture`?
551 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
552
553 # Visible texture unit
554 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
555
556 # Coordinates on the textures, per vertex
557 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
558
559 # Color tint per vertex
560 var color = attributes["color"].as(AttributeVec4) is lazy
561
562 # Translation applied to each vertex
563 var translation = attributes["translation"].as(AttributeVec4) is lazy
564
565 # Rotation matrix, row 0
566 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
567
568 # Rotation matrix, row 1
569 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
570
571 # Rotation matrix, row 2
572 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
573
574 # Rotation matrix, row 3
575 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
576
577 # Scaling per vertex
578 var scale = attributes["scale"].as(AttributeFloat) is lazy
579
580 # Model view projection matrix
581 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
582 end
583
584 redef class Point3d[N]
585 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
586 fun offset(x, y, z: Numeric): Point3d[Float]
587 do
588 return new Point3d[Float](self.x.to_f+x.to_f, self.y.to_f+y.to_f, self.z.to_f+z.to_f)
589 end
590
591 # ---
592 # Associate each point to its sprites
593
594 private var sprites: nullable Array[Sprite] = null
595
596 private fun sprites_add(sprite: Sprite)
597 do
598 var sprites = sprites
599 if sprites == null then
600 sprites = new Array[Sprite]
601 self.sprites = sprites
602 end
603 sprites.add sprite
604 end
605
606 private fun sprites_remove(sprite: Sprite)
607 do
608 var sprites = sprites
609 assert sprites != null
610 sprites.remove sprite
611 end
612
613 # ---
614 # Notify `sprites` on attribute modification
615
616 private fun needs_update
617 do
618 var sprites = sprites
619 if sprites != null then for s in sprites do s.needs_update
620 end
621
622 redef fun x=(v)
623 do
624 if isset _x and v != x then needs_update
625 super
626 end
627
628 redef fun y=(v)
629 do
630 if isset _y and v != y then needs_update
631 super
632 end
633
634 redef fun z=(v)
635 do
636 if isset _z and v != z then needs_update
637 super
638 end
639 end
640
641 # Set of sprites sorting them into different `SpriteContext`
642 private class SpriteSet
643 super HashSet[Sprite]
644
645 # Map texture then static vs dynamic to a `SpriteContext`
646 var contexts_map = new HashMap2[RootTexture, Bool, SpriteContext]
647
648 # Contexts in `contexts_map`
649 var contexts_items = new Array[SpriteContext]
650
651 # Sprites needing resorting in `contexts_map`
652 var sprites_to_remap = new Array[Sprite]
653
654 # Add a sprite to the appropriate context
655 fun map_sprite(sprite: Sprite)
656 do
657 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
658
659 var texture = sprite.texture.root
660 var context = contexts_map[texture, sprite.static]
661
662 if context == null then
663 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
664 context = new SpriteContext(texture, usage)
665
666 contexts_map[texture, sprite.static] = context
667 contexts_items.add context
668 end
669
670 context.sprites.add sprite
671 context.sprites_to_update.add sprite
672
673 sprite.context = context
674 sprite.sprite_set = self
675 end
676
677 # Remove a sprite from its context
678 fun unmap_sprite(sprite: Sprite)
679 do
680 var context = sprite.context
681 assert context != null
682 context.sprites.remove sprite
683
684 sprite.context = null
685 sprite.sprite_set = null
686 end
687
688 # Draw all sprites by all contexts
689 fun draw
690 do
691 for sprite in sprites_to_remap do
692 unmap_sprite sprite
693 map_sprite sprite
694 end
695 sprites_to_remap.clear
696
697 for context in contexts_items do context.draw
698 end
699
700 redef fun add(e)
701 do
702 if contexts_items.has(e.context) then return
703 map_sprite e
704 super
705 end
706
707 redef fun remove(e)
708 do
709 super
710 if e isa Sprite then unmap_sprite e
711 end
712
713 redef fun remove_all(e)
714 do
715 if not has(e) then return
716 remove e
717 end
718
719 redef fun clear
720 do
721 for sprite in self do
722 sprite.context = null
723 sprite.sprite_set = null
724 end
725 super
726 for c in contexts_items do c.destroy
727 contexts_map.clear
728 contexts_items.clear
729 end
730 end
731
732 # Context for calls to `glDrawElements`
733 #
734 # Each context has only one `texture` and `usage`, but many sprites.
735 private class SpriteContext
736
737 # ---
738 # Context config and state
739
740 # Only root texture drawn by this context
741 var texture: nullable RootTexture
742
743 # OpenGL ES usage of `buffer_array` and `buffer_element`
744 var usage: GLBufferUsage
745
746 # Sprites drawn by this context
747 var sprites = new GroupedArray[Sprite]
748
749 # Sprites to update since last `draw`
750 var sprites_to_update = new Set[Sprite]
751
752 # Sprites that have been update and for which `needs_update` can be set to false
753 var updated_sprites = new Array[Sprite]
754
755 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
756 #
757 # Require: `resize_ratio >= 1.0`
758 var resize_ratio = 1.2
759
760 # ---
761 # OpenGL ES data
762
763 # OpenGL ES buffer name for vertex data
764 var buffer_array: Int = -1
765
766 # OpenGL ES buffer name for indices
767 var buffer_element: Int = -1
768
769 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
770 var buffer_capacity = 0
771
772 # C buffers used to pass the data of a single sprite
773 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
774 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
775
776 # ---
777 # Constants
778
779 # Number of GL_FLOAT per vertex of `Simple2dProgram`
780 var float_per_vertex: Int is lazy do
781 # vec4 translation, vec4 color, vec4 coord,
782 # float scale, vec2 tex_coord, vec4 rotation_row*
783 return 4 + 4 + 4 +
784 1 + 2 + 4*4
785 end
786
787 # Number of bytes per vertex of `Simple2dProgram`
788 var bytes_per_vertex: Int is lazy do
789 var fs = 4 # sizeof(GL_FLOAT)
790 return fs * float_per_vertex
791 end
792
793 # Number of bytes per sprite
794 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
795
796 # Number of vertex indices per sprite draw call (2 triangles)
797 var indices_per_sprite = 6
798
799 # ---
800 # Main services
801
802 # Allocate `buffer_array` and `buffer_element`
803 fun prepare
804 do
805 var bufs = glGenBuffers(2)
806 buffer_array = bufs[0]
807 buffer_element = bufs[1]
808
809 var gl_error = glGetError
810 assert gl_error == gl_NO_ERROR else print_error gl_error
811 end
812
813 # Destroy `buffer_array` and `buffer_element`
814 fun destroy
815 do
816 glDeleteBuffers([buffer_array, buffer_element])
817 var gl_error = glGetError
818 assert gl_error == gl_NO_ERROR else print_error gl_error
819
820 buffer_array = -1
821 buffer_element = -1
822 end
823
824 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
825 fun resize
826 do
827 app.perf_clock_sprites.lapse
828
829 # Allocate a bit more space
830 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
831
832 var array_bytes = capacity * bytes_per_sprite
833 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
834 assert glIsBuffer(buffer_array)
835 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
836 var gl_error = glGetError
837 assert gl_error == gl_NO_ERROR else print_error gl_error
838
839 # GL_TRIANGLES 6 vertices * sprite
840 var n_indices = capacity * indices_per_sprite
841 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
842 var element_bytes = n_indices * ius
843 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
844 assert glIsBuffer(buffer_element)
845 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
846 gl_error = glGetError
847 assert gl_error == gl_NO_ERROR else print_error gl_error
848
849 buffer_capacity = capacity
850
851 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
852 end
853
854 # Update GPU data of `sprite`
855 fun update_sprite(sprite: Sprite)
856 do
857 var sprite_index = sprites.index_of(sprite)
858 if sprite_index == -1 then return
859
860 # Vertices data
861
862 var data = local_data_buffer
863 var o = 0
864 for v in [0..4[ do
865 # vec4 translation
866 data[o+ 0] = sprite.center.x
867 data[o+ 1] = sprite.center.y
868 data[o+ 2] = sprite.center.z
869 data[o+ 3] = 0.0
870
871 # vec4 color
872 data[o+ 4] = sprite.tint[0]
873 data[o+ 5] = sprite.tint[1]
874 data[o+ 6] = sprite.tint[2]
875 data[o+ 7] = sprite.tint[3]
876
877 # float scale
878 data[o+ 8] = sprite.scale
879
880 # vec4 coord
881 data[o+ 9] = sprite.texture.vertices[v*3+0]
882 data[o+10] = sprite.texture.vertices[v*3+1]
883 data[o+11] = sprite.texture.vertices[v*3+2]
884 data[o+12] = 0.0
885
886 # vec2 tex_coord
887 var texture = texture
888 if texture != null then
889 var tc = if sprite.invert_x then
890 sprite.texture.texture_coords_invert_x
891 else sprite.texture.texture_coords
892 data[o+13] = tc[v*2+0]
893 data[o+14] = tc[v*2+1]
894 end
895
896 # mat4 rotation
897 var rot
898 if sprite.rotation == 0.0 then
899 # Cache the matrix at no rotation
900 rot = once new Matrix.identity(4)
901 else
902 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
903 end
904 data.fill_from_matrix(rot, o+15)
905
906 o += float_per_vertex
907 end
908
909 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
910 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
911
912 var gl_error = glGetError
913 assert gl_error == gl_NO_ERROR else print_error gl_error
914
915 # Element / indices
916 #
917 # 0--1
918 # | /|
919 # |/ |
920 # 2--3
921
922 var indices = local_indices_buffer
923 var io = sprite_index*4
924 indices[0] = io+0
925 indices[1] = io+2
926 indices[2] = io+1
927 indices[3] = io+1
928 indices[4] = io+2
929 indices[5] = io+3
930
931 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
932 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
933
934 gl_error = glGetError
935 assert gl_error == gl_NO_ERROR else print_error gl_error
936 end
937
938 # Draw all `sprites`
939 #
940 # Call `resize` and `update_sprite` as needed before actual draw operation.
941 #
942 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
943 fun draw
944 do
945 if buffer_array == -1 then prepare
946
947 assert buffer_array > 0 and buffer_element > 0 else
948 print_error "Internal error: {self} was destroyed"
949 end
950
951 # Setup
952 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
953 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
954
955 # Resize GPU buffers?
956 if sprites.capacity > buffer_capacity then
957 # Try to defragment first
958 var moved = sprites.defragment
959
960 if sprites.capacity > buffer_capacity then
961 # Defragmentation wasn't enough, grow
962 resize
963
964 # We must update everything
965 for s in sprites.items do if s != null then sprites_to_update.add s
966 else
967 # Just update the moved sprites
968 for s in moved do sprites_to_update.add s
969 end
970 else if sprites.available.not_empty then
971 # Defragment a bit anyway
972 # TODO defrag only when there's time left on a frame
973 var moved = sprites.defragment(1)
974 for s in moved do sprites_to_update.add s
975 end
976
977 # Update GPU sprites data
978 if sprites_to_update.not_empty then
979 app.perf_clock_sprites.lapse
980
981 for sprite in sprites_to_update do update_sprite(sprite)
982 sprites_to_update.clear
983
984 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
985 end
986
987 # Update uniforms specific to this context
988 var texture = texture
989 app.simple_2d_program.use_texture.uniform texture != null
990 if texture != null then
991 glActiveTexture gl_TEXTURE0
992 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
993 app.simple_2d_program.texture.uniform 0
994 end
995 var gl_error = glGetError
996 assert gl_error == gl_NO_ERROR else print_error gl_error
997
998 # Configure attributes, in order:
999 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
1000 var offset = 0
1001 var p = app.simple_2d_program
1002 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1003
1004 var size = 4 # Number of floats
1005 glEnableVertexAttribArray p.translation.location
1006 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1007 offset += size * sizeof_gl_float
1008 gl_error = glGetError
1009 assert gl_error == gl_NO_ERROR else print_error gl_error
1010
1011 size = 4
1012 glEnableVertexAttribArray p.color.location
1013 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1014 offset += size * sizeof_gl_float
1015 gl_error = glGetError
1016 assert gl_error == gl_NO_ERROR else print_error gl_error
1017
1018 size = 1
1019 glEnableVertexAttribArray p.scale.location
1020 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1021 offset += size * sizeof_gl_float
1022 gl_error = glGetError
1023 assert gl_error == gl_NO_ERROR else print_error gl_error
1024
1025 size = 4
1026 glEnableVertexAttribArray p.coord.location
1027 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1028 offset += size * sizeof_gl_float
1029 gl_error = glGetError
1030 assert gl_error == gl_NO_ERROR else print_error gl_error
1031
1032 size = 2
1033 glEnableVertexAttribArray p.tex_coord.location
1034 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1035 offset += size * sizeof_gl_float
1036 gl_error = glGetError
1037 assert gl_error == gl_NO_ERROR else print_error gl_error
1038
1039 size = 4
1040 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1041 if r.is_active then
1042 glEnableVertexAttribArray r.location
1043 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1044 end
1045 offset += size * sizeof_gl_float
1046 gl_error = glGetError
1047 assert gl_error == gl_NO_ERROR else print_error gl_error
1048 end
1049
1050 # Actual draw
1051 for s in sprites.starts, e in sprites.ends do
1052 var l = e-s
1053 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1054 gl_error = glGetError
1055 assert gl_error == gl_NO_ERROR else print_error gl_error
1056 end
1057
1058 # Take down
1059 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1060 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1061 if not attr.is_active then continue
1062 glDisableVertexAttribArray(attr.location)
1063 gl_error = glGetError
1064 assert gl_error == gl_NO_ERROR else print_error gl_error
1065 end
1066
1067 glBindBuffer(gl_ARRAY_BUFFER, 0)
1068 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1069 gl_error = glGetError
1070 assert gl_error == gl_NO_ERROR else print_error gl_error
1071 end
1072 end
1073
1074 # Representation of sprite data on the GPU
1075 #
1076 # The main purpose of this class is to optimize the use of contiguous
1077 # space in GPU memory. Each contiguous memory block can be drawn in a
1078 # single call. The starts index of each block is kept by `starts,
1079 # and the end + 1 by `ends`.
1080 #
1081 # The data can be compressed by a call to `defragment`.
1082 #
1083 # ~~~
1084 # intrude import gamnit::flat
1085 #
1086 # var array = new GroupedArray[String]
1087 # assert array.to_s == ""
1088 #
1089 # array.add "a"
1090 # array.add "b"
1091 # array.add "c"
1092 # array.add "d"
1093 # array.add "e"
1094 # array.add "f"
1095 # assert array.to_s == "[a,b,c,d,e,f]"
1096 # assert array.capacity == 6
1097 #
1098 # array.remove "a"
1099 # assert array.to_s == "[b,c,d,e,f]"
1100 #
1101 # array.remove "b"
1102 # assert array.to_s == "[c,d,e,f]"
1103 #
1104 # array.remove "f"
1105 # assert array.to_s == "[c,d,e]"
1106 #
1107 # array.remove "d"
1108 # assert array.to_s == "[c][e]"
1109 #
1110 # array.add "A"
1111 # assert array.to_s == "[A][c][e]"
1112 #
1113 # array.add "B"
1114 # assert array.to_s == "[A,B,c][e]"
1115 #
1116 # array.remove "e"
1117 # assert array.to_s == "[A,B,c]"
1118 #
1119 # array.add "D"
1120 # assert array.to_s == "[A,B,c,D]"
1121 #
1122 # array.add "E"
1123 # assert array.to_s == "[A,B,c,D,E]"
1124 # assert array.capacity == 6
1125 # assert array.length == 5
1126 #
1127 # array.remove "A"
1128 # array.remove "B"
1129 # array.remove "c"
1130 # array.remove "D"
1131 # array.remove "E"
1132 # assert array.to_s == ""
1133 #
1134 # array.add "a"
1135 # assert array.to_s == "[a]"
1136 # ~~~
1137 private class GroupedArray[E]
1138
1139 # Memory with actual objects, and null in empty slots
1140 var items = new Array[nullable E]
1141
1142 # Number of items in the array
1143 var length = 0
1144
1145 # Number of item slots in the array
1146 fun capacity: Int do return items.length
1147
1148 # Index of `item`
1149 fun index_of(item: E): Int do return items.index_of(item)
1150
1151 # List of available slots
1152 var available = new MinHeap[Int].default
1153
1154 # Start index of filled chunks
1155 var starts = new List[Int]
1156
1157 # Index of the spots after filled chunks
1158 var ends = new List[Int]
1159
1160 # Add `item` to the first available slot
1161 fun add(item: E)
1162 do
1163 length += 1
1164
1165 if available.not_empty then
1166 # starts & ends can't be empty
1167
1168 var i = available.take
1169 items[i] = item
1170
1171 if i == starts.first - 1 then
1172 # slot 0 free, 1 taken
1173 starts.first -= 1
1174 else if i == 0 then
1175 # slot 0 and more free
1176 starts.unshift 0
1177 ends.unshift 1
1178 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1179 # merge 2 chunks
1180 ends.remove_at 0
1181 starts.remove_at 1
1182 else
1183 # at end of first chunk
1184 ends.first += 1
1185 end
1186 return
1187 end
1188
1189 items.add item
1190 if ends.is_empty then
1191 starts.add 0
1192 ends.add 1
1193 else ends.last += 1
1194 end
1195
1196 # Remove the first instance of `item`
1197 fun remove(item: E)
1198 do
1199 var i = items.index_of(item)
1200 assert i != -1
1201 length -= 1
1202 items[i] = null
1203
1204 var ii = 0
1205 for s in starts, e in ends do
1206 if s <= i and i < e then
1207 if s == e-1 then
1208 # single item chunk
1209 starts.remove_at ii
1210 ends.remove_at ii
1211
1212 if starts.is_empty then
1213 items.clear
1214 available.clear
1215 return
1216 end
1217 else if e-1 == i then
1218 # last item of chunk
1219 ends[ii] -= 1
1220
1221 else if s == i then
1222 # first item of chunk
1223 starts[ii] += 1
1224 else
1225 # break up chunk
1226 ends.insert(ends[ii], ii+1)
1227 ends[ii] = i
1228 starts.insert(i+1, ii+1)
1229 end
1230
1231 available.add i
1232 return
1233 end
1234 ii += 1
1235 end
1236
1237 abort
1238 end
1239
1240 # Defragment and compress everything into a single chunks beginning at 0
1241 #
1242 # Returns the elements that moved as a list.
1243 #
1244 # ~~~
1245 # intrude import gamnit::flat
1246 #
1247 # var array = new GroupedArray[String]
1248 # array.add "a"
1249 # array.add "b"
1250 # array.add "c"
1251 # array.add "d"
1252 # array.remove "c"
1253 # array.remove "a"
1254 # assert array.to_s == "[b][d]"
1255 #
1256 # var moved = array.defragment
1257 # assert moved.to_s == "[d]"
1258 # assert array.to_s == "[d,b]"
1259 # assert array.length == 2
1260 # assert array.capacity == 2
1261 #
1262 # array.add "e"
1263 # array.add "f"
1264 # assert array.to_s == "[d,b,e,f]"
1265 # ~~~
1266 fun defragment(max: nullable Int): Array[E]
1267 do
1268 app.perf_clock_sprites.lapse
1269 max = max or else length
1270
1271 var moved = new Array[E]
1272 while max > 0 and (starts.length > 1 or starts.first != 0) do
1273 var i = ends.last - 1
1274 var e = items[i]
1275 remove e
1276 add e
1277 moved.add e
1278 max -= 1
1279 end
1280
1281 if starts.length == 1 and starts.first == 0 then
1282 for i in [length..capacity[ do items.pop
1283 available.clear
1284 end
1285
1286 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1287 return moved
1288 end
1289
1290 redef fun to_s
1291 do
1292 var ss = new Array[String]
1293 for s in starts, e in ends do
1294 ss.add "["
1295 for i in [s..e[ do
1296 var item: nullable Object = items[i]
1297 if item == null then item = "null"
1298 ss.add item.to_s
1299 if i != e-1 then ss.add ","
1300 end
1301 ss.add "]"
1302 end
1303 return ss.join
1304 end
1305 end
1306
1307 redef class GLfloatArray
1308 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1309 do
1310 dst_offset = dst_offset or else 0
1311 var mat_len = matrix.width*matrix.height
1312 assert length >= mat_len + dst_offset
1313 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1314 end
1315 end
1316
1317 redef class NativeGLfloatArray
1318 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1319 int i;
1320 for (i = 0; i < len; i ++)
1321 self[i+dst_offset] = (GLfloat)matrix[i];
1322 `}
1323 end