GLCanvas.java 25.9 KB
Newer Older
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
1 2 3 4
package com.projectseptember.RNGL;

import static android.opengl.GLES20.*;

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
5
import android.graphics.Bitmap;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
6
import android.graphics.Matrix;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
7
import android.graphics.PixelFormat;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
8
import android.net.Uri;
9
import android.opengl.GLException;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
10
import android.opengl.GLSurfaceView;
11
import android.util.Base64;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
12
import android.util.DisplayMetrics;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
13 14
import android.util.Log;
import android.view.View;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
15 16
import android.view.ViewGroup;

17
import com.facebook.imagepipeline.core.ExecutorSupplier;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
18 19 20 21 22 23
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableMap;
24 25
import com.facebook.react.uimanager.PointerEvents;
import com.facebook.react.uimanager.ReactPointerEventsView;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
26 27 28
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;

29
import java.io.ByteArrayOutputStream;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
30 31 32 33 34 35
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
36
import java.util.HashSet;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
37 38 39 40
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
41
import java.util.Set;
42
import java.util.concurrent.Executor;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
43 44 45 46

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

47 48
public class GLCanvas extends GLSurfaceView
        implements GLSurfaceView.Renderer, Executor, ReactPointerEventsView {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
49 50 51

    private ReactContext reactContext;
    private RNGLContext rnglContext;
52 53
    private boolean dirtyOnLoad = true;
    private boolean neverRendered = true;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
54 55
    private boolean deferredRendering = false;
    private GLRenderData renderData;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
56
    private int defaultFBO;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
57 58 59 60

    private int nbContentTextures;
    private boolean autoRedraw;
    private GLData data;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
61
    private List<Uri> imagesToPreload;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
62
    private List<Uri> preloaded = new ArrayList<>();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
63

Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
64
    private Map<Uri, GLImage> images = new HashMap<>();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
65
    private List<GLTexture> contentTextures = new ArrayList<>();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
66
    private List<Bitmap> contentBitmaps = new ArrayList<>();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
67

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
68 69
    private Map<Integer, GLShader> shaders;
    private Map<Integer, GLFBO> fbos;
70 71
    private ExecutorSupplier executorSupplier;
    private final Queue<Runnable> mRunOnDraw = new LinkedList<>();
72
    private boolean captureFrameRequested = false;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
73

74
    public GLCanvas(ThemedReactContext context, ExecutorSupplier executorSupplier) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
75 76
        super(context);
        reactContext = context;
77
        this.executorSupplier = executorSupplier;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
78 79
        rnglContext = context.getNativeModule(RNGLContext.class);
        setEGLContextClientVersion(2);
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
80

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
81
        setEGLConfigChooser(8, 8, 8, 8, 16, 0);
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
82 83 84
        getHolder().setFormat(PixelFormat.RGB_888);
        setZOrderOnTop(true);

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
85 86 87
        setRenderer(this);
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
88

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
89 90 91 92 93
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        syncContentBitmaps();
        requestRender();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
94 95
    }

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
96 97
    public GLFBO getFBO (Integer id) {
        if (!fbos.containsKey(id)) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
98
            fbos.put(id, new GLFBO(this));
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
99 100 101 102 103 104 105 106 107 108 109 110 111
        }
        return fbos.get(id);
    }

    public GLShader getShader (Integer id) {
        if (!shaders.containsKey(id)) {
            GLShaderData shaderData = rnglContext.getShader(id);
            if (shaderData == null) return null;
            shaders.put(id, new GLShader(shaderData));
        }
        return shaders.get(id);
    }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
112 113
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
114 115
        fbos = new HashMap<>();
        shaders = new HashMap<>();
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
116 117 118 119 120
        images = new HashMap<>();
        contentTextures = new ArrayList<>();
        contentBitmaps = new ArrayList<>();
        renderData = null;
        requestSyncData();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
121 122 123
    }

    @Override
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
124
    public void onSurfaceChanged(GL10 gl, int width, int height) {}
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
125 126 127 128 129

    @Override
    public void onDrawFrame(GL10 gl) {
        runAll(mRunOnDraw);

Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
130 131 132
        if (contentTextures.size() != this.nbContentTextures)
            resizeUniformContentTextures(nbContentTextures);

133 134 135 136 137 138
        if (haveRemainingToPreload()) {
            if (neverRendered) {
                neverRendered = false;
                glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
                glClear(GL_COLOR_BUFFER_BIT);
            }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
139 140
            return;
        }
141
        neverRendered = false;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
142

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
143 144 145 146 147 148 149 150 151 152
        final boolean shouldRenderNow = deferredRendering || autoRedraw || nbContentTextures == 0;
        if (nbContentTextures > 0) {
            reactContext.runOnUiQueueThread(new Runnable() {
                public void run() {
                    syncContentBitmaps();
                    if (!deferredRendering) {
                        deferredRendering = true;
                        requestRender();
                    }
                }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
153 154
            });
        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
155 156

        if (shouldRenderNow) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
157 158
            this.render();
            deferredRendering = false;
159 160 161 162 163 164 165 166 167
            if (captureFrameRequested) {
                captureFrameRequested = false;
                Bitmap capture = createSnapshot();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                capture.compress(Bitmap.CompressFormat.PNG, 100, baos);
                String frame = "data:image/png;base64,"+
                        Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
                dispatchOnCaptureFrame(frame);
            }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
168 169 170
        }
    }

171 172 173 174 175 176 177 178 179
    private boolean haveRemainingToPreload() {
        for (Uri uri: imagesToPreload) {
            if (!preloaded.contains(uri)) {
                return true;
            }
        }
        return false;
    }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
180 181
    public void setNbContentTextures(int n) {
        this.nbContentTextures = n;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
182
        requestRender();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
183 184 185
    }

    public void setRenderId(int renderId) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
186
        if (nbContentTextures > 0) {
187
            if (!haveRemainingToPreload()) syncContentBitmaps();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
188 189
            requestRender();
        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
190 191 192 193
    }

    public void setOpaque(boolean opaque) {
        if (opaque) {
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
194
            this.getHolder().setFormat(PixelFormat.RGB_888);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
195 196 197 198
        }
        else {
            this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        }
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
199
        this.requestRender();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
200 201 202 203 204 205 206 207 208
    }

    public void setAutoRedraw(boolean autoRedraw) {
        this.autoRedraw = autoRedraw;
        this.setRenderMode(autoRedraw ? GLSurfaceView.RENDERMODE_CONTINUOUSLY : GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    public void setData (GLData data) {
        this.data = data;
209
        if (!haveRemainingToPreload()) syncContentBitmaps();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
210
        requestSyncData();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
211 212 213
    }


Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
214 215 216
    public void setImagesToPreload (ReadableArray imagesToPreloadRA) {
        List<Uri> imagesToPreload = new ArrayList<>();
        for (int i=0; i<imagesToPreloadRA.size(); i++) {
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
217
            imagesToPreload.add(resolveSrc(imagesToPreloadRA.getMap(i).getString("uri")));
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
218
        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
219
        this.imagesToPreload = imagesToPreload;
220
        requestSyncData();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
221 222 223 224
    }

    // Sync methods

225 226
    @Override
    public void execute (final Runnable runnable) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240
        synchronized (mRunOnDraw) {
            mRunOnDraw.add(runnable);
            requestRender();
        }
    }
    private void runAll(Queue<Runnable> queue) {
        synchronized (queue) {
            while (!queue.isEmpty()) {
                queue.poll().run();
            }
        }
    }

    public void requestSyncData () {
241
        execute(new Runnable() {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
242
            public void run() {
243
                // FIXME: maybe should set a flag so we don't do it twice??
244
                if (!syncData())
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
245 246 247 248 249
                    requestSyncData();
            }
        });
    }

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    public static Bitmap captureView (View view) {
        int w = view.getWidth();
        int h = view.getHeight();
        if (w <= 0 || h <= 0)
            return Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888);
        Bitmap bitmap = view.getDrawingCache();
        if (bitmap == null)
            view.setDrawingCacheEnabled(true);
        bitmap = view.getDrawingCache();
        if (bitmap == null) {
            Log.e("GLCanvas", "view.getDrawingCache() is null. view="+view);
            return Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888);
        }
        Matrix matrix = new Matrix();
        matrix.postScale(1, -1);
        Bitmap reversed = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return reversed;
    }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
269 270 271 272 273 274 275 276
    /**
     * Snapshot the content views and save to contentBitmaps (must run in UI Thread)
     */
    public int syncContentBitmaps() {
        List<Bitmap> bitmaps = new ArrayList<>();
        ViewGroup parent = (ViewGroup) this.getParent();
        int count = parent == null ? 0 : parent.getChildCount() - 1;
        for (int i = 0; i < count; i++) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
277 278 279 280 281 282 283 284 285 286
            View view = parent.getChildAt(i);
            if (view instanceof ViewGroup) {
                ViewGroup group = (ViewGroup) view;
                if (group.getChildCount() == 1) {
                    // If the content container only contain one other container,
                    // we will use it for rasterization. That way we screenshot without cropping.
                    view = group.getChildAt(0);
                }
            }
            bitmaps.add(captureView(view));
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
287
        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
288 289 290 291 292 293 294 295 296 297 298 299 300
        contentBitmaps = bitmaps;

        return count;
    }

    /**
     * Draw contentBitmaps to contentTextures (must run in GL Thread)
     */
    public int syncContentTextures() {
        int size = Math.min(contentTextures.size(), contentBitmaps.size());
        for (int i=0; i<size; i++)
            contentTextures.get(i).setPixels(contentBitmaps.get(i));
        return size;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
301 302 303 304 305 306 307 308 309 310
    }

    public void resizeUniformContentTextures (int n) {
        int length = contentTextures.size();
        if (length == n) return;
        if (n < length) {
            contentTextures = contentTextures.subList(0, n);
        }
        else {
            for (int i = contentTextures.size(); i < n; i++) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
311
                contentTextures.add(new GLTexture(this));
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
312 313 314 315 316 317 318
            }
        }
    }


    private int countPreloaded () {
        int nb = 0;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
319 320 321 322
        for (Uri toload: imagesToPreload) {
            if (preloaded.contains(toload)) {
                nb++;
            }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
323 324 325 326
        }
        return nb;
    }

Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
327
    private void onImageLoad (Uri loaded) {
328 329 330 331 332 333 334
        preloaded.add(loaded);
        int count = countPreloaded();
        int total = imagesToPreload.size();
        double progress = ((double) count) / ((double) total);
        dispatchOnProgress(progress, count, total);
        dirtyOnLoad = true;
        requestSyncData();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
335 336
    }

Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    public Uri resolveSrc (String src) {
        Uri uri = null;
        if (src != null) {
            try {
                uri = Uri.parse(src);
                // Verify scheme is set, so that relative uri (used by static resources) are not handled.
                if (uri.getScheme() == null) {
                    uri = null;
                }
            } catch (Exception e) {
                // ignore malformed uri, then attempt to extract resource ID.
            }
            if (uri == null) {
                uri = GLImage.getResourceDrawableUri(reactContext, src);
            }
        }
        return uri;
    }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
355

Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
356
    public Uri srcResource (ReadableMap res) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
357 358 359 360
        String src = null;
        boolean isStatic = res.hasKey("isStatic") && res.getBoolean("isStatic");
        if (res.hasKey("path")) src = res.getString("path");
        if (src==null || isStatic) src = res.getString("uri");
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
361
        return resolveSrc(src);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
362 363
    }

364
    private GLRenderData recSyncData (GLData data, HashMap<Uri, GLImage> images) {
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
365
        Map<Uri, GLImage> prevImages = this.images;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
366

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
367
        GLShader shader = getShader(data.shader);
368
        if (shader == null || !shader.ensureCompile()) return null;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
369 370 371 372 373 374 375 376 377
        Map<String, Integer> uniformsInteger = new HashMap<>();
        Map<String, Float> uniformsFloat = new HashMap<>();
        Map<String, IntBuffer> uniformsIntBuffer = new HashMap<>();
        Map<String, FloatBuffer> uniformsFloatBuffer = new HashMap<>();
        Map<String,GLTexture> textures = new HashMap<>();
        List<GLRenderData> contextChildren = new ArrayList<>();
        List<GLRenderData> children = new ArrayList<>();

        for (GLData child: data.contextChildren) {
378 379 380
            GLRenderData node = recSyncData(child, images);
            if (node == null) return null;
            contextChildren.add(node);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
381 382 383
        }

        for (GLData child: data.children) {
384 385 386
            GLRenderData node = recSyncData(child, images);
            if (node == null) return null;
            children.add(node);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        }

        Map<String, Integer> uniformTypes = shader.getUniformTypes();

        int units = 0;
        ReadableMapKeySetIterator iterator = data.uniforms.keySetIterator();
        while (iterator.hasNextKey()) {
            String uniformName = iterator.nextKey();
            int type = uniformTypes.get(uniformName);

            ReadableMap dataUniforms = data.uniforms;

            if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) {
                uniformsInteger.put(uniformName, units++);

                if (dataUniforms.isNull(uniformName)) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
403
                    GLTexture emptyTexture = new GLTexture(this);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
404 405 406 407 408 409 410 411
                    emptyTexture.setPixelsEmpty();
                    textures.put(uniformName, emptyTexture);
                }
                else {
                    ReadableMap value = dataUniforms.getMap(uniformName);
                    String t = value.getString("type");
                    if (t.equals("content")) {
                        int id = value.getInt("id");
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
412 413 414
                        if (id >= contentTextures.size()) {
                            resizeUniformContentTextures(id+1);
                        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
415 416 417 418
                        textures.put(uniformName, contentTextures.get(id));
                    }
                    else if (t.equals("fbo")) {
                        int id = value.getInt("id");
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
419
                        GLFBO fbo = getFBO(id);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
420 421 422
                        textures.put(uniformName, fbo.color.get(0));
                    }
                    else if (t.equals("uri")) {
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
423 424
                        final Uri src = srcResource(value);
                        if (src == null) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
425
                            shader.runtimeException("texture uniform '"+uniformName+"': Invalid uri format '"+value+"'");
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
426 427 428 429 430 431 432 433 434
                        }

                        GLImage image = images.get(src);
                        if (image == null) {
                            image = prevImages.get(src);
                            if (image != null)
                                images.put(src, image);
                        }
                        if (image == null) {
435
                            image = new GLImage(this, executorSupplier.forDecode(), new Runnable() {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
436 437 438
                                public void run() {
                                    onImageLoad(src);
                                }
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
439
                            });
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
440 441 442 443 444 445
                            image.setSrc(src);
                            images.put(src, image);
                        }
                        textures.put(uniformName, image.getTexture());
                    }
                    else {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
446
                        shader.runtimeException("texture uniform '" + uniformName + "': Unexpected type '" + type + "'");
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
                    }
                }
            }
            else {
                switch (type) {
                    case GL_INT:
                        uniformsInteger.put(uniformName, dataUniforms.getInt(uniformName));
                        break;

                    case GL_BOOL:
                        uniformsInteger.put(uniformName, dataUniforms.getBoolean(uniformName) ? 1 : 0);
                        break;

                    case GL_FLOAT:
                        uniformsFloat.put(uniformName, (float) dataUniforms.getDouble(uniformName));
                        break;

                    case GL_FLOAT_VEC2:
                    case GL_FLOAT_VEC3:
                    case GL_FLOAT_VEC4:
                    case GL_FLOAT_MAT2:
                    case GL_FLOAT_MAT3:
                    case GL_FLOAT_MAT4:
                        ReadableArray arr = dataUniforms.getArray(uniformName);
                        if (arraySizeForType(type) != arr.size()) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
472 473
                            shader.runtimeException(
                                    "uniform '"+uniformName+
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487
                                    "': Invalid array size: "+arr.size()+
                                    ". Expected: "+arraySizeForType(type));
                        }
                        uniformsFloatBuffer.put(uniformName, parseAsFloatArray(arr));
                        break;

                    case GL_INT_VEC2:
                    case GL_INT_VEC3:
                    case GL_INT_VEC4:
                    case GL_BOOL_VEC2:
                    case GL_BOOL_VEC3:
                    case GL_BOOL_VEC4:
                        ReadableArray arr2 = dataUniforms.getArray(uniformName);
                        if (arraySizeForType(type) != arr2.size()) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
488 489
                            shader.runtimeException(
                                    "uniform '"+uniformName+
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
490 491 492 493 494 495 496
                                    "': Invalid array size: "+arr2.size()+
                                    ". Expected: "+arraySizeForType(type));
                        }
                        uniformsIntBuffer.put(uniformName, parseAsIntArray(arr2));
                        break;

                    default:
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
497 498
                        shader.runtimeException(
                                "uniform '"+uniformName+
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
499 500 501 502 503 504 505 506 507
                                "': type not supported: "+type);
                }

            }
        }

        int[] maxTextureUnits = new int[1];
        glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, maxTextureUnits, 0);
        if (units > maxTextureUnits[0]) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
508
            shader.runtimeException("Maximum number of texture reach. got " + units + " >= max " + maxTextureUnits);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
509 510 511 512 513 514 515
        }

        for (String uniformName: uniformTypes.keySet()) {
            if (!uniformsFloat.containsKey(uniformName) &&
                !uniformsInteger.containsKey(uniformName) &&
                !uniformsFloatBuffer.containsKey(uniformName) &&
                !uniformsIntBuffer.containsKey(uniformName)) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
516
                shader.runtimeException("All defined uniforms must be provided. Missing '"+uniformName+"'");
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
            }
        }

        return new GLRenderData(
                shader,
                uniformsInteger,
                uniformsFloat,
                uniformsIntBuffer,
                uniformsFloatBuffer,
                textures,
                data.width,
                data.height,
                data.fboId,
                contextChildren,
                children);
    }

    private FloatBuffer parseAsFloatArray(ReadableArray array) {
        int size = array.size();
        FloatBuffer buf = ByteBuffer.allocateDirect(size * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        for (int i=0; i<size; i++)
          buf.put((float) array.getDouble(i));
        buf.position(0);
        return buf;
    }

    private IntBuffer parseAsIntArray(ReadableArray array) {
        int size = array.size();
        IntBuffer buf = ByteBuffer.allocateDirect(size * 4)
                .order(ByteOrder.nativeOrder())
                .asIntBuffer();
        for (int i=0; i<size; i++)
            buf.put(array.getInt(i));
        buf.position(0);
        return buf;
    }

    private int arraySizeForType(int type) {
        switch (type) {
            case GL_FLOAT_VEC2:
            case GL_INT_VEC2:
            case GL_BOOL_VEC2:
                return 2;

            case GL_FLOAT_VEC3:
            case GL_INT_VEC3:
            case GL_BOOL_VEC3:
                return 3;

            case GL_FLOAT_VEC4:
            case GL_INT_VEC4:
            case GL_BOOL_VEC4:
            case GL_FLOAT_MAT2:
                return 4;

            case GL_FLOAT_MAT3:
                return 9;

            case GL_FLOAT_MAT4:
                return 16;

            default:
                throw new Error("Invalid array type: "+type);
        }
    }

585 586


587 588
    private boolean syncData () {
        if (data == null) return true;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
589
        HashMap<Uri, GLImage> images = new HashMap<>();
590 591
        GLRenderData node = recSyncData(data, images);
        if (node == null) return false;
592
        Set<Uri> imagesGone = diff(this.images.keySet(), images.keySet());
593
        renderData = node;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
594
        this.images = images;
595
        this.preloaded.removeAll(imagesGone);
596
        return true;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
597 598
    }

599
    private void recRender (GLRenderData renderData) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
600 601
        DisplayMetrics dm = reactContext.getResources().getDisplayMetrics();

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
602 603
        int w = Float.valueOf(renderData.width.floatValue() * dm.density).intValue();
        int h = Float.valueOf(renderData.height.floatValue() * dm.density).intValue();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
604 605 606 607 608 609 610 611

        for (GLRenderData child: renderData.contextChildren)
            recRender(child);

        for (GLRenderData child: renderData.children)
            recRender(child);

        if (renderData.fboId == -1) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
612
            glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
613 614 615
            glViewport(0, 0, w, h);
        }
        else {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
616
            GLFBO fbo = getFBO(renderData.fboId);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
            fbo.setShape(w, h);
            fbo.bind();
        }

        renderData.shader.bind();

        for (String uniformName: renderData.textures.keySet()) {
            GLTexture texture = renderData.textures.get(uniformName);
            int unit = renderData.uniformsInteger.get(uniformName);
            texture.bind(unit);
        }

        Map<String, Integer> uniformTypes = renderData.shader.getUniformTypes();
        for (String uniformName: renderData.uniformsInteger.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsInteger.get(uniformName));
        }
        for (String uniformName: renderData.uniformsFloat.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsFloat.get(uniformName));
        }
        for (String uniformName: renderData.uniformsFloatBuffer.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsFloatBuffer.get(uniformName), uniformTypes.get(uniformName));
        }
        for (String uniformName: renderData.uniformsIntBuffer.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsIntBuffer.get(uniformName), uniformTypes.get(uniformName));
        }

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDrawArrays(GL_TRIANGLES, 0, 6);
    }

649
    private void render () {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
650
        if (renderData == null) return;
Gaëtan Renaudeau's avatar
wip  
Gaëtan Renaudeau committed
651
        syncContentTextures();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
652

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
653 654 655
        int[] defaultFBOArr = new int[1];
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, defaultFBOArr, 0);
        defaultFBO = defaultFBOArr[0];
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
656 657 658
        glEnable(GL_BLEND);
        recRender(renderData);
        glDisable(GL_BLEND);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
659
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
660 661 662 663 664

        if (dirtyOnLoad && !haveRemainingToPreload()) {
            dirtyOnLoad = false;
            dispatchOnLoad();
        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
665 666
    }

667 668 669 670 671 672 673 674
    private void dispatchOnCaptureFrame (String frame) {
        WritableMap event = Arguments.createMap();
        event.putString("frame", frame);
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "captureFrame",
                event);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
675 676
    }

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
677
    private void dispatchOnProgress (double progress, int loaded, int total) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
678
        WritableMap event = Arguments.createMap();
679
        event.putDouble("progress", Double.isNaN(progress) ? 0.0 : progress);
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
680
        event.putInt("loaded", loaded);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
681 682 683 684 685 686 687 688
        event.putInt("total", total);
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "progress",
                event);
    }

689
    private void dispatchOnLoad () {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
690 691 692 693 694 695 696
        WritableMap event = Arguments.createMap();
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "load",
                event);
    }
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

    public void requestCaptureFrame() {
        captureFrameRequested = true;
        this.requestRender();
    }

    private Bitmap createSnapshot () {
        return createSnapshot(0, 0, getWidth(), getHeight());
    }

    private Bitmap createSnapshot (int x, int y, int w, int h) {
        int bitmapBuffer[] = new int[w * h];
        int bitmapSource[] = new int[w * h];
        IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
        intBuffer.position(0);

        try {
            glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, intBuffer);
            int offset1, offset2;
            for (int i = 0; i < h; i++) {
                offset1 = i * w;
                offset2 = (h - i - 1) * w;
                for (int j = 0; j < w; j++) {
                    int texturePixel = bitmapBuffer[offset1 + j];
                    int blue = (texturePixel >> 16) & 0xff;
                    int red = (texturePixel << 16) & 0x00ff0000;
                    int pixel = (texturePixel & 0xff00ff00) | red | blue;
                    bitmapSource[offset2 + j] = pixel;
                }
            }
        } catch (GLException e) {
            return null;
        }

        return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
    }

    private PointerEvents mPointerEvents = PointerEvents.AUTO;

    @Override
    public PointerEvents getPointerEvents() {
        return mPointerEvents;
    }

    void setPointerEvents(PointerEvents pointerEvents) {
        mPointerEvents = pointerEvents;
    }

745 746 747 748 749 750
    static <A> Set<A> diff(Set<A> a, Set<A> b) {
        Set<A> d = new HashSet<>();
        d.addAll(a);
        d.removeAll(b);
        return d;
    }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
751
}