1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Simple API for 2D games, built around `Sprite` and `App::update`
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.
21 # This system relies on two cameras `App::world_camera` and `App::ui_camera`.
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`.
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`.
32 # See the sample game at `contrib/asteronits/` and the basic project template
33 # at `lib/gamnit/examples/template/`.
37 intrude import geometry
::points_and_lines
# For _x, _y and _z
39 import matrix
::projection
40 import more_collections
41 import performance_analysis
44 import gamnit
::cameras_cache
45 import gamnit
::dynamic_resolution
46 import gamnit
::limit_fps
47 import gamnit
::camera_control
49 # Visible 2D entity in the game world or UI
51 # Similar to `gamnit::Actor` which is in 3D.
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.
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
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))
70 # # Add sprite to the visible game world
71 # app.sprites.add sprite
73 # # Extra configuration of the sprite
74 # sprite.rotation = pi/2.0
77 # # Show only the blue colors
82 # To add a sprite to the UI it can be anchored to screen borders
83 # with `ui_camera.top_left` and the likes.
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)
89 # # Load texture and create sprite
90 # var texture = new Texture("path/in/assets.png")
91 # var sprite = new Sprite(texture, pos)
93 # # Add it to the UI (above world sprites)
94 # app.ui_sprites.add sprite
98 # Texture drawn to screen
99 var texture
: Texture is writable(texture_direct
=)
101 # Texture drawn to screen
102 fun texture
=(value
: Texture)
104 if isset _texture
and value
!= texture
then
106 if value
.root
!= texture
.root
then needs_remap
108 texture_direct
= value
111 # Center position of this sprite in world coordinates
112 var center
: Point3d[Float] is writable(center_direct
=), noautoinit
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
118 center
.sprites_remove
self
121 value
.sprites_add
self
122 center_direct
= value
125 # Rotation on the Z axis, positive values turn counterclockwise
126 var rotation
= 0.0 is writable(rotation_direct
=)
128 # Rotation on the Z axis, positive values turn counterclockwise
129 fun rotation
=(value
: Float)
131 if isset _rotation
and value
!= rotation
then needs_update
132 rotation_direct
= value
135 # Mirror `texture` horizontally, inverting each pixel on the X axis
136 var invert_x
= false is writable(invert_x_direct
=)
138 # Mirror `texture` horizontally, inverting each pixel on the X axis
139 fun invert_x
=(value
: Bool)
141 if isset _invert_x
and value
!= invert_x
then needs_update
142 invert_x_direct
= value
145 # Scale applied to this sprite
147 # The basic size of `self` depends on the size in pixels of `texture`.
148 var scale
= 1.0 is writable(scale_direct
=)
150 # Scale applied to this sprite
152 # The basic size of `self` depends on the size in pixels of `texture`.
153 fun scale
=(value
: Float)
155 if isset _scale
and value
!= scale
then needs_update
159 # Red tint applied to `texture` on draw
160 fun red
: Float do return tint
[0]
162 # Red tint applied to `texture` on draw
163 fun red
=(value
: Float)
165 if isset _tint
and value
!= red
then needs_update
169 # Green tint applied to `texture` on draw
170 fun green
: Float do return tint
[1]
172 # Green tint applied to `texture` on draw
173 fun green
=(value
: Float)
175 if isset _tint
and value
!= green
then needs_update
179 # Blue tint applied to `texture` on draw
180 fun blue
: Float do return tint
[2]
182 # Blue tint applied to `texture` on draw
183 fun blue
=(value
: Float)
185 if isset _tint
and value
!= blue
then needs_update
189 # Transparency applied to `texture` on draw
190 fun alpha
: Float do return tint
[3]
192 # Transparency applied to `texture` on draw
193 fun alpha
=(value
: Float)
195 if isset _tint
and value
!= alpha
then needs_update
199 # Tint applied to `texture` on draw
201 # Alternative to the accessors `red, green, blue & alpha`.
202 # Changes inside the array do not automatically set `needs_update`.
204 # Require: `tint.length == 4`
205 var tint
: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct
=)
207 # Tint applied to `texture` on draw, see `tint`
208 fun tint
=(value
: Array[Float])
210 if isset _tint
and value
!= tint
then needs_update
214 # Is this sprite static and added in bulk?
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
=)
222 # Is this sprite static and added in bulk? see `static`
223 fun static
=(value
: Bool)
225 if isset _static
and value
!= static
then needs_remap
226 static_direct
= value
229 # Request an update on the CPU
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.
237 if c
!= null then c
.sprites_to_update
.add
self
240 # Request a resorting of this sprite in its sprite list
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.
249 if l
!= null then l
.sprites_to_remap
.add
self
252 # Current context to which `self` was sorted
253 private var context
: nullable SpriteContext = null
255 # Current context to which `self` belongs
256 private var sprite_set
: nullable SpriteSet = null
260 # Default graphic program to draw `sprites`
261 private var simple_2d_program
= new Simple2dProgram is lazy
263 # Camera for world `sprites` and `depth::actors` with perspective
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))
270 # Aim for full HD pixel resolution at level 0
271 camera
.reset_height
1080.0
277 # Camera for `ui_sprites` using an orthogonal view
278 var ui_camera
= new UICamera(app
.display
.as(not null)) is lazy
280 # World sprites drawn as seen by `world_camera`
281 var sprites
: Set[Sprite] = new SpriteSet
283 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
284 var ui_sprites
: Set[Sprite] = new SpriteSet
286 # Main method to refine in clients to update game logic and `sprites`
287 fun update
(dt
: Float) do end
289 # Display `texture` as a splash screen
291 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
292 fun show_splash_screen
(texture
: Texture)
296 ui_camera
.reset_height
1080.0
298 var splash
= new Sprite(texture
, ui_camera
.center
)
299 ui_sprites
.add splash
301 var display
= display
302 assert display
!= null
303 glClear gl_COLOR_BUFFER_BIT
304 frame_core_ui_sprites display
307 ui_sprites
.remove splash
311 # Support and implementation
313 # Main clock used to count each frame `dt`, lapsed for `update` only
314 private var clock
= new Clock is lazy
316 # Performance clock to for `frame_core_draw` operations
317 private var perf_clock_main
= new Clock
319 # Second performance clock for smaller operations
320 private var perf_clock_sprites
= new Clock is lazy
326 var display
= display
327 assert display
!= null
329 var gl_error
= glGetError
330 assert gl_error
== gl_NO_ERROR
else print_error gl_error
333 var program
= simple_2d_program
334 program
.compile_and_link
336 var gamnit_error
= program
.error
337 assert gamnit_error
== null else print_error gamnit_error
340 gl
.capabilities
.blend
.enable
341 glBlendFunc
(gl_SRC_ALPHA
, gl_ONE_MINUS_SRC_ALPHA
)
344 gl
.capabilities
.depth_test
.enable
345 glDepthFunc gl_LEQUAL
348 # Prepare viewport and background color
349 glViewport
(0, 0, display
.width
, display
.height
)
350 glClearColor
(0.0, 0.0, 0.0, 1.0)
352 gl_error
= glGetError
353 assert gl_error
== gl_NO_ERROR
else print_error gl_error
356 for tex
in all_root_textures
do
358 gamnit_error
= tex
.error
359 if gamnit_error
!= null then print_error gamnit_error
361 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
362 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
369 simple_2d_program
.delete
372 var display
= display
373 if display
!= null then display
.close
376 redef fun frame_core
(display
)
378 # Prepare to draw, clear buffers
379 glClear
(gl_COLOR_BUFFER_BIT
| gl_DEPTH_BUFFER_BIT
)
382 var gl_error
= glGetError
383 assert gl_error
== gl_NO_ERROR
else print_error gl_error
385 # Update game logic and set sprites
386 perf_clock_main
.lapse
387 var dt
= clock
.lapse
.to_f
389 sys
.perfs
["gamnit flat update client"].add perf_clock_main
.lapse
391 # Draw and flip screen
392 frame_core_draw display
396 gl_error
= glGetError
397 assert gl_error
== gl_NO_ERROR
else print_error gl_error
400 # Draw the whole screen, all `glDraw...` calls should be executed here
401 protected fun frame_core_draw
(display
: GamnitDisplay)
403 frame_core_dynamic_resolution_before display
405 perf_clock_main
.lapse
406 frame_core_world_sprites display
407 perfs
["gamnit flat world_sprites"].add perf_clock_main
.lapse
409 frame_core_ui_sprites display
410 perfs
["gamnit flat ui_sprites"].add perf_clock_main
.lapse
412 frame_core_dynamic_resolution_after display
415 private fun frame_core_sprites
(display
: GamnitDisplay, sprite_set
: SpriteSet, camera
: Camera)
417 var simple_2d_program
= app
.simple_2d_program
418 simple_2d_program
.use
419 simple_2d_program
.mvp
.uniform camera
.mvp_matrix
425 # Draw world sprites from `sprites`
426 protected fun frame_core_world_sprites
(display
: GamnitDisplay)
428 frame_core_sprites
(display
, sprites
.as(SpriteSet), world_camera
)
431 # Draw UI sprites from `ui_sprites`
432 protected fun frame_core_ui_sprites
(display
: GamnitDisplay)
434 # Reset only the depth buffer
435 glClear gl_DEPTH_BUFFER_BIT
437 frame_core_sprites
(display
, ui_sprites
.as(SpriteSet), ui_camera
)
443 # Vertices coordinates of the base geometry
445 # Defines the default width and height of related sprites.
446 private var vertices
: Array[Float] is lazy
do
449 return [-0.5*w
, 0.5*h
, 0.0,
455 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
456 private var texture_coords
: Array[Float] is lazy
do
459 var b
= offset_bottom
467 # Coordinates of this texture on the `root` texture, inverting the X axis
468 private var texture_coords_invert_x
: Array[Float] is lazy
do
471 var b
= offset_bottom
480 # Graphic program to display simple models with a texture, translation, rotation and scale
481 private class Simple2dProgram
482 super GamnitProgramFromSource
484 redef var vertex_shader_source
= """
485 // Vertex coordinates
486 attribute vec4 coord;
489 attribute vec4 color;
491 // Vertex translation
492 attribute vec4 translation;
495 attribute float scale;
497 // Vertex coordinates on textures
498 attribute vec2 tex_coord;
500 // Model view projection matrix
504 attribute vec4 rotation_row0;
505 attribute vec4 rotation_row1;
506 attribute vec4 rotation_row2;
507 attribute vec4 rotation_row3;
511 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
514 // Output to the fragment shader
515 varying vec4 v_color;
516 varying vec2 v_coord;
520 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
524 """ @ glsl_vertex_shader
526 redef var fragment_shader_source
= """
527 precision mediump float;
529 // Does this object use a texture?
530 uniform bool use_texture;
532 // Texture to apply on this object
533 uniform sampler2D texture0;
535 // Input from the vertex shader
536 varying vec4 v_color;
537 varying vec2 v_coord;
542 gl_FragColor = v_color * texture2D(texture0, v_coord);
543 if (gl_FragColor.a <= 0.01) discard;
545 gl_FragColor = v_color;
548 """ @ glsl_fragment_shader
550 # Vertices coordinates
551 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
553 # Should this program use the texture `texture`?
554 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
556 # Visible texture unit
557 var texture
= uniforms
["texture0"].as(UniformSampler2D) is lazy
559 # Coordinates on the textures, per vertex
560 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
562 # Color tint per vertex
563 var color
= attributes
["color"].as(AttributeVec4) is lazy
565 # Translation applied to each vertex
566 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
568 # Rotation matrix, row 0
569 var rotation_row0
= attributes
["rotation_row0"].as(AttributeVec4) is lazy
571 # Rotation matrix, row 1
572 var rotation_row1
= attributes
["rotation_row1"].as(AttributeVec4) is lazy
574 # Rotation matrix, row 2
575 var rotation_row2
= attributes
["rotation_row2"].as(AttributeVec4) is lazy
577 # Rotation matrix, row 3
578 var rotation_row3
= attributes
["rotation_row3"].as(AttributeVec4) is lazy
581 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
583 # Model view projection matrix
584 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
587 redef class Point3d[N
]
588 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
589 fun offset
(x
, y
, z
: Numeric): Point3d[Float]
591 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
)
595 # Associate each point to its sprites
597 private var sprites
: nullable Array[Sprite] = null
599 private fun sprites_add
(sprite
: Sprite)
601 var sprites
= sprites
602 if sprites
== null then
603 sprites
= new Array[Sprite]
604 self.sprites
= sprites
609 private fun sprites_remove
(sprite
: Sprite)
611 var sprites
= sprites
612 assert sprites
!= null
613 sprites
.remove sprite
617 # Notify `sprites` on attribute modification
619 private fun needs_update
621 var sprites
= sprites
622 if sprites
!= null then for s
in sprites
do s
.needs_update
627 if isset _x
and v
!= x
then needs_update
633 if isset _y
and v
!= y
then needs_update
639 if isset _z
and v
!= z
then needs_update
644 # Set of sprites sorting them into different `SpriteContext`
645 private class SpriteSet
646 super HashSet[Sprite]
648 # Map texture then static vs dynamic to a `SpriteContext`
649 var contexts_map
= new HashMap2[RootTexture, Bool, SpriteContext]
651 # Contexts in `contexts_map`
652 var contexts_items
= new Array[SpriteContext]
654 # Sprites needing resorting in `contexts_map`
655 var sprites_to_remap
= new Array[Sprite]
657 # Add a sprite to the appropriate context
658 fun map_sprite
(sprite
: Sprite)
660 assert sprite
.context
== null else print_error
"Sprite {sprite} belongs to another SpriteSet"
662 var texture
= sprite
.texture
.root
663 var context
= contexts_map
[texture
, sprite
.static
]
665 if context
== null then
666 var usage
= if sprite
.static
then gl_STATIC_DRAW
else gl_DYNAMIC_DRAW
667 context
= new SpriteContext(texture
, usage
)
669 contexts_map
[texture
, sprite
.static
] = context
670 contexts_items
.add context
673 context
.sprites
.add sprite
674 context
.sprites_to_update
.add sprite
676 sprite
.context
= context
677 sprite
.sprite_set
= self
680 # Remove a sprite from its context
681 fun unmap_sprite
(sprite
: Sprite)
683 var context
= sprite
.context
684 assert context
!= null
685 context
.sprites
.remove sprite
687 sprite
.context
= null
688 sprite
.sprite_set
= null
691 # Draw all sprites by all contexts
694 for sprite
in sprites_to_remap
do
698 sprites_to_remap
.clear
700 for context
in contexts_items
do context
.draw
705 if contexts_items
.has
(e
.context
) then return
713 if e
isa Sprite then unmap_sprite e
716 redef fun remove_all
(e
)
718 if not has
(e
) then return
724 for sprite
in self do
725 sprite
.context
= null
726 sprite
.sprite_set
= null
729 for c
in contexts_items
do c
.destroy
735 # Context for calls to `glDrawElements`
737 # Each context has only one `texture` and `usage`, but many sprites.
738 private class SpriteContext
741 # Context config and state
743 # Only root texture drawn by this context
744 var texture
: nullable RootTexture
746 # OpenGL ES usage of `buffer_array` and `buffer_element`
747 var usage
: GLBufferUsage
749 # Sprites drawn by this context
750 var sprites
= new GroupedArray[Sprite]
752 # Sprites to update since last `draw`
753 var sprites_to_update
= new Set[Sprite]
755 # Sprites that have been update and for which `needs_update` can be set to false
756 var updated_sprites
= new Array[Sprite]
758 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
760 # Require: `resize_ratio >= 1.0`
761 var resize_ratio
= 1.2
766 # OpenGL ES buffer name for vertex data
767 var buffer_array
: Int = -1
769 # OpenGL ES buffer name for indices
770 var buffer_element
: Int = -1
772 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
773 var buffer_capacity
= 0
775 # C buffers used to pass the data of a single sprite
776 var local_data_buffer
= new GLfloatArray(float_per_vertex
*4) is lazy
777 var local_indices_buffer
= new CUInt16Array(indices_per_sprite
) is lazy
782 # Number of GL_FLOAT per vertex of `Simple2dProgram`
783 var float_per_vertex
: Int is lazy
do
784 # vec4 translation, vec4 color, vec4 coord,
785 # float scale, vec2 tex_coord, vec4 rotation_row*
790 # Number of bytes per vertex of `Simple2dProgram`
791 var bytes_per_vertex
: Int is lazy
do
792 var fs
= 4 # sizeof(GL_FLOAT)
793 return fs
* float_per_vertex
796 # Number of bytes per sprite
797 var bytes_per_sprite
: Int is lazy
do return bytes_per_vertex
* 4
799 # Number of vertex indices per sprite draw call (2 triangles)
800 var indices_per_sprite
= 6
805 # Allocate `buffer_array` and `buffer_element`
808 var bufs
= glGenBuffers
(2)
809 buffer_array
= bufs
[0]
810 buffer_element
= bufs
[1]
812 var gl_error
= glGetError
813 assert gl_error
== gl_NO_ERROR
else print_error gl_error
816 # Destroy `buffer_array` and `buffer_element`
819 glDeleteBuffers
([buffer_array
, buffer_element
])
820 var gl_error
= glGetError
821 assert gl_error
== gl_NO_ERROR
else print_error gl_error
827 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
830 app
.perf_clock_sprites
.lapse
832 # Allocate a bit more space
833 var capacity
= (sprites
.capacity
.to_f
* resize_ratio
).to_i
835 var array_bytes
= capacity
* bytes_per_sprite
836 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
837 assert glIsBuffer
(buffer_array
)
838 glBufferData
(gl_ARRAY_BUFFER
, array_bytes
, new Pointer.nul
, usage
)
839 var gl_error
= glGetError
840 assert gl_error
== gl_NO_ERROR
else print_error gl_error
842 # GL_TRIANGLES 6 vertices * sprite
843 var n_indices
= capacity
* indices_per_sprite
844 var ius
= 2 # sizeof(GL_UNSIGNED_SHORT)
845 var element_bytes
= n_indices
* ius
846 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
847 assert glIsBuffer
(buffer_element
)
848 glBufferData
(gl_ELEMENT_ARRAY_BUFFER
, element_bytes
, new Pointer.nul
, usage
)
849 gl_error
= glGetError
850 assert gl_error
== gl_NO_ERROR
else print_error gl_error
852 buffer_capacity
= capacity
854 sys
.perfs
["gamnit flat gpu resize"].add app
.perf_clock_sprites
.lapse
857 # Update GPU data of `sprite`
858 fun update_sprite
(sprite
: Sprite)
860 var sprite_index
= sprites
.index_of
(sprite
)
861 if sprite_index
== -1 then return
865 var data
= local_data_buffer
869 data
[o
+ 0] = sprite
.center
.x
870 data
[o
+ 1] = sprite
.center
.y
871 data
[o
+ 2] = sprite
.center
.z
875 data
[o
+ 4] = sprite
.tint
[0]
876 data
[o
+ 5] = sprite
.tint
[1]
877 data
[o
+ 6] = sprite
.tint
[2]
878 data
[o
+ 7] = sprite
.tint
[3]
881 data
[o
+ 8] = sprite
.scale
884 data
[o
+ 9] = sprite
.texture
.vertices
[v
*3+0]
885 data
[o
+10] = sprite
.texture
.vertices
[v
*3+1]
886 data
[o
+11] = sprite
.texture
.vertices
[v
*3+2]
890 var texture
= texture
891 if texture
!= null then
892 var tc
= if sprite
.invert_x
then
893 sprite
.texture
.texture_coords_invert_x
894 else sprite
.texture
.texture_coords
895 data
[o
+13] = tc
[v
*2+0]
896 data
[o
+14] = tc
[v
*2+1]
901 if sprite
.rotation
== 0.0 then
902 # Cache the matrix at no rotation
903 rot
= once
new Matrix.identity
(4)
905 rot
= new Matrix.rotation
(sprite
.rotation
, 0.0, 0.0, 1.0)
907 data
.fill_from_matrix
(rot
, o
+15)
909 o
+= float_per_vertex
912 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
913 glBufferSubData
(gl_ARRAY_BUFFER
, sprite_index
*bytes_per_sprite
, bytes_per_sprite
, data
.native_array
)
915 var gl_error
= glGetError
916 assert gl_error
== gl_NO_ERROR
else print_error gl_error
925 var indices
= local_indices_buffer
926 var io
= sprite_index
*4
934 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
935 glBufferSubData
(gl_ELEMENT_ARRAY_BUFFER
, sprite_index
*6*2, 6*2, indices
.native_array
)
937 gl_error
= glGetError
938 assert gl_error
== gl_NO_ERROR
else print_error gl_error
943 # Call `resize` and `update_sprite` as needed before actual draw operation.
945 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
948 if buffer_array
== -1 then prepare
950 assert buffer_array
> 0 and buffer_element
> 0 else
951 print_error
"Internal error: {self} was destroyed"
955 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
956 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
958 # Resize GPU buffers?
959 if sprites
.capacity
> buffer_capacity
then
960 # Try to defragment first
961 var moved
= sprites
.defragment
963 if sprites
.capacity
> buffer_capacity
then
964 # Defragmentation wasn't enough, grow
967 # We must update everything
968 for s
in sprites
.items
do if s
!= null then sprites_to_update
.add s
970 # Just update the moved sprites
971 for s
in moved
do sprites_to_update
.add s
973 else if sprites
.available
.not_empty
then
974 # Defragment a bit anyway
975 # TODO defrag only when there's time left on a frame
976 var moved
= sprites
.defragment
(1)
977 for s
in moved
do sprites_to_update
.add s
980 # Update GPU sprites data
981 if sprites_to_update
.not_empty
then
982 app
.perf_clock_sprites
.lapse
984 for sprite
in sprites_to_update
do update_sprite
(sprite
)
985 sprites_to_update
.clear
987 sys
.perfs
["gamnit flat gpu update"].add app
.perf_clock_sprites
.lapse
990 # Update uniforms specific to this context
991 var texture
= texture
992 app
.simple_2d_program
.use_texture
.uniform texture
!= null
993 if texture
!= null then
994 glActiveTexture gl_TEXTURE0
995 glBindTexture
(gl_TEXTURE_2D
, texture
.gl_texture
)
996 app
.simple_2d_program
.texture
.uniform
0
998 var gl_error
= glGetError
999 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1001 # Configure attributes, in order:
1002 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
1004 var p
= app
.simple_2d_program
1005 var sizeof_gl_float
= 4 # sizeof(GL_FLOAT)
1007 var size
= 4 # Number of floats
1008 glEnableVertexAttribArray p
.translation
.location
1009 glVertexAttribPointeri
(p
.translation
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1010 offset
+= size
* sizeof_gl_float
1011 gl_error
= glGetError
1012 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1015 glEnableVertexAttribArray p
.color
.location
1016 glVertexAttribPointeri
(p
.color
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1017 offset
+= size
* sizeof_gl_float
1018 gl_error
= glGetError
1019 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1022 glEnableVertexAttribArray p
.scale
.location
1023 glVertexAttribPointeri
(p
.scale
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1024 offset
+= size
* sizeof_gl_float
1025 gl_error
= glGetError
1026 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1029 glEnableVertexAttribArray p
.coord
.location
1030 glVertexAttribPointeri
(p
.coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1031 offset
+= size
* sizeof_gl_float
1032 gl_error
= glGetError
1033 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1036 glEnableVertexAttribArray p
.tex_coord
.location
1037 glVertexAttribPointeri
(p
.tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1038 offset
+= size
* sizeof_gl_float
1039 gl_error
= glGetError
1040 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1043 for r
in [p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
] do
1045 glEnableVertexAttribArray r
.location
1046 glVertexAttribPointeri
(r
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1048 offset
+= size
* sizeof_gl_float
1049 gl_error
= glGetError
1050 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1054 for s
in sprites
.starts
, e
in sprites
.ends
do
1056 glDrawElementsi
(gl_TRIANGLES
, l
*indices_per_sprite
, gl_UNSIGNED_SHORT
, 2*s
*indices_per_sprite
)
1057 gl_error
= glGetError
1058 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1062 for attr
in [p
.translation
, p
.color
, p
.scale
, p
.coord
, p
.tex_coord
,
1063 p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
: Attribute] do
1064 if not attr
.is_active
then continue
1065 glDisableVertexAttribArray
(attr
.location
)
1066 gl_error
= glGetError
1067 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1070 glBindBuffer
(gl_ARRAY_BUFFER
, 0)
1071 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, 0)
1072 gl_error
= glGetError
1073 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1077 # Representation of sprite data on the GPU
1079 # The main purpose of this class is to optimize the use of contiguous
1080 # space in GPU memory. Each contiguous memory block can be drawn in a
1081 # single call. The starts index of each block is kept by `starts,
1082 # and the end + 1 by `ends`.
1084 # The data can be compressed by a call to `defragment`.
1087 # intrude import gamnit::flat
1089 # var array = new GroupedArray[String]
1090 # assert array.to_s == ""
1098 # assert array.to_s == "[a,b,c,d,e,f]"
1099 # assert array.capacity == 6
1102 # assert array.to_s == "[b,c,d,e,f]"
1105 # assert array.to_s == "[c,d,e,f]"
1108 # assert array.to_s == "[c,d,e]"
1111 # assert array.to_s == "[c][e]"
1114 # assert array.to_s == "[A][c][e]"
1117 # assert array.to_s == "[A,B,c][e]"
1120 # assert array.to_s == "[A,B,c]"
1123 # assert array.to_s == "[A,B,c,D]"
1126 # assert array.to_s == "[A,B,c,D,E]"
1127 # assert array.capacity == 6
1128 # assert array.length == 5
1135 # assert array.to_s == ""
1138 # assert array.to_s == "[a]"
1140 private class GroupedArray[E
]
1142 # Memory with actual objects, and null in empty slots
1143 var items
= new Array[nullable E
]
1145 # Number of items in the array
1148 # Number of item slots in the array
1149 fun capacity
: Int do return items
.length
1152 fun index_of
(item
: E
): Int do return items
.index_of
(item
)
1154 # List of available slots
1155 var available
= new MinHeap[Int].default
1157 # Start index of filled chunks
1158 var starts
= new List[Int]
1160 # Index of the spots after filled chunks
1161 var ends
= new List[Int]
1163 # Add `item` to the first available slot
1168 if available
.not_empty
then
1169 # starts & ends can't be empty
1171 var i
= available
.take
1174 if i
== starts
.first
- 1 then
1175 # slot 0 free, 1 taken
1178 # slot 0 and more free
1181 else if starts
.length
>= 2 and ends
.first
+ 1 == starts
[1] then
1186 # at end of first chunk
1193 if ends
.is_empty
then
1199 # Remove the first instance of `item`
1202 var i
= items
.index_of
(item
)
1208 for s
in starts
, e
in ends
do
1209 if s
<= i
and i
< e
then
1215 if starts
.is_empty
then
1220 else if e-1
== i
then
1221 # last item of chunk
1225 # first item of chunk
1229 ends
.insert
(ends
[ii
], ii
+1)
1231 starts
.insert
(i
+1, ii
+1)
1243 # Defragment and compress everything into a single chunks beginning at 0
1245 # Returns the elements that moved as a list.
1248 # intrude import gamnit::flat
1250 # var array = new GroupedArray[String]
1257 # assert array.to_s == "[b][d]"
1259 # var moved = array.defragment
1260 # assert moved.to_s == "[d]"
1261 # assert array.to_s == "[d,b]"
1262 # assert array.length == 2
1263 # assert array.capacity == 2
1267 # assert array.to_s == "[d,b,e,f]"
1269 fun defragment
(max
: nullable Int): Array[E
]
1271 app
.perf_clock_sprites
.lapse
1272 max
= max
or else length
1274 var moved
= new Array[E
]
1275 while max
> 0 and (starts
.length
> 1 or starts
.first
!= 0) do
1276 var i
= ends
.last
- 1
1284 if starts
.length
== 1 and starts
.first
== 0 then
1285 for i
in [length
..capacity
[ do items
.pop
1289 sys
.perfs
["gamnit flat gpu defrag"].add app
.perf_clock_sprites
.lapse
1295 var ss
= new Array[String]
1296 for s
in starts
, e
in ends
do
1299 var item
: nullable Object = items
[i
]
1300 if item
== null then item
= "null"
1302 if i
!= e-1
then ss
.add
","
1310 redef class GLfloatArray
1311 private fun fill_from_matrix
(matrix
: Matrix, dst_offset
: nullable Int)
1313 dst_offset
= dst_offset
or else 0
1314 var mat_len
= matrix
.width
*matrix
.height
1315 assert length
>= mat_len
+ dst_offset
1316 native_array
.fill_from_matrix_native
(matrix
.items
, dst_offset
, mat_len
)
1320 redef class NativeGLfloatArray
1321 private fun fill_from_matrix_native
(matrix
: matrix
::NativeDoubleArray, dst_offset
, len
: Int) `{
1323 for (i = 0; i < len; i ++)
1324 self[i+dst_offset] = (GLfloat)matrix[i];