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 # Low-level services to load pixel data from the assets
18 intrude import android
::assets_and_resources
21 redef class CByteArray
22 # Get a `Java_nio_ByteBuffer` wrapping `native_array`
23 fun to_java_nio_buffer
: Java_nio_ByteBuffer
25 return jni_env
.new_direct_byte_buffer
(native_array
, length
)
29 redef extern class NativeBitmap
31 # Copy the pixel data into a new `CByteArray`
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
38 var row_bytes
= row_bytes
39 var bytes
= row_bytes
* height
41 var w2
= width
.next_pow
(2)
42 var h2
= height
.next_pow
(2)
43 var row_bytes2
= row_bytes
* w2
/ width
46 if pad_to_pow2
== true then capacity
= row_bytes2
* h2
48 var buf
= new CByteArray(capacity
)
49 var java_buf
= buf
.to_java_nio_buffer
50 copy_pixels_to_buffer java_buf
52 if has_alpha
then buf
.native_array
.unmultiply
(width
, height
)
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
)
65 # Copy raw pixel data to `buffer`
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);
74 # The first power of `exp` greater or equal to `self`
75 private fun next_pow
(exp
: Int): Int
78 while p
< self do p
= p
*exp
83 redef class NativeCByteArray
84 # Reverse Android multiplication of color values per the alpha channel
85 private fun unmultiply
(w
, h
: Int) `{
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;