gamnit: resize in dynamic resolution
[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
83 var gl_error = glGetError
84 assert gl_error == gl_NO_ERROR else print_error gl_error
85 return
86 end
87
88 # Draw to our dynamic framebuffer
89 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_context.dynamic_framebuffer)
90 glClear gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT
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 var gl_error = glGetError
98 assert gl_error == gl_NO_ERROR else print_error gl_error
99 end
100
101 # Draw the dynamic screen to the real screen if `dynamic_resolution_ratio != 1.0`
102 protected fun frame_core_dynamic_resolution_after(display: GamnitDisplay)
103 do
104 if dynamic_resolution_ratio == 1.0 then return
105 perf_clock_dynamic_resolution.lapse
106
107 var ratio = dynamic_resolution_ratio
108 ratio = ratio.clamp(min_dynamic_resolution_ratio, max_dynamic_resolution_ratio)
109
110 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_context.screen_framebuffer)
111 glBindBuffer(gl_ARRAY_BUFFER, dynamic_context.buffer_array)
112 glViewport(0, 0, display.width, display.height)
113 glClear gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT
114 dynres_program.use
115
116 # Uniforms
117 glActiveTexture gl_TEXTURE0
118 glBindTexture(gl_TEXTURE_2D, dynamic_context.texture)
119 dynres_program.texture.uniform 0
120 dynres_program.ratio.uniform ratio
121
122 # Attributes
123 var sizeof_gl_float = 4
124 var n_floats = 3
125 glEnableVertexAttribArray dynres_program.coord.location
126 glVertexAttribPointeri(dynres_program.coord.location, n_floats, gl_FLOAT, false, 0, 0)
127 var offset = 4 * n_floats * sizeof_gl_float
128
129 n_floats = 2
130 glEnableVertexAttribArray dynres_program.tex_coord.location
131 glVertexAttribPointeri(dynres_program.tex_coord.location, n_floats, gl_FLOAT, false, 0, offset)
132 var gl_error = glGetError
133 assert gl_error == gl_NO_ERROR else print_error gl_error
134
135 # Draw
136 glDrawArrays(gl_TRIANGLE_STRIP, 0, 4)
137
138 gl_error = glGetError
139 assert gl_error == gl_NO_ERROR else print_error gl_error
140
141 sys.perfs["gamnit flat dyn res"].add app.perf_clock_dynamic_resolution.lapse
142 end
143
144 # Framebuffer and texture for dynamic resolution intermediate drawing
145 private var dynamic_context: DynamicContext = create_dynamic_context is lazy
146
147 private fun create_dynamic_context: DynamicContext
148 do
149 # TODO option or flag to regen on real resolution change.
150
151 var display = display
152 assert display != null
153
154 var context = new DynamicContext
155 context.prepare_once(display, max_dynamic_resolution_ratio)
156 return context
157 end
158 end
159
160 # Program drawing the dynamic screen to the real screen
161 private class DynamicContext
162
163 # Real screen framebuffer
164 var screen_framebuffer: Int = -1
165
166 # Dynamic screen framebuffer
167 var dynamic_framebuffer: Int = -1
168
169 # Depth renderbuffer attached to `dynamic_framebuffer`
170 var depth_renderbuffer: Int = -1
171
172 # Texture attached to `dynamic_framebuffer` as color attachment
173 var texture: Int = -1
174
175 # Buffer name for vertex data
176 var buffer_array: Int = -1
177
178 var float_per_vertex: Int is lazy do return 4 + 4 + 3
179
180 # Prepare all attributes once per resolution change
181 fun prepare_once(display: GamnitDisplay, max_dynamic_resolution_ratio: Float)
182 do
183 # TODO enable antialiasing.
184
185 # Set aside the real screen framebuffer name
186 var screen_framebuffer = glGetIntegerv(gl_FRAMEBUFFER_BINDING, 0)
187 self.screen_framebuffer = screen_framebuffer
188
189 # Framebuffer
190 var framebuffer = glGenFramebuffers(1).first
191 glBindFramebuffer(gl_FRAMEBUFFER, framebuffer)
192 assert glIsFramebuffer(framebuffer)
193 self.dynamic_framebuffer = framebuffer
194 var gl_error = glGetError
195 assert gl_error == gl_NO_ERROR else print_error gl_error
196
197 # Depth & texture/color
198 var depthbuffer = glGenRenderbuffers(1).first
199 self.depth_renderbuffer = depthbuffer
200 var texture = glGenTextures(1).first
201 self.texture = texture
202 gl_error = glGetError
203 assert gl_error == gl_NO_ERROR else print_error gl_error
204
205 resize(display, max_dynamic_resolution_ratio)
206 assert glCheckFramebufferStatus(gl_FRAMEBUFFER) == gl_FRAMEBUFFER_COMPLETE
207
208 # Array buffer
209 buffer_array = glGenBuffers(1).first
210 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
211 assert glIsBuffer(buffer_array)
212 gl_error = glGetError
213 assert gl_error == gl_NO_ERROR else print_error gl_error
214
215 ## coord
216 var data = new Array[Float]
217 data.add_all([-1.0, -1.0, 0.0,
218 1.0, -1.0, 0.0,
219 -1.0, 1.0, 0.0,
220 1.0, 1.0, 0.0])
221 ## tex_coord
222 data.add_all([0.0, 0.0,
223 1.0, 0.0,
224 0.0, 1.0,
225 1.0, 1.0])
226 var c_data = new GLfloatArray.from(data)
227 glBufferData(gl_ARRAY_BUFFER, data.length*4, c_data.native_array, gl_STATIC_DRAW)
228
229 glBindBuffer(gl_ARRAY_BUFFER, 0)
230
231 gl_error = glGetError
232 assert gl_error == gl_NO_ERROR else print_error gl_error
233 end
234
235 # Init size or resize `depth_renderbuffer` and `texture`
236 fun resize(display: GamnitDisplay, max_dynamic_resolution_ratio: Float)
237 do
238 var width = (display.width.to_f * max_dynamic_resolution_ratio).to_i
239 var height = (display.height.to_f * max_dynamic_resolution_ratio).to_i
240
241 glBindFramebuffer(gl_FRAMEBUFFER, dynamic_framebuffer)
242
243 var depthbuffer = self.depth_renderbuffer
244 var texture = self.texture
245
246 # Depth
247 glBindRenderbuffer(gl_RENDERBUFFER, depthbuffer)
248 assert glIsRenderbuffer(depthbuffer)
249 glRenderbufferStorage(gl_RENDERBUFFER, gl_DEPTH_COMPNENT16, width, height)
250 glFramebufferRenderbuffer(gl_FRAMEBUFFER, gl_DEPTH_ATTACHMENT, gl_RENDERBUFFER, depthbuffer)
251 var gl_error = glGetError
252 assert gl_error == gl_NO_ERROR else print_error gl_error
253
254 # Texture
255 glBindTexture(gl_TEXTURE_2D, texture)
256 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
257 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
258 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_WRAP_S, gl_CLAMP_TO_EDGE)
259 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_WRAP_T, gl_CLAMP_TO_EDGE)
260 glTexImage2D(gl_TEXTURE_2D, 0, gl_RGB, width, height,
261 0, gl_RGB, gl_UNSIGNED_BYTE, new Pointer.nul)
262 glFramebufferTexture2D(gl_FRAMEBUFFER, gl_COLOR_ATTACHMENT0, gl_TEXTURE_2D, texture, 0)
263
264 gl_error = glGetError
265 assert gl_error == gl_NO_ERROR else print_error gl_error
266
267 # Take down
268 glBindRenderbuffer(gl_RENDERBUFFER, 0)
269 glBindFramebuffer(gl_FRAMEBUFFER, 0)
270
271 gl_error = glGetError
272 assert gl_error == gl_NO_ERROR else print_error gl_error
273 end
274
275 var destroyed = false
276 fun destroy
277 do
278 if destroyed then return
279 destroyed = true
280
281 # Free the buffer
282 glDeleteBuffers([buffer_array])
283 var gl_error = glGetError
284 assert gl_error == gl_NO_ERROR else print_error gl_error
285 buffer_array = -1
286
287 # Free the dynamic framebuffer and its attachments
288 glDeleteBuffers([buffer_array])
289 glDeleteFramebuffers([dynamic_framebuffer])
290 glDeleteRenderbuffers([depth_renderbuffer])
291 glDeleteTextures([texture])
292 end
293 end
294
295 private class DynamicResolutionProgram
296 super GamnitProgramFromSource
297
298 redef var vertex_shader_source = """
299 // Vertex coordinates
300 attribute vec3 coord;
301
302 // Vertex coordinates on textures
303 attribute vec2 tex_coord;
304
305 // Output to the fragment shader
306 varying vec2 v_coord;
307
308 void main()
309 {
310 gl_Position = vec4(coord, 1.0);
311 v_coord = tex_coord;
312 }
313 """ @ glsl_vertex_shader
314
315 redef var fragment_shader_source = """
316 precision mediump float;
317
318 // Virtual screen texture / color attachment
319 uniform sampler2D texture0;
320
321 // Input from the vertex shader
322 varying vec2 v_coord;
323
324 // Ratio of the virtual screen to draw
325 uniform float ratio;
326
327 void main()
328 {
329 gl_FragColor = texture2D(texture0, v_coord*ratio);
330 }
331 """ @ glsl_fragment_shader
332
333 # Vertices coordinates
334 var coord = attributes["coord"].as(AttributeVec3) is lazy
335
336 # Coordinates on the textures, per vertex
337 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
338
339 # Virtual screen texture / color attachment
340 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
341
342 # Ratio of the virtual screen to draw
343 var ratio = uniforms["ratio"].as(UniformFloat) is lazy
344 end