File: camera-access-marker.html

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1055 lines) | stat: -rw-r--r-- 43,935 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
<!doctype html>
<!--
Copyright 2022 The Immersive Web Community Group

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
  <head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'>
    <meta name='mobile-web-app-capable' content='yes'>
    <meta name='apple-mobile-web-app-capable' content='yes'>

    <title>WebXR Camera Access Marker Tracking</title>
    <link href='../css/common.css' rel='stylesheet'></link>
    <style>
      #text-info {
        position: absolute;
        bottom: 5%;
        left: 2%;
        font-family: monospace;
        color: white;
        background-color: rgba(0, 0, 0, 0.5);
      }

      canvas {
        position: relative;
        left: initial;
        top: initial;
        right: initial;
        bottom: initial;
        /*width: initial;*/
        width: 50%;
        height: initial;
      }
    </style>

    <!--
        This needs a version of opencv.js that's built including opencv_contrib to ensure
        modules/aruco/ is present. The default distribution doesn't include that.

        Here are the build instructions for a non-multithreaded WASM build with SIMD enabled, based
        on https://docs.opencv.org/4.x/d4/da1/tutorial_js_setup.html . The specific instructions
        are for a Debian/Ubuntu system, please adjust as needed for other platforms.

          sudo apt-get install emscripten

          git clone https://github.com/opencv/opencv.git
          git clone https://github.com/opencv/opencv_contrib.git

          python3 ./opencv/platforms/js/build_js.py \
            --emscripten_dir /usr/share/emscripten \
            --cmake_option="-DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules" \
            --build_wasm --simd build_wasm_simd

        The resulting output file is: build_wasm_simd/bin/opencv.js
    -->
    <script src="opencv/opencv.js"></script>

  </head>
  <body>
    <header>
      <details open>
        <summary>Camera Access Marker Tracking</summary>
        This sample tracks <a href="https://docs.opencv.org/4.x/d5/dae/tutorial_aruco_detection.html">ArUco markers</a> using OpenCV.js with WASM and SIMD enabled.
        <p>
          <input id="asyncRead" type="checkbox" checked>
          <label for="asyncRead">Read pixel data asynchronously<br/>
          <input id="delayImage" type="checkbox" checked>
          <label for="delayImage">In async mode, delay camera image to match poses<br/>
          <input id="debugOpenCV" type="checkbox">
          <label for="debugOpenCV">Show debug image for OpenCV</label><br/>
          <input type="range" id="cvDownscale" min="1" max="8" value="4">
          <label for="cvDownscale">Downscale image <span id="cvDownscaleValue">4</span>x before marker detection.</label><br/>

          <a class="back" href="./index.html">Back</a>
        </p>
        <div id="warning-zone"></div>
        <button id="xr-button" class="barebones-button" disabled>XR not found</button>
      </details>
    </header>
    <div id="text-overlay">
      <div id="text-info"></div>
      <canvas id="out-canvas" width="25%" height="25%" style='display: none; top: 10px; left: 10px; border: 2px solid green;'>
    </div>
    <main style='text-align: center;'>
      <p>Click 'Enter AR' to see content</p>
    </main>
    <script type="module">
        import * as mat4 from "../js/third-party/gl-matrix/mat4.js"
        import * as vec3 from "../js/third-party/gl-matrix/vec3.js"
        import * as vec4 from "../js/third-party/gl-matrix/vec4.js"
        import {QueryArgs} from '../js/cottontail/src/util/query-args.js';

        // XR globals.
        let xrButton = document.getElementById('xr-button');
        let xrSession = null;
        let xrRefSpace = null;

        // WebGL scene globals.
        let gl = null;
        let glBinding = null;
        let cubeRotation = 0.0;
        let rotationSpeed = 0.01;
        let shaderProgram = null;
        let programInfo = null;
        let buffers = null;
        let readback_framebuffer = null;
        let readback_pixels = null;
        let framebufferCompletenessChecked = false;
        let glErrorsChecked = false;

        let scaledWidth = 0;
        let scaledHeight = 0;
        let quadCopyShaderProgram = null;
        let quadCopyProgramInfo = null;
        let quadCopyBuffers = null;
        let quadCopyTextures = [];
        let quadCopyTexIdx = 0;
        let backgroundTexture = null;
        let readPixelBuf = null;
        let readPixelsStarted = false;
        let readPixelsDone = false;
        let pendingMarkerDetection = null;
        let frameNum = 0;

        let arc = null;
        let markersInFrame = [];
        let imgScale = parseInt(document.getElementById('cvDownscale').value);

        // If requested, use DOM overlay to provide information about the read color:
        const use_dom_overlay = QueryArgs.getBool('useDomOverlay', true);

        // Optionally, enable time traces for use with chrome://tracing . This
        // is off by default since it spams the console log with timing data.
        const use_timers = QueryArgs.getBool('useTimers', false);

        const textOverlayElement = document.querySelector("#text-overlay");
        if (!textOverlayElement) {
          console.error("#text-overlay element not found!");
          throw new Error("#text-overlay element not found!");
        }

        const textInfoElement = document.querySelector("#text-info");
        if (!textInfoElement) {
          console.error("#text-info element not found!");
          throw new Error("#text-info element not found!");
        }

        document.getElementById('cvDownscale').onchange = (ev) => {
          document.getElementById('cvDownscaleValue').innerText = ev.target.value;
        };

        document.getElementById('asyncRead').onchange = (ev) => {
            // Disable the "delay image" input if in synchronous mode since it's
            // not applicable in that case.
            document.getElementById('delayImage').disabled =
                ev.target.checked ? '' : 'disabled';
        };

        let isWebXRSupported = false;
        let isOpenCVLoaded = false;

        cv.then(() => {
          console.log('OpenCV load complete.');
          // Hack: the cv module doesn't seem to be loading properly?
          if (!cv.imread) cv = Module;
          isOpenCVLoaded = true;
          updateXRButton();
        });

        function updateXRButton() {
          console.log('isWebXRSupported=' + isWebXRSupported + " isOpenCVLoaded=" + isOpenCVLoaded);
          if (isWebXRSupported && isOpenCVLoaded) {
            xrButton.innerHTML = 'Enter AR';
            xrButton.disabled = false;
          } else {
            xrButton.innerHTML = 'AR not found';
            xrButton.disabled = true;
          }
        }
        function checkSupportedState() {
            navigator.xr.isSessionSupported('immersive-ar').then((supported) => {
              console.log('isSessionSupported returned ' + supported);
              isWebXRSupported = supported;
              updateXRButton();
            });
        }

        function initXR() {
            if (!window.isSecureContext) {
                let message = "WebXR unavailable due to insecure context";
                document.getElementById("warning-zone").innerText = message;
            }

            if (navigator.xr) {
                xrButton.addEventListener('click', onButtonClicked);
                navigator.xr.addEventListener('devicechange', checkSupportedState);
                checkSupportedState();
            }
        }

        function onButtonClicked() {
            if (!xrSession) {
                const sessionOptions = {
                  requiredFeatures: ['camera-access'],
                  trackedImages: [],
                  //optionalFeatures: ['image-tracking'], // for autofocus
                  optionalFeatures: [],
                };

                if (use_dom_overlay) {
                  sessionOptions.requiredFeatures.push('dom-overlay');
                  //sessionOptions.domOverlay = { root: document.body };
                  sessionOptions.domOverlay = { root: textOverlayElement };
                }

                navigator.xr.requestSession('immersive-ar', sessionOptions)
                            .then(onSessionStarted, onRequestSessionError);
            } else {
                xrSession.end();
            }
        }

        function onSessionStarted(session) {
            xrSession = session;
            xrButton.innerHTML = 'Exit AR';

            session.addEventListener('end', onSessionEnded);
            let canvas = document.createElement('canvas');
            gl = canvas.getContext('webgl2', {
                xrCompatible: true
            });

            glBinding = new XRWebGLBinding(session, gl);

            // Init cube geometry and cube's default texture.
            initializeGLCube(gl);

            initializeGLQuadCopy(gl);

            document.getElementById('out-canvas').style.display =
               document.getElementById('debugOpenCV').checked ?
              'initial' : 'none';

            for (let i = 0; i < 2; ++i) {
              quadCopyTextures[i] = gl.createTexture();
            }
            readback_framebuffer = gl.createFramebuffer();
            readPixelBuf = gl.createBuffer();

            session.updateRenderState({ baseLayer: new XRWebGLLayer(session, gl) });
            session.requestReferenceSpace('viewer').then((refSpace) => {
                xrRefSpace = refSpace;
                session.requestAnimationFrame(onXRFrame);
            });

          imgScale = parseInt(document.getElementById('cvDownscale').value);
          initializeMarkerTracking();
        }

        function onRequestSessionError(ex) {
            alert("Failed to start immersive AR session.");
            console.error(ex.message);
        }

        function onEndSession(session) {
            session.end();
        }

        function onSessionEnded(event) {
            xrSession = null;
            xrButton.innerHTML = 'Enter AR';
            gl = null;
            framebufferCompletenessChecked = false;
            glErrorsChecked = false;
            lastTime = 0;
            readback_pixels = null;
            backgroundTexture = null;
            readPixelsStarted = false;
            readPixelsDone = false;
            pendingMarkerDetection = null;
            markersInFrame = [];
        }

        // Only print each unique intrinsic string once.
        const intrinsicsPrinted = {};

        // Calculates the camera intrinsics matrix from a projection matrix and viewport.
        // See camera-access-barebones.html in this directory for a detailed comment about
        // this function.
        function getCameraIntrinsics(projectionMatrix, viewport) {
            const p = projectionMatrix;
            // Principal point in pixels (typically at or near the center of the viewport)
            let u0 = (1 - p[8]) * viewport.width / 2 + viewport.x;
            let v0 = (1 - p[9]) * viewport.height / 2 + viewport.y;
            // Focal lengths in pixels (these are equal for square pixels)
            let ax = viewport.width / 2 * p[0];
            let ay = viewport.height / 2 * p[5];
            // Skew factor in pixels (nonzero for rhomboid pixels)
            let gamma = viewport.width / 2 * p[4];

            // Print the calculated intrinsics, but once per unique value to
            // avoid log spam. These can change every frame for some XR devices.
            const intrinsicString = (
                "intrinsics: u0=" +u0 + " v0=" + v0 + " ax=" + ax + " ay=" + ay +
                    " gamma=" + gamma + " for viewport {width=" +
                    viewport.width + ",height=" + viewport.height + ",x=" +
                    viewport.x + ",y=" + viewport.y + "}");
            if (!intrinsicsPrinted[intrinsicString]) {
                console.log("projection:", Array.from(projectionMatrix).join(", "));
                console.log(intrinsicString);
                intrinsicsPrinted[intrinsicString] = true;
            }
          return {u0, v0, ax, ay, gamma};
        }

        let lastTime = 0;
        const frameTimes = [];
        const frameTimeMax = 10;
        let frameTimeIdx = 0;

        function showFps(timestamp) {
            if (lastTime) {
                const delta = timestamp - lastTime;
                frameTimes[frameTimeIdx] = delta;
                frameTimeIdx = (frameTimeIdx + 1) % frameTimeMax;

                if (frameTimes.length >= frameTimeMax - 1) {
                    const fps = Math.round(1000 * frameTimeMax / frameTimes.reduce((sum, v) => sum + v));
                    const msg = '' + fps + ' fps';
                    console.debug(msg);
                    if (use_dom_overlay) {
                      document.getElementById('text-info').innerText = msg;
                    }
                }
            }
            lastTime = timestamp;
        }

        function consoleTimeStart(name) {
          if (use_timers) console.time(name);
        }

        function consoleTimeEnd(name) {
          if (use_timers) console.timeEnd(name);
        }

        function onXRFrame(frameTimestamp, frame) {
            ++frameNum;
            let session = frame.session;
            session.requestAnimationFrame(onXRFrame);
            let pose = frame.getViewerPose(xrRefSpace);
            if (!pose) return;

            for (let view of pose.views) {
                let viewport = session.renderState.baseLayer.getViewport(view);

                let asyncRead = document.getElementById('asyncRead').checked;
                if (asyncRead) {
                    // Use asynchronous readPixels and draw the augmented scene based on the
                    // last-detected marker poses, effectively adding a frame of delay to the
                    // session. If the scene also had elements that are based on poses from the XR
                    // session, such as hit test results, those poses would also need to be saved
                    // to match the marker poses.

                    // WebXR rAF for frame N
                    //   start async readPixels for frame N
                    //   run marker detection for frame N-1
                    //   draw scene for frame N-1
                    //
                    // WebXR rAF for frame N+1
                    //   start async readPixels for frame N+1
                    //   run marker detection for frame N
                    //   draw scene for frame N
                    //
                    // ... etc. There may be be rAF calls where the async readPixels for the
                    // previous frame hasn't completed yet. In that case, just re-draw the
                    // scene based on the last-available marker poses, reusing the corresponding
                    // old camera image as background as appropriate.

                    if (pendingMarkerDetection) {
                       // We have read the pixels for a previous frame, but haven't started marker
                       // detection on it yet. It's now time to grab a fresh frame. Marker processing
                       // will start below.
                      readPixelsDone = false;
                    }

                    if (!readPixelsStarted && !readPixelsDone) {
                      // We're not currently running marker detection. Copy the camera frame and kick
                      // off the asynchronous readPixels + marker detection for it.
                      console.debug('start frame ' + frameNum + ' readPixels');
                      if (!view.camera) return;
                      if (!copyCameraTexture(view)) return;
                      readPixelsAndScheduleMarkerDetectionAsync(view);
                      readPixelsStarted = true;

                      // Update the FPS counter whenever we start processing a fresh image.
                      showFps(frameTimestamp);
                    }

                    if (pendingMarkerDetection) {
                       // Run marker detection on the previous frame synchronously, while the
                       // asynchronous readPixels for the current frame is happening in the
                       // background.
                       pendingMarkerDetection();
                       pendingMarkerDetection = null;
                    }

                    // Draw the scene based on the last-available camera image and marker poses.
                    console.debug('draw frame ' + frameNum);
                    const delayImage = document.getElementById('delayImage').checked;
                    drawMarkerScene(session, viewport, view, delayImage);
                } else {
                    // Simple version - copy the camera texture, readPixels, detect markers, draw them.

                    if (!view.camera) return;
                    if (!copyCameraTexture(view)) return;

                    consoleTimeStart("readPixelsSync");
                    gl.readPixels(0, 0, scaledWidth, scaledHeight,
                                  gl.RGBA, gl.UNSIGNED_BYTE, readback_pixels);
                    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
                    consoleTimeEnd("readPixelsSync");

                    detectMarkers(new Uint8ClampedArray(readback_pixels.buffer),
                                  scaledWidth, scaledHeight, view);

                    drawMarkerScene(session, viewport, view, false);

                    // Update the FPS counter. This is the simple case, there's one processed camera frame
                    // per rAF callback.
                    showFps(frameTimestamp);
                }
            }


            // Once per session, check for GL errors and report them. Then turn
            // off this expensive check.
            if (!glErrorsChecked) {
                const e = gl.getError();
                if (e != 0) {
                    console.warn("Got a GL error:", e);
                } else {
                    glErrorsChecked = true;
                }
            }
        }

        function copyCameraTexture(view) {
            const cameraTexture = glBinding.getCameraImage(view.camera);

            scaledWidth = Math.floor(view.camera.width / imgScale);
            scaledHeight = Math.floor(view.camera.height / imgScale);
            const texture_bytes = scaledWidth * scaledHeight * 4;
            if (!readback_pixels || readback_pixels.length != texture_bytes) {
                readback_pixels = new Uint8Array(texture_bytes);
                for (let i = 0; i < quadCopyTextures.length; ++i) {
                    gl.bindTexture(gl.TEXTURE_2D, quadCopyTextures[i]);
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, scaledWidth, scaledHeight,
                                  0, gl.RGBA, gl.UNSIGNED_BYTE, null);
                }
            }

            console.debug('frame ' + frameNum + ' update texture ' + quadCopyTexIdx);
            gl.bindTexture(gl.TEXTURE_2D, quadCopyTextures[quadCopyTexIdx]);
            gl.bindFramebuffer(gl.FRAMEBUFFER, readback_framebuffer);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
                                    gl.TEXTURE_2D, quadCopyTextures[quadCopyTexIdx], 0);

            // Once per session, check if the framebuffer setup worked.
            if (!framebufferCompletenessChecked &&
                gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) {
                console.warn("Framebuffer incomplete!");
                return false;
            }
            framebufferCompletenessChecked = true;

            gl.viewport(0, 0, scaledWidth, scaledHeight);
            quadCopyDraw(gl, quadCopyProgramInfo, quadCopyBuffers, cameraTexture);

            return true;
        }

        function readPixelsAndScheduleMarkerDetectionAsync(view) {
            const subtaskFrameNum = frameNum;
            const subtaskQuadCopyTexIdx = quadCopyTexIdx;

            consoleTimeStart("readPixelsAsync");
            //readback_pixels.fill(0);
            readPixelsAsync(gl, 0, 0, scaledWidth, scaledHeight, gl.RGBA, gl.UNSIGNED_BYTE,
                            readback_pixels, readPixelBuf).then(() => {
                consoleTimeEnd("readPixelsAsync");
                console.debug('finished frame ' + subtaskFrameNum + ' readPixels');

                readPixelsStarted = false;

                // session ended?
                if (!readback_pixels) return;

                readPixelsDone = true;

                pendingMarkerDetection = () => {
                  console.debug('async do frame ' + subtaskFrameNum + ' marker detection, texture ' + subtaskQuadCopyTexIdx);
                  detectMarkers(new Uint8ClampedArray(readback_pixels.buffer),
                                scaledWidth, scaledHeight, view);

                  backgroundTexture = quadCopyTextures[subtaskQuadCopyTexIdx];
                  console.debug('finished frame ' + subtaskFrameNum + ' marker detection, new background texture ' + subtaskQuadCopyTexIdx);
                };
            });
            quadCopyTexIdx = (quadCopyTexIdx + 1) % quadCopyTextures.length;
            gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        }

        function drawMarkerScene(session, viewport, view, drawBackground) {
            consoleTimeStart("drawMarkerScene");

            gl.bindFramebuffer(gl.FRAMEBUFFER, session.renderState.baseLayer.framebuffer);
            gl.clearColor(0, 0, 0, 0);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            gl.enable(gl.DEPTH_TEST);
            gl.enable(gl.CULL_FACE);
            gl.cullFace(gl.BACK);
            gl.viewport(viewport.x, viewport.y,
                        viewport.width, viewport.height);

            if (drawBackground && backgroundTexture) {
                // Draw the stored camera image matching the scene's pose to the screen. Note that
                // the backgroundTexture was flipped vertically (to match OpenCV expectations), and
                // is now flipped vertically again to ensure a correctly oriented image.
                gl.disable(gl.DEPTH_TEST);
                quadCopyDraw(gl, quadCopyProgramInfo, quadCopyBuffers, backgroundTexture);
                gl.enable(gl.DEPTH_TEST);
            }

            if (drawBackground) {
                gl.enable(gl.BLEND);
                gl.blendFunc(gl.SRC_COLOR, gl.DST_COLOR);
            }
            const markerColor = vec4.fromValues(1, 0, 0, 0.75);
            for (let i = 0; i < markersInFrame.length; ++i) {
                let pose = markersInFrame[i].pose;
                let id = markersInFrame[i].id;
                //console.log('i=', i, 'id=', id, 'pose=', pose);
                markerColor[0] = (1 + Math.cos(id * 2.5)) / 2;
                markerColor[1] = (1 + Math.sin(id * 2.5)) / 2;
                markerColor[2] = (1 + Math.sin(id * 4.1)) / 2;
                drawCube(pose, gl, programInfo, buffers, view, markerColor);
            }
            gl.disable(gl.BLEND);
            consoleTimeEnd("drawMarkerScene");
        }

        let markerImage = null;
        let dictionary = null;
        let markerCorners = null;
        let markerIds = null;
        let rvecs = null;
        let tvecs = null;
        let detectorParams = null;
        function initializeMarkerTracking() {
            markerImage = new cv.Mat();
            dictionary = new cv.aruco_Dictionary(cv.DICT_6X6_250);
            markerCorners  = new cv.MatVector();
            markerIds = new cv.Mat();
            rvecs = new cv.Mat();
            tvecs = new cv.Mat();
            detectorParams = new cv.aruco_DetectorParameters();
            detectorParams.useAruco3Detection = true;
        }

        function detectMarkers(rawData, scaledWidth, scaledHeight, view) {
            consoleTimeStart("detectMarkers");
            const debugOpenCV = document.getElementById('debugOpenCV').checked;

            const img = new cv.Mat(scaledHeight, scaledWidth, cv.CV_8UC4);
            img.data.set(rawData);

            // OpenCV needs either a three-channel RGB image or a grayscale image. The source is
            // four-channel RGBA and needs to be converted.
            cv.cvtColor(img, img, cv.COLOR_RGBA2GRAY, 0);

            // Run ArUco marker detection
            cv.detectMarkers(img, dictionary, markerCorners, markerIds, detectorParams);

            // Assume that the camera image is undistorted. We don't have access to distortion
            // parameters. The AR implementation should have taken care of any required corrections.
            let distCoeffs = cv.matFromArray(5, 1, cv.CV_64F, [0, 0, 0, 0, 0]);

            // Calculate camera intrinsics based on the scaled texture size. Note that the image
            // data was vertically flipped by the quad copy, so the data starts with the top left
            // pixel as expected by OpenCV.  The marker pose transformation will convert from
            // OpenCV's camera space to WebXR viewer space.
            let intrinsics = getCameraIntrinsics(view.projectionMatrix,
                                                 {width: scaledWidth, height: scaledHeight, x: 0, y: 0});
            let cameraMatrix = cv.matFromArray(3, 3, cv.CV_64F,
                                               [intrinsics.ax, 0, intrinsics.u0,
                                                0, intrinsics.ay, intrinsics.v0,
                                                0, 0, 1]);

            // Marker detection needs to know the physical marker size in meters.  If the real size
            // is different, a 3D rendering based on the tracked marker will still look correct on a
            // 2D screen, but the depth will be wrong. This could lead to occlusion or physics
            // issues where a correct depth would be necessary.
            const markerSize = 0.1;
            cv.estimatePoseSingleMarkers(markerCorners, markerSize, cameraMatrix, distCoeffs, rvecs, tvecs);

            markersInFrame = [];
            for (let i = 0; i < markerIds.rows; ++i) {
                // Rotation vector pointing along the rotation axis. Its length
                // provides the rotation angle in radians.
                let rvec = cv.matFromArray(3, 1, cv.CV_64F,
                                           [rvecs.doublePtr(0, i)[0],
                                            rvecs.doublePtr(0, i)[1],
                                            rvecs.doublePtr(0, i)[2]]);
                // Translation vector in OpenCV camera space.
                let tvec = cv.matFromArray(3, 1, cv.CV_64F,
                                           [tvecs.doublePtr(0, i)[0],
                                            tvecs.doublePtr(0, i)[1],
                                            tvecs.doublePtr(0, i)[2]]);

                if (debugOpenCV) {
                  cv.drawFrameAxes(img, cameraMatrix, distCoeffs, rvec, tvec, markerSize);
                }

                // Convert rvec/tvec to a pose in XR space. (For clarity, read these operations from
                // the bottom up to see how the transform from model space to world space is
                // constructed.)
                let m = mat4.create();
                // OpenCV's camera coordinate system has +x right, +y down, +z away.
                // We need +y down and -z away, this is a 180 degree rotation around the X axis.
                mat4.fromRotation(m, Math.PI, [1, 0, 0]);
                // Apply the tvec translation.
                mat4.translate(m, m, tvecs.doublePtr(0, i));
                // Rotate the cube based on rvec's length and axis.
                mat4.rotate(m, m, vec3.length(rvecs.doublePtr(0, i)), rvecs.doublePtr(0, i))
                // Resize the cube to match the marker size.
                mat4.scale(m, m, [markerSize / 2, markerSize / 2, markerSize / 2]);
                // The drawn cube has a 2 unit (meter) edge length. Translate it so that
                // its origin is in the center of the bottom face.
                mat4.translate(m, m, [0, 0, 1]);

                // Save the marker for rendering.
                markersInFrame.push({id: markerIds.intAt(i), pose: m});
            }
            if (debugOpenCV) {
                cv.drawDetectedMarkers(img, markerCorners, markerIds);
                cv.imshow('out-canvas', img);
            }
            img.delete();
            consoleTimeEnd("detectMarkers");
        }

// This GL rendering code is adapted from a publicly provided code sample found at
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL

        function initializeGLQuadCopy(gl) {
            quadCopyShaderProgram = initShaderProgram(gl, `
                attribute vec2 a_position;
                varying vec2 v_uv;
                void main() {
                    gl_Position = vec4(a_position, 0.0, 1.0);
                    // Rescale UV from [-1, 1] to [0, 1]. This also adds
                    // a Y flip since OpenCV expects the image data to start
                    // at the top left corner. When drawing the resulting
                    // texture to the screen, it'll be Y flipped again to
                    // appear in its normal orientation.
                    v_uv.x = (a_position.x + 1.0) * 0.5;
                    v_uv.y = (1.0 - a_position.y) * 0.5;
                }
              `, `
                precision mediump float;
                varying vec2 v_uv;
                uniform sampler2D u_texture;
                void main() {
                    gl_FragColor = texture2D(u_texture, v_uv);
                    gl_FragColor.a = 1.0;
                }
              `);
            quadCopyProgramInfo = {
                program: quadCopyShaderProgram,
                attribLocations: {
                  vertexPosition: gl.getAttribLocation(quadCopyShaderProgram, 'a_position'),
                },
                uniformLocations: {
                  uSampler: gl.getUniformLocation(quadCopyShaderProgram, 'u_texture'),
                },
            };
            quadCopyBuffers = initQuadCopyBuffers(gl);
        }

        function initQuadCopyBuffers(gl) {
            // Create a buffer for the cube's vertex positions.
            const positionBuffer = gl.createBuffer();

            // Select the positionBuffer as the one to apply buffer
            // operations to from here out.
            gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

            // Now create an array of positions for the cube.
            const positions = [
                -1, 1,
                -1, -1,
                1, -1,
                1, -1,
                1, 1,
                -1, 1,
            ]
            // Now pass the list of positions into WebGL to build the
            // shape. We do this by creating a Float32Array from the
            // JavaScript array, then use it to fill the current buffer.
            gl.bufferData(
                gl.ARRAY_BUFFER,
                new Float32Array(positions),
                gl.STATIC_DRAW
            );

            return {
                position: positionBuffer,
            };
        }

        function quadCopyDraw(gl, programInfo, buffers, texture, view) {
            // Tell WebGL how to pull out the positions from the position
            // buffer into the vertexPosition attribute
            {
              const numComponents = 2;
              const type = gl.FLOAT;
              const normalize = false;
              const stride = 0;
              const offset = 0;
              gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
              gl.vertexAttribPointer(
                  programInfo.attribLocations.vertexPosition,
                  numComponents,
                  type,
                  normalize,
                  stride,
                  offset
              );
              gl.enableVertexAttribArray(
                  programInfo.attribLocations.vertexPosition
              );
            }

            gl.useProgram(programInfo.program);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

            // Mipmaps might be useful for >2x downscaling, but this
            // apparently doesn't work for the opaque camera texture. It
            // requires a WebGL2 context since it's non-power-of-2, but
            // still fails silently (framebuffer incomplete).
            //gl.generateMipmap(gl.TEXTURE_2D);

            gl.uniform1i(programInfo.uniformLocations.uSampler, 0);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
        }

        // Vertex shader program
        const vsSource = `
            attribute vec4 aVertexPosition;
            uniform mat4 uModelViewMatrix;
            uniform mat4 uProjectionMatrix;
            void main(void) {
              gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
            }
        `;

        // Fragment shader program
        const fsSource = `
            uniform mediump vec4 uBaseColor;
            precision mediump float;
            void main(void) {
              gl_FragColor = uBaseColor;
            }
        `;

        function initializeGLCube(gl) {
            // Initialize a shader program; this is where all the lighting
            // for the vertices and so forth is established.
            shaderProgram = initShaderProgram(gl, vsSource, fsSource);

            // Collect all the info needed to use the shader program.
            // Look up which attributes our shader program is using
            // for aVertexPosition, aTextureCoord and also
            // look up uniform locations.
            programInfo = {
                program: shaderProgram,
                attribLocations: {
                  vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
                },
                uniformLocations: {
                  projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
                  modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
                  uBaseColor: gl.getUniformLocation(shaderProgram, 'uBaseColor'),
                },
            };

            // Here's where we call the routine that builds all the
            // objects we'll be drawing.
            buffers = initBuffers(gl);
        }

        // Initialize the buffers we'll need. For this demo, we just
        // have one object -- a simple three-dimensional cube.
        function initBuffers(gl) {
          // Create a buffer for the cube's vertex positions.
          const positionBuffer = gl.createBuffer();

          // Select the positionBuffer as the one to apply buffer
          // operations to from here out.
          gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

          // Now create an array of positions for the cube.
          const positions = [
            // Front face
            -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
            // Back face
            -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
            // Top face
            -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
            // Bottom face
            -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
            // Right face
            1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
            // Left face
            -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
          ];

          // Now pass the list of positions into WebGL to build the
          // shape. We do this by creating a Float32Array from the
          // JavaScript array, then use it to fill the current buffer.
          gl.bufferData(
            gl.ARRAY_BUFFER,
            new Float32Array(positions),
            gl.STATIC_DRAW
          );

          // Build the element array buffer; this specifies the indices
          // into the vertex arrays for each face's vertices.

          const indexBuffer = gl.createBuffer();
          gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);

          // This array defines each face as two triangles, using the
          // indices into the vertex array to specify each triangle's
          // position.

          const indices = [
            0, 1, 2, 0, 2, 3, // front
            4, 5, 6, 4, 6, 7, // back
            8, 9, 10, 8, 10, 11, // top
            12, 13, 14, 12, 14, 15, // bottom
            16, 17, 18, 16, 18, 19, // right
            20, 21, 22, 20, 22, 23, // left
          ];

          // Now send the element array to GL
          gl.bufferData(
            gl.ELEMENT_ARRAY_BUFFER,
            new Uint16Array(indices),
            gl.STATIC_DRAW
          );

          return {
            position: positionBuffer,
            indices: indexBuffer,
          };
        }

        function drawCube(modelViewMatrix, gl, programInfo, buffers, view, baseColor) {
          // Tell WebGL how to pull out the positions from the position
          // buffer into the vertexPosition attribute
          {
            const numComponents = 3;
            const type = gl.FLOAT;
            const normalize = false;
            const stride = 0;
            const offset = 0;
            gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
            gl.vertexAttribPointer(
              programInfo.attribLocations.vertexPosition,
              numComponents,
              type,
              normalize,
              stride,
              offset
            );
            gl.enableVertexAttribArray(
              programInfo.attribLocations.vertexPosition
            );
          }

          // Tell WebGL which indices to use to index the vertices
          gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);

          // Tell WebGL to use our program when drawing
          gl.useProgram(programInfo.program);

          // Set the shader uniforms
          gl.uniformMatrix4fv(
            programInfo.uniformLocations.projectionMatrix,
            false,
            view.projectionMatrix
          );
          gl.uniformMatrix4fv(
            programInfo.uniformLocations.modelViewMatrix,
            false,
            modelViewMatrix
          );

          gl.uniform4fv(programInfo.uniformLocations.uBaseColor, baseColor);

          {
            const vertexCount = 36;
            const type = gl.UNSIGNED_SHORT;
            const offset = 0;
            gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
          }
        }

        // Initialize a shader program, so WebGL knows how to draw our data
        //
        function initShaderProgram(gl, vsSource, fsSource) {
          const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
          const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);

          // Create the shader program

          const shaderProgram = gl.createProgram();
          gl.attachShader(shaderProgram, vertexShader);
          gl.attachShader(shaderProgram, fragmentShader);
          gl.linkProgram(shaderProgram);

          // If creating the shader program failed, alert

          if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert(
              "Unable to initialize the shader program: " +
                gl.getProgramInfoLog(shaderProgram)
            );
            return null;
          }

          return shaderProgram;
        }

        // Creates a shader of the given type, uploads the source and
        // compiles it.
        //
        function loadShader(gl, type, source) {
          const shader = gl.createShader(type);

          // Send the source to the shader object

          gl.shaderSource(shader, source);

          // Compile the shader program

          gl.compileShader(shader);

          // See if it compiled successfully

          if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            alert(
              "An error occurred compiling the shaders: " +
                gl.getShaderInfoLog(shader)
            );
            gl.deleteShader(shader);
            return null;
          }

          return shader;
        }

// ... end of GL rendering code adapted from a publicly provided code sample found at
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL


// This non-blocking async data readback implementation is adapted from a publicly provided code sample found at
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#use_non-blocking_async_data_readback

        function clientWaitAsync(gl, sync, flags, interval_ms) {
          return new Promise((resolve, reject) => {
            function test() {
              const res = gl.clientWaitSync(sync, flags, 0);
              if (res === gl.WAIT_FAILED) {
                reject();
                return;
              }
              if (res === gl.TIMEOUT_EXPIRED) {
                setTimeout(test, interval_ms);
                return;
              }
              resolve();
            }
            test();
          });
        }

        async function getBufferSubDataAsync(
            gl, target, buffer, srcByteOffset, dstBuffer,
            /* optional */ dstOffset, /* optional */ length) {
          const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
          gl.flush();

          await clientWaitAsync(gl, sync, 0, 1);
          gl.deleteSync(sync);

          gl.bindBuffer(target, buffer);
          gl.getBufferSubData(target, srcByteOffset, dstBuffer, dstOffset, length);
          gl.bindBuffer(target, null);

          return dstBuffer;
        }

        async function readPixelsAsync(gl, x, y, w, h, format, type, dest, buf) {
          gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);
          gl.bufferData(gl.PIXEL_PACK_BUFFER, dest.byteLength, gl.STREAM_READ);
          gl.readPixels(x, y, w, h, format, type, 0);
          gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);

          await getBufferSubDataAsync(gl, gl.PIXEL_PACK_BUFFER, buf, 0, dest);

          return dest;
        }

// ... end of non-blocking async data readback implementation adapted from a publicly provided code sample found at
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#use_non-blocking_async_data_readback


        initXR();
    </script>
  </body>
</html>