Merge: gamnit: new services and a lot of bug fixes and performance improvements
[nit.git] / lib / gamnit / textures.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 # Load textures, create subtextures and manage their life-cycle
16 module textures
17
18 import display
19
20 # Texture composed of pixels, loaded from the assets folder by default
21 #
22 # Most textures should be created with `App` (as attributes)
23 # for the method `create_scene` to load them.
24 #
25 # ~~~
26 # import gamnit::flat
27 #
28 # redef class App
29 # # Create the texture object, it will be loaded automatically
30 # var texture = new Texture("path/in/assets.png")
31 #
32 # redef fun create_scene()
33 # do
34 # # Let `create_scene` load the texture
35 # super
36 #
37 # # Use the texture
38 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
39 # app.sprites.add sprite
40 # end
41 # end
42 # ~~~
43 #
44 # Otherwise, they can be loaded and error checked explicitly after `create_scene`.
45 #
46 # ~~~nitish
47 # var texture = new Texture("path/in/assets.png")
48 # texture.load
49 # var error = texture.error
50 # if error != null then print_error error
51 # ~~~
52 #
53 # A texture may also be created programmatically, like `CheckerTexture`,
54 # or derived from another texture, using `subtexture`.
55 # Textures with actual pixel data (not `Subtexture`) are `RootTexture`.
56 # Texture loaded from the assets folder may in the PNG or JPG formats.
57 abstract class Texture
58
59 # Prepare a texture located at `path` within the `assets` folder
60 new (path: Text) do return new TextureAsset(path.to_s)
61
62 # Root texture from which `self` is derived
63 fun root: RootTexture is abstract
64
65 # Width in pixels of this texture
66 var width = 0.0
67
68 # Height in pixels of this texture
69 var height = 0.0
70
71 # Load this texture, force reloading it if `force`
72 fun load(force: nullable Bool) do end
73
74 # Last error on this texture
75 var error: nullable Error = null
76
77 # OpenGL handle to this texture
78 fun gl_texture: Int do return root.gl_texture
79
80 # Prepare a subtexture from this texture, from the given pixel offsets
81 fun subtexture(left, top, width, height: Numeric): Subtexture
82 do
83 return new AbsoluteSubtexture(self, left.to_f, top.to_f, width.to_f, height.to_f)
84 end
85
86 # Offset of the left border on `root` from 0.0 to 1.0
87 fun offset_left: Float do return 0.0
88
89 # Offset of the top border on `root` from 0.0 to 1.0
90 fun offset_top: Float do return 0.0
91
92 # Offset of the right border on `root` from 0.0 to 1.0
93 fun offset_right: Float do return 1.0
94
95 # Offset of the bottom border on `root` from 0.0 to 1.0
96 fun offset_bottom: Float do return 1.0
97
98 # Should this texture be drawn pixelated when magnified? otherwise it is interpolated
99 #
100 # This setting affects all the textures based on the same pixel data, or `root`.
101 #
102 # Must be set after a successful call to `load`.
103 fun pixelated=(pixelated: Bool)
104 do
105 if root.gl_texture == -1 then return
106
107 # TODO do not modify `root` by using *sampler objects* in glesv3
108 glBindTexture(gl_TEXTURE_2D, root.gl_texture)
109
110 var param = if pixelated then gl_NEAREST else gl_LINEAR
111 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, param)
112 end
113 end
114
115 # Colorful small texture of 32x32 pixels by default
116 class CheckerTexture
117 super RootTexture
118
119 # Width and height in pixels, defaults to 32
120 var size = 32 is optional
121
122 redef fun load(force)
123 do
124 if gl_texture != -1 then return
125 load_checker size
126 loaded = true
127 end
128 end
129
130 # Custom texture with pixel values filled programmatically
131 #
132 # At creation, the texture is composed of `width` by `height` (rounded down)
133 # transparent pixels. The pixels value can be set using `[]=`.
134 #
135 # ~~~
136 # # Build a texture with 4 colors
137 # var tex = new CustomTexture(2.0, 2.0)
138 # tex[0, 0] = [1.0, 0.0, 0.0] # Red
139 # tex[0, 1] = [0.0, 1.0, 0.0] # Green
140 # tex[1, 0] = [0.0, 0.0, 1.0] # Blue
141 # tex[1, 1] = [1.0, 1.0, 1.0, 0.5] # Transparent white
142 # tex.load
143 # ~~~
144 class CustomTexture
145 super RootTexture
146
147 redef var width
148 redef var height
149
150 private var cpixels = new CByteArray(4*width.to_i*height.to_i) is lazy
151
152 # Set the `color` of the pixel at `x`, `y` (from the top-left corner)
153 #
154 # The argument `color` should be an array of up to 4 floats (RGBA).
155 # If `color` has less than 4 items, the missing items are replaced by 1.0.
156 #
157 # Require: `x < width.to_i and y < height.to_i`
158 fun []=(x, y: Int, color: Array[Float])
159 do
160 assert x < width.to_i and y < height.to_i else print_error "{class_name}::[] out of bounds"
161
162 # Simple conversion from [0.0..1.0] to [0..255]
163 var bytes = [for c in color do (c*255.0).round.to_i.clamp(0, 255).to_bytes.last]
164 while bytes.length < 4 do bytes.add 255u8
165
166 var offset = 4*(x + y*width.to_i)
167 for i in [0..4[ do cpixels[offset+i] = bytes[i]
168
169 loaded = false
170 end
171
172 # Overwrite all pixels with `color`, return `self`
173 #
174 # The argument `color` should be an array of up to 4 floats (RGBA).
175 # If `color` has less than 4 items, the missing items are replaced by 1.0.
176 fun fill(color: Array[Float]): SELF
177 do
178 # Simple conversion from [0.0..1.0] to [0..255]
179 var bytes = [for c in color do (c*255.0).round.to_i.clamp(0, 255).to_bytes.last]
180 while bytes.length < 4 do bytes.add 255u8
181
182 var i = 0
183 for x in [0..width.to_i[ do
184 for y in [0..height.to_i[ do
185 for j in [0..4[ do cpixels[i+j] = bytes[j]
186 i += 4
187 end
188 end
189
190 loaded = false
191 return self
192 end
193
194 redef fun load(force)
195 do
196 force = force or else false
197 if loaded and not force then return
198
199 if force and glIsTexture(gl_texture) then
200 # Was already loaded, free the previous GL name
201 glDeleteTextures([gl_texture])
202 end
203 gl_texture = -1
204
205 # Round down the desired dimension
206 var width = width.to_i
207 var height = height.to_i
208 self.width = width.to_f
209 self.height = height.to_f
210
211 load_from_pixels(cpixels.native_array, width, height, gl_RGBA)
212
213 loaded = true
214 end
215 end
216
217 # Texture with its own pixel data
218 class RootTexture
219 super Texture
220
221 redef fun root do return self
222
223 # Has this texture been loaded yet?
224 var loaded = false
225
226 redef var gl_texture = -1
227
228 init do all_root_textures.add self
229
230 # Should the pixels RGB values be premultiplied by their alpha value at loading?
231 #
232 # All gamnit textures must have premultiplied alpha, it provides a better
233 # alpha blending, avoids artifacts and allows for additive blending.
234 #
235 # When at `true`, the default, pixels RGB values are premultiplied
236 # at loading. Set to `false` if pixels RGB values are already
237 # premultiplied in the source data.
238 #
239 # This value must be set before calling `load`.
240 var premultiply_alpha = true is writable
241
242 private fun load_from_pixels(pixels: Pointer, width, height: Int, format: GLPixelFormat)
243 do
244 var max_texture_size = glGetIntegerv(gl_MAX_TEXTURE_SIZE, 0)
245 if width > max_texture_size then
246 error = new Error("Texture width larger than gl_MAX_TEXTURE_SIZE ({max_texture_size}) in {self} at {width}")
247 return
248 else if height > max_texture_size then
249 error = new Error("Texture height larger than gl_MAX_TEXTURE_SIZE ({max_texture_size}) in {self} at {height}")
250 return
251 end
252
253 # Premultiply alpha?
254 if premultiply_alpha and format == gl_RGBA then
255 pixels.premultiply_alpha(width, height)
256 end
257
258 glPixelStorei(gl_UNPACK_ALIGNEMENT, 1)
259 var tex = glGenTextures(1)[0]
260 gl_texture = tex
261
262 glBindTexture(gl_TEXTURE_2D, tex)
263 glTexImage2D(gl_TEXTURE_2D, 0, format, width, height, 0, format, gl_UNSIGNED_BYTE, pixels)
264
265 glHint(gl_GENERATE_MIPMAP_HINT, gl_NICEST)
266 glGenerateMipmap(gl_TEXTURE_2D)
267 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR_MIPMAP_LINEAR)
268
269 glBindTexture(gl_TEXTURE_2D, 0)
270 end
271
272 private fun load_checker(size: Int)
273 do
274 var cpixels = new CByteArray(3*size*size)
275
276 var i = 0
277 for x in [0..size[ do
278 var quadrant_x = if x < size/2 then 0 else 1
279 for y in [0..size[ do
280 var quadrant_y = if y < size/2 then 0 else 1
281 var color = if quadrant_x == quadrant_y then
282 [0u8, 0u8, 0u8, 255u8]
283 else [255u8, 255u8, 255u8, 255u8]
284
285 for j in [0..3[ do cpixels[i+j] = color[j]
286 i += 3
287 end
288 end
289
290 width = size.to_f
291 height = size.to_f
292 load_from_pixels(cpixels.native_array, size, size, gl_RGB)
293
294 cpixels.destroy
295 end
296
297 # Has this resource been deleted?
298 var deleted = false
299
300 # Delete this texture and free all its resources
301 #
302 # Use caution with this service as the subtextures may rely on the deleted data.
303 fun delete
304 do
305 if deleted or not loaded then return
306
307 deleted = true
308 end
309 end
310
311 # Texture loaded from the assets folder
312 class TextureAsset
313 super RootTexture
314
315 # Path to this texture within the `assets` folder
316 var path: String
317
318 redef fun load(force)
319 do
320 if loaded and force != true then return
321
322 load_from_platform
323
324 # If no pixel data was loaded, load the pixel default texture
325 if gl_texture == -1 then load_checker 32
326
327 loaded = true
328 end
329
330 # Partially load this texture from platform-specific features
331 #
332 # This method should fill `width`, `height` and `pixels`.
333 private fun load_from_platform is abstract
334
335 redef fun to_s do return "<{class_name} path:{path}>"
336 end
337
338 # Texture derived from another texture, does not own its pixels
339 abstract class Subtexture
340 super Texture
341
342 # Parent texture, from which this texture was created
343 var parent: Texture
344
345 redef fun root do return parent.root
346
347 redef fun load(force) do root.load(force)
348 end
349
350 # Subtexture created from pixel coordinates within `parent`
351 class AbsoluteSubtexture
352 super Subtexture
353
354 # Left border of this texture relative to `parent`
355 var left: Float
356
357 # Top border of this texture relative to `parent`
358 var top: Float
359
360 private fun set_wh(width, height: Float)
361 is autoinit do
362 self.width = width
363 self.height = height
364 end
365
366 redef var offset_left = parent.offset_left + left / root.width is lazy
367 redef var offset_top = parent.offset_top + top / root.height is lazy
368 redef var offset_right = offset_left + width / root.width is lazy
369 redef var offset_bottom = offset_top + height / root.height is lazy
370 end
371
372 # Subtexture created from relative coordinates ([0..1]) out of the `root` texture
373 class RelativeSubtexture
374 super Subtexture
375
376 redef var offset_left
377 redef var offset_top
378 redef var offset_right
379 redef var offset_bottom
380
381 redef fun width do return root.width * (offset_right - offset_left)
382 redef fun height do return root.height * (offset_bottom - offset_top)
383 end
384
385 redef class Sys
386 # All declared root textures
387 var all_root_textures = new TextureSet
388 end
389
390 # Group of `Texture`
391 class TextureSet
392 super HashSet[Texture]
393
394 # Load all texture of this set
395 fun load_all do for t in self do t.load
396 end
397
398 redef class Pointer
399 # Multiply RGB values by their alpha value
400 private fun premultiply_alpha(width, height: Int) `{
401 uint8_t *bytes = (uint8_t *)self;
402 int x, y, i = 0;
403 for(y = 0; y < height; y ++) {
404 for(x = 0; x < width; x ++) {
405 int a = bytes[i+3];
406 bytes[i ] = bytes[i ] * a / 255;
407 bytes[i+1] = bytes[i+1] * a / 255;
408 bytes[i+2] = bytes[i+2] * a / 255;
409 i += 4;
410 }
411 }
412 `}
413 end