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_flat/`.
37 intrude import geometry
::points_and_lines
# For _x, _y and _z
38 import matrix
::projection
39 import more_collections
40 import performance_analysis
43 import gamnit
::cameras
44 import gamnit
::limit_fps
45 import gamnit
::camera_control
47 # Draw a `texture` at `center`
49 # An instance of `Sprite` can only belong to a single `SpriteSet` at
50 # a time. The on screen position depends on the camera associated
54 # Texture drawn to screen
55 var texture
: Texture is writable(texture_direct
=)
57 # Texture drawn to screen
58 fun texture
=(value
: Texture)
60 if isset _texture
and value
!= texture
then
62 if value
.root
!= texture
.root
then needs_remap
64 texture_direct
= value
67 # Center position of this sprite in world coordinates
68 var center
: Point3d[Float] is writable(center_direct
=), noautoinit
70 # Center position of this sprite in world coordinates
71 fun center
=(value
: Point3d[Float]) is autoinit
do
72 if isset _center
and value
!= center
then
74 center
.sprites_remove
self
77 value
.sprites_add
self
81 # Rotation on the Z axis, positive values go counterclockwise
82 var rotation
= 0.0 is writable(rotation_direct
=)
84 # Rotation on the Z axis, positive values go counterclockwise
85 fun rotation
=(value
: Float)
87 if isset _rotation
and value
!= rotation
then needs_update
88 rotation_direct
= value
91 # Mirror `texture` horizontally, inverting each pixel on the X axis
92 var invert_x
= false is writable(invert_x_direct
=)
94 # Mirror `texture` horizontally, inverting each pixel on the X axis
95 fun invert_x
=(value
: Bool)
97 if isset _invert_x
and value
!= invert_x
then needs_update
98 invert_x_direct
= value
101 # Scale applied to this sprite
103 # The default size of `self` depends on the size in pixels of `texture`.
104 var scale
= 1.0 is writable(scale_direct
=)
106 # Scale applied to this sprite, see `scale`
107 fun scale
=(value
: Float)
109 if isset _scale
and value
!= scale
then needs_update
113 # Red tint applied to `texture` on draw
114 fun red
: Float do return tint
[0]
116 # Red tint applied to `texture` on draw
117 fun red
=(value
: Float)
119 if isset _tint
and value
!= red
then needs_update
123 # Green tint applied to `texture` on draw
124 fun green
: Float do return tint
[1]
126 # Green tint applied to `texture` on draw
127 fun green
=(value
: Float)
129 if isset _tint
and value
!= green
then needs_update
133 # Blue tint applied to `texture` on draw
134 fun blue
: Float do return tint
[2]
136 # Blue tint applied to `texture` on draw
137 fun blue
=(value
: Float)
139 if isset _tint
and value
!= blue
then needs_update
143 # Transparency applied to `texture` on draw
144 fun alpha
: Float do return tint
[3]
146 # Transparency applied to `texture` on draw
147 fun alpha
=(value
: Float)
149 if isset _tint
and value
!= alpha
then needs_update
153 # Tint applied to `texture` on draw
155 # Alternative to the accessors `red, green, blue & alpha`.
156 # Changes inside the array do not automatically set `needs_update`.
158 # Require: `tint.length == 4`
159 var tint
: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct
=)
161 # Tint applied to `texture` on draw, see `tint`
162 fun tint
=(value
: Array[Float])
164 if isset _tint
and value
!= tint
then needs_update
168 # Is this sprite static and added in bulk?
170 # Set to `true` to give a hint to the framework that this sprite won't
171 # change often and that it is added in bulk with other static sprites.
172 # This value can be ignored in the prototyping phase of a game and
173 # added only when better performance are needed.
174 var static
= false is writable(static_direct
=)
176 # Is this sprite static and added in bulk? see `static`
177 fun static
=(value
: Bool)
179 if isset _static
and value
!= static
then needs_remap
180 static_direct
= value
183 # Request an update on the CPU
185 # This is called automatically on modification of any value of `Sprite`.
186 # However, it can still be set manually if a modification can't be
187 # detected or by subclasses.
191 if c
!= null then c
.sprites_to_update
.add
self
194 # Request a resorting of this sprite in its sprite list
196 # Resorting is required when `static` or the root of `texture` changes.
197 # This is called automatically when such changes are detected.
198 # However, it can still be set manually if a modification can't be
199 # detected or by subclasses.
203 if l
!= null then l
.sprites_to_remap
.add
self
206 # Current context to which `self` was sorted
207 private var context
: nullable SpriteContext = null
209 # Current context to which `self` belongs
210 private var sprite_set
: nullable SpriteSet = null
214 # Default graphic program to draw `sprites`
215 private var simple_2d_program
= new Simple2dProgram is lazy
217 # Camera for world `sprites` and `depth::actors` with perspective
219 # By default, the camera is configured to respect the resolution
220 # of the screen in world coordinates at `z == 0.0`.
221 var world_camera
: EulerCamera is lazy
do
222 var camera
= new EulerCamera(app
.display
.as(not null))
224 # Aim for pixel resolution at level 0
231 # Camera for `ui_sprites` using an orthogonal view
232 var ui_camera
: UICamera = new UICamera(app
.display
.as(not null)) is lazy
234 # World sprites to draw as seen by `world_camera`
235 var sprites
: Set[Sprite] = new SpriteSet
237 # UI sprites to draw as seen by `ui_camera`, drawn over world `sprites`
238 var ui_sprites
: Set[Sprite] = new SpriteSet
240 # Main method to refine in clients to update game logic and `sprites`
241 fun update
(dt
: Float) do end
243 # Display `texture` as a splash screen
245 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
246 fun show_splash_screen
(texture
: Texture)
250 ui_camera
.reset_height
1080.0
252 var splash
= new Sprite(texture
, ui_camera
.center
)
253 ui_sprites
.add splash
255 var display
= display
256 assert display
!= null
257 glClear gl_COLOR_BUFFER_BIT
258 frame_core_ui_sprites display
261 ui_sprites
.remove splash
265 # Support and implementation
267 # Main clock used to count each frame `dt`, lapsed for `update` only
268 private var clock
= new Clock is lazy
270 # Performance clock to for `frame_core_draw` operations
271 private var perf_clock_main
= new Clock
273 # Second performance clock for smaller operations
274 private var perf_clock_sprites
= new Clock is lazy
280 var display
= display
281 assert display
!= null
283 var gl_error
= glGetError
284 assert gl_error
== gl_NO_ERROR
else print_error gl_error
287 var program
= simple_2d_program
288 program
.compile_and_link
290 var gamnit_error
= program
.error
291 assert gamnit_error
== null else print_error gamnit_error
294 gl
.capabilities
.blend
.enable
295 glBlendFunc
(gl_SRC_ALPHA
, gl_ONE_MINUS_SRC_ALPHA
)
298 gl
.capabilities
.depth_test
.enable
299 glDepthFunc gl_LEQUAL
302 # Prepare viewport and background color
303 glViewport
(0, 0, display
.width
, display
.height
)
304 glClearColor
(0.0, 0.0, 0.0, 1.0)
306 gl_error
= glGetError
307 assert gl_error
== gl_NO_ERROR
else print_error gl_error
310 for tex
in all_root_textures
do
312 gamnit_error
= tex
.error
313 if gamnit_error
!= null then print_error gamnit_error
315 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
316 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
323 simple_2d_program
.delete
326 var display
= display
327 if display
!= null then display
.close
330 redef fun frame_core
(display
)
332 # Prepare to draw, clear buffers
333 glClear
(gl_COLOR_BUFFER_BIT
| gl_DEPTH_BUFFER_BIT
)
336 var gl_error
= glGetError
337 assert gl_error
== gl_NO_ERROR
else print_error gl_error
339 # Update game logic and set sprites
340 perf_clock_main
.lapse
341 var dt
= clock
.lapse
.to_f
343 sys
.perfs
["gamnit flat update client"].add perf_clock_main
.lapse
345 # Draw and flip screen
346 frame_core_draw display
350 gl_error
= glGetError
351 assert gl_error
== gl_NO_ERROR
else print_error gl_error
354 # Draw the whole screen, all `glDraw...` calls should be executed here
355 protected fun frame_core_draw
(display
: GamnitDisplay)
357 perf_clock_main
.lapse
359 frame_core_world_sprites display
360 perfs
["gamnit flat world_sprites"].add perf_clock_main
.lapse
362 frame_core_ui_sprites display
363 perfs
["gamnit flat ui_sprites"].add perf_clock_main
.lapse
366 private fun frame_core_sprites
(display
: GamnitDisplay, sprite_set
: SpriteSet, camera
: Camera)
368 var simple_2d_program
= app
.simple_2d_program
369 simple_2d_program
.use
370 simple_2d_program
.mvp
.uniform camera
.mvp_matrix
376 # Draw world sprites from `sprites`
377 protected fun frame_core_world_sprites
(display
: GamnitDisplay)
379 frame_core_sprites
(display
, sprites
.as(SpriteSet), world_camera
)
382 # Draw UI sprites from `ui_sprites`
383 protected fun frame_core_ui_sprites
(display
: GamnitDisplay)
385 # Reset only the depth buffer
386 glClear gl_DEPTH_BUFFER_BIT
388 frame_core_sprites
(display
, ui_sprites
.as(SpriteSet), ui_camera
)
394 # Vertices coordinates of the base geometry
396 # Defines the default width and height of related sprites.
397 private var vertices
: Array[Float] is lazy
do
400 return [-0.5*w
, 0.5*h
, 0.0,
406 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
407 private var texture_coords
: Array[Float] is lazy
do
410 var b
= offset_bottom
418 # Coordinates of this texture on the `root` texture, inverting the X axis
419 private var texture_coords_invert_x
: Array[Float] is lazy
do
422 var b
= offset_bottom
431 # Graphic program to display simple models with a texture, translation, rotation and scale
432 private class Simple2dProgram
433 super GamnitProgramFromSource
435 redef var vertex_shader_source
= """
436 // Vertex coordinates
437 attribute vec4 coord;
440 attribute vec4 color;
442 // Vertex translation
443 attribute vec4 translation;
446 attribute float scale;
448 // Vertex coordinates on textures
449 attribute vec2 tex_coord;
451 // Model view projection matrix
455 attribute vec4 rotation_row0;
456 attribute vec4 rotation_row1;
457 attribute vec4 rotation_row2;
458 attribute vec4 rotation_row3;
462 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
465 // Output to the fragment shader
466 varying vec4 v_color;
467 varying vec2 v_coord;
471 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
475 """ @ glsl_vertex_shader
477 redef var fragment_shader_source
= """
478 precision mediump float;
480 // Does this object use a texture?
481 uniform bool use_texture;
483 // Texture to apply on this object
484 uniform sampler2D texture0;
486 // Input from the vertex shader
487 varying vec4 v_color;
488 varying vec2 v_coord;
493 gl_FragColor = v_color * texture2D(texture0, v_coord);
494 if (gl_FragColor.a <= 0.1) discard;
496 gl_FragColor = v_color;
499 """ @ glsl_fragment_shader
501 # Vertices coordinates
502 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
504 # Should this program use the texture `texture`?
505 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
507 # Visible texture unit
508 var texture
= uniforms
["texture0"].as(UniformSampler2D) is lazy
510 # Coordinates on the textures, per vertex
511 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
513 # Color tint per vertex
514 var color
= attributes
["color"].as(AttributeVec4) is lazy
516 # Translation applied to each vertex
517 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
519 # Rotation matrix, row 0
520 var rotation_row0
= attributes
["rotation_row0"].as(AttributeVec4) is lazy
522 # Rotation matrix, row 1
523 var rotation_row1
= attributes
["rotation_row1"].as(AttributeVec4) is lazy
525 # Rotation matrix, row 2
526 var rotation_row2
= attributes
["rotation_row2"].as(AttributeVec4) is lazy
528 # Rotation matrix, row 3
529 var rotation_row3
= attributes
["rotation_row3"].as(AttributeVec4) is lazy
532 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
534 # Model view projection matrix
535 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
538 redef class Point3d[N
]
539 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
540 fun offset
(x
, y
, z
: Numeric): Point3d[Float]
542 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
)
546 # Associate each point to its sprites
548 private var sprites
: nullable Array[Sprite] = null
550 private fun sprites_add
(sprite
: Sprite)
552 var sprites
= sprites
553 if sprites
== null then
554 sprites
= new Array[Sprite]
555 self.sprites
= sprites
560 private fun sprites_remove
(sprite
: Sprite)
562 var sprites
= sprites
563 assert sprites
!= null
564 sprites
.remove sprite
568 # Notify `sprites` on attribute modification
570 private fun needs_update
572 var sprites
= sprites
573 if sprites
!= null then for s
in sprites
do s
.needs_update
578 if isset _x
and v
!= x
then needs_update
584 if isset _y
and v
!= y
then needs_update
590 if isset _z
and v
!= z
then needs_update
595 # Set of sprites sorting them into different `SpriteContext`
596 private class SpriteSet
597 super HashSet[Sprite]
599 # Map texture then static vs dynamic to a `SpriteContext`
600 var contexts_map
= new HashMap2[GamnitRootTexture, Bool, SpriteContext]
602 # Contexts in `contexts_map`
603 var contexts_items
= new Array[SpriteContext]
605 # Sprites needing resorting in `contexts_map`
606 var sprites_to_remap
= new Array[Sprite]
608 # Add a sprite to the appropriate context
609 fun map_sprite
(sprite
: Sprite)
611 assert sprite
.context
== null else print_error
"Sprite {sprite} belongs to another SpriteSet"
613 var texture
= sprite
.texture
.root
614 var context
= contexts_map
[texture
, sprite
.static
]
616 if context
== null then
617 var usage
= if sprite
.static
then gl_STATIC_DRAW
else gl_DYNAMIC_DRAW
618 context
= new SpriteContext(texture
, usage
)
620 contexts_map
[texture
, sprite
.static
] = context
621 contexts_items
.add context
624 context
.sprites
.add sprite
625 context
.sprites_to_update
.add sprite
627 sprite
.context
= context
628 sprite
.sprite_set
= self
631 # Remove a sprite from its context
632 fun unmap_sprite
(sprite
: Sprite)
634 var context
= sprite
.context
635 assert context
!= null
636 context
.sprites
.remove sprite
638 sprite
.context
= null
639 sprite
.sprite_set
= null
642 # Draw all sprites by all contexts
645 for sprite
in sprites_to_remap
do
649 sprites_to_remap
.clear
651 for context
in contexts_items
do context
.draw
656 if contexts_items
.has
(e
.context
) then return
664 if e
isa Sprite then unmap_sprite e
667 redef fun remove_all
(e
)
669 if not has
(e
) then return
676 for c
in contexts_items
do c
.destroy
682 # Context for calls to `glDrawElements`
684 # Each context has only one `texture` and `usage`, but many sprites.
685 private class SpriteContext
688 # Context config and state
690 # Only root texture drawn by this context
691 var texture
: nullable GamnitRootTexture
693 # OpenGL ES usage of `buffer_array` and `buffer_element`
694 var usage
: GLBufferUsage
696 # Sprites drawn by this context
697 var sprites
= new GroupedArray[Sprite]
699 # Sprites to update since last `draw`
700 var sprites_to_update
= new Set[Sprite]
702 # Sprites that have been update and for which `needs_update` can be set to false
703 var updated_sprites
= new Array[Sprite]
705 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
707 # Require: `resize_ratio >= 1.0`
708 var resize_ratio
= 1.2
713 # OpenGL ES buffer name for vertex data
714 var buffer_array
: Int = -1
716 # OpenGL ES buffer name for indices
717 var buffer_element
: Int = -1
719 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
720 var buffer_capacity
= 0
722 # C buffers used to pass the data of a single sprite
723 var local_data_buffer
= new GLfloatArray(float_per_vertex
*4) is lazy
724 var local_indices_buffer
= new CUInt16Array(indices_per_sprite
) is lazy
729 # Number of GL_FLOAT per vertex of `Simple2dProgram`
730 var float_per_vertex
: Int is lazy
do
731 # vec4 translation, vec4 color, vec4 coord,
732 # float scale, vec2 tex_coord, vec4 rotation_row*
737 # Number of bytes per vertex of `Simple2dProgram`
738 var bytes_per_vertex
: Int is lazy
do
739 var fs
= 4 # sizeof(GL_FLOAT)
740 return fs
* float_per_vertex
743 # Number of bytes per sprite
744 var bytes_per_sprite
: Int is lazy
do return bytes_per_vertex
* 4
746 # Number of vertex indices per sprite draw call (2 triangles)
747 var indices_per_sprite
= 6
752 # Allocate `buffer_array` and `buffer_element`
755 var bufs
= glGenBuffers
(2)
756 buffer_array
= bufs
[0]
757 buffer_element
= bufs
[1]
759 var gl_error
= glGetError
760 assert gl_error
== gl_NO_ERROR
else print_error gl_error
763 # Destroy `buffer_array` and `buffer_element`
766 glDeleteBuffers
([buffer_array
, buffer_element
])
767 var gl_error
= glGetError
768 assert gl_error
== gl_NO_ERROR
else print_error gl_error
774 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
777 app
.perf_clock_sprites
.lapse
779 # Allocate a bit more space
780 var capacity
= (sprites
.capacity
.to_f
* resize_ratio
).to_i
782 var array_bytes
= capacity
* bytes_per_sprite
783 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
784 assert glIsBuffer
(buffer_array
)
785 glBufferData
(gl_ARRAY_BUFFER
, array_bytes
, new Pointer.nul
, usage
)
786 var gl_error
= glGetError
787 assert gl_error
== gl_NO_ERROR
else print_error gl_error
789 # GL_TRIANGLES 6 vertices * sprite
790 var n_indices
= capacity
* indices_per_sprite
791 var ius
= 2 # sizeof(GL_UNSIGNED_SHORT)
792 var element_bytes
= n_indices
* ius
793 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
794 assert glIsBuffer
(buffer_element
)
795 glBufferData
(gl_ELEMENT_ARRAY_BUFFER
, element_bytes
, new Pointer.nul
, usage
)
796 gl_error
= glGetError
797 assert gl_error
== gl_NO_ERROR
else print_error gl_error
799 buffer_capacity
= capacity
801 sys
.perfs
["gamnit flat gpu resize"].add app
.perf_clock_sprites
.lapse
804 # Update GPU data of `sprite`
805 fun update_sprite
(sprite
: Sprite)
807 var sprite_index
= sprites
.index_of
(sprite
)
808 if sprite_index
== -1 then return
812 var data
= local_data_buffer
816 data
[o
+ 0] = sprite
.center
.x
817 data
[o
+ 1] = sprite
.center
.y
818 data
[o
+ 2] = sprite
.center
.z
822 data
[o
+ 4] = sprite
.tint
[0]
823 data
[o
+ 5] = sprite
.tint
[1]
824 data
[o
+ 6] = sprite
.tint
[2]
825 data
[o
+ 7] = sprite
.tint
[3]
828 data
[o
+ 8] = sprite
.scale
831 data
[o
+ 9] = sprite
.texture
.vertices
[v
*3+0]
832 data
[o
+10] = sprite
.texture
.vertices
[v
*3+1]
833 data
[o
+11] = sprite
.texture
.vertices
[v
*3+2]
837 var texture
= texture
838 if texture
!= null then
839 var tc
= if sprite
.invert_x
then
840 sprite
.texture
.texture_coords_invert_x
841 else sprite
.texture
.texture_coords
842 data
[o
+13] = tc
[v
*2+0]
843 data
[o
+14] = tc
[v
*2+1]
848 if sprite
.rotation
== 0.0 then
849 # Cache the matrix at no rotation
850 rot
= once
new Matrix.identity
(4)
852 rot
= new Matrix.rotation
(sprite
.rotation
, 0.0, 0.0, 1.0)
854 data
.fill_from
(rot
.items
, o
+15)
856 o
+= float_per_vertex
859 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
860 glBufferSubData
(gl_ARRAY_BUFFER
, sprite_index
*bytes_per_sprite
, bytes_per_sprite
, data
.native_array
)
862 var gl_error
= glGetError
863 assert gl_error
== gl_NO_ERROR
else print_error gl_error
872 var indices
= local_indices_buffer
873 var io
= sprite_index
*4
881 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
882 glBufferSubData
(gl_ELEMENT_ARRAY_BUFFER
, sprite_index
*6*2, 6*2, indices
.native_array
)
884 gl_error
= glGetError
885 assert gl_error
== gl_NO_ERROR
else print_error gl_error
890 # Call `resize` and `update_sprite` as needed before actual draw operation.
892 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
895 if buffer_array
== -1 then prepare
897 assert buffer_array
> 0 and buffer_element
> 0 else
898 print_error
"Internal error: {self} was destroyed"
902 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
903 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
905 # Resize GPU buffers?
906 if sprites
.capacity
> buffer_capacity
then
907 # Try to defragment first
908 var moved
= sprites
.defragment
910 if sprites
.capacity
> buffer_capacity
then
911 # Defragmentation wasn't enough, grow
914 # We must update everything
915 for s
in sprites
.items
do if s
!= null then sprites_to_update
.add s
917 # Just update the moved sprites
918 for s
in moved
do sprites_to_update
.add s
920 else if sprites
.available
.not_empty
then
921 # Defragment a bit anyway
922 # TODO defrag only when there's time left on a frame
923 var moved
= sprites
.defragment
(1)
924 for s
in moved
do sprites_to_update
.add s
927 # Update GPU sprites data
928 if sprites_to_update
.not_empty
then
929 app
.perf_clock_sprites
.lapse
931 for sprite
in sprites_to_update
do update_sprite
(sprite
)
932 sprites_to_update
.clear
934 sys
.perfs
["gamnit flat gpu update"].add app
.perf_clock_sprites
.lapse
937 # Update uniforms specific to this context
938 var texture
= texture
939 app
.simple_2d_program
.use_texture
.uniform texture
!= null
940 if texture
!= null then
941 glActiveTexture gl_TEXTURE0
942 glBindTexture
(gl_TEXTURE_2D
, texture
.gl_texture
)
943 app
.simple_2d_program
.texture
.uniform
0
945 var gl_error
= glGetError
946 assert gl_error
== gl_NO_ERROR
else print_error gl_error
948 # Configure attributes, in order:
949 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
951 var p
= app
.simple_2d_program
952 var sizeof_gl_float
= 4 # sizeof(GL_FLOAT)
954 var size
= 4 # Number of floats
955 glEnableVertexAttribArray p
.translation
.location
956 glVertexAttribPointeri
(p
.translation
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
957 offset
+= size
* sizeof_gl_float
958 gl_error
= glGetError
959 assert gl_error
== gl_NO_ERROR
else print_error gl_error
962 glEnableVertexAttribArray p
.color
.location
963 glVertexAttribPointeri
(p
.color
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
964 offset
+= size
* sizeof_gl_float
965 gl_error
= glGetError
966 assert gl_error
== gl_NO_ERROR
else print_error gl_error
969 glEnableVertexAttribArray p
.scale
.location
970 glVertexAttribPointeri
(p
.scale
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
971 offset
+= size
* sizeof_gl_float
972 gl_error
= glGetError
973 assert gl_error
== gl_NO_ERROR
else print_error gl_error
976 glEnableVertexAttribArray p
.coord
.location
977 glVertexAttribPointeri
(p
.coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
978 offset
+= size
* sizeof_gl_float
979 gl_error
= glGetError
980 assert gl_error
== gl_NO_ERROR
else print_error gl_error
983 glEnableVertexAttribArray p
.tex_coord
.location
984 glVertexAttribPointeri
(p
.tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
985 offset
+= size
* sizeof_gl_float
986 gl_error
= glGetError
987 assert gl_error
== gl_NO_ERROR
else print_error gl_error
990 for r
in [p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
] do
992 glEnableVertexAttribArray r
.location
993 glVertexAttribPointeri
(r
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
995 offset
+= size
* sizeof_gl_float
996 gl_error
= glGetError
997 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1001 for s
in sprites
.starts
, e
in sprites
.ends
do
1003 glDrawElementsi
(gl_TRIANGLES
, l
*indices_per_sprite
, gl_UNSIGNED_SHORT
, 2*s
*indices_per_sprite
)
1004 gl_error
= glGetError
1005 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1009 for attr
in [p
.translation
, p
.color
, p
.scale
, p
.coord
, p
.tex_coord
,
1010 p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
: Attribute] do
1011 if not attr
.is_active
then continue
1012 glDisableVertexAttribArray
(attr
.location
)
1013 gl_error
= glGetError
1014 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1017 glBindBuffer
(gl_ARRAY_BUFFER
, 0)
1018 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, 0)
1019 gl_error
= glGetError
1020 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1024 # Representation of sprite data on the GPU
1026 # The main purpose of this class is to optimize the use of contiguous
1027 # space in GPU memory. Each contiguous memory block can be drawn in a
1028 # single call. The starts index of each block is kept by `starts,
1029 # and the end + 1 by `ends`.
1031 # The data can be compressed by a call to `defragment`.
1034 # var array = new GroupedArray[String]
1035 # assert array.to_s == ""
1043 # assert array.to_s == "[a,b,c,d,e,f]"
1044 # assert array.capacity == 6
1047 # assert array.to_s == "[b,c,d,e,f]"
1050 # assert array.to_s == "[c,d,e,f]"
1053 # assert array.to_s == "[c,d,e]"
1056 # assert array.to_s == "[c][e]"
1059 # assert array.to_s == "[A][c][e]"
1062 # assert array.to_s == "[A,B,c][e]"
1065 # assert array.to_s == "[A,B,c]"
1068 # assert array.to_s == "[A,B,c,D]"
1071 # assert array.to_s == "[A,B,c,D,E]"
1072 # assert array.capacity == 5
1073 # assert array.length == 5
1080 # assert array.to_s == ""
1083 # assert array.to_s == "[a]"
1085 private class GroupedArray[E
]
1087 # Memory with actual objects, and null in empty slots
1088 var items
= new Array[nullable E
]
1090 # Number of items in the array
1093 # Number of item slots in the array
1094 fun capacity
: Int do return items
.length
1097 fun index_of
(item
: E
): Int do return items
.index_of
(item
)
1099 # List of available slots
1100 var available
= new MinHeap[Int].default
1102 # Start index of filled chunks
1103 var starts
= new List[Int]
1105 # Index of the spots after filled chunks
1106 var ends
= new List[Int]
1108 # Add `item` to the first available slot
1113 if available
.not_empty
then
1114 # starts & ends can't be empty
1116 var i
= available
.take
1119 if i
== starts
.first
- 1 then
1120 # slot 0 free, 1 taken
1123 # slot 0 and more free
1126 else if starts
.length
>= 2 and ends
.first
+ 1 == starts
[1] then
1131 # at end of first chunk
1138 if ends
.is_empty
then
1144 # Remove the first instance of `item`
1147 var i
= items
.index_of
(item
)
1153 for s
in starts
, e
in ends
do
1154 if s
<= i
and i
< e
then
1160 if starts
.is_empty
then
1165 else if e-1
== i
then
1166 # last item of chunk
1170 # first item of chunk
1174 ends
.insert
(ends
[ii
], ii
+1)
1176 starts
.insert
(i
+1, ii
+1)
1188 # Defragment and compress everything into a single chunks beginning at 0
1190 # Returns the elements that moved as a list.
1193 # var array = new GroupedArray[String]
1200 # assert array.to_s == "[b][d]"
1202 # var moved = array.defragment
1203 # assert moved.to_s == "[d]"
1204 # assert array.to_s == "[d,b]"
1205 # assert array.length == 2
1206 # assert array.capacity == 2
1210 # assert array.to_s == "[d,b,e,f]"
1212 fun defragment
(max
: nullable Int): Array[E
]
1214 app
.perf_clock_sprites
.lapse
1215 max
= max
or else length
1217 var moved
= new Array[E
]
1218 while max
> 0 and (starts
.length
> 1 or starts
.first
!= 0) do
1219 var i
= ends
.last
- 1
1227 if starts
.length
== 1 and starts
.first
== 0 then
1228 for i
in [length
..capacity
[ do items
.pop
1232 sys
.perfs
["gamnit flat gpu defrag"].add app
.perf_clock_sprites
.lapse
1238 var ss
= new Array[String]
1239 for s
in starts
, e
in ends
do
1242 var item
: nullable Object = items
[i
]
1243 if item
== null then item
= "null"
1245 if i
!= e-1
then ss
.add
","