bc3cb0227cbe246f6c3a21b6b66eded3bb424325
[nit.git] / lib / android / load_image.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 # Low-level services to load pixel data from the assets
16 module load_image
17
18 intrude import android::assets_and_resources
19 import c
20
21 redef class CByteArray
22 # Get a `Java_nio_ByteBuffer` wrapping `native_array`
23 fun to_java_nio_buffer: Java_nio_ByteBuffer
24 do
25 return jni_env.new_direct_byte_buffer(native_array, length)
26 end
27 end
28
29 redef extern class NativeBitmap
30
31 # Copy the pixel data into a new `CByteArray`
32 #
33 # If `pad_to_pow2` the new buffer contains artificial pixels used to make
34 # the width and the height powers of 2 for compatibility with OpenGL.
35 fun copy_pixels(pad_to_pow2: nullable Bool): CByteArray
36 do
37 var height = height
38 var row_bytes = row_bytes
39 var bytes = row_bytes * height
40
41 var w2 = width.next_pow(2)
42 var h2 = height.next_pow(2)
43 var row_bytes2 = row_bytes * w2 / width
44
45 var capacity = bytes
46 if pad_to_pow2 == true then capacity = row_bytes2 * h2
47
48 var buf = new CByteArray(capacity)
49 var java_buf = buf.to_java_nio_buffer
50 copy_pixels_to_buffer java_buf
51
52 if has_alpha then buf.native_array.unmultiply(width, height)
53
54 if pad_to_pow2 == true then
55 for r in [height-1..0[.step(-1) do
56 var src_offset = row_bytes*r
57 var dst_offset = row_bytes2*r
58 buf.move(dst_offset, src_offset, row_bytes)
59 end
60 end
61
62 return buf
63 end
64
65 # Copy raw pixel data to `buffer`
66 #
67 # Wraps Java: `void android.graphics.Bitmap.copyPixelsToBuffer(java.nio.Buffer)`
68 fun copy_pixels_to_buffer(buffer: Java_nio_Buffer) in "Java" `{
69 self.copyPixelsToBuffer(buffer);
70 `}
71 end
72
73 redef universal Int
74 # The first power of `exp` greater or equal to `self`
75 private fun next_pow(exp: Int): Int
76 do
77 var p = 1
78 while p < self do p = p*exp
79 return p
80 end
81 end
82
83 redef class NativeCByteArray
84 # Reverse Android multiplication of color values per the alpha channel
85 private fun unmultiply(w, h: Int) `{
86 int offset = 0;
87 int x, y;
88 for (x = 0; x < w; x ++)
89 for (y = 0; y < h; y ++) {
90 unsigned char a = self[offset+3];
91 if (a != 0 && a != 0xFF) {
92 self[offset] = self[offset] * 256 / a;
93 self[offset+1] = self[offset+1] * 256 / a;
94 self[offset+2] = self[offset+2] * 256 / a;
95 }
96 offset += 4;
97 }
98 `}
99 end