gamnit: make `SpriteSet` public so clients can use its services
[nit.git] / lib / gamnit / dynamic_resolution.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 # Virtual screen with a resolution independent from the real screen
16 #
17 # The attribute `dynamic_resolution_ratio` sets the size of the virtual screen
18 # in relation to the real screen. See its documentation for more information.
19 #
20 # Reference implementation:
21 # https://software.intel.com/en-us/articles/dynamic-resolution-rendering-on-opengl-es-2
22 module dynamic_resolution
23
24 import performance_analysis
25
26 import gamnit
27
28 redef class App
29 # Resolution of the dynamic screen as ratio of the real screen resolution.
30 #
31 # - At 1.0, the default, the virtual screen is not used and the visuals are
32 # drawn directly to the real screen and pixels.
33 # - When below 1.0, there is less pixels in the dynamic screen than in the
34 # real screen. This reduces the strain on the GPU, especially of high
35 # resolution displays.
36 # - Values above 1.0 are not supported at this point, but they would allow
37 # super-sampling.
38 #
39 # This value must be set either by the user using a video quality slider or
40 # by an heuristic according to the device capabilities.
41 # A lower value should use less battery power on mobile devices.
42 #
43 # This value is applied to both X and Y, so it has an exponential effect on
44 # the number of pixels.
45 var dynamic_resolution_ratio = 1.0
46
47 # Minimum dynamic screen resolution
48 var min_dynamic_resolution_ratio = 0.0125 is writable
49
50 # Maximum dynamic screen resolution, must be set before first draw
51 var max_dynamic_resolution_ratio = 1.0 is writable
52
53 private var dynres_program = new DynamicResolutionProgram
54
55 private var perf_clock_dynamic_resolution = new Clock is lazy
56
57 redef fun on_create
58 do
59 super
60
61 var program = dynres_program
62 program.compile_and_link
63 var error = program.error
64 assert error == null else print_error error
65 end
66
67 redef fun on_resize(display)
68 do
69 dynamic_context.resize(display, max_dynamic_resolution_ratio)
70 super
71 end
72
73 # Prepare to draw to the dynamic screen if `dynamic_resolution_ratio != 1.0`
74 protected fun frame_core_dynamic_resolution_before(display: GamnitDisplay)
75 do
76 # TODO autodetect when to lower/increase resolution
77
78 if dynamic_resolution_ratio == 1.0 then
79 # Draw directly to the screen framebuffer
80 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_context.screen_framebuffer)
81 glViewport(0, 0, display.width, display.height)
82 glClear gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT
83
84 var gl_error = glGetError
85 assert gl_error == gl_NO_ERROR else print_error gl_error
86 return
87 end
88
89 # Draw to our dynamic framebuffer
90 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_context.dynamic_framebuffer)
91
92 var ratio = dynamic_resolution_ratio
93 ratio = ratio.clamp(min_dynamic_resolution_ratio, max_dynamic_resolution_ratio)
94 glViewport(0, 0, (display.width.to_f*ratio).to_i,
95 (display.height.to_f*ratio).to_i)
96
97 glClear gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT
98
99 var gl_error = glGetError
100 assert gl_error == gl_NO_ERROR else print_error gl_error
101 end
102
103 # Draw the dynamic screen to the real screen if `dynamic_resolution_ratio != 1.0`
104 protected fun frame_core_dynamic_resolution_after(display: GamnitDisplay)
105 do
106 if dynamic_resolution_ratio == 1.0 then return
107 perf_clock_dynamic_resolution.lapse
108
109 var ratio = dynamic_resolution_ratio
110 ratio = ratio.clamp(min_dynamic_resolution_ratio, max_dynamic_resolution_ratio)
111
112 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_context.screen_framebuffer)
113 glBindBuffer(gl_ARRAY_BUFFER, dynamic_context.buffer_array)
114 glViewport(0, 0, display.width, display.height)
115 glClear gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT
116 dynres_program.use
117
118 # Uniforms
119 glActiveTexture gl_TEXTURE0
120 glBindTexture(gl_TEXTURE_2D, dynamic_context.texture)
121 dynres_program.texture.uniform 0
122 dynres_program.ratio.uniform ratio
123
124 # Attributes
125 var sizeof_gl_float = 4
126 var n_floats = 3
127 glEnableVertexAttribArray dynres_program.coord.location
128 glVertexAttribPointeri(dynres_program.coord.location, n_floats, gl_FLOAT, false, 0, 0)
129 var offset = 4 * n_floats * sizeof_gl_float
130
131 n_floats = 2
132 glEnableVertexAttribArray dynres_program.tex_coord.location
133 glVertexAttribPointeri(dynres_program.tex_coord.location, n_floats, gl_FLOAT, false, 0, offset)
134 var gl_error = glGetError
135 assert gl_error == gl_NO_ERROR else print_error gl_error
136
137 # Draw
138 glDrawArrays(gl_TRIANGLE_STRIP, 0, 4)
139
140 gl_error = glGetError
141 assert gl_error == gl_NO_ERROR else print_error gl_error
142
143 sys.perfs["gamnit flat dyn res"].add app.perf_clock_dynamic_resolution.lapse
144 end
145
146 # Framebuffer and texture for dynamic resolution intermediate drawing
147 private var dynamic_context: DynamicContext = create_dynamic_context is lazy
148
149 private fun create_dynamic_context: DynamicContext
150 do
151 # TODO option or flag to regen on real resolution change.
152
153 var display = display
154 assert display != null
155
156 var context = new DynamicContext
157 context.prepare_once(display, max_dynamic_resolution_ratio)
158 return context
159 end
160 end
161
162 # Program drawing the dynamic screen to the real screen
163 private class DynamicContext
164
165 # Real screen framebuffer
166 var screen_framebuffer: Int = -1
167
168 # Dynamic screen framebuffer
169 var dynamic_framebuffer: Int = -1
170
171 # Depth renderbuffer attached to `dynamic_framebuffer`
172 var depth_renderbuffer: Int = -1
173
174 # Texture attached to `dynamic_framebuffer` as color attachment
175 var texture: Int = -1
176
177 # Buffer name for vertex data
178 var buffer_array: Int = -1
179
180 var float_per_vertex: Int is lazy do return 4 + 4 + 3
181
182 # Prepare all attributes once per resolution change
183 fun prepare_once(display: GamnitDisplay, max_dynamic_resolution_ratio: Float)
184 do
185 # TODO enable antialiasing.
186
187 # Set aside the real screen framebuffer name
188 var screen_framebuffer = glGetIntegerv(gl_FRAMEBUFFER_BINDING, 0)
189 self.screen_framebuffer = screen_framebuffer
190
191 # Framebuffer
192 var framebuffer = glGenFramebuffers(1).first
193 glBindFramebuffer(gl_FRAMEBUFFER, framebuffer)
194 assert glIsFramebuffer(framebuffer)
195 self.dynamic_framebuffer = framebuffer
196 var gl_error = glGetError
197 assert gl_error == gl_NO_ERROR else print_error gl_error
198
199 # Depth & texture/color
200 var depthbuffer = glGenRenderbuffers(1).first
201 self.depth_renderbuffer = depthbuffer
202 var texture = glGenTextures(1).first
203 self.texture = texture
204 gl_error = glGetError
205 assert gl_error == gl_NO_ERROR else print_error gl_error
206
207 resize(display, max_dynamic_resolution_ratio)
208 assert glCheckFramebufferStatus(gl_FRAMEBUFFER) == gl_FRAMEBUFFER_COMPLETE
209
210 # Array buffer
211 buffer_array = glGenBuffers(1).first
212 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
213 assert glIsBuffer(buffer_array)
214 gl_error = glGetError
215 assert gl_error == gl_NO_ERROR else print_error gl_error
216
217 ## coord
218 var data = new Array[Float]
219 data.add_all([-1.0, -1.0, 0.0,
220 1.0, -1.0, 0.0,
221 -1.0, 1.0, 0.0,
222 1.0, 1.0, 0.0])
223 ## tex_coord
224 data.add_all([0.0, 0.0,
225 1.0, 0.0,
226 0.0, 1.0,
227 1.0, 1.0])
228 var c_data = new GLfloatArray.from(data)
229 glBufferData(gl_ARRAY_BUFFER, data.length*4, c_data.native_array, gl_STATIC_DRAW)
230
231 glBindBuffer(gl_ARRAY_BUFFER, 0)
232
233 gl_error = glGetError
234 assert gl_error == gl_NO_ERROR else print_error gl_error
235 end
236
237 # Init size or resize `depth_renderbuffer` and `texture`
238 fun resize(display: GamnitDisplay, max_dynamic_resolution_ratio: Float)
239 do
240 var width = (display.width.to_f * max_dynamic_resolution_ratio).to_i
241 var height = (display.height.to_f * max_dynamic_resolution_ratio).to_i
242
243 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_framebuffer)
244
245 var depthbuffer = self.depth_renderbuffer
246 var texture = self.texture
247
248 # Depth
249 glBindRenderbuffer(gl_RENDERBUFFER, depthbuffer)
250 assert glIsRenderbuffer(depthbuffer)
251 glRenderbufferStorage(gl_RENDERBUFFER, gl_DEPTH_COMPNENT16, width, height)
252 glFramebufferRenderbuffer(gl_FRAMEBUFFER, gl_DEPTH_ATTACHMENT, gl_RENDERBUFFER, depthbuffer)
253 var gl_error = glGetError
254 assert gl_error == gl_NO_ERROR else print_error gl_error
255
256 # Texture
257 glBindTexture(gl_TEXTURE_2D, texture)
258 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
259 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
260 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_WRAP_S, gl_CLAMP_TO_EDGE)
261 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_WRAP_T, gl_CLAMP_TO_EDGE)
262 glTexImage2D(gl_TEXTURE_2D, 0, gl_RGB, width, height,
263 0, gl_RGB, gl_UNSIGNED_BYTE, new Pointer.nul)
264 glFramebufferTexture2D(gl_FRAMEBUFFER, gl_COLOR_ATTACHMENT0, gl_TEXTURE_2D, texture, 0)
265
266 gl_error = glGetError
267 assert gl_error == gl_NO_ERROR else print_error gl_error
268
269 # Take down
270 glBindRenderbuffer(gl_RENDERBUFFER, 0)
271 glBindFramebuffer(gl_FRAMEBUFFER, 0)
272
273 gl_error = glGetError
274 assert gl_error == gl_NO_ERROR else print_error gl_error
275 end
276
277 var destroyed = false
278 fun destroy
279 do
280 if destroyed then return
281 destroyed = true
282
283 # Free the buffer
284 glDeleteBuffers([buffer_array])
285 var gl_error = glGetError
286 assert gl_error == gl_NO_ERROR else print_error gl_error
287 buffer_array = -1
288
289 # Free the dynamic framebuffer and its attachments
290 glDeleteBuffers([buffer_array])
291 glDeleteFramebuffers([dynamic_framebuffer])
292 glDeleteRenderbuffers([depth_renderbuffer])
293 glDeleteTextures([texture])
294 end
295 end
296
297 private class DynamicResolutionProgram
298 super GamnitProgramFromSource
299
300 redef var vertex_shader_source = """
301 // Vertex coordinates
302 attribute vec3 coord;
303
304 // Vertex coordinates on textures
305 attribute vec2 tex_coord;
306
307 // Output to the fragment shader
308 varying vec2 v_coord;
309
310 void main()
311 {
312 gl_Position = vec4(coord, 1.0);
313 v_coord = tex_coord;
314 }
315 """ @ glsl_vertex_shader
316
317 redef var fragment_shader_source = """
318 precision mediump float;
319
320 // Virtual screen texture / color attachment
321 uniform sampler2D texture0;
322
323 // Input from the vertex shader
324 varying vec2 v_coord;
325
326 // Ratio of the virtual screen to draw
327 uniform float ratio;
328
329 void main()
330 {
331 gl_FragColor = texture2D(texture0, v_coord*ratio);
332 }
333 """ @ glsl_fragment_shader
334
335 # Vertices coordinates
336 var coord = attributes["coord"].as(AttributeVec3) is lazy
337
338 # Coordinates on the textures, per vertex
339 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
340
341 # Virtual screen texture / color attachment
342 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
343
344 # Ratio of the virtual screen to draw
345 var ratio = uniforms["ratio"].as(UniformFloat) is lazy
346 end