geometry: move up `Point3d::offset` from gamnit
[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 var splash = new Sprite(texture, ui_camera.center)
297 ui_sprites.add splash
298
299 var display = display
300 assert display != null
301 glClear gl_COLOR_BUFFER_BIT
302 frame_core_ui_sprites display
303 display.flip
304
305 ui_sprites.remove splash
306 end
307
308 # ---
309 # Support and implementation
310
311 # Main clock used to count each frame `dt`, lapsed for `update` only
312 private var clock = new Clock is lazy
313
314 # Performance clock to for `frame_core_draw` operations
315 private var perf_clock_main = new Clock
316
317 # Second performance clock for smaller operations
318 private var perf_clock_sprites = new Clock is lazy
319
320 redef fun on_create
321 do
322 super
323
324 var display = display
325 assert display != null
326
327 var gl_error = glGetError
328 assert gl_error == gl_NO_ERROR else print_error gl_error
329
330 # Prepare program
331 var program = simple_2d_program
332 program.compile_and_link
333
334 var gamnit_error = program.error
335 assert gamnit_error == null else print_error gamnit_error
336
337 # Enable blending
338 gl.capabilities.blend.enable
339 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
340
341 # Enable depth test
342 gl.capabilities.depth_test.enable
343 glDepthFunc gl_LEQUAL
344 glDepthMask true
345
346 # Prepare viewport and background color
347 glViewport(0, 0, display.width, display.height)
348 glClearColor(0.0, 0.0, 0.0, 1.0)
349
350 gl_error = glGetError
351 assert gl_error == gl_NO_ERROR else print_error gl_error
352
353 # Prepare to draw
354 for tex in all_root_textures do
355 tex.load
356 gamnit_error = tex.error
357 if gamnit_error != null then print_error gamnit_error
358
359 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
360 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
361 end
362 end
363
364 redef fun on_stop
365 do
366 # Clean up
367 simple_2d_program.delete
368
369 # Close gamnit
370 var display = display
371 if display != null then display.close
372 end
373
374 redef fun frame_core(display)
375 do
376 # Prepare to draw, clear buffers
377 glClear(gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT)
378
379 # Check errors
380 var gl_error = glGetError
381 assert gl_error == gl_NO_ERROR else print_error gl_error
382
383 # Update game logic and set sprites
384 perf_clock_main.lapse
385 var dt = clock.lapse.to_f
386 update dt
387 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
388
389 # Draw and flip screen
390 frame_core_draw display
391 display.flip
392
393 # Check errors
394 gl_error = glGetError
395 assert gl_error == gl_NO_ERROR else print_error gl_error
396 end
397
398 # Draw the whole screen, all `glDraw...` calls should be executed here
399 protected fun frame_core_draw(display: GamnitDisplay)
400 do
401 frame_core_dynamic_resolution_before display
402
403 perf_clock_main.lapse
404 frame_core_world_sprites display
405 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
406
407 frame_core_ui_sprites display
408 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
409
410 frame_core_dynamic_resolution_after display
411 end
412
413 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
414 do
415 var simple_2d_program = app.simple_2d_program
416 simple_2d_program.use
417 simple_2d_program.mvp.uniform camera.mvp_matrix
418
419 # draw
420 sprite_set.draw
421 end
422
423 # Draw world sprites from `sprites`
424 protected fun frame_core_world_sprites(display: GamnitDisplay)
425 do
426 frame_core_sprites(display, sprites.as(SpriteSet), world_camera)
427 end
428
429 # Draw UI sprites from `ui_sprites`
430 protected fun frame_core_ui_sprites(display: GamnitDisplay)
431 do
432 # Reset only the depth buffer
433 glClear gl_DEPTH_BUFFER_BIT
434
435 frame_core_sprites(display, ui_sprites.as(SpriteSet), ui_camera)
436 end
437 end
438
439 redef class Texture
440
441 # Vertices coordinates of the base geometry
442 #
443 # Defines the default width and height of related sprites.
444 private var vertices: Array[Float] is lazy do
445 var w = width
446 var h = height
447 return [-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 0.5*w, -0.5*h, 0.0]
451 end
452
453 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
454 private var texture_coords: Array[Float] is lazy do
455 var l = offset_left
456 var r = offset_right
457 var b = offset_bottom
458 var t = offset_top
459 return [l, t,
460 r, t,
461 l, b,
462 r, b]
463 end
464
465 # Coordinates of this texture on the `root` texture, inverting the X axis
466 private var texture_coords_invert_x: Array[Float] is lazy do
467 var l = offset_left
468 var r = offset_right
469 var b = offset_bottom
470 var t = offset_top
471 return [r, t,
472 l, t,
473 r, b,
474 l, b]
475 end
476 end
477
478 # Graphic program to display simple models with a texture, translation, rotation and scale
479 private class Simple2dProgram
480 super GamnitProgramFromSource
481
482 redef var vertex_shader_source = """
483 // Vertex coordinates
484 attribute vec4 coord;
485
486 // Vertex color tint
487 attribute vec4 color;
488
489 // Vertex translation
490 attribute vec4 translation;
491
492 // Vertex scaling
493 attribute float scale;
494
495 // Vertex coordinates on textures
496 attribute vec2 tex_coord;
497
498 // Model view projection matrix
499 uniform mat4 mvp;
500
501 // Rotation matrix
502 attribute vec4 rotation_row0;
503 attribute vec4 rotation_row1;
504 attribute vec4 rotation_row2;
505 attribute vec4 rotation_row3;
506
507 mat4 rotation()
508 {
509 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
510 }
511
512 // Output to the fragment shader
513 varying vec4 v_color;
514 varying vec2 v_coord;
515
516 void main()
517 {
518 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
519 v_color = color;
520 v_coord = tex_coord;
521 }
522 """ @ glsl_vertex_shader
523
524 redef var fragment_shader_source = """
525 precision mediump float;
526
527 // Does this object use a texture?
528 uniform bool use_texture;
529
530 // Texture to apply on this object
531 uniform sampler2D texture0;
532
533 // Input from the vertex shader
534 varying vec4 v_color;
535 varying vec2 v_coord;
536
537 void main()
538 {
539 if(use_texture) {
540 gl_FragColor = v_color * texture2D(texture0, v_coord);
541 if (gl_FragColor.a <= 0.01) discard;
542 } else {
543 gl_FragColor = v_color;
544 }
545 }
546 """ @ glsl_fragment_shader
547
548 # Vertices coordinates
549 var coord = attributes["coord"].as(AttributeVec4) is lazy
550
551 # Should this program use the texture `texture`?
552 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
553
554 # Visible texture unit
555 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
556
557 # Coordinates on the textures, per vertex
558 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
559
560 # Color tint per vertex
561 var color = attributes["color"].as(AttributeVec4) is lazy
562
563 # Translation applied to each vertex
564 var translation = attributes["translation"].as(AttributeVec4) is lazy
565
566 # Rotation matrix, row 0
567 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
568
569 # Rotation matrix, row 1
570 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
571
572 # Rotation matrix, row 2
573 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
574
575 # Rotation matrix, row 3
576 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
577
578 # Scaling per vertex
579 var scale = attributes["scale"].as(AttributeFloat) is lazy
580
581 # Model view projection matrix
582 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
583 end
584
585 redef class Point3d[N]
586 # ---
587 # Associate each point to its sprites
588
589 private var sprites: nullable Array[Sprite] = null
590
591 private fun sprites_add(sprite: Sprite)
592 do
593 var sprites = sprites
594 if sprites == null then
595 sprites = new Array[Sprite]
596 self.sprites = sprites
597 end
598 sprites.add sprite
599 end
600
601 private fun sprites_remove(sprite: Sprite)
602 do
603 var sprites = sprites
604 assert sprites != null
605 sprites.remove sprite
606 end
607
608 # ---
609 # Notify `sprites` on attribute modification
610
611 private fun needs_update
612 do
613 var sprites = sprites
614 if sprites != null then for s in sprites do s.needs_update
615 end
616
617 redef fun x=(v)
618 do
619 if isset _x and v != x then needs_update
620 super
621 end
622
623 redef fun y=(v)
624 do
625 if isset _y and v != y then needs_update
626 super
627 end
628
629 redef fun z=(v)
630 do
631 if isset _z and v != z then needs_update
632 super
633 end
634 end
635
636 # Set of sprites sorting them into different `SpriteContext`
637 private class SpriteSet
638 super HashSet[Sprite]
639
640 # Map texture then static vs dynamic to a `SpriteContext`
641 var contexts_map = new HashMap2[RootTexture, Bool, SpriteContext]
642
643 # Contexts in `contexts_map`
644 var contexts_items = new Array[SpriteContext]
645
646 # Sprites needing resorting in `contexts_map`
647 var sprites_to_remap = new Array[Sprite]
648
649 # Add a sprite to the appropriate context
650 fun map_sprite(sprite: Sprite)
651 do
652 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
653
654 var texture = sprite.texture.root
655 var context = contexts_map[texture, sprite.static]
656
657 if context == null then
658 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
659 context = new SpriteContext(texture, usage)
660
661 contexts_map[texture, sprite.static] = context
662 contexts_items.add context
663 end
664
665 context.sprites.add sprite
666 context.sprites_to_update.add sprite
667
668 sprite.context = context
669 sprite.sprite_set = self
670 end
671
672 # Remove a sprite from its context
673 fun unmap_sprite(sprite: Sprite)
674 do
675 var context = sprite.context
676 assert context != null
677 context.sprites.remove sprite
678
679 sprite.context = null
680 sprite.sprite_set = null
681 end
682
683 # Draw all sprites by all contexts
684 fun draw
685 do
686 for sprite in sprites_to_remap do
687 unmap_sprite sprite
688 map_sprite sprite
689 end
690 sprites_to_remap.clear
691
692 for context in contexts_items do context.draw
693 end
694
695 redef fun add(e)
696 do
697 if contexts_items.has(e.context) then return
698 map_sprite e
699 super
700 end
701
702 redef fun remove(e)
703 do
704 super
705 if e isa Sprite then unmap_sprite e
706 end
707
708 redef fun remove_all(e)
709 do
710 if not has(e) then return
711 remove e
712 end
713
714 redef fun clear
715 do
716 for sprite in self do
717 sprite.context = null
718 sprite.sprite_set = null
719 end
720 super
721 for c in contexts_items do c.destroy
722 contexts_map.clear
723 contexts_items.clear
724 end
725 end
726
727 # Context for calls to `glDrawElements`
728 #
729 # Each context has only one `texture` and `usage`, but many sprites.
730 private class SpriteContext
731
732 # ---
733 # Context config and state
734
735 # Only root texture drawn by this context
736 var texture: nullable RootTexture
737
738 # OpenGL ES usage of `buffer_array` and `buffer_element`
739 var usage: GLBufferUsage
740
741 # Sprites drawn by this context
742 var sprites = new GroupedArray[Sprite]
743
744 # Sprites to update since last `draw`
745 var sprites_to_update = new Set[Sprite]
746
747 # Sprites that have been update and for which `needs_update` can be set to false
748 var updated_sprites = new Array[Sprite]
749
750 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
751 #
752 # Require: `resize_ratio >= 1.0`
753 var resize_ratio = 1.2
754
755 # ---
756 # OpenGL ES data
757
758 # OpenGL ES buffer name for vertex data
759 var buffer_array: Int = -1
760
761 # OpenGL ES buffer name for indices
762 var buffer_element: Int = -1
763
764 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
765 var buffer_capacity = 0
766
767 # C buffers used to pass the data of a single sprite
768 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
769 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
770
771 # ---
772 # Constants
773
774 # Number of GL_FLOAT per vertex of `Simple2dProgram`
775 var float_per_vertex: Int is lazy do
776 # vec4 translation, vec4 color, vec4 coord,
777 # float scale, vec2 tex_coord, vec4 rotation_row*
778 return 4 + 4 + 4 +
779 1 + 2 + 4*4
780 end
781
782 # Number of bytes per vertex of `Simple2dProgram`
783 var bytes_per_vertex: Int is lazy do
784 var fs = 4 # sizeof(GL_FLOAT)
785 return fs * float_per_vertex
786 end
787
788 # Number of bytes per sprite
789 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
790
791 # Number of vertex indices per sprite draw call (2 triangles)
792 var indices_per_sprite = 6
793
794 # ---
795 # Main services
796
797 # Allocate `buffer_array` and `buffer_element`
798 fun prepare
799 do
800 var bufs = glGenBuffers(2)
801 buffer_array = bufs[0]
802 buffer_element = bufs[1]
803
804 var gl_error = glGetError
805 assert gl_error == gl_NO_ERROR else print_error gl_error
806 end
807
808 # Destroy `buffer_array` and `buffer_element`
809 fun destroy
810 do
811 glDeleteBuffers([buffer_array, buffer_element])
812 var gl_error = glGetError
813 assert gl_error == gl_NO_ERROR else print_error gl_error
814
815 buffer_array = -1
816 buffer_element = -1
817 end
818
819 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
820 fun resize
821 do
822 app.perf_clock_sprites.lapse
823
824 # Allocate a bit more space
825 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
826
827 var array_bytes = capacity * bytes_per_sprite
828 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
829 assert glIsBuffer(buffer_array)
830 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
831 var gl_error = glGetError
832 assert gl_error == gl_NO_ERROR else print_error gl_error
833
834 # GL_TRIANGLES 6 vertices * sprite
835 var n_indices = capacity * indices_per_sprite
836 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
837 var element_bytes = n_indices * ius
838 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
839 assert glIsBuffer(buffer_element)
840 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
841 gl_error = glGetError
842 assert gl_error == gl_NO_ERROR else print_error gl_error
843
844 buffer_capacity = capacity
845
846 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
847 end
848
849 # Update GPU data of `sprite`
850 fun update_sprite(sprite: Sprite)
851 do
852 var sprite_index = sprites.index_of(sprite)
853 if sprite_index == -1 then return
854
855 # Vertices data
856
857 var data = local_data_buffer
858 var o = 0
859 for v in [0..4[ do
860 # vec4 translation
861 data[o+ 0] = sprite.center.x
862 data[o+ 1] = sprite.center.y
863 data[o+ 2] = sprite.center.z
864 data[o+ 3] = 0.0
865
866 # vec4 color
867 data[o+ 4] = sprite.tint[0]
868 data[o+ 5] = sprite.tint[1]
869 data[o+ 6] = sprite.tint[2]
870 data[o+ 7] = sprite.tint[3]
871
872 # float scale
873 data[o+ 8] = sprite.scale
874
875 # vec4 coord
876 data[o+ 9] = sprite.texture.vertices[v*3+0]
877 data[o+10] = sprite.texture.vertices[v*3+1]
878 data[o+11] = sprite.texture.vertices[v*3+2]
879 data[o+12] = 0.0
880
881 # vec2 tex_coord
882 var texture = texture
883 if texture != null then
884 var tc = if sprite.invert_x then
885 sprite.texture.texture_coords_invert_x
886 else sprite.texture.texture_coords
887 data[o+13] = tc[v*2+0]
888 data[o+14] = tc[v*2+1]
889 end
890
891 # mat4 rotation
892 var rot
893 if sprite.rotation == 0.0 then
894 # Cache the matrix at no rotation
895 rot = once new Matrix.identity(4)
896 else
897 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
898 end
899 data.fill_from_matrix(rot, o+15)
900
901 o += float_per_vertex
902 end
903
904 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
905 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
906
907 var gl_error = glGetError
908 assert gl_error == gl_NO_ERROR else print_error gl_error
909
910 # Element / indices
911 #
912 # 0--1
913 # | /|
914 # |/ |
915 # 2--3
916
917 var indices = local_indices_buffer
918 var io = sprite_index*4
919 indices[0] = io+0
920 indices[1] = io+2
921 indices[2] = io+1
922 indices[3] = io+1
923 indices[4] = io+2
924 indices[5] = io+3
925
926 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
927 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
928
929 gl_error = glGetError
930 assert gl_error == gl_NO_ERROR else print_error gl_error
931 end
932
933 # Draw all `sprites`
934 #
935 # Call `resize` and `update_sprite` as needed before actual draw operation.
936 #
937 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
938 fun draw
939 do
940 if buffer_array == -1 then prepare
941
942 assert buffer_array > 0 and buffer_element > 0 else
943 print_error "Internal error: {self} was destroyed"
944 end
945
946 # Setup
947 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
948 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
949
950 # Resize GPU buffers?
951 if sprites.capacity > buffer_capacity then
952 # Try to defragment first
953 var moved = sprites.defragment
954
955 if sprites.capacity > buffer_capacity then
956 # Defragmentation wasn't enough, grow
957 resize
958
959 # We must update everything
960 for s in sprites.items do if s != null then sprites_to_update.add s
961 else
962 # Just update the moved sprites
963 for s in moved do sprites_to_update.add s
964 end
965 else if sprites.available.not_empty then
966 # Defragment a bit anyway
967 # TODO defrag only when there's time left on a frame
968 var moved = sprites.defragment(1)
969 for s in moved do sprites_to_update.add s
970 end
971
972 # Update GPU sprites data
973 if sprites_to_update.not_empty then
974 app.perf_clock_sprites.lapse
975
976 for sprite in sprites_to_update do update_sprite(sprite)
977 sprites_to_update.clear
978
979 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
980 end
981
982 # Update uniforms specific to this context
983 var texture = texture
984 app.simple_2d_program.use_texture.uniform texture != null
985 if texture != null then
986 glActiveTexture gl_TEXTURE0
987 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
988 app.simple_2d_program.texture.uniform 0
989 end
990 var gl_error = glGetError
991 assert gl_error == gl_NO_ERROR else print_error gl_error
992
993 # Configure attributes, in order:
994 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
995 var offset = 0
996 var p = app.simple_2d_program
997 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
998
999 var size = 4 # Number of floats
1000 glEnableVertexAttribArray p.translation.location
1001 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1002 offset += size * sizeof_gl_float
1003 gl_error = glGetError
1004 assert gl_error == gl_NO_ERROR else print_error gl_error
1005
1006 size = 4
1007 glEnableVertexAttribArray p.color.location
1008 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1009 offset += size * sizeof_gl_float
1010 gl_error = glGetError
1011 assert gl_error == gl_NO_ERROR else print_error gl_error
1012
1013 size = 1
1014 glEnableVertexAttribArray p.scale.location
1015 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1016 offset += size * sizeof_gl_float
1017 gl_error = glGetError
1018 assert gl_error == gl_NO_ERROR else print_error gl_error
1019
1020 size = 4
1021 glEnableVertexAttribArray p.coord.location
1022 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1023 offset += size * sizeof_gl_float
1024 gl_error = glGetError
1025 assert gl_error == gl_NO_ERROR else print_error gl_error
1026
1027 size = 2
1028 glEnableVertexAttribArray p.tex_coord.location
1029 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1030 offset += size * sizeof_gl_float
1031 gl_error = glGetError
1032 assert gl_error == gl_NO_ERROR else print_error gl_error
1033
1034 size = 4
1035 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1036 if r.is_active then
1037 glEnableVertexAttribArray r.location
1038 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1039 end
1040 offset += size * sizeof_gl_float
1041 gl_error = glGetError
1042 assert gl_error == gl_NO_ERROR else print_error gl_error
1043 end
1044
1045 # Actual draw
1046 for s in sprites.starts, e in sprites.ends do
1047 var l = e-s
1048 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1049 gl_error = glGetError
1050 assert gl_error == gl_NO_ERROR else print_error gl_error
1051 end
1052
1053 # Take down
1054 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1055 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1056 if not attr.is_active then continue
1057 glDisableVertexAttribArray(attr.location)
1058 gl_error = glGetError
1059 assert gl_error == gl_NO_ERROR else print_error gl_error
1060 end
1061
1062 glBindBuffer(gl_ARRAY_BUFFER, 0)
1063 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1064 gl_error = glGetError
1065 assert gl_error == gl_NO_ERROR else print_error gl_error
1066 end
1067 end
1068
1069 # Representation of sprite data on the GPU
1070 #
1071 # The main purpose of this class is to optimize the use of contiguous
1072 # space in GPU memory. Each contiguous memory block can be drawn in a
1073 # single call. The starts index of each block is kept by `starts,
1074 # and the end + 1 by `ends`.
1075 #
1076 # The data can be compressed by a call to `defragment`.
1077 #
1078 # ~~~
1079 # intrude import gamnit::flat
1080 #
1081 # var array = new GroupedArray[String]
1082 # assert array.to_s == ""
1083 #
1084 # array.add "a"
1085 # array.add "b"
1086 # array.add "c"
1087 # array.add "d"
1088 # array.add "e"
1089 # array.add "f"
1090 # assert array.to_s == "[a,b,c,d,e,f]"
1091 # assert array.capacity == 6
1092 #
1093 # array.remove "a"
1094 # assert array.to_s == "[b,c,d,e,f]"
1095 #
1096 # array.remove "b"
1097 # assert array.to_s == "[c,d,e,f]"
1098 #
1099 # array.remove "f"
1100 # assert array.to_s == "[c,d,e]"
1101 #
1102 # array.remove "d"
1103 # assert array.to_s == "[c][e]"
1104 #
1105 # array.add "A"
1106 # assert array.to_s == "[A][c][e]"
1107 #
1108 # array.add "B"
1109 # assert array.to_s == "[A,B,c][e]"
1110 #
1111 # array.remove "e"
1112 # assert array.to_s == "[A,B,c]"
1113 #
1114 # array.add "D"
1115 # assert array.to_s == "[A,B,c,D]"
1116 #
1117 # array.add "E"
1118 # assert array.to_s == "[A,B,c,D,E]"
1119 # assert array.capacity == 6
1120 # assert array.length == 5
1121 #
1122 # array.remove "A"
1123 # array.remove "B"
1124 # array.remove "c"
1125 # array.remove "D"
1126 # array.remove "E"
1127 # assert array.to_s == ""
1128 #
1129 # array.add "a"
1130 # assert array.to_s == "[a]"
1131 # ~~~
1132 private class GroupedArray[E]
1133
1134 # Memory with actual objects, and null in empty slots
1135 var items = new Array[nullable E]
1136
1137 # Number of items in the array
1138 var length = 0
1139
1140 # Number of item slots in the array
1141 fun capacity: Int do return items.length
1142
1143 # Index of `item`
1144 fun index_of(item: E): Int do return items.index_of(item)
1145
1146 # List of available slots
1147 var available = new MinHeap[Int].default
1148
1149 # Start index of filled chunks
1150 var starts = new List[Int]
1151
1152 # Index of the spots after filled chunks
1153 var ends = new List[Int]
1154
1155 # Add `item` to the first available slot
1156 fun add(item: E)
1157 do
1158 length += 1
1159
1160 if available.not_empty then
1161 # starts & ends can't be empty
1162
1163 var i = available.take
1164 items[i] = item
1165
1166 if i == starts.first - 1 then
1167 # slot 0 free, 1 taken
1168 starts.first -= 1
1169 else if i == 0 then
1170 # slot 0 and more free
1171 starts.unshift 0
1172 ends.unshift 1
1173 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1174 # merge 2 chunks
1175 ends.remove_at 0
1176 starts.remove_at 1
1177 else
1178 # at end of first chunk
1179 ends.first += 1
1180 end
1181 return
1182 end
1183
1184 items.add item
1185 if ends.is_empty then
1186 starts.add 0
1187 ends.add 1
1188 else ends.last += 1
1189 end
1190
1191 # Remove the first instance of `item`
1192 fun remove(item: E)
1193 do
1194 var i = items.index_of(item)
1195 assert i != -1
1196 length -= 1
1197 items[i] = null
1198
1199 var ii = 0
1200 for s in starts, e in ends do
1201 if s <= i and i < e then
1202 if s == e-1 then
1203 # single item chunk
1204 starts.remove_at ii
1205 ends.remove_at ii
1206
1207 if starts.is_empty then
1208 items.clear
1209 available.clear
1210 return
1211 end
1212 else if e-1 == i then
1213 # last item of chunk
1214 ends[ii] -= 1
1215
1216 else if s == i then
1217 # first item of chunk
1218 starts[ii] += 1
1219 else
1220 # break up chunk
1221 ends.insert(ends[ii], ii+1)
1222 ends[ii] = i
1223 starts.insert(i+1, ii+1)
1224 end
1225
1226 available.add i
1227 return
1228 end
1229 ii += 1
1230 end
1231
1232 abort
1233 end
1234
1235 # Defragment and compress everything into a single chunks beginning at 0
1236 #
1237 # Returns the elements that moved as a list.
1238 #
1239 # ~~~
1240 # intrude import gamnit::flat
1241 #
1242 # var array = new GroupedArray[String]
1243 # array.add "a"
1244 # array.add "b"
1245 # array.add "c"
1246 # array.add "d"
1247 # array.remove "c"
1248 # array.remove "a"
1249 # assert array.to_s == "[b][d]"
1250 #
1251 # var moved = array.defragment
1252 # assert moved.to_s == "[d]"
1253 # assert array.to_s == "[d,b]"
1254 # assert array.length == 2
1255 # assert array.capacity == 2
1256 #
1257 # array.add "e"
1258 # array.add "f"
1259 # assert array.to_s == "[d,b,e,f]"
1260 # ~~~
1261 fun defragment(max: nullable Int): Array[E]
1262 do
1263 app.perf_clock_sprites.lapse
1264 max = max or else length
1265
1266 var moved = new Array[E]
1267 while max > 0 and (starts.length > 1 or starts.first != 0) do
1268 var i = ends.last - 1
1269 var e = items[i]
1270 remove e
1271 add e
1272 moved.add e
1273 max -= 1
1274 end
1275
1276 if starts.length == 1 and starts.first == 0 then
1277 for i in [length..capacity[ do items.pop
1278 available.clear
1279 end
1280
1281 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1282 return moved
1283 end
1284
1285 redef fun to_s
1286 do
1287 var ss = new Array[String]
1288 for s in starts, e in ends do
1289 ss.add "["
1290 for i in [s..e[ do
1291 var item: nullable Object = items[i]
1292 if item == null then item = "null"
1293 ss.add item.to_s
1294 if i != e-1 then ss.add ","
1295 end
1296 ss.add "]"
1297 end
1298 return ss.join
1299 end
1300 end
1301
1302 redef class GLfloatArray
1303 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1304 do
1305 dst_offset = dst_offset or else 0
1306 var mat_len = matrix.width*matrix.height
1307 assert length >= mat_len + dst_offset
1308 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1309 end
1310 end
1311
1312 redef class NativeGLfloatArray
1313 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1314 int i;
1315 for (i = 0; i < len; i ++)
1316 self[i+dst_offset] = (GLfloat)matrix[i];
1317 `}
1318 end